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 | f81d2c5302319a2bcf2abeb8b2e960a6d1840b98 | 0 | AlexKomm/Google-Directions-Android,openresearch/Google-Directions-Android,fcduarte/Google-Directions-Android,moltak/Google-Directions-Android,0359xiaodong/Google-Directions-Android,ScHaFeR/Google-Directions-Android,jd-alexander/Google-Directions-Android | package com.directions.route;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
/**
* Async Task to access the Google Direction API and return the routing data.
* Created by Furkan Tektas on 10/14/14.
*/
public class Routing extends AbstractRouting {
private final TravelMode travelMode;
private final List<LatLng> waypoints;
private final int avoidKinds;
private final boolean optimize;
private Routing(Builder builder) {
super(builder.listener);
this.travelMode = builder.travelMode;
this.waypoints = builder.waypoints;
this.avoidKinds = builder.avoidKinds;
this.optimize = builder.optimize;
}
protected String constructURL () {
final StringBuffer stringBuffer = new StringBuffer(AbstractRouting.DIRECTIONS_API_URL);
// origin
final LatLng origin = waypoints.get(0);
stringBuffer.append("origin=");
stringBuffer.append(origin.latitude);
stringBuffer.append(',');
stringBuffer.append(origin.longitude);
// destination
final LatLng destination = waypoints.get(waypoints.size() - 1);
stringBuffer.append("&destination=");
stringBuffer.append(destination.latitude);
stringBuffer.append(',');
stringBuffer.append(destination.longitude);
// travel
stringBuffer.append("&mode=");
stringBuffer.append(travelMode.getValue());
// waypoints
if (waypoints.size() > 2) {
stringBuffer.append("&waypoints=");
if(optimize)
stringBuffer.append("optimize:true|");
for (int i = 1; i < waypoints.size() - 1; i++) {
final LatLng p = waypoints.get(i);
stringBuffer.append("via:"); // we don't want to parse the resulting JSON for 'legs'.
stringBuffer.append(p.latitude);
stringBuffer.append(",");
stringBuffer.append(p.longitude);
stringBuffer.append("|");
}
}
// avoid
if (avoidKinds > 0) {
stringBuffer.append("&avoid=");
stringBuffer.append(AvoidKind.getRequestParam(avoidKinds));
}
// sensor
stringBuffer.append("&sensor=true");
return stringBuffer.toString();
}
public static class Builder {
private TravelMode travelMode;
private List<LatLng> waypoints;
private int avoidKinds;
private RoutingListener listener;
private boolean optimize;
public Builder () {
this.travelMode = TravelMode.DRIVING;
this.waypoints = new ArrayList<>();
this.avoidKinds = 0;
this.listener = null;
this.optimize = false;
}
public Builder travelMode (TravelMode travelMode) {
this.travelMode = travelMode;
return this;
}
public Builder waypoints (LatLng... points) {
waypoints.clear();
for (LatLng p : points) {
waypoints.add(p);
}
return this;
}
public Builder waypoints (List<LatLng> waypoints) {
this.waypoints = new ArrayList<>(waypoints);
return this;
}
public Builder optimize(boolean optimize) {
this.optimize = optimize;
return this;
}
public Builder avoid (AvoidKind... avoids) {
for (AvoidKind avoidKind : avoids) {
this.avoidKinds |= avoidKind.getBitValue();
}
return this;
}
public Builder withListener (RoutingListener listener) {
this.listener = listener;
return this;
}
public Routing build () {
if (this.waypoints.size() < 2) {
throw new IllegalArgumentException("Must supply at least two waypoints to route between.");
}
if (this.waypoints.size() <= 2 && this.optimize) {
throw new IllegalArgumentException("You need at least three waypoints to enable optimize");
}
return new Routing(this);
}
}
}
| library/src/main/java/com/directions/route/Routing.java | package com.directions.route;
import com.google.android.gms.maps.model.LatLng;
import java.nio.charset.IllegalCharsetNameException;
import java.util.ArrayList;
import java.util.List;
/**
* Async Task to access the Google Direction API and return the routing data.
* Created by Furkan Tektas on 10/14/14.
*/
public class Routing extends AbstractRouting {
private final TravelMode travelMode;
private final List<LatLng> waypoints;
private final int avoidKinds;
private final boolean optimize;
private Routing(Builder builder) {
super(builder.listener);
this.travelMode = builder.travelMode;
this.waypoints = builder.waypoints;
this.avoidKinds = builder.avoidKinds;
this.optimize = builder.optimize;
}
protected String constructURL () {
final StringBuffer stringBuffer = new StringBuffer(AbstractRouting.DIRECTIONS_API_URL);
// origin
final LatLng origin = waypoints.get(0);
stringBuffer.append("origin=");
stringBuffer.append(origin.latitude);
stringBuffer.append(',');
stringBuffer.append(origin.longitude);
// destination
final LatLng destination = waypoints.get(waypoints.size() - 1);
stringBuffer.append("&destination=");
stringBuffer.append(destination.latitude);
stringBuffer.append(',');
stringBuffer.append(destination.longitude);
// travel
stringBuffer.append("&mode=");
stringBuffer.append(travelMode.getValue());
// waypoints
if (waypoints.size() > 2) {
stringBuffer.append("&waypoints=");
if(optimize)
stringBuffer.append("optimize:true|");
for (int i = 1; i < waypoints.size() - 1; i++) {
final LatLng p = waypoints.get(i);
stringBuffer.append("via:"); // we don't want to parse the resulting JSON for 'legs'.
stringBuffer.append(p.latitude);
stringBuffer.append(",");
stringBuffer.append(p.longitude);
stringBuffer.append("|");
}
}
// avoid
if (avoidKinds > 0) {
stringBuffer.append("&avoid=");
stringBuffer.append(AvoidKind.getRequestParam(avoidKinds));
}
// sensor
stringBuffer.append("&sensor=true");
return stringBuffer.toString();
}
public static class Builder {
private TravelMode travelMode;
private List<LatLng> waypoints;
private int avoidKinds;
private RoutingListener listener;
private boolean optimize;
public Builder () {
this.travelMode = TravelMode.DRIVING;
this.waypoints = new ArrayList<>();
this.avoidKinds = 0;
this.listener = null;
this.optimize = false;
}
public Builder travelMode (TravelMode travelMode) {
this.travelMode = travelMode;
return this;
}
public Builder waypoints (LatLng... points) {
waypoints.clear();
for (LatLng p : points) {
waypoints.add(p);
}
return this;
}
public Builder waypoints (List<LatLng> waypoints) {
this.waypoints = new ArrayList<>(waypoints);
return this;
}
public Builder optimize(boolean optimize) {
this.optimize = optimize;
return this;
}
public Builder avoid (AvoidKind... avoids) {
for (AvoidKind avoidKind : avoids) {
this.avoidKinds |= avoidKind.getBitValue();
}
return this;
}
public Builder withListener (RoutingListener listener) {
this.listener = listener;
return this;
}
public Routing build () {
if (this.waypoints.size() < 2) {
throw new IllegalArgumentException("Must supply at least two waypoints to route between.");
}
if (this.waypoints.size() <= 2 && this.optimize) {
throw new IllegalCharsetNameException("You need at least three waypoints to enable optimize");
}
return new Routing(this);
}
}
}
| fix the wrong type of exception
| library/src/main/java/com/directions/route/Routing.java | fix the wrong type of exception | <ide><path>ibrary/src/main/java/com/directions/route/Routing.java
<ide>
<ide> import com.google.android.gms.maps.model.LatLng;
<ide>
<del>import java.nio.charset.IllegalCharsetNameException;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> throw new IllegalArgumentException("Must supply at least two waypoints to route between.");
<ide> }
<ide> if (this.waypoints.size() <= 2 && this.optimize) {
<del> throw new IllegalCharsetNameException("You need at least three waypoints to enable optimize");
<add> throw new IllegalArgumentException("You need at least three waypoints to enable optimize");
<ide> }
<ide> return new Routing(this);
<ide> } |
|
Java | apache-2.0 | ea917b183d9c647f34f5c78ed1d928088cfd6a28 | 0 | dachuanz/crypto | package net.oschina.crypto;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public abstract class RC2Coder {
/*
*
* @return
* @throws NoSuchAlgorithmException
*/
public static byte[] initKey() throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//kg.init(256);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
/**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encypt(byte[] data, byte[] key) throws Exception {
Key key2 = toKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key2);
return cipher.doFinal(data);
}
/**
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
return secretKey;
}
/**
*
* 解密
* @param data 数据
* @param key 密钥
* @return
* @throws Exception
*/
public static byte[] decypt(byte[] data, byte[] key) throws Exception {
Key key2 = toKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key2);
return cipher.doFinal(data);
}
/**
*
*/
public static final String KEY_ALGORITHM = "RC2";
public static final String CIPHER_ALGORITHM = "RC2/ECB/PKCS5Padding";
}
| src/net/oschina/crypto/RC2Coder.java | package net.oschina.crypto;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public abstract class RC2Coder {
/*
*
* @return
* @throws NoSuchAlgorithmException
*/
public static byte[] initKey() throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//kg.init(256);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
/**
*
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encypt(byte[] data, byte[] key) throws Exception {
Key key2 = toKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key2);
return cipher.doFinal(data);
}
/**
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
return secretKey;
}
/**
*
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decypt(byte[] data, byte[] key) throws Exception {
Key key2 = toKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key2);
return cipher.doFinal(data);
}
/**
*
*/
public static final String KEY_ALGORITHM = "RC2";
public static final String CIPHER_ALGORITHM = "RC2/ECB/PKCS5Padding";
}
| Update RC2Coder.java | src/net/oschina/crypto/RC2Coder.java | Update RC2Coder.java | <ide><path>rc/net/oschina/crypto/RC2Coder.java
<ide> }
<ide>
<ide> /**
<del> *
<add> * 加密
<ide> *
<ide> * @param data
<ide> * @param key
<ide>
<ide> /**
<ide> *
<del> *
<del> * @param data
<del> * @param key
<add> * 解密
<add> * @param data 数据
<add> * @param key 密钥
<ide> * @return
<ide> * @throws Exception
<ide> */ |
|
Java | lgpl-2.1 | 7bd48ceea0974fd8355aa89b4b47a4c99e8cf4d5 | 0 | pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/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.rendering.macro.velocity;
import java.util.Collections;
import org.junit.Test;
import org.xwiki.rendering.block.MacroBlock;
import org.xwiki.rendering.macro.Macro;
import org.xwiki.rendering.macro.script.ScriptMockSetup;
import org.xwiki.rendering.renderer.PrintRendererFactory;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.MacroTransformationContext;
import org.xwiki.test.AbstractComponentTestCase;
import static org.xwiki.rendering.test.BlockAssert.*;
/**
* Verify that a Velocity macro defined in one page is not visible from another page.
*
* @version $Id$
* @since 2.4M2
*/
public class VelocityMacroIsolationTest extends AbstractComponentTestCase
{
private Macro velocityMacro;
@Override
protected void registerComponents() throws Exception
{
new ScriptMockSetup(getMockery(), getComponentManager());
this.velocityMacro = getComponentManager().lookup(Macro.class, "velocity");
}
@Test
public void testVelocityMacroIsolation() throws Exception
{
String expected = "beginDocument\n"
+ "beginParagraph\n"
+ "onSpecialSymbol [#]\n"
+ "onWord [testMacrosAreLocal]\n"
+ "onSpecialSymbol [(]\n"
+ "onSpecialSymbol [)]\n"
+ "endParagraph\n"
+ "endDocument";
VelocityMacroParameters params = new VelocityMacroParameters();
MacroTransformationContext context = new MacroTransformationContext();
context.setSyntax(Syntax.XWIKI_2_0);
context.setCurrentMacroBlock(new MacroBlock("velocity", Collections.<String, String>emptyMap(), false));
// Execute the velocity macro in the context of a first page
context.setId("page1");
this.velocityMacro.execute(params, "#macro(testMacrosAreLocal)mymacro#end", context);
// And then in the context of a second independent page
context.setId("page2");
assertBlocks(expected, this.velocityMacro.execute(params, "#testMacrosAreLocal()", context),
getComponentManager().lookup(PrintRendererFactory.class, "event/1.0"));
}
}
| xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-velocity/src/test/java/org/xwiki/rendering/macro/velocity/VelocityMacroIsolationTest.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.rendering.macro.velocity;
import org.junit.Test;
import org.xwiki.rendering.macro.Macro;
import org.xwiki.rendering.macro.script.ScriptMockSetup;
import org.xwiki.rendering.renderer.PrintRendererFactory;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.MacroTransformationContext;
import org.xwiki.test.AbstractComponentTestCase;
import static org.xwiki.rendering.test.BlockAssert.*;
/**
* Verify that a Velocity macro defined in one page is not visible from another page.
*
* @version $Id$
* @since 2.4M2
*/
public class VelocityMacroIsolationTest extends AbstractComponentTestCase
{
private Macro velocityMacro;
@Override
protected void registerComponents() throws Exception
{
new ScriptMockSetup(getMockery(), getComponentManager());
this.velocityMacro = getComponentManager().lookup(Macro.class, "velocity");
}
@Test
public void testVelocityMacroIsolation() throws Exception
{
String expected = "beginDocument\n"
+ "beginParagraph\n"
+ "onSpecialSymbol [#]\n"
+ "onWord [testMacrosAreLocal]\n"
+ "onSpecialSymbol [(]\n"
+ "onSpecialSymbol [)]\n"
+ "endParagraph\n"
+ "endDocument";
VelocityMacroParameters params = new VelocityMacroParameters();
MacroTransformationContext context = new MacroTransformationContext();
context.setSyntax(Syntax.XWIKI_2_0);
// Execute the velocity macro in the context of a first page
context.setId("page1");
this.velocityMacro.execute(params, "#macro(testMacrosAreLocal)mymacro#end", context);
// And then in the context of a second independent page
context.setId("page2");
assertBlocks(expected, this.velocityMacro.execute(params, "#testMacrosAreLocal()", context),
getComponentManager().lookup(PrintRendererFactory.class, "event/1.0"));
}
}
| Fix NPE in test
| xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-velocity/src/test/java/org/xwiki/rendering/macro/velocity/VelocityMacroIsolationTest.java | Fix NPE in test | <ide><path>wiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-velocity/src/test/java/org/xwiki/rendering/macro/velocity/VelocityMacroIsolationTest.java
<ide> */
<ide> package org.xwiki.rendering.macro.velocity;
<ide>
<add>import java.util.Collections;
<add>
<ide> import org.junit.Test;
<add>import org.xwiki.rendering.block.MacroBlock;
<ide> import org.xwiki.rendering.macro.Macro;
<ide> import org.xwiki.rendering.macro.script.ScriptMockSetup;
<ide> import org.xwiki.rendering.renderer.PrintRendererFactory;
<ide> VelocityMacroParameters params = new VelocityMacroParameters();
<ide> MacroTransformationContext context = new MacroTransformationContext();
<ide> context.setSyntax(Syntax.XWIKI_2_0);
<add> context.setCurrentMacroBlock(new MacroBlock("velocity", Collections.<String, String>emptyMap(), false));
<ide>
<ide> // Execute the velocity macro in the context of a first page
<ide> context.setId("page1"); |
|
Java | apache-2.0 | 948d9060dbbaee0fe21a2580c51c488f70b270b5 | 0 | synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung | package org.synyx.urlaubsverwaltung.person;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import static java.lang.invoke.MethodHandles.lookup;
import static java.util.stream.Collectors.toList;
import static org.slf4j.LoggerFactory.getLogger;
import static org.synyx.urlaubsverwaltung.person.Role.INACTIVE;
/**
* Implementation for {@link PersonService}.
*/
@Service("personService")
class PersonServiceImpl implements PersonService {
private static final Logger LOG = getLogger(lookup().lookupClass());
private final PersonDAO personDAO;
@Autowired
PersonServiceImpl(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@Override
public Person create(String loginName, String lastName, String firstName, String email,
List<MailNotification> notifications, List<Role> permissions) {
final Person person = new Person(loginName, lastName, firstName, email);
person.setNotifications(notifications);
person.setPermissions(permissions);
LOG.info("Create person: {}", person);
return save(person);
}
@Override
public Person update(Integer id, String loginName, String lastName, String firstName, String email,
List<MailNotification> notifications, List<Role> permissions) {
Person person = getPersonByID(id).orElseThrow(() ->
new IllegalArgumentException("Can not find a person for ID = " + id));
person.setLoginName(loginName);
person.setLastName(lastName);
person.setFirstName(firstName);
person.setEmail(email);
person.setNotifications(notifications);
person.setPermissions(permissions);
LOG.info("Update person: {}", person);
return save(person);
}
@Override
public Person create(Person person) {
LOG.info("Create person: {}", person);
return save(person);
}
@Override
public Person update(Person person) {
if (person.getId() == null) {
throw new IllegalArgumentException("Can not update a person that is not persisted yet");
}
LOG.info("Updated person: {}", person);
return save(person);
}
@Override
public Person save(Person person) {
return personDAO.save(person);
}
@Override
public Optional<Person> getPersonByID(Integer id) {
return personDAO.findById(id);
}
@Override
public Optional<Person> getPersonByLogin(String loginName) {
return Optional.ofNullable(personDAO.findByLoginName(loginName));
}
@Override
public List<Person> getActivePersons() {
return personDAO.findAll()
.stream()
.filter(person -> !person.hasRole(INACTIVE))
.sorted(personComparator())
.collect(toList());
}
private Comparator<Person> personComparator() {
return Comparator.comparing(p -> p.getNiceName().toLowerCase());
}
@Override
public List<Person> getInactivePersons() {
return personDAO.findAll()
.stream()
.filter(person -> person.hasRole(INACTIVE))
.sorted(personComparator())
.collect(toList());
}
@Override
public List<Person> getActivePersonsByRole(final Role role) {
return getActivePersons().stream().filter(person -> person.hasRole(role)).collect(toList());
}
@Override
public List<Person> getPersonsWithNotificationType(final MailNotification notification) {
return getActivePersons().stream()
.filter(person -> person.hasNotificationType(notification))
.collect(toList());
}
@Override
public Person getSignedInUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("No authentication found in context.");
}
String user = authentication.getName();
Optional<Person> person = getPersonByLogin(user);
if (!person.isPresent()) {
throw new IllegalStateException("Can not get the person for the signed in user with username = " + user);
}
return person.get();
}
}
| src/main/java/org/synyx/urlaubsverwaltung/person/PersonServiceImpl.java | package org.synyx.urlaubsverwaltung.person;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.lang.invoke.MethodHandles.lookup;
import static java.util.stream.Collectors.toList;
import static org.slf4j.LoggerFactory.getLogger;
import static org.synyx.urlaubsverwaltung.person.Role.INACTIVE;
/**
* Implementation for {@link PersonService}.
*/
@Service("personService")
class PersonServiceImpl implements PersonService {
private static final Logger LOG = getLogger(lookup().lookupClass());
private final PersonDAO personDAO;
@Autowired
PersonServiceImpl(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@Override
public Person create(String loginName, String lastName, String firstName, String email,
List<MailNotification> notifications, List<Role> permissions) {
final Person person = new Person(loginName, lastName, firstName, email);
person.setNotifications(notifications);
person.setPermissions(permissions);
LOG.info("Create person: {}", person);
return save(person);
}
@Override
public Person update(Integer id, String loginName, String lastName, String firstName, String email,
List<MailNotification> notifications, List<Role> permissions) {
Person person = getPersonByID(id).orElseThrow(() ->
new IllegalArgumentException("Can not find a person for ID = " + id));
person.setLoginName(loginName);
person.setLastName(lastName);
person.setFirstName(firstName);
person.setEmail(email);
person.setNotifications(notifications);
person.setPermissions(permissions);
LOG.info("Update person: {}", person);
return save(person);
}
@Override
public Person create(Person person) {
LOG.info("Create person: {}", person);
return save(person);
}
@Override
public Person update(Person person) {
if (person.getId() == null) {
throw new IllegalArgumentException("Can not update a person that is not persisted yet");
}
LOG.info("Updated person: {}", person);
return save(person);
}
@Override
public Person save(Person person) {
return personDAO.save(person);
}
@Override
public Optional<Person> getPersonByID(Integer id) {
return personDAO.findById(id);
}
@Override
public Optional<Person> getPersonByLogin(String loginName) {
return Optional.ofNullable(personDAO.findByLoginName(loginName));
}
@Override
public List<Person> getActivePersons() {
return personDAO.findAll()
.stream()
.filter(person -> !person.hasRole(INACTIVE))
.sorted(personComparator())
.collect(toList());
}
private Comparator<Person> personComparator() {
return Comparator.comparing(p -> p.getNiceName().toLowerCase());
}
@Override
public List<Person> getInactivePersons() {
return personDAO.findAll()
.stream()
.filter(person -> person.hasRole(INACTIVE))
.sorted(personComparator())
.collect(toList());
}
@Override
public List<Person> getActivePersonsByRole(final Role role) {
return getActivePersons().stream().filter(person -> person.hasRole(role)).collect(toList());
}
@Override
public List<Person> getPersonsWithNotificationType(final MailNotification notification) {
return getActivePersons().stream()
.filter(person -> person.hasNotificationType(notification))
.collect(toList());
}
@Override
public Person getSignedInUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("No authentication found in context.");
}
String user = authentication.getName();
Optional<Person> person = getPersonByLogin(user);
if (!person.isPresent()) {
throw new IllegalStateException("Can not get the person for the signed in user with username = " + user);
}
return person.get();
}
}
| Remove not needed import
| src/main/java/org/synyx/urlaubsverwaltung/person/PersonServiceImpl.java | Remove not needed import | <ide><path>rc/main/java/org/synyx/urlaubsverwaltung/person/PersonServiceImpl.java
<ide> import java.util.Comparator;
<ide> import java.util.List;
<ide> import java.util.Optional;
<del>import java.util.stream.Collectors;
<ide>
<ide> import static java.lang.invoke.MethodHandles.lookup;
<ide> import static java.util.stream.Collectors.toList; |
|
Java | lgpl-2.1 | 45bc1d3de1ebb9cd24fa2398abc250330994334b | 0 | SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer | package ch.unizh.ini.jaer.projects.rbodo.opticalflow;
import ch.unizh.ini.jaer.projects.davis.calibration.SingleCameraCalibration;
import ch.unizh.ini.jaer.projects.minliu.PatchMatchFlow;
import com.jmatio.io.MatFileReader;
import com.jmatio.io.MatFileWriter;
import com.jmatio.types.MLDouble;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.gl2.GLUT;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.event.orientation.ApsDvsMotionOrientationEvent;
import net.sf.jaer.event.orientation.DvsMotionOrientationEvent;
import net.sf.jaer.event.orientation.MotionOrientationEventInterface;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventio.ros.RosbagFileInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import net.sf.jaer.util.WarningDialogWithDontShowPreference;
import net.sf.jaer.util.filter.LowpassFilter3D;
import net.sf.jaer.util.filter.LowpassFilter3D.Point3D;
import org.jetbrains.bio.npy.NpyArray;
import org.jetbrains.bio.npy.NpyFile;
/**
* Abstract base class for motion flow filters. The filters that extend this
* class use different methods to compute the optical flow vectors and override
* the filterPacket method in this class. Several methods were taken from
* AbstractDirectionSelectiveFilter and Steadicam and slightly modified.
*
* @author rbodo
*/
@Description("Abstract base class for motion optical flow.")
@DevelopmentStatus(DevelopmentStatus.Status.Abstract)
abstract public class AbstractMotionFlowIMU extends EventFilter2DMouseAdaptor implements FrameAnnotater, PropertyChangeListener {
// Observed motion flow.
public static float vx, vy, v;
public int numInputTypes;
/**
* Basic event information. Type is event polarity value, 0=OFF and 1=ON,
* typically but not always
*/
public int x, y, ts, type, lastTs;
/**
* (Subsampled) chip sizes.
*/
protected int sizex, sizey, subSizeX, subSizeY;
/**
* Subsampling
*/
private int subSampleShift = getInt("subSampleShift", 0);
protected boolean[][] subsampledPixelIsSet;
// Map of input orientation event times
// [x][y][type] where type is mixture of orienation and polarity.
protected int[][][] lastTimesMap;
// xyFilter.
private int xMin = getInt("xMin", 0);
private static final int DEFAULT_XYMAX = 1000;
private int xMax = getInt("xMax", DEFAULT_XYMAX); // (tobi) set to large value to make sure any chip will have full area processed by default
private int yMin = getInt("yMin", 0);
private int yMax = getInt("yMax", DEFAULT_XYMAX);
// Display
private boolean displayVectorsEnabled = getBoolean("displayVectorsEnabled", true);
private boolean displayVectorsAsUnitVectors = getBoolean("displayVectorsAsUnitVectors", false);
private boolean displayVectorsAsColorDots = getBoolean("displayVectorsAsColorDots", false);
private boolean displayZeroLengthVectorsEnabled = getBoolean("displayZeroLengthVectorsEnabled", true);
private boolean displayRawInput = getBoolean("displayRawInput", true);
private boolean displayColorWheelLegend = getBoolean("displayColorWheelLegend", true);
private boolean randomScatterOnFlowVectorOrigins = getBoolean("randomScatterOnFlowVectorOrigins", true);
private static final float RANDOM_SCATTER_PIXELS = 1;
private Random random = new Random();
protected float motionVectorTransparencyAlpha = getFloat("motionVectorTransparencyAlpha", .7f);
private float ppsScale = getFloat("ppsScale", 0.1f);
private boolean ppsScaleDisplayRelativeOFLength = getBoolean("ppsScaleDisplayRelativeOFLength", false);
// A pixel can fire an event only after this period. Used for smoother flow
// and speedup.
private int refractoryPeriodUs = getInt("refractoryPeriodUs", 0);
// Global translation, rotation and expansion.
private boolean displayGlobalMotion = getBoolean("displayGlobalMotion", true);
protected int statisticsWindowSize = getInt("statisticsWindowSize", 10000);
protected EngineeringFormat engFmt = new EngineeringFormat();
/**
* The output events, also used for rendering output events.
*/
protected EventPacket dirPacket;
/**
* The output packet iterator
*/
protected OutputEventIterator outItr;
/**
* The current input event
*/
protected PolarityEvent e;
/**
* The current output event
*/
protected ApsDvsMotionOrientationEvent eout;
/**
* Use IMU gyro values to estimate motion flow.
*/
public ImuFlowEstimator imuFlowEstimator;
// Focal length of camera lens in mm needed to convert rad/s to pixel/s.
// Conversion factor is atan(pixelWidth/focalLength).
private float lensFocalLengthMm = 4.5f;
// Focal length of camera lens needed to convert rad/s to pixel/s.
// Conversion factor is atan(pixelWidth/focalLength).
private float radPerPixel;
private boolean addedViewerPropertyChangeListener = false; // TODO promote these to base EventFilter class
private boolean addTimeStampsResetPropertyChangeListener = false;
// Performing statistics and logging results. lastLoggingFolder starts off
// at user.dir which is startup folder "host/java" where .exe launcher lives
private String loggingFolder = getPrefs().get("DataLogger.loggingFolder", System.getProperty("user.dir"));
public boolean measureAccuracy = getBoolean("measureAccuracy", true);
boolean measureProcessingTime = getBoolean("measureProcessingTime", false);
public int countIn, countOut, countOutliers;
protected MotionFlowStatistics motionFlowStatistics;
double[][] vxGTframe, vyGTframe, tsGTframe;
public float vxGT, vyGT, vGT;
private boolean importedGTfromMatlab;
private boolean importedGTfromNPZ = false;
private String npzFilePath = getString("npzFilePath", "");
// Discard events that are considerably faster than average
private float avgSpeed = 0;
boolean speedControlEnabled = getBoolean("speedControlEnabled", true);
private float speedMixingFactor = getFloat("speedMixingFactor", 1e-3f);
private float excessSpeedRejectFactor = getFloat("excessSpeedRejectFactor", 2f);
// Motion flow vectors can be filtered out if the angle between the observed
// optical flow and ground truth is greater than a certain threshold.
// At the moment, this option is not included in the jAER filter settings
// and defaults to false.
protected boolean discardOutliersForStatisticalMeasurementEnabled = false;
// Threshold angle in degree. Discard measured optical flow vector if it
// deviates from ground truth by more than discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg.
protected float discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg = 10f;
// outlier filtering that only allows through motion events that agree with at least N most-recent neigbor events
// in max angle difference
// private boolean outlierMotionFilteringEnabled = getBoolean("outlierMotionFilteringEnabled", false);
protected float outlierMotionFilteringMaxAngleDifferenceDeg = getFloat("outlierMotionFilteringMaxAngleDifferenceDeg", 30f);
protected int outlierMotionFilteringSubsampleShift = getInt("outlierMotionFilteringSubsampleShift", 1);
protected int outlierMotionFilteringMinSameAngleInNeighborhood = getInt("outlierMotionFilteringMinSameAngleInNeighborhood", 2);
protected int[][] outlierMotionFilteringLastAngles = null;
private float motionVectorLineWidthPixels = getFloat("motionVectorLineWidthPixels", 4);
// MotionField that aggregates motion
protected MotionField motionField = new MotionField();
/**
* Relative scale of displayed global flow vector
*/
protected static final float GLOBAL_MOTION_DRAWING_SCALE = 1;
/**
* Used for logging motion vector events to a text log file
*/
protected TobiLogger motionVectorEventLogger = null;
final String filterClassName;
private boolean exportedFlowToMatlab;
private double[][] vxOut = null;
private double[][] vyOut = null;
public Iterator inItr;
protected static String dispTT = "Display";
protected static String measureTT = "Measure";
protected static String imuTT = "IMU";
protected static String smoothingTT = "Smoothing";
protected static String motionFieldTT = "Motion field";
protected SingleCameraCalibration cameraCalibration = null;
int uidx;
protected boolean useColorForMotionVectors = getBoolean("useColorForMotionVectors", true);
// NPZ ground truth data files from MVSEC
float MVSEC_FPS = 45; // of the MVSEC frames
private double[] tsDataS; // timestamp of frames in MVSEC GT in seconds (to avoid roundoff problems in us
private float[] xOFData;
private float[] yOFData;
private int[] gtOFArrayShape;
// for computing offset to find corresponding GT data for DVS events
private double aeInputStartTimeS = Double.NaN;
private double gtInputStartTimeS = Double.NaN;
private double offsetTimeThatGTStartsAfterRosbagS = Double.NaN;
// for drawing GT flow at a point
private volatile MotionOrientationEventInterface mouseVectorEvent = new ApsDvsMotionOrientationEvent();
private volatile String mouseVectorString = null;
public AbstractMotionFlowIMU(AEChip chip) {
super(chip);
imuFlowEstimator = new ImuFlowEstimator();
dirPacket = new EventPacket(ApsDvsMotionOrientationEvent.class);
filterClassName = getClass().getSimpleName();
FilterChain chain = new FilterChain(chip);
try {
cameraCalibration = new SingleCameraCalibration(chip);
cameraCalibration.setRealtimePatternDetectionEnabled(false);
cameraCalibration.setFilterEnabled(false);
getSupport().addPropertyChangeListener(SingleCameraCalibration.EVENT_NEW_CALIBRATION, this);
chain.add(cameraCalibration);
} catch (Exception e) {
log.warning("could not add calibration for DVS128");
}
setEnclosedFilterChain(chain);
// Labels for setPropertyTooltip.
setPropertyTooltip("LogMotionVectorEvents", "toggles saving motion vector events to a human readable file; auto stops on rewind");
setPropertyTooltip("LogAccuracyStatistics", "toggles logging accuracy statisticcs; automatically stops on rewind");
setPropertyTooltip("logGlobalMotionFlows", "toggle saving global motion flow vectors to a human readable file; auto stops on rewind");
setPropertyTooltip("printStatistics", "<html> Prints to console as log output a single instance of statistics collected since <b>measureAccuracy</b> was selected. (These statistics are reset when the filter is reset, e.g. at rewind.)");
setPropertyTooltip("reseetStatistics", "Reset (clear) statistics collected");
setPropertyTooltip(measureTT, "measureAccuracy", "<html> Writes a txt file with various motion statistics, by comparing the ground truth <br>(either estimated online using an embedded IMUFlow or loaded from file) <br> with the measured optical flow events. <br>This measurment function is called for every event to assign the local ground truth<br> (vxGT,vyGT) at location (x,y) a value from the imported ground truth field (vxGTframe,vyGTframe).");
setPropertyTooltip(measureTT, "measureProcessingTime", "writes a text file with timestamp filename with the packet's mean processing time of an event. Processing time is also logged to console.");
setPropertyTooltip(measureTT, "loggingFolder", "directory to store logged data files");
setPropertyTooltip(measureTT, "statisticsWindowSize", "Window in samples for measuring statistics of global flow, optical flow errors, and processing times");
setPropertyTooltip(dispTT, "ppsScale", "<html>When <i>ppsScaleDisplayRelativeOFLength=false</i>, then this is <br>scale of screen pixels per px/s flow to draw local motion vectors; <br>global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE + "<p>"
+ "When <i>ppsScaleDisplayRelativeOFLength=true</i>, then local motion vectors are scaled by average speed of flow");
setPropertyTooltip(dispTT, "ppsScaleDisplayRelativeOFLength", "<html>Display flow vector lengths relative to global average speed");
setPropertyTooltip(dispTT, "displayVectorsEnabled", "shows local motion vector evemts as arrows");
setPropertyTooltip(dispTT, "displayVectorsAsColorDots", "shows local motion vector events as color dots, rather than arrows");
setPropertyTooltip(dispTT, "displayVectorsAsUnitVectors", "shows local motion vector events with unit vector length");
setPropertyTooltip(dispTT, "displayZeroLengthVectorsEnabled", "shows local motion vector evemts even if they indicate zero motion (stationary features)");
setPropertyTooltip(dispTT, "displayColorWheelLegend", "Plots a color wheel to show flow direction colors.");
setPropertyTooltip(dispTT, "displayGlobalMotion", "shows global tranlational, rotational, and expansive motion. These vectors are scaled by ppsScale * " + GLOBAL_MOTION_DRAWING_SCALE + " pixels/second per chip pixel");
setPropertyTooltip(dispTT, "displayRawInput", "shows the input events, instead of the motion types");
setPropertyTooltip(dispTT, "randomScatterOnFlowVectorOrigins", "scatters flow vectors a bit to show density better");
setPropertyTooltip(dispTT, "xMin", "events with x-coordinate below this are filtered out.");
setPropertyTooltip(dispTT, "xMax", "events with x-coordinate above this are filtered out.");
setPropertyTooltip(dispTT, "yMin", "events with y-coordinate below this are filtered out.");
setPropertyTooltip(dispTT, "yMax", "events with y-coordinate above this are filtered out.");
setPropertyTooltip(dispTT, "motionVectorLineWidthPixels", "line width to draw motion vectors");
setPropertyTooltip(dispTT, "motionVectorTransparencyAlpha", "transparency alpha setting for motion vector rendering");
setPropertyTooltip(dispTT, "useColorForMotionVectors", "display the output motion vectors in color");
setPropertyTooltip(smoothingTT, "subSampleShift", "shift subsampled timestamp map stores by this many bits");
setPropertyTooltip(smoothingTT, "refractoryPeriodUs", "compute no flow vector if a flow vector has already been computed within this period at the same location.");
setPropertyTooltip(smoothingTT, "speedControlEnabled", "enables filtering of excess speeds");
setPropertyTooltip(smoothingTT, "speedControl_ExcessSpeedRejectFactor", "local speeds this factor higher than average are rejected as non-physical");
setPropertyTooltip(smoothingTT, "speedControl_speedMixingFactor", "speeds computed are mixed with old values with this factor");
// setPropertyTooltip(imuTT, "discardOutliersForStatisticalMeasurementEnabled", "discard measured local motion vector if it deviates from IMU estimate");
// setPropertyTooltip(imuTT, "discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg", "threshold angle in degree. Discard measured optical flow vector if it deviates from IMU-estimate by more than discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg");
setPropertyTooltip(imuTT, "lensFocalLengthMm", "lens focal length in mm. Used for computing the IMU flow from pan and tilt camera rotations. 4.5mm is focal length for dataset data.");
setPropertyTooltip(imuTT, "calibrationSamples", "number of IMU samples to average over for measuring IMU offset.");
setPropertyTooltip(imuTT, "startIMUCalibration", "<html> Starts estimating the IMU offsets based on next calibrationSamples samples. Should be used only with stationary recording to store these offsets in the preferences. <p> <b>measureAccuracy</b> must be selected as well to actually do the calibration.");
setPropertyTooltip(imuTT, "eraseIMUCalibration", "Erases the IMU offsets to zero. Can be used to observe effect of these offsets on a stationary recording in the IMUFlow filter.");
setPropertyTooltip(imuTT, "importGTfromMatlab", "Allows importing two 2D-arrays containing the x-/y- components of the motion flow field used as ground truth.");
setPropertyTooltip(imuTT, "importGTfromNPZ", "Allows importing ground truth from numpy uncompressed zip archive of multiple variables file (NPZ); only used for MVSEC dataset.");
setPropertyTooltip(imuTT, "clearGroundTruth", "Clears the ground truth optical flow that was imported from matlab or NPZ files. Used in the measureAccuracy option.");
setPropertyTooltip(imuTT, "selectLoggingFolder", "Allows selection of the folder to store the measured accuracies and optical flow events.");
// setPropertyTooltip(motionFieldTT, "motionFieldMixingFactor", "Flow events are mixed with the motion field with this factor. Use 1 to replace field content with each event, or e.g. 0.01 to update only by 1%.");
setPropertyTooltip(motionFieldTT, "displayMotionField", "computes and shows the average motion field (see MotionField section)");
setPropertyTooltip(motionFieldTT, "motionFieldSubsamplingShift", "The motion field is computed at this subsampled resolution, e.g. 1 means 1 motion field vector for each 2x2 pixel area.");
setPropertyTooltip(motionFieldTT, "maxAgeUs", "Maximum age of motion field value for display and for unconditionally replacing with latest flow event");
setPropertyTooltip(motionFieldTT, "minSpeedPpsToDrawMotionField", "Motion field locations where speed in pixels/second is less than this quantity are not drawn");
setPropertyTooltip(motionFieldTT, "consistentWithNeighbors", "Motion field value must be consistent with several neighbors if this option is selected.");
setPropertyTooltip(motionFieldTT, "consistentWithCurrentAngle", "Motion field value is only updated if flow event angle is in same half plane as current estimate, i.e. has non-negative dot product.");
setPropertyTooltip(motionFieldTT, "motionFieldTimeConstantMs", "Motion field low pass filter time constant in ms.");
setPropertyTooltip(motionFieldTT, "displayMotionFieldColorBlobs", "Shows color blobs for motion field as well as the flow vector arrows");
setPropertyTooltip(motionFieldTT, "displayMotionFieldUsingColor", "Shows motion field flow vectors in color; otherwise shown as monochrome color arrows");
setPropertyTooltip(motionFieldTT, "motionFieldDiffusionEnabled", "Enables an event-driven diffusive averaging of motion field values");
setPropertyTooltip(motionFieldTT, "decayTowardsZeroPeridiclly", "Decays motion field values periodically (with update interval of the time constant) towards zero velocity, i.e. enforce zero flow prior");
File lf = new File(loggingFolder);
if (!lf.exists() || !lf.isDirectory()) {
log.log(Level.WARNING, "loggingFolder {0} doesn't exist or isn't a directory, defaulting to {1}", new Object[]{lf, lf});
setLoggingFolder(System.getProperty("user.dir"));
}
}
synchronized public void doSelectLoggingFolder() {
if (loggingFolder == null || loggingFolder.isEmpty()) {
loggingFolder = System.getProperty("user.dir");
}
JFileChooser chooser = new JFileChooser(loggingFolder);
chooser.setDialogTitle("Choose data logging folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setMultiSelectionEnabled(false);
if (chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame()) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (f != null && f.isDirectory()) {
setLoggingFolder(f.toString());
log.log(Level.INFO, "Selected data logging folder {0}", loggingFolder);
} else {
log.log(Level.WARNING, "Tried to select invalid logging folder named {0}", f);
}
}
}
// Allows importing two 2D-arrays containing the x-/y- components of the
// motion flow field used as ground truth.
synchronized public void doImportGTfromMatlab() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose ground truth file");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(false);
if (chooser.showOpenDialog(chip.getAeViewer().getFilterFrame()) == JFileChooser.APPROVE_OPTION) {
try {
vxGTframe = ((MLDouble) (new MatFileReader(chooser.getSelectedFile().getPath())).getMLArray("vxGT")).getArray();
vyGTframe = ((MLDouble) (new MatFileReader(chooser.getSelectedFile().getPath())).getMLArray("vyGT")).getArray();
tsGTframe = ((MLDouble) (new MatFileReader(chooser.getSelectedFile().getPath())).getMLArray("ts")).getArray();
importedGTfromMatlab = true;
log.info("Imported ground truth file");
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
}
}
}
/**
* Read numpy timestamps of ground truth flow information as provided by
* MVSEC
*
* @param filePath The file full path
* @param scale set scale to scale all value (for flow vector scaling from
* pix to px/s)
* @param progressMonitor a progress monitor to show progress
* @return the final double[] times array
*/
private double[] readNpyTsArray(String filePath, ProgressMonitor progressMonitor) {
if (filePath == null) {
return null;
}
Path p = new File(filePath).toPath();
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
progressMonitor.setMaximum(3);
progressMonitor.setProgress(0);
long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String msg = String.format("<html>Loading Numpy NdArray <br>%s; <p>Free RAM %.1f GB", p.toString(), 1e-9 * presumableFreeMemory);
log.info(msg);
progressMonitor.setNote(msg);
progressMonitor.setProgress(1);
NpyArray a = NpyFile.read(p, 1 << 18);
String err = null;
int[] sh = a.getShape();
if (sh.length != 1) {
err = String.format("Shape of input NpyArray is wrong, got %d dimensions and not 1", sh.length);
}
if (err != null) {
showWarningDialogInSwingThread(err, "Bad timestamp file?");
}
progressMonitor.setProgress(2);
double[] d = a.asDoubleArray();
return d;
}
/**
* Read numpy file with ground truth flow information as provided by MVSEC
*
* @param filePath The file full path
* @param scale set scale to scale all value (for flow vector scaling from
* pix to px/s)
* @param progressMonitor a progress monitor to show progress
* @return the final float[] array which is flattened for the flow u and v
* matrices
*/
private float[] readNpyOFArray(String filePath, float scale, ProgressMonitor progressMonitor) {
if (filePath == null) {
return null;
}
Path p = new File(filePath).toPath();
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
progressMonitor.setMaximum(3);
progressMonitor.setProgress(0);
long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String msg = String.format("<html>Loading Numpy NdArray <br>%s; <p>Free RAM %.1f GB", p.toString(), 1e-9 * presumableFreeMemory);
log.info(msg);
progressMonitor.setNote(msg);
progressMonitor.setProgress(1);
NpyArray a = NpyFile.read(p, 1 << 20); // make it large enough to hold really big array of frames of flow component data
String err = null;
int[] sh = a.getShape();
if (sh.length != 3) {
err = String.format("Shape of input NpyArray is wrong, got %d dimensions and not 3", sh.length);
} else if (sh[1] != chip.getSizeY() || sh[2] != chip.getSizeX()) {
err = String.format("<html>Dimension of NpyArray flow matrix is wrong, got [H=%d,W=%d] pixels, but this chip has [H=%d,W=%d] pixels.<p>Did you choose the correct AEChip and GT file to match?<p>Will assume this array is centered on the AEChip.", sh[1], sh[2], chip.getSizeY(), chip.getSizeX());
}
if (err != null) {
showWarningDialogInSwingThread(err, "Wrong AEChip or wrong GT file?");
}
gtOFArrayShape = a.getShape(); // hack, save the shape of whatever the last flow data to look up values in float[] later.
progressMonitor.setProgress(2);
double[] d = a.asDoubleArray();
allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String msg2 = String.format("<html>Converting %s to float[]<p>Free RAM %.1f GB", p, 1e-9 * presumableFreeMemory);
progressMonitor.setNote(msg2);
float[] f = new float[d.length];
progressMonitor.setMaximum(d.length);
final int checkInterval = 10000;
for (int i = 0; i < d.length; i++) {
f[i] = (float) (scale * (d[i]));
if (i % checkInterval == 0) {
if (progressMonitor.isCanceled()) {
return null;
}
progressMonitor.setProgress(i);
}
}
return f;
}
// Allows importing two 2D-arrays containing the x-/y- components of the
// motion flow field used as ground truth from numpy file .npz.
// Primarily used for MVSEC dataset.
synchronized public void doImportGTfromNPZ() {
// check to ensure a rosbag file is playing already, so that we have starting time of the file
JFileChooser chooser = new JFileChooser(npzFilePath);
chooser.setDialogTitle("Choose ground truth MVSEC extracted folder that has the timestamps, vx and vy .npy files");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// FileFilter filter = new FileNameExtensionFilter("NPZ folder", "npz", "NPZ");
// chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
Component comp = chip.getAeViewer().getFilterFrame();
if (chooser.showOpenDialog(comp) == JFileChooser.APPROVE_OPTION) {
String fileName = chooser.getSelectedFile().getPath();
File dir = new File(fileName);
npzFilePath = dir.toString();
putString("npzFilePath", npzFilePath);
final ProgressMonitor progressMonitor = new ProgressMonitor(comp, "Opening " + npzFilePath, "Reading npy files", 0, 100);
progressMonitor.setMillisToPopup(0);
progressMonitor.setMillisToDecideToPopup(0);
final SwingWorker<Void, Void> worker = new SwingWorker() {
private String checkPaths(String f1, String f2) {
String s = null;
s = npzFilePath + File.separator + f1;
if (Files.isReadable(new File(s).toPath())) {
return s;
}
s = npzFilePath + File.separator + f2;
if (Files.isReadable(new File(s).toPath())) {
return s;
}
return null;
}
@Override
protected Object doInBackground() throws Exception {
try {
chip.getAeViewer().getAePlayer().setPaused(true); // to speed up disk access
System.gc();
if (comp != null) {
comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
tsDataS = readNpyTsArray(checkPaths("timestamps.npy", "ts.npy"), progressMonitor); // don't check size for timestamp array
if (tsDataS == null) {
throw new IOException("could not read timestamps for flow data from " + npzFilePath);
}
gtInputStartTimeS = tsDataS[0];
offsetTimeThatGTStartsAfterRosbagS = ((gtInputStartTimeS - aeInputStartTimeS)); // pos if GT later than DVS
MVSEC_FPS = (float) (1 / (tsDataS[1] - tsDataS[0]));
for (int i = 0; i < tsDataS.length; i++) { // subtract first time from all others
tsDataS[i] -= gtInputStartTimeS;
}
xOFData = readNpyOFArray(checkPaths("x_flow_dist.npy", "x_flow_tensor.npy"), MVSEC_FPS, progressMonitor); // check size for vx, vy arrays
if (xOFData == null) {
throw new IOException("could not read vx flow data from " + npzFilePath);
}
yOFData = readNpyOFArray(checkPaths("y_flow_dist.npy", "y_flow_tensor.npy"), MVSEC_FPS, progressMonitor);
if (yOFData == null) {
throw new IOException("could not read vy flow data from " + npzFilePath);
}
progressMonitor.setMinimum(0);
progressMonitor.setMaximum(2);
progressMonitor.setProgress(0);
progressMonitor.setNote("Running garbage collection and finalization");
System.gc();
progressMonitor.setProgress(1);
System.runFinalization();
progressMonitor.setProgress(2);
progressMonitor.close();
String s = String.format("<html>Imported %,d frames spanning t=[%,g]s<br>from %s. <p>Frame rate is %.1fHz. <p>GT flow starts %.3fs later than rosbag",
tsDataS.length,
(tsDataS[tsDataS.length - 1] - tsDataS[0]), npzFilePath,
MVSEC_FPS,
offsetTimeThatGTStartsAfterRosbagS);
log.info(s);
log.info(String.format("NPZ starts at epoch timestamp %,.3fs", tsDataS[0]));
showPlainMessageDialogInSwingThread(s, "NPZ import succeeded");
importedGTfromNPZ = true;
return true;
} catch (Exception e) {
log.warning("Could not parse, caught " + e.toString());
showWarningDialogInSwingThread("Could not parse, caught " + e.toString(), "NPZ load error");
return e;
} catch (OutOfMemoryError e) {
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String s = "<html>Ran out of memory: " + e.toString() + "; increase VM with e.g. -Xmx10000m for 10GB VM in JVM startup"
+ "<p> Presumable free memory now is " + String.format("%,fGB", (float) presumableFreeMemory * 1e-9f);
log.warning(s);
showWarningDialogInSwingThread(s, "Out of memory");
return e;
} finally {
chip.getAeViewer().getAePlayer().setPaused(false); // to speed up disk access
comp.setCursor(Cursor.getDefaultCursor());
}
}
@Override
protected void done() {
progressMonitor.close();
}
};
worker.execute();
}
}
// Allows exporting flow vectors that were accumulated between tmin and tmax
// to a mat-file which can be processed in MATLAB.
public void exportFlowToMatlab(final int tmin, final int tmax) {
if (!exportedFlowToMatlab) {
int firstTs = dirPacket.getFirstTimestamp();
if (firstTs > tmin && firstTs < tmax) {
if (vxOut == null) {
vxOut = new double[sizey][sizex];
vyOut = new double[sizey][sizex];
}
for (Object o : dirPacket) {
ApsDvsMotionOrientationEvent ev = (ApsDvsMotionOrientationEvent) o;
if (ev.hasDirection) {
vxOut[ev.y][ev.x] = ev.velocity.x;
vyOut[ev.y][ev.x] = ev.velocity.y;
}
}
}
if (firstTs > tmax && vxOut != null) {
ArrayList list = new ArrayList();
list.add(new MLDouble("vx", vxOut));
list.add(new MLDouble("vy", vyOut));
try {
MatFileWriter matFileWriter = new MatFileWriter(loggingFolder + "/flowExport.mat", list);
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
}
log.log(Level.INFO, "Exported motion flow to {0}/flowExport.mat", loggingFolder);
exportedFlowToMatlab = true;
vxOut = null;
vyOut = null;
}
}
}
void clearGroundTruth() {
importedGTfromMatlab = false;
vxGTframe = null;
vyGTframe = null;
tsGTframe = null;
vxGT = 0;
vyGT = 0;
vGT = 0;
tsDataS = null;
xOFData = null;
yOFData = null;
importedGTfromNPZ = false;
}
synchronized public void doClearGroundTruth() {
clearGroundTruth();
}
/**
* @return the useColorForMotionVectors
*/
public boolean isUseColorForMotionVectors() {
return useColorForMotionVectors;
}
/**
* @param useColorForMotionVectors the useColorForMotionVectors to set
*/
public void setUseColorForMotionVectors(boolean useColorForMotionVectors) {
this.useColorForMotionVectors = useColorForMotionVectors;
putBoolean("useColorForMotionVectors", useColorForMotionVectors);
}
// <editor-fold defaultstate="collapsed" desc="ImuFlowEstimator Class">
public class ImuFlowEstimator {
// Motion flow from IMU gyro values or GT file
private float vx;
private float vy;
private float v;
// Highpass filters for angular rates.
private float panRateDps, tiltRateDps, rollRateDps; // In deg/s
// Calibration
private boolean calibrating = false; // used to flag cameraCalibration state
private int calibrationSamples = getInt("calibrationSamples", 100); // number of samples, typically they come at 1kHz
private final Measurand panCalibrator, tiltCalibrator, rollCalibrator;
private float panOffset;
private float tiltOffset;
private float rollOffset;
private boolean calibrated = false;
// Deal with leftover IMU data after timestamps reset
private static final int FLUSH_COUNT = 1;
private int flushCounter;
protected ImuFlowEstimator() {
panCalibrator = new Measurand();
tiltCalibrator = new Measurand();
rollCalibrator = new Measurand();
// Some initial IMU cameraCalibration values.
// Will be overwritten when calibrating IMU
panOffset = getFloat("panOffset", 0);
tiltOffset = getFloat("tiltOffset", 0);
rollOffset = getFloat("rollOffset", 0); // tobi set back to zero rather than using hard coded values.
if (panOffset != 0 || rollOffset != 0 || tiltOffset != 0) {
log.warning("using existing calibration (offset) IMU rate gyro values stored in preferences: " + this.toString());
calibrated = true;
}
reset();
}
protected final synchronized void reset() {
flushCounter = FLUSH_COUNT;
panRateDps = 0;
tiltRateDps = 0;
rollRateDps = 0;
radPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * lensFocalLengthMm));
vx = 0;
vy = 0;
v = 0;
}
float getVx() {
return vx;
}
float getVy() {
return vy;
}
float getV() {
return v;
}
boolean isCalibrationSet() {
return calibrated;
}
private int imuFlowGTWarnings = 0;
final private int GT_Flow_WarningsPrintedInterval = 100000;
/**
* Calculate GT motion flow from IMU sample.
*
* @param o event
* @return true if flow is computed, either from IMU sample or GT flow
* loaded from file. If event is an IMU event, so enclosing loop can
* continue to next event, skipping flow processing of this IMU event.
*
* Return false if event is real event or no flow available. Return true
* if IMU event or calibration loaded that lables every time with GT
* flow for x,y address.
*/
public boolean calculateImuFlow(Object o) {
if (importedGTfromMatlab) {
if (ts >= tsGTframe[0][0] && ts < tsGTframe[0][1]) {
vx = (float) vxGTframe[y][x];
vy = (float) vyGTframe[y][x];
v = (float) Math.sqrt(vx * vx + vy * vy);
} else {
vx = 0;
vy = 0;
}
return false;
} else if (importedGTfromNPZ) {
if (!(o instanceof ApsDvsEvent)) {
return true; // continue processing this event outside
}
ApsDvsEvent e = (ApsDvsEvent) o;
if (getChip().getAeViewer().getAePlayer().getAEInputStream() == null) {
return false;
}
double tsRelativeToStartS = 1e-6 * ((e.timestamp - getChip().getAeViewer().getAePlayer().getAEInputStream().getFirstTimestamp()));
if (Double.isNaN(offsetTimeThatGTStartsAfterRosbagS)) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("Offset between starting times of GT flow and rosbag input not available"));
}
return false;
}
if (tsRelativeToStartS - offsetTimeThatGTStartsAfterRosbagS < 0 || tsRelativeToStartS - offsetTimeThatGTStartsAfterRosbagS >= (tsDataS[tsDataS.length - 1] - tsDataS[0])) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("Cannot find NPZ file flow for time relative to rosbag start of %.3fs in tsData from NPZ GT; data starts at offset %.3fs",
tsRelativeToStartS, offsetTimeThatGTStartsAfterRosbagS));
}
return false;
}
// int frameIdx = (int) (ts / (MVSEC_FPS * 1000)); // MVSEC's OF is updated at 45 MVSEC_FPS
int frameIdx = Math.abs(Arrays.binarySearch(tsDataS, tsRelativeToStartS - offsetTimeThatGTStartsAfterRosbagS)) - 2;
// minus 2 is because for timestamps less than the 2nd time (the first time is zero),
// the insertion point would be 1, so binarySearch returns -1-1=-2 but we want 0 for the frameIdx
/* binarySearch Returns:
index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).
The insertion point is defined as the point at which the key would be inserted into the array:
the index of the first element greater than the key, or a.length if all elements in the array are
less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
*/
if (frameIdx < 0 || frameIdx >= tsDataS.length) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("Cannot find GT flow for relative to start ts=%,.6fs in tsData from NPZ GT, resulting frameIdx=%,d is outside tsData times array bounds [%,.0f,%,.0f] s", tsRelativeToStartS, frameIdx, tsDataS[0], tsDataS[tsDataS.length - 1]));
}
vx = 0;
vy = 0;
v = 0;
return false;
}
final int cpix = chip.getNumPixels();
final int cx = chip.getSizeX(), cy = chip.getSizeY();
final int sx = gtOFArrayShape[2], sy = gtOFArrayShape[1], npix = sx * sy; // the loaded GT or EV-Flownet shape is used to look up values
// now find the GT flow. Assume the GT array is centered on the chip
// subtract from the event address half of the difference in width and height
final int ex = e.x - ((cx - sx) / 2), ey = e.y - ((cy - sy) / 2);
if (ex < 0 || ex >= sx || ey < 0 || ey >= sy) {
vx = 0;
vy = 0;
v = 0;
return false;
}
final int idx = (frameIdx * npix) + ((sy - 1 - ey) * sx) + ex;
if (idx < 0 || idx > xOFData.length) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("idx=%,d is outside bounds of the flow arrays", idx));
}
return false;
}
vx = (float) xOFData[idx];
vy = (float) yOFData[idx];
vy = -vy; // flip for jAER coordinate frame starting at LL corner
v = (float) Math.sqrt(vx * vx + vy * vy);
return false;
}
if (!(o instanceof ApsDvsEvent)) {
return true; // continue processing this event outside
}
ApsDvsEvent e = (ApsDvsEvent) o;
if (e.isImuSample()) {
IMUSample imuSample = e.getImuSample();
float panRateDpsSample = imuSample.getGyroYawY(); // update pan tilt roll state from IMU
float tiltRateDpsSample = imuSample.getGyroTiltX();
float rollRateDpsSample = imuSample.getGyroRollZ();
if (calibrating) {
if (panCalibrator.getN() > getCalibrationSamples()) {
calibrating = false;
panOffset = (float) panCalibrator.getMean();
tiltOffset = (float) tiltCalibrator.getMean();
rollOffset = (float) rollCalibrator.getMean();
log.info(String.format("calibration finished. %,d samples averaged"
+ " to (pan,tilt,roll)=(%.3f,%.3f,%.3f)", getCalibrationSamples(), panOffset, tiltOffset, rollOffset));
calibrated = true;
putFloat("panOffset", panOffset);
putFloat("tiltOffset", tiltOffset);
putFloat("rollOffset", rollOffset);
} else {
panCalibrator.addValue(panRateDpsSample);
tiltCalibrator.addValue(tiltRateDpsSample);
rollCalibrator.addValue(rollRateDpsSample);
}
return false;
}
panRateDps = panRateDpsSample - panOffset;
tiltRateDps = tiltRateDpsSample - tiltOffset;
rollRateDps = rollRateDpsSample - rollOffset;
return true;
} else {
// otherwise, if not IMU sample, use last IMU sample to compute GT flow from last IMU sample and event location
// then transform, then move them back to their origin.
//
// The flow is computed from trigonometry assuming a pinhole lens. This lens projects points at larger angular distance with
// smaller pixel spacing. i.e. the math is the following.
// If the distance of the pixel from the middle of the image is l, the angle to the point is w, the focal length is f, then
// tan(w)=l/f,
// and dl/dt=f dw/dt (sec^2(w))
int nx = e.x - sizex / 2; // TODO assumes principal point is at center of image
int ny = e.y - sizey / 2;
// panRateDps=0; tiltRateDps=0; // debug
final float rrrad = -(float) (rollRateDps * Math.PI / 180);
final float radfac = (float) (Math.PI / 180);
final float pixfac = radfac / radPerPixel;
final float pixdim = chip.getPixelWidthUm() * 1e-3f;
final float thetax = (float) Math.atan2(nx * pixdim, lensFocalLengthMm);
final float secx = (float) (1f / Math.cos(thetax));
final float xprojfac = (float) (secx * secx);
final float thetay = (float) Math.atan2(ny * pixdim, lensFocalLengthMm);
final float secy = (float) (1f / Math.cos(thetay));
final float yprojfac = (float) (secy * secy);
vx = -(float) (-ny * rrrad + panRateDps * pixfac) * xprojfac;
vy = -(float) (nx * rrrad - tiltRateDps * pixfac) * yprojfac;
v = (float) Math.sqrt(vx * vx + vy * vy);
}
return false;
}
/**
* @return the calibrationSamples
*/
public int getCalibrationSamples() {
return calibrationSamples;
}
/**
* @param calibrationSamples the calibrationSamples to set
*/
public void setCalibrationSamples(int calibrationSamples) {
this.calibrationSamples = calibrationSamples;
}
@Override
public String toString() {
return "ImuFlowEstimator{" + "panOffset=" + panOffset + ", tiltOffset=" + tiltOffset + ", rollOffset=" + rollOffset + ", flushCounter=" + flushCounter + '}';
}
private void eraseIMUCalibration() {
panOffset = 0;
tiltOffset = 0;
rollOffset = 0;
calibrated = false;
putFloat("panOffset", panOffset);
putFloat("tiltOffset", tiltOffset);
putFloat("rollOffset", rollOffset);
log.info("IMU calibration erased (all offsets set to zero)");
}
/**
*
* @return the panRateDps in deg/s
*/
public float getPanRateDps() {
return panRateDps;
}
/**
* @return the tiltRateDps in deg/s
*/
public float getTiltRateDps() {
return tiltRateDps;
}
/**
* @return the rollRateDps in deg/s
*/
public float getRollRateDps() {
return rollRateDps;
}
}
// </editor-fold>
@Override
public abstract EventPacket filterPacket(EventPacket in);
synchronized void allocateMaps() {
subsampledPixelIsSet = new boolean[subSizeX][subSizeY];
lastTimesMap = new int[subSizeX][subSizeY][numInputTypes];
resetMaps();
}
protected void resetMaps() {
for (boolean[] a : subsampledPixelIsSet) {
Arrays.fill(a, false);
}
for (int[][] a : lastTimesMap) {
for (int[] b : a) {
Arrays.fill(b, Integer.MIN_VALUE);
}
}
}
@Override
public synchronized void resetFilter() {
if (measureAccuracy || measureProcessingTime && (motionFlowStatistics != null && motionFlowStatistics.getSampleCount() > 0)) {
doPrintStatistics();
}
resetMaps();
imuFlowEstimator.reset();
exportedFlowToMatlab = false;
motionField.reset();
motionFlowStatistics.reset(subSizeX, subSizeY, statisticsWindowSize);
if ("DirectionSelectiveFlow".equals(filterClassName) && getEnclosedFilter() != null) {
getEnclosedFilter().resetFilter();
}
setXMax(chip.getSizeX());
setYMax(chip.getSizeY());
}
@Override
public void initFilter() {
sizex = chip.getSizeX();
sizey = chip.getSizeY();
subSizeX = sizex >> subSampleShift;
subSizeY = sizey >> subSampleShift;
motionFlowStatistics = new MotionFlowStatistics(filterClassName, subSizeX, subSizeY, statisticsWindowSize);
if (chip.getAeViewer() != null) {
chip.getAeViewer().getSupport().addPropertyChangeListener(this); // AEViewer refires these events for convenience
}
allocateMaps();
setMeasureAccuracy(getBoolean("measureAccuracy", true));
setMeasureProcessingTime(getBoolean("measureProcessingTime", false));
setDisplayGlobalMotion(getBoolean("displayGlobalMotion", true));// these setters set other flags, so call them to set these flags to default values
resetFilter();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case AEViewer.EVENT_TIMESTAMPS_RESET:
if (isFilterEnabled()) {
resetFilter();
}
break;
case AEInputStream.EVENT_REWOUND:
case AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP:
case AEInputStream.EVENT_REPOSITIONED:
if (isFilterEnabled()) {
log.info(evt.toString() + ": resetting filter after printing collected statistics if measurement enabled");
doToggleOffLogGlobalMotionFlows();
doToggleOffLogMotionVectorEvents();
doToggleOffLogAccuracyStatistics();
}
break;
case AEViewer.EVENT_FILEOPEN:
log.info("EVENT_FILEOPEN=" + evt.toString());
if ((chip.getAeViewer() != null) && (chip.getAeViewer().getAePlayer().getAEInputStream() instanceof RosbagFileInputStream)) {
RosbagFileInputStream rosbag = (RosbagFileInputStream) chip.getAeViewer().getAePlayer().getAEInputStream();
aeInputStartTimeS = rosbag.getStartAbsoluteTimeS();
offsetTimeThatGTStartsAfterRosbagS = ((gtInputStartTimeS - aeInputStartTimeS)); // pos if GT later than DVS
// showPlainMessageDialogInSwingThread("Opened a rosbag file input stream", "Opened Rosbag first");
}
if (isFilterEnabled()) {
resetFilter();
}
break;
case AEViewer.EVENT_CHIP:
clearGroundTruth(); // save a lot of memory
break;
}
super.propertyChange(evt); // call super.propertyChange() after we have processed event here first, to e.g. print statistics
}
/**
* Draw a motion vector at location x,y with velocity vx, vy
*
* @param gl GL2 context
* @param x x location
* @param y y location
* @param vx x component of velocity in px/s
* @param vy y component in px/s
* @return the float[] RGBA color used to draw the vector
*/
protected float[] drawMotionVector(GL2 gl, int x, int y, float vx, float vy) {
float[] rgba = null;
if (useColorForMotionVectors) {
rgba = motionColor(vx, vy, 1, 1);
} else {
rgba = new float[]{0, 0, 1, motionVectorTransparencyAlpha};
}
gl.glColor4fv(rgba, 0);
float scale = ppsScale;
if (ppsScaleDisplayRelativeOFLength && displayGlobalMotion) {
scale = 100 * ppsScale / motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
}
if (displayVectorsEnabled) {
gl.glPushMatrix();
gl.glLineWidth(motionVectorLineWidthPixels);
// start arrow from event
// DrawGL.drawVector(gl, e.getX() + .5f, e.getY() + .5f, e.getVelocity().x, e.getVelocity().y, motionVectorLineWidthPixels, ppsScale);
// center arrow on location, rather that start from event location
float dx, dy;
dx = vx * scale;
dy = vy * scale;
if (displayVectorsAsUnitVectors) {
float s = 100 * scale / (float) Math.sqrt(dx * dx + dy * dy);
dx *= s;
dy *= s;
}
float x0 = x - (dx / 2) + .5f, y0 = y - (dy / 2) + .5f;
float rx = 0, ry = 0;
if (randomScatterOnFlowVectorOrigins) {
rx = RANDOM_SCATTER_PIXELS * (random.nextFloat() - .5f);
ry = RANDOM_SCATTER_PIXELS * (random.nextFloat() - .5f);
}
DrawGL.drawVector(gl, x0 + rx, y0 + ry, dx, dy, motionVectorLineWidthPixels / 2, 1);
gl.glPopMatrix();
}
if (displayVectorsAsColorDots) {
gl.glPointSize(motionVectorLineWidthPixels * 5);
gl.glEnable(GL2.GL_POINT_SMOOTH);
gl.glBegin(GL.GL_POINTS);
gl.glVertex2f(e.getX(), e.getY());
gl.glEnd();
}
return rgba;
}
/**
* Plots a single motion vector which is the number of pixels per second
* times scaling. Color vectors by angle to x-axis.
*
* @param gl the OpenGL context
* @return the float[] RGBA color used to draw the vector
*/
protected float[] drawMotionVector(GL2 gl, MotionOrientationEventInterface e) {
return drawMotionVector(gl, e.getX(), e.getY(), (float) e.getVelocity().getX(), (float) e.getVelocity().getY());
}
protected float[] motionColor(float angle) {
return motionColor((float) Math.cos(angle), (float) Math.sin(angle), 1, 1);
}
protected float[] motionColor(float angle, float saturation, float brightness) {
return motionColor((float) Math.cos(angle), (float) Math.sin(angle), saturation, brightness);
}
protected float[] motionColor(MotionOrientationEventInterface e1) {
return motionColor(e1.getVelocity().x, e1.getVelocity().y, 1, 1);
}
/**
* Returns a motion barb vector color including transparency
*
* @param x x component of velocity
* @param y y component of velocity
* @param saturation
* @param brightness
* @return float[] with 4 components RGBA
*/
protected float[] motionColor(float x, float y, float saturation, float brightness) {
float angle01 = (float) (Math.atan2(y, x) / (2 * Math.PI) + 0.5);
// atan2 returns -pi to +pi, so dividing by 2*pi gives -.5 to +.5. Adding .5 gives range 0 to 1.
// angle01=.5f; // debug
int rgbValue = Color.HSBtoRGB(angle01, saturation, brightness);
Color color = new Color(rgbValue);
float[] c = color.getRGBComponents(null);
return new float[]{c[0], c[1], c[2], motionVectorTransparencyAlpha};
}
@Override
public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
GL2 gl = drawable.getGL().getGL2();
if (gl == null) {
return;
}
// Draw individual motion vectors
if (dirPacket != null && (displayVectorsEnabled || displayVectorsAsColorDots)) {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_DST_COLOR);
gl.glBlendEquation(GL.GL_FUNC_ADD);
for (Object o : dirPacket) {
MotionOrientationEventInterface ei = (MotionOrientationEventInterface) o;
// If we passAllEvents then the check is needed to not annotate
// the events without a real direction.
if (ei.isHasDirection()) {
drawMotionVector(gl, ei);
} else if (displayZeroLengthVectorsEnabled) {
gl.glPushMatrix();
gl.glTranslatef(ei.getX(), ei.getY(), 0);
gl.glPointSize(motionVectorLineWidthPixels * 2);
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_POINTS);
gl.glVertex2i(0, 0);
gl.glEnd();
gl.glPopMatrix();
}
}
gl.glDisable(GL.GL_BLEND);
// draw scale bar vector at bottom
gl.glPushMatrix();
float speed = (chip.getSizeX() / 2);
if (displayGlobalMotion) {
speed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
}
DvsMotionOrientationEvent e = new DvsMotionOrientationEvent();
final int px = 10, py = -10;
float[] rgba = drawMotionVector(gl, px, py, speed, 0);
gl.glRasterPos2f(px + 100 * ppsScale, py); // use same scaling
String s = null;
if (displayGlobalMotion) {
s = String.format("%.1f px/s avg. speed and OF vector scale", speed);
} else {
s = String.format("%.1f px/s OF scale", speed);
}
// gl.glColor3f(1, 1, 1);
DrawGL.drawString(gl, 10, px+20, py, 0, new Color(rgba[0], rgba[1], rgba[2], rgba[3]), s);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glPopMatrix();
}
if (isDisplayGlobalMotion()) {
gl.glLineWidth(getMotionVectorLineWidthPixels());
gl.glColor3f(1, 1, 1);
// Draw global translation vector
gl.glPushMatrix();
DrawGL.drawVector(gl, sizex / 2, sizey / 2,
motionFlowStatistics.getGlobalMotion().meanGlobalVx,
motionFlowStatistics.getGlobalMotion().meanGlobalVy,
4, ppsScale * GLOBAL_MOTION_DRAWING_SCALE);
gl.glRasterPos2i(2, 10);
String flowMagPps = engFmt.format(motionFlowStatistics.getGlobalMotion().meanGlobalTrans);
chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
String.format("glob. trans.=%s px/s (local: %s)", flowMagPps, ppsScaleDisplayRelativeOFLength ? "rel." : "abs."));
gl.glPopMatrix();
// System.out.println(String.format("%5.3f\t%5.2f",ts*1e-6f, motionFlowStatistics.getGlobalMotion().meanGlobalTrans)); // debug
// draw quartiles statistics ellipse
gl.glPushMatrix();
gl.glTranslatef(sizex / 2 + motionFlowStatistics.getGlobalMotion().meanGlobalVx * ppsScale,
sizey / 2 + motionFlowStatistics.getGlobalMotion().meanGlobalVy * ppsScale,
0);
DrawGL.drawEllipse(gl, 0, 0, (float) motionFlowStatistics.getGlobalMotion().sdGlobalVx * ppsScale,
(float) motionFlowStatistics.getGlobalMotion().sdGlobalVy * ppsScale,
0, 16);
gl.glPopMatrix();
// Draw global rotation vector as line left/right
gl.glPushMatrix();
DrawGL.drawLine(gl,
sizex / 2,
sizey * 3 / 4,
(float) (-motionFlowStatistics.getGlobalMotion().getGlobalRotation().getMean()),
0, ppsScale * GLOBAL_MOTION_DRAWING_SCALE);
gl.glPopMatrix();
// Draw global expansion as circle with radius proportional to
// expansion metric, smaller for contraction, larger for expansion
gl.glPushMatrix();
DrawGL.drawCircle(gl, sizex / 2, sizey / 2, ppsScale * GLOBAL_MOTION_DRAWING_SCALE
* (1 + motionFlowStatistics.getGlobalMotion().meanGlobalExpansion), 15);
gl.glPopMatrix();
}
if (displayColorWheelLegend) {
final int segments = 16;
final float scale = 15;
gl.glPushMatrix();
gl.glTranslatef(-20, chip.getSizeY() / 2, 0);
gl.glScalef(scale, scale, 1);
for (float val01 = 0; val01 < 1; val01 += 1f / segments) {
float[] rgb = motionColor((float) ((val01 - .5f) * 2 * Math.PI), 1f, .5f);
gl.glColor3fv(rgb, 0);
// gl.glLineWidth(motionVectorLineWidthPixels);
// final double angleRad = 2*Math.PI*(val01-.5f);
// DrawGL.drawVector(gl, 0,0,(float)Math.cos(angleRad), (float)Math.sin(angleRad),.3f,2);
final float angle0 = (val01 - .5f) * 2 * (float) Math.PI;
final float angle1 = ((val01 - .5f) + 1f / segments) * 2 * (float) Math.PI;
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor4f(rgb[0], rgb[1], rgb[2], 1f);
gl.glVertex3d(0, 0, 0);
gl.glVertex3d(Math.cos(angle0), Math.sin(angle0), 0);
gl.glVertex3d(Math.cos(angle1), Math.sin(angle1), 0);
gl.glEnd();
}
gl.glPopMatrix();
}
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 1);
// Display statistics
if (measureProcessingTime) {
gl.glPushMatrix();
gl.glRasterPos2i(chip.getSizeX(), 0);
chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
String.format("%4.2f +/- %5.2f us", new Object[]{
motionFlowStatistics.processingTime.getMean(),
motionFlowStatistics.processingTime.getStandardDeviation()}));
gl.glPopMatrix();
}
if (measureAccuracy) {
MultilineAnnotationTextRenderer.resetToYPositionPixels(-20);
// MultilineAnnotationTextRenderer.setDefaultScale();
MultilineAnnotationTextRenderer.setScale(.4f);
// MultilineAnnotationTextRenderer.setFontSize(24);
String s = String.format("Accuracy statistics:%n%s%n%s%n%s",
motionFlowStatistics.endpointErrorAbs.graphicsString("AEE:", "px/s"),
motionFlowStatistics.endpointErrorRel.graphicsString("AREE:", "%"),
motionFlowStatistics.angularError.graphicsString("AAE:", "deg"),
String.format("Outliers (>%.0f px/s error): %.1f%%", motionFlowStatistics.OUTLIER_ABS_PPS, motionFlowStatistics.getOutlierPercentage()));
MultilineAnnotationTextRenderer.renderMultilineString(s);
// gl.glPushMatrix();
// final int ystart = -15, yoffset = -10, xoffset = 10;
// gl.glRasterPos2i(xoffset, ystart + yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.endpointErrorAbs.graphicsString("AEE(abs):", "px/s"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 2 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.endpointErrorRel.graphicsString("AEE(rel):", "%"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 3 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.angularError.graphicsString("AAE:", "deg"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 4 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.eventDensity.graphicsString("Density:", "%"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 5 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// String.format("Outliers (>%.0f px/s error): %.1f%%", motionFlowStatistics.OUTLIER_ABS_PPS, motionFlowStatistics.getOutlierPercentage()));
// gl.glPopMatrix();
}
motionField.draw(gl);
// draw the mouse vector GT flow event
if (mouseVectorEvent != null && mouseVectorString != null) {
gl.glPushMatrix();
drawMotionVector(gl, mouseVectorEvent);
DrawGL.drawString(drawable, 20, (float) mouseVectorEvent.getX() / chip.getSizeX(), (float) mouseVectorEvent.getY() / chip.getSizeY(), .5f, Color.yellow, mouseVectorString);
gl.glPopMatrix();
}
}
synchronized public void setupFilter(EventPacket in) {
maybeAddListeners(chip);
inItr = in.iterator();
outItr = dirPacket.outputIterator();
subsampledPixelIsSet = new boolean[subSizeX][subSizeY];
countIn = 0;
countOut = 0;
countOutliers = 0;
if (measureProcessingTime) {
motionFlowStatistics.processingTime.startTime = System.nanoTime();
}
motionField.checkArrays();
getEnclosedFilterChain().filterPacket(in);
}
/**
* @return true if ... 1) the event lies outside the chip. 2) the event's
* subsampled address falls on a pixel location that has already had an
* event within this packet. We don't want to process or render it.
* Important: This prevents events to acccumulate at the same pixel
* location, which is an essential part of the Lucas-Kanade method.
* Therefore, subsampling should be avoided in LucasKanadeFlow when the goal
* is to optimize accuracy.
* @param d equals the spatial search distance plus some extra spacing
* needed for applying finite differences to calculate gradients.
*/
protected synchronized boolean isInvalidAddress(int d) {
if (x >= d && y >= d && x < subSizeX - d && y < subSizeY - d) {
if (subSampleShift > 0 && !subsampledPixelIsSet[x][y]) {
subsampledPixelIsSet[x][y] = true;
}
return false;
}
return true;
}
// Returns true if the event lies outside certain spatial bounds.
protected boolean xyFilter() {
return x < xMin || x >= xMax || y < yMin || y >= yMax;
}
/**
* returns true if timestamp is invalid, e.g. if the timestamp is LATER
* (nonmonotonic) or is too soon after the last event from the same pixel
* |refractoryPeriodUs). Does NOT check for events that are too old relative
* to the current event.
* <p>
* If the event is nonmonotonic, triggers a resetFilter()
*
* @return true if invalid timestamp, older than refractoryPeriodUs ago
*/
protected synchronized boolean isInvalidTimestamp() {
lastTs = lastTimesMap[x][y][type];
lastTimesMap[x][y][type] = ts;
if (ts < lastTs) {
log.warning(String.format("invalid timestamp ts=%,d < lastTs=%,d, resetting filter", ts, lastTs));
resetFilter(); // For NonMonotonicTimeException.
}
return ts < lastTs + refractoryPeriodUs;
}
/**
* extracts the event into to fields e, x,y,ts,type. x and y are in
* subsampled address space
*
* @param ein input event
* @return true if result is in-bounds, false if not, which can occur when
* the camera cameraCalibration magnifies the address beyond the sensor
* coordinates
*/
protected synchronized boolean extractEventInfo(Object ein) {
e = (PolarityEvent) ein;
// If camera calibrated, undistort pixel locations
x = e.x >> subSampleShift;
y = e.y >> subSampleShift;
ts = e.getTimestamp();
type = e.getPolarity() == PolarityEvent.Polarity.Off ? 0 : 1;
return true;
}
/**
* Takes output event eout and logs it
*
*/
synchronized public void processGoodEvent() {
// Copy the input event to a new output event and appendCopy the computed optical flow properties
eout = (ApsDvsMotionOrientationEvent) outItr.nextOutput();
eout.copyFrom(e);
eout.x = (short) (x << subSampleShift);
eout.y = (short) (y << subSampleShift);
eout.velocity.x = vx;
eout.velocity.y = vy;
eout.speed = v;
eout.hasDirection = v != 0;
if (v != 0) {
countOut++;
}
if (measureAccuracy) {
vxGT = imuFlowEstimator.getVx();
vyGT = imuFlowEstimator.getVy();
vGT = imuFlowEstimator.getV();
getMotionFlowStatistics().update(vx, vy, v, vxGT, vyGT, vGT);
}
if (displayGlobalMotion || ppsScaleDisplayRelativeOFLength) {
motionFlowStatistics.getGlobalMotion().update(vx, vy, v, eout.x, eout.y);
}
if (motionVectorEventLogger != null && motionVectorEventLogger.isEnabled()) {
if (getClass().getSimpleName().equals("PatchMatchFlow")) {
try {
Method sliceIndexMethod;
sliceIndexMethod = getClass().getDeclaredMethod("sliceIndex", Integer.TYPE);
sliceIndexMethod.setAccessible(true);
Object currentSliceIdxObj = sliceIndexMethod.invoke(this, 1);
int currentSliceIdx = (int) currentSliceIdxObj;
Field startTimeFiled = getClass().getDeclaredField("sliceStartTimeUs");
startTimeFiled.setAccessible(true);
Object sliceTminus1StartTime = startTimeFiled.get((PatchMatchFlow) this);
int[] sliceStartTimeUs = (int[]) sliceTminus1StartTime;
Field endTimeFiled = getClass().getDeclaredField("sliceEndTimeUs");
endTimeFiled.setAccessible(true);
Object sliceTminus1EndTime = endTimeFiled.get((PatchMatchFlow) this);
int[] sliceEndTimeUs = (int[]) sliceTminus1EndTime;
String s = String.format("%d %d %d %d %d %d %.3g %.3g %.3g %d", eout.timestamp,
sliceStartTimeUs[currentSliceIdx], sliceEndTimeUs[currentSliceIdx],
eout.x, eout.y, eout.type, eout.velocity.x, eout.velocity.y, eout.speed, eout.hasDirection ? 1 : 0);
motionVectorEventLogger.log(s);
} catch (NoSuchFieldException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String s = String.format("%d %d %d %d %.3g %.3g %.3g %d", eout.timestamp, eout.x, eout.y, eout.type, eout.velocity.x, eout.velocity.y, eout.speed, eout.hasDirection ? 1 : 0);
motionVectorEventLogger.log(s);
}
}
motionField.update(ts, x, y, vx, vy, v);
}
/**
* Returns true if motion event passes accuracy tests
*
* @return true if event is accurate enough, false if it should be rejected.
*/
synchronized public boolean accuracyTests() {
// 1.) Filter out events with speed high above average.
// 2.) Filter out events whose velocity deviates from IMU estimate by a
// certain degree.
return speedControlEnabled && isSpeeder() || discardOutliersForStatisticalMeasurementEnabled
&& Math.abs(motionFlowStatistics.angularError.calculateError(vx, vy, v, vxGT, vyGT, vGT))
> discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg;
}
// <editor-fold defaultstate="collapsed" desc="Speed Control">
protected boolean isSpeeder() {
// Discard events if velocity is too far above average
avgSpeed = (1 - speedMixingFactor) * avgSpeed + speedMixingFactor * v;
return v > avgSpeed * excessSpeedRejectFactor;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="IMUCalibration Start and Reset buttons">
synchronized public void doStartIMUCalibration() {
imuFlowEstimator.calibrating = true;
imuFlowEstimator.calibrated = false;
imuFlowEstimator.panCalibrator.clear();
imuFlowEstimator.tiltCalibrator.clear();
imuFlowEstimator.rollCalibrator.clear();
if (measureAccuracy) {
log.info("IMU calibration started");
} else {
log.warning("IMU calibration flagged, but will not start until measureAccuracy is selected");
}
}
synchronized public void doEraseIMUCalibration() {
imuFlowEstimator.eraseIMUCalibration();
}
// </editor-fold>
WarningDialogWithDontShowPreference imuWarningDialog;
synchronized public void doResetStatistics() {
if (motionFlowStatistics != null) {
motionFlowStatistics.reset(subSizeX, subSizeY, statisticsWindowSize);
}
}
// <editor-fold defaultstate="collapsed" desc="Statistics logging trigger button">
synchronized public void doPrintStatistics() {
if (motionFlowStatistics.getSampleCount() == 0) {
log.warning("No samples collected");
return;
}
log.log(Level.INFO, "{0}\n{1}", new Object[]{this.getClass().getSimpleName(), motionFlowStatistics.toString()});
if (!imuFlowEstimator.isCalibrationSet()) {
log.warning("IMU has not been calibrated yet! Load a file with no camera motion and hit the StartIMUCalibration button");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (imuWarningDialog != null) {
imuWarningDialog.setVisible(false);
imuWarningDialog.dispose();
}
imuWarningDialog = new WarningDialogWithDontShowPreference(null, false, "Uncalibrated IMU",
"<html>IMU has not been calibrated yet! <p>Load a file with no camera motion and hit the StartIMUCalibration button");
imuWarningDialog.setVisible(true);
}
});
} else if (imuWarningDialog != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (imuWarningDialog != null) {
imuWarningDialog.setVisible(false);
imuWarningDialog.dispose();
}
}
});
}
}
// </editor-fold>
synchronized public void doToggleOnLogMotionVectorEvents() {
if (motionVectorEventLogger != null && motionVectorEventLogger.isEnabled()) {
log.info("logging already started");
return;
}
String filename = null, filepath = null;
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(getString("lastFile", System.getProperty("user.dir")))); // defaults to startup runtime folder
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
fc.setDialogTitle("Select folder and base file name for the logged motion vector event data");
int ret = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putString("lastFile", file.toString());
motionVectorEventLogger = new TobiLogger(file.getPath(), "Motion vector events output from normal optical flow method");
motionVectorEventLogger.setNanotimeEnabled(false);
if (getClass().getSimpleName().equals("PatchMatchFlow")) {
motionVectorEventLogger.setColumnHeaderLine("timestamp(us) sliceStartTime(us) sliceEndTime(us) x y type vx(pps) vy(pps) speed(pps) validity");
motionVectorEventLogger.setSeparator(" ");
} else {
motionVectorEventLogger.setColumnHeaderLine("timestamp(us) x y type vx(pps) vy(pps) speed(pps) validity");
motionVectorEventLogger.setSeparator(" ");
}
motionVectorEventLogger.setEnabled(true);
} else {
log.info("Cancelled logging motion vectors");
}
}
synchronized public void doToggleOffLogMotionVectorEvents() {
if (motionVectorEventLogger == null) {
return;
}
log.info("stopping motion vector logging from " + motionVectorEventLogger);
motionVectorEventLogger.setEnabled(false);
motionVectorEventLogger = null;
}
synchronized public void doToggleOnLogGlobalMotionFlows() {
if (motionFlowStatistics.globalMotionVectorLogger != null && motionFlowStatistics.globalMotionVectorLogger.isEnabled()) {
log.info("logging already started");
return;
}
String filename = null, filepath = null;
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(getString("lastFile", System.getProperty("user.dir")))); // defaults to startup runtime folder
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
fc.setDialogTitle("Select folder and base file name for the logged global flows data");
int ret = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putString("lastFile", file.toString());
motionFlowStatistics.globalMotionVectorLogger = new TobiLogger(file.getPath(), "Global flows output from optical flow method");
motionFlowStatistics.globalMotionVectorLogger.setNanotimeEnabled(false);
motionFlowStatistics.globalMotionVectorLogger.setColumnHeaderLine("system_time(ms) timestamp(us) meanGlobalVx(pps) meanGlobalVy(pps)");
motionFlowStatistics.globalMotionVectorLogger.setSeparator(" ");
motionFlowStatistics.globalMotionVectorLogger.setEnabled(true);
} else {
log.info("Cancelled logging global flows");
}
}
synchronized public void doToggleOffLogGlobalMotionFlows() {
if (motionFlowStatistics.globalMotionVectorLogger == null) {
return;
}
log.info("Stopping global motion logging from " + motionFlowStatistics.globalMotionVectorLogger);
motionFlowStatistics.globalMotionVectorLogger.setEnabled(false);
motionFlowStatistics.globalMotionVectorLogger = null;
}
synchronized public void doToggleOnLogAccuracyStatistics() {
if (motionFlowStatistics.accuracyStatisticsLogger != null && motionFlowStatistics.accuracyStatisticsLogger.isEnabled()) {
log.info("logging already started");
return;
}
String filename = null, filepath = null;
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(getString("lastFile", System.getProperty("user.dir")))); // defaults to startup runtime folder
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
fc.setDialogTitle("Select folder and base file name for the logged motionFlowStatistics.accuracyStatisticsLogger");
int ret = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putString("lastFile", file.toString());
motionFlowStatistics.accuracyStatisticsLogger = new TobiLogger(file.getPath(), "Accuracy statistics");
motionFlowStatistics.accuracyStatisticsLogger.setNanotimeEnabled(false);
motionFlowStatistics.accuracyStatisticsLogger.setColumnHeaderLine("system_time(ms) timestamp(us) AEE(px/s) AREE(%) AAE(deg) N");
motionFlowStatistics.accuracyStatisticsLogger.setSeparator(" ");
motionFlowStatistics.accuracyStatisticsLogger.setEnabled(true);
} else {
log.info("Cancelled logging motionFlowStatistics.accuracyStatisticsLogger");
}
}
synchronized public void doToggleOffLogAccuracyStatistics() {
if (motionFlowStatistics.accuracyStatisticsLogger == null) {
return;
}
log.info("Stopping motionFlowStatistics.accuracyStatisticsLogger logging from " + motionFlowStatistics.accuracyStatisticsLogger);
motionFlowStatistics.accuracyStatisticsLogger.setEnabled(false);
motionFlowStatistics.accuracyStatisticsLogger = null;
}
// <editor-fold defaultstate="collapsed" desc="getter/setter for --speedControlEnabled--">
public boolean isSpeedControlEnabled() {
return speedControlEnabled;
}
public void setSpeedControlEnabled(boolean speedControlEnabled) {
support.firePropertyChange("speedControlEnabled", this.speedControlEnabled, speedControlEnabled);
this.speedControlEnabled = speedControlEnabled;
putBoolean("speedControlEnabled", speedControlEnabled);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --speedControl_speedMixingFactor--">
public float getSpeedControl_SpeedMixingFactor() {
return speedMixingFactor;
}
public void setSpeedControl_SpeedMixingFactor(float speedMixingFactor) {
if (speedMixingFactor > 1) {
speedMixingFactor = 1;
} else if (speedMixingFactor < Float.MIN_VALUE) {
speedMixingFactor = Float.MIN_VALUE;
}
this.speedMixingFactor = speedMixingFactor;
putFloat("speedMixingFactor", speedMixingFactor);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --speedControl_excessSpeedRejectFactor--">
public float getSpeedControl_ExcessSpeedRejectFactor() {
return excessSpeedRejectFactor;
}
public void setSpeedControl_ExcessSpeedRejectFactor(float excessSpeedRejectFactor) {
this.excessSpeedRejectFactor = excessSpeedRejectFactor;
putFloat("excessSpeedRejectFactor", excessSpeedRejectFactor);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg--">
// public float getEpsilon() {
// return discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg;
// }
//
// synchronized public void setEpsilon(float discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg) {
// if (discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg > 180) {
// discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg = 180;
// }
// this.discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg = discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg;
// putFloat("discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg", discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg);
// }
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --discardOutliersForStatisticalMeasurementEnabled--">
// public boolean getDiscardOutliersEnabled() {
// return this.discardOutliersForStatisticalMeasurementEnabled;
// }
//
// public void setDiscardOutliersEnabled(final boolean discardOutliersForStatisticalMeasurementEnabled) {
// support.firePropertyChange("discardOutliersForStatisticalMeasurementEnabled", this.discardOutliersForStatisticalMeasurementEnabled, discardOutliersForStatisticalMeasurementEnabled);
// this.discardOutliersForStatisticalMeasurementEnabled = discardOutliersForStatisticalMeasurementEnabled;
// putBoolean("discardOutliersForStatisticalMeasurementEnabled", discardOutliersForStatisticalMeasurementEnabled);
// }
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --loggingFolder--">
public String getLoggingFolder() {
return loggingFolder;
}
private void setLoggingFolder(String loggingFolder) {
getSupport().firePropertyChange("loggingFolder", this.loggingFolder, loggingFolder);
this.loggingFolder = loggingFolder;
getPrefs().put("DataLogger.loggingFolder", loggingFolder);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --measureAccuracy--">
public synchronized boolean isMeasureAccuracy() {
return measureAccuracy;
}
public synchronized void setMeasureAccuracy(boolean measureAccuracy) {
support.firePropertyChange("measureAccuracy", this.measureAccuracy, measureAccuracy);
this.measureAccuracy = measureAccuracy;
putBoolean("measureAccuracy", measureAccuracy);
motionFlowStatistics.setMeasureAccuracy(measureAccuracy);
if (measureAccuracy) {
//setMeasureProcessingTime(false);
resetFilter();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --measureProcessingTime--">
public synchronized boolean isMeasureProcessingTime() {
return measureProcessingTime;
}
public synchronized void setMeasureProcessingTime(boolean measureProcessingTime) {
motionFlowStatistics.setMeasureProcessingTime(measureProcessingTime);
if (measureProcessingTime) {
setRefractoryPeriodUs(1);
//support.firePropertyChange("measureAccuracy",this.measureAccuracy,false);
//this.measureAccuracy = false;
resetFilter();
this.measureProcessingTime = measureProcessingTime;
//motionFlowStatistics.processingTime.openLog(loggingFolder);
} //else motionFlowStatistics.processingTime.closeLog(loggingFolder,searchDistance);
support.firePropertyChange("measureProcessingTime", this.measureProcessingTime, measureProcessingTime);
this.measureProcessingTime = measureProcessingTime;
putBoolean("measureProcessingTime", measureProcessingTime);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --displayGlobalMotion--">
public boolean isDisplayGlobalMotion() {
return displayGlobalMotion;
}
public void setDisplayGlobalMotion(boolean displayGlobalMotion) {
boolean old = this.displayGlobalMotion;
motionFlowStatistics.setMeasureGlobalMotion(displayGlobalMotion);
this.displayGlobalMotion = displayGlobalMotion;
putBoolean("displayGlobalMotion", displayGlobalMotion);
if (displayGlobalMotion) {
resetFilter();
}
getSupport().firePropertyChange("displayGlobalMotion", old, displayGlobalMotion);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --displayVectorsEnabled--">
public boolean isDisplayVectorsEnabled() {
return displayVectorsEnabled;
}
public void setDisplayVectorsEnabled(boolean displayVectorsEnabled) {
boolean old = this.displayVectorsEnabled;
this.displayVectorsEnabled = displayVectorsEnabled;
putBoolean("displayVectorsEnabled", displayVectorsEnabled);
getSupport().firePropertyChange("displayVectorsEnabled", old, displayVectorsEnabled);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --ppsScale--">
public float getPpsScale() {
return ppsScale;
}
/**
* scale for drawn motion vectors, pixels per second per pixel
*
* @param ppsScale
*/
public void setPpsScale(float ppsScale) {
float old = this.ppsScale;
this.ppsScale = ppsScale;
putFloat("ppsScale", ppsScale);
getSupport().firePropertyChange("ppsScale", old, this.ppsScale);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --showRawInputEnable--">
public boolean isDisplayRawInput() {
return displayRawInput;
}
public void setDisplayRawInput(boolean displayRawInput) {
this.displayRawInput = displayRawInput;
putBoolean("displayRawInput", displayRawInput);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --subSampleShift--">
public int getSubSampleShift() {
return subSampleShift;
}
/**
* Sets the number of spatial bits to subsample events times by. Setting
* this equal to 1, for example, subsamples into an event time map with
* halved spatial resolution, aggregating over more space at coarser
* resolution but increasing the search range by a factor of two at no
* additional cost
*
* @param subSampleShift the number of bits, 0 means no subsampling
*/
synchronized public void setSubSampleShift(int subSampleShift) {
if (subSampleShift < 0) {
subSampleShift = 0;
} else if (subSampleShift > 4) {
subSampleShift = 4;
}
this.subSampleShift = subSampleShift;
putInt("subSampleShift", subSampleShift);
subSizeX = sizex >> subSampleShift;
subSizeY = sizey >> subSampleShift;
allocateMaps();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --refractoryPeriodUs--">
public int getRefractoryPeriodUs() {
return refractoryPeriodUs;
}
public void setRefractoryPeriodUs(int refractoryPeriodUs) {
support.firePropertyChange("refractoryPeriodUs", this.refractoryPeriodUs, refractoryPeriodUs);
this.refractoryPeriodUs = refractoryPeriodUs;
putInt("refractoryPeriodUs", refractoryPeriodUs);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --xMin--">
public int getXMin() {
return xMin;
}
public void setXMin(int xMin) {
if (xMin > xMax) {
xMin = xMax;
}
this.xMin = xMin;
putInt("xMin", xMin);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --xMax--">
public int getXMax() {
return xMax;
}
public void setXMax(int xMax) {
int old = this.xMax;
if (xMax > subSizeX) {
xMax = subSizeX;
}
this.xMax = xMax;
putInt("xMax", xMax);
getSupport().firePropertyChange("xMax", old, this.xMax);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --yMin--">
public int getYMin() {
return yMin;
}
public void setYMin(int yMin) {
if (yMin > yMax) {
yMin = yMax;
}
this.yMin = yMin;
putInt("yMin", yMin);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --yMax--">
public int getYMax() {
return yMax;
}
public void setYMax(int yMax) {
int old = this.yMax;
if (yMax > subSizeY) {
yMax = subSizeY;
}
this.yMax = yMax;
putInt("yMax", yMax);
getSupport().firePropertyChange("yMax", old, this.yMax);
}
// </editor-fold>
/**
* @return the lensFocalLengthMm
*/
public float getLensFocalLengthMm() {
return lensFocalLengthMm;
}
/**
* @param aLensFocalLengthMm the lensFocalLengthMm to set
*/
public void setLensFocalLengthMm(float aLensFocalLengthMm) {
lensFocalLengthMm = aLensFocalLengthMm;
radPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * lensFocalLengthMm));
}
protected boolean outlierMotionFilteringKeepThisEvent(MotionOrientationEventInterface e) {
if (outlierMotionFilteringLastAngles == null) {
outlierMotionFilteringLastAngles = new int[chip.getSizeX()][chip.getSizeY()];
}
return true;
}
/**
* returns unsigned angle difference that is in range 0-180
*
* @param a
* @param b
* @return unsigned angle difference that is in range 0-180
*/
private int angleDiff(int a, int b) {
int d = Math.abs(a - b) % 360;
int r = d > 180 ? 360 - d : d;
return r;
}
/**
* Encapsulates the computed motion field that is estimated from the flow
* events, with outlier rejection etc.
*
*/
protected class MotionField {
int sx = 0, sy = 0; // size of arrays
private LowpassFilter3D[][] velocities;
// private LowpassFilter[][] speeds;
private int[][] lastTs;
private int lastDecayTimestamp = Integer.MAX_VALUE;
private int motionFieldSubsamplingShift = getInt("motionFieldSubsamplingShift", 3);
// private float motionFieldMixingFactor = getFloat("motionFieldMixingFactor", 1e-1f);
private int motionFieldTimeConstantMs = getInt("motionFieldTimeConstantMs", 100);
private int maxAgeUs = getInt("motionFieldMaxAgeUs", 100000);
private float minSpeedPpsToDrawMotionField = getFloat("minVelocityPps", 1);
private boolean consistentWithNeighbors = getBoolean("motionFieldConsistentWithNeighbors", false);
private boolean consistentWithCurrentAngle = getBoolean("motionFieldConsistentWithCurrentAngle", false);
private boolean displayMotionField = getBoolean("displayMotionField", false);
private boolean displayMotionFieldColorBlobs = getBoolean("displayMotionFieldColorBlobs", false);
;
private boolean displayMotionFieldUsingColor = getBoolean("displayMotionFieldUsingColor", true);
;
private boolean motionFieldDiffusionEnabled = getBoolean("motionFieldDiffusionEnabled", false);
private boolean decayTowardsZeroPeridiclly = getBoolean("decayTowardsZeroPeridiclly", false);
public MotionField() {
}
public void checkArrays() {
if (chip.getNumPixels() == 0) {
return;
}
int newsx = (chip.getSizeX() >> motionFieldSubsamplingShift);
int newsy = (chip.getSizeY() >> motionFieldSubsamplingShift);
if (newsx == 0 || newsy == 0) {
return; // not yet
}
if (sx == 0 || sy == 0 || sx != newsx || sy != newsy || lastTs == null || lastTs.length != sx
|| velocities == null || velocities.length != sx) {
sx = newsx;
sy = newsy;
lastTs = new int[sx][sy];
velocities = new LowpassFilter3D[sx][sy];
// speeds = new LowpassFilter[sx][sy];
for (x = 0; x < sx; x++) {
for (y = 0; y < sy; y++) {
velocities[x][y] = new LowpassFilter3D(motionFieldTimeConstantMs);
// speeds[x][y]=new LowpassFilter(motionFieldTimeConstantMs);
}
}
}
}
public void reset() {
if (chip.getNumPixels() == 0) {
return;
}
lastDecayTimestamp = Integer.MIN_VALUE;
checkArrays();
for (int[] a : lastTs) {
Arrays.fill(a, Integer.MAX_VALUE);
}
for (LowpassFilter3D[] a : velocities) {
for (LowpassFilter3D f : a) {
f.reset();
f.setInitialized(true); // start out with zero motion
}
}
// for (LowpassFilter[] a : speeds) {
// for (LowpassFilter f : a) {
// f.reset();
// }
// }
}
/**
* Decays all values towards zero
*
* @param timestamp current time in us
*/
public void decayAllTowardsZero(int timestamp) {
for (LowpassFilter3D[] a : velocities) {
for (LowpassFilter3D f : a) {
f.filter(0, 0, 0, timestamp);
}
}
}
/**
* updates motion field
*
* @param timestamp in us
* @param x1 location pixel x before subsampling
* @param y1
* @param vx flow vx, pps
* @param vy
*/
synchronized public void update(int timestamp, int x, int y, float vx, float vy, float speed) {
if (!displayMotionField) {
return;
}
int dtDecay = timestamp - lastDecayTimestamp;
if (decayTowardsZeroPeridiclly && dtDecay > motionFieldTimeConstantMs * 1000 || dtDecay < 0) {
decayAllTowardsZero(timestamp);
lastDecayTimestamp = timestamp;
}
int x1 = x >> motionFieldSubsamplingShift, y1 = y >> motionFieldSubsamplingShift;
if (x1 < 0 || x1 >= velocities.length || y1 < 0 || y1 >= velocities[0].length) {
return;
}
if (checkConsistent(timestamp, x1, y1, vx, vy)) {
velocities[x1][y1].filter(vx, vy, speed, timestamp);
if (motionFieldDiffusionEnabled) {
// diffuse by average of neighbors and ourselves
int n = 0;
float dvx = 0, dvy = 0, dvs = 0;
for (int dx = -1; dx <= 1; dx++) {
int x2 = x1 + dx;
if (x2 >= 0 && x2 < velocities.length) {
for (int dy = -1; dy <= 1; dy++) {
int y2 = y1 + dy;
if (dx == 0 && dy == 0) {
continue; // don't count ourselves
}
if (y2 >= 0 && y2 < velocities[0].length) {
n++;
Point3D p = velocities[x2][y2].getValue3D();
dvx += p.x;
dvy += p.y;
dvs += p.z;
}
}
}
}
float r = 1f / n; // recip of sum to compute average
LowpassFilter3D v = velocities[x1][y1];
Point3D c = v.getValue3D();
v.setInternalValue3D(.5f * (c.x + r * dvx), .5f * (c.y + r * dvy), .5f * (c.z + r * dvs));
}
}
lastTs[x1][y1] = ts;
}
/**
* Checks if new flow event is consistent sufficiently with motion field
*
* @param timestamp in us
* @param x1 location pixel x after subsampling
* @param y1
* @param vx flow vx, pps
* @param vy
* @return true if sufficiently consistent
*/
private boolean checkConsistent(int timestamp, int x1, int y1, float vx, float vy) {
int dt = timestamp - lastTs[x1][y1];
if (dt > maxAgeUs) {
return false;
}
boolean thisAngleConsistentWithCurrentAngle = true;
if (consistentWithCurrentAngle) {
Point3D p = velocities[x1][y1].getValue3D();
float dot = vx * p.x + vy * p.y;
thisAngleConsistentWithCurrentAngle = (dot >= 0);
}
boolean thisAngleConsistentWithNeighbors = true;
if (consistentWithNeighbors) {
int countConsistent = 0, count = 0;
final int[] xs = {-1, 0, 1, 0}, ys = {0, 1, 0, -1}; // 4 neigbors
int nNeighbors = xs.length;
for (int i = 0; i < nNeighbors; i++) {
int x = xs[i], y = ys[i];
int x2 = x1 + x, y2 = y1 + y;
if (x2 < 0 || x2 >= velocities.length || y2 < 0 || y2 >= velocities[0].length) {
continue;
}
count++;
Point3D p = velocities[x2][y2].getValue3D();
float dot2 = vx * p.x + vy * p.y;
if (dot2 >= 0) {
countConsistent++;
}
}
if (countConsistent > count / 2) {
thisAngleConsistentWithNeighbors = true;
} else {
thisAngleConsistentWithNeighbors = false;
}
}
return thisAngleConsistentWithCurrentAngle && thisAngleConsistentWithNeighbors;
}
public void draw(GL2 gl) {
if (!displayMotionField || velocities == null) {
return;
}
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
e.printStackTrace();
}
float shift = ((1 << motionFieldSubsamplingShift) * .5f);
final float saturationSpeedScaleInversePixels = ppsScale * 0.1f; // this length of vector in pixels makes full brightness
for (int ix = 0; ix < sx; ix++) {
float x = (ix << motionFieldSubsamplingShift) + shift;
for (int iy = 0; iy < sy; iy++) {
final float y = (iy << motionFieldSubsamplingShift) + shift;
final int dt = ts - lastTs[ix][iy]; // use last timestamp of any event that is processed by extractEventInfo
gl.glColor4f(0, 0, 1, 1f);
final float dotRadius = .75f;
gl.glRectf(x - dotRadius, y - dotRadius, x + dotRadius, y + dotRadius);
if (dt > maxAgeUs || dt < 0) {
continue;
}
final float speed = velocities[ix][iy].getValue3D().z;
if (speed < minSpeedPpsToDrawMotionField) {
continue;
}
final Point3D p = velocities[ix][iy].getValue3D();
final float vx = p.x, vy = p.y;
float brightness = p.z * saturationSpeedScaleInversePixels;
if (brightness > 1) {
brightness = 1;
}
// TODO use motionColor()
float[] rgb;
if (displayMotionFieldUsingColor) {
rgb = motionColor(vx, vy, 1, 1);
} else {
rgb = new float[]{0, 0, 1};
}
gl.glColor4f(rgb[0], rgb[1], rgb[2], 1f);
gl.glLineWidth(motionVectorLineWidthPixels);
// gl.glColor4f(angle, 1 - angle, 1 / (1 + 10 * angle), .5f);
gl.glPushMatrix();
DrawGL.drawVector(gl, x, y, vx * ppsScale, vy * ppsScale, motionVectorLineWidthPixels, 1);
gl.glPopMatrix();
if (displayMotionFieldColorBlobs) {
gl.glColor4f(rgb[0], rgb[1], rgb[2], .01f);
final float s = shift / 4;
// draw a blurred square showing motion field direction
// TODO appendCopy brightness to show magnitude somehow
for (float dxx = -shift; dxx < shift; dxx += s) {
for (float dyy = -shift; dyy < shift; dyy += s) {
gl.glRectf(x - shift + dxx, y - shift + dyy, x + shift + dxx, y + shift + dyy);
}
}
}
}
}
}
private boolean isDisplayMotionField() {
return displayMotionField;
}
private void setDisplayMotionField(boolean yes) {
displayMotionField = yes;
putBoolean("displayMotionField", yes);
}
/**
* @return the motionFieldSubsamplingShift
*/
public int getMotionFieldSubsamplingShift() {
return motionFieldSubsamplingShift;
}
/**
* @param motionFieldSubsamplingShift the motionFieldSubsamplingShift to
* set
*/
synchronized public void setMotionFieldSubsamplingShift(int motionFieldSubsamplingShift) {
if (motionFieldSubsamplingShift < 0) {
motionFieldSubsamplingShift = 0;
} else if (motionFieldSubsamplingShift > 5) {
motionFieldSubsamplingShift = 5;
}
this.motionFieldSubsamplingShift = motionFieldSubsamplingShift;
putInt("motionFieldSubsamplingShift", motionFieldSubsamplingShift);
reset();
}
// /**
// * @return the motionFieldMixingFactor
// */
// public float getMotionFieldMixingFactor() {
// return motionFieldMixingFactor;
// }
//
// /**
// * @param motionFieldMixingFactor the motionFieldMixingFactor to set
// */
// public void setMotionFieldMixingFactor(float motionFieldMixingFactor) {
// if (motionFieldMixingFactor < 1e-6f) {
// this.motionFieldMixingFactor = 1e-6f;
// } else if (motionFieldMixingFactor > 1) {
// this.motionFieldMixingFactor = 1;
// }
// this.motionFieldMixingFactor = motionFieldMixingFactor;
// putFloat("motionFieldMixingFactor", motionFieldMixingFactor);
// }
/**
* @return the maxAgeUs
*/
public int getMaxAgeUs() {
return maxAgeUs;
}
/**
* @param maxAgeUs the maxAgeUs to set
*/
public void setMaxAgeUs(int maxAgeUs) {
this.maxAgeUs = maxAgeUs;
putInt("motionFieldMaxAgeUs", maxAgeUs);
}
/**
* @return the consistentWithNeighbors
*/
public boolean isConsistentWithNeighbors() {
return consistentWithNeighbors;
}
/**
* @param consistentWithNeighbors the consistentWithNeighbors to set
*/
public void setConsistentWithNeighbors(boolean consistentWithNeighbors) {
this.consistentWithNeighbors = consistentWithNeighbors;
putBoolean("motionFieldConsistentWithNeighbors", consistentWithNeighbors);
}
/**
* @return the consistentWithCurrentAngle
*/
public boolean isConsistentWithCurrentAngle() {
return consistentWithCurrentAngle;
}
/**
* @param consistentWithCurrentAngle the consistentWithCurrentAngle to
* set
*/
public void setConsistentWithCurrentAngle(boolean consistentWithCurrentAngle) {
this.consistentWithCurrentAngle = consistentWithCurrentAngle;
putBoolean("motionFieldConsistentWithCurrentAngle", consistentWithCurrentAngle);
}
/**
* @return the minSpeedPpsToDrawMotionField
*/
public float getMinSpeedPpsToDrawMotionField() {
return minSpeedPpsToDrawMotionField;
}
/**
* @param minSpeedPpsToDrawMotionField the minSpeedPpsToDrawMotionField
* to set
*/
public void setMinSpeedPpsToDrawMotionField(float minSpeedPpsToDrawMotionField) {
this.minSpeedPpsToDrawMotionField = minSpeedPpsToDrawMotionField;
putFloat("minSpeedPpsToDrawMotionField", minSpeedPpsToDrawMotionField);
}
/**
* @return the motionFieldTimeConstantMs
*/
public int getMotionFieldTimeConstantMs() {
return motionFieldTimeConstantMs;
}
/**
* @param motionFieldTimeConstantMs the motionFieldTimeConstantMs to set
*/
public void setMotionFieldTimeConstantMs(int motionFieldTimeConstantMs) {
this.motionFieldTimeConstantMs = motionFieldTimeConstantMs;
putInt("motionFieldTimeConstantMs", motionFieldTimeConstantMs);
setTimeConstant(motionFieldTimeConstantMs);
}
private void setTimeConstant(int motionFieldTimeConstantMs) {
if (sx == 0 || sy == 0) {
return;
}
for (LowpassFilter3D[] a : velocities) {
for (LowpassFilter3D f : a) {
f.setTauMs(motionFieldTimeConstantMs);
}
}
// for (LowpassFilter[] a : speeds) {
// for (LowpassFilter f : a) {
// f.setTauMs(motionFieldTimeConstantMs);
// }
// }
}
/**
* @return the displayMotionFieldColorBlobs
*/
public boolean isDisplayMotionFieldColorBlobs() {
return displayMotionFieldColorBlobs;
}
/**
* @param displayMotionFieldColorBlobs the displayMotionFieldColorBlobs
* to set
*/
public void setDisplayMotionFieldColorBlobs(boolean displayMotionFieldColorBlobs) {
this.displayMotionFieldColorBlobs = displayMotionFieldColorBlobs;
putBoolean("displayMotionFieldColorBlobs", displayMotionFieldColorBlobs);
}
/**
* @return the displayMotionFieldUsingColor
*/
public boolean isDisplayMotionFieldUsingColor() {
return displayMotionFieldUsingColor;
}
/**
* @param displayMotionFieldUsingColor the displayMotionFieldUsingColor
* to set
*/
public void setDisplayMotionFieldUsingColor(boolean displayMotionFieldUsingColor) {
this.displayMotionFieldUsingColor = displayMotionFieldUsingColor;
putBoolean("displayMotionFieldUsingColor", displayMotionFieldUsingColor);
}
/**
* @return the motionFieldDiffusionEnabled
*/
public boolean isMotionFieldDiffusionEnabled() {
return motionFieldDiffusionEnabled;
}
/**
* @param motionFieldDiffusionEnabled the motionFieldDiffusionEnabled to
* set
*/
public void setMotionFieldDiffusionEnabled(boolean motionFieldDiffusionEnabled) {
this.motionFieldDiffusionEnabled = motionFieldDiffusionEnabled;
putBoolean("motionFieldDiffusionEnabled", motionFieldDiffusionEnabled);
}
/**
* @return the decayTowardsZeroPeridiclly
*/
public boolean isDecayTowardsZeroPeridiclly() {
return decayTowardsZeroPeridiclly;
}
/**
* @param decayTowardsZeroPeridiclly the decayTowardsZeroPeridiclly to
* set
*/
public void setDecayTowardsZeroPeridiclly(boolean decayTowardsZeroPeridiclly) {
this.decayTowardsZeroPeridiclly = decayTowardsZeroPeridiclly;
putBoolean("decayTowardsZeroPeridiclly", decayTowardsZeroPeridiclly);
}
} // MotionField
public boolean isDisplayMotionField() {
return motionField.isDisplayMotionField();
}
public void setDisplayMotionField(boolean yes) {
motionField.setDisplayMotionField(yes);
}
public int getMotionFieldSubsamplingShift() {
return motionField.getMotionFieldSubsamplingShift();
}
public void setMotionFieldSubsamplingShift(int motionFieldSubsamplingShift) {
motionField.setMotionFieldSubsamplingShift(motionFieldSubsamplingShift);
}
// public float getMotionFieldMixingFactor() {
// return motionField.getMotionFieldMixingFactor();
// }
//
// public void setMotionFieldMixingFactor(float motionFieldMixingFactor) {
// motionField.setMotionFieldMixingFactor(motionFieldMixingFactor);
// }
public int getMotionFieldTimeConstantMs() {
return motionField.getMotionFieldTimeConstantMs();
}
public void setMotionFieldTimeConstantMs(int motionFieldTimeConstantMs) {
motionField.setMotionFieldTimeConstantMs(motionFieldTimeConstantMs);
}
public int getMaxAgeUs() {
return motionField.getMaxAgeUs();
}
public void setMaxAgeUs(int maxAgeUs) {
motionField.setMaxAgeUs(maxAgeUs);
}
public boolean isConsistentWithNeighbors() {
return motionField.isConsistentWithNeighbors();
}
public void setConsistentWithNeighbors(boolean consistentWithNeighbors) {
motionField.setConsistentWithNeighbors(consistentWithNeighbors);
}
public boolean isConsistentWithCurrentAngle() {
return motionField.isConsistentWithCurrentAngle();
}
public void setConsistentWithCurrentAngle(boolean consistentWithCurrentAngle) {
motionField.setConsistentWithCurrentAngle(consistentWithCurrentAngle);
}
public float getMinSpeedPpsToDrawMotionField() {
return motionField.getMinSpeedPpsToDrawMotionField();
}
public void setMinSpeedPpsToDrawMotionField(float minSpeedPpsToDrawMotionField) {
motionField.setMinSpeedPpsToDrawMotionField(minSpeedPpsToDrawMotionField);
}
/**
* Returns the object holding flow statistics.
*
* @return the motionFlowStatistics
*/
public MotionFlowStatistics getMotionFlowStatistics() {
return motionFlowStatistics;
}
public int getCalibrationSamples() {
return imuFlowEstimator.getCalibrationSamples();
}
public void setCalibrationSamples(int calibrationSamples) {
imuFlowEstimator.setCalibrationSamples(calibrationSamples);
}
public boolean isDisplayColorWheelLegend() {
return this.displayColorWheelLegend;
}
public void setDisplayColorWheelLegend(boolean displayColorWheelLegend) {
this.displayColorWheelLegend = displayColorWheelLegend;
putBoolean("displayColorWheelLegend", displayColorWheelLegend);
}
/**
* @return the motionVectorLineWidthPixels
*/
public float getMotionVectorLineWidthPixels() {
return motionVectorLineWidthPixels;
}
/**
* @param motionVectorLineWidthPixels the motionVectorLineWidthPixels to set
*/
public void setMotionVectorLineWidthPixels(float motionVectorLineWidthPixels) {
if (motionVectorLineWidthPixels < .1f) {
motionVectorLineWidthPixels = .1f;
} else if (motionVectorLineWidthPixels > 10) {
motionVectorLineWidthPixels = 10;
}
this.motionVectorLineWidthPixels = motionVectorLineWidthPixels;
putFloat("motionVectorLineWidthPixels", motionVectorLineWidthPixels);
}
/**
* @return the displayZeroLengthVectorsEnabled
*/
public boolean isDisplayZeroLengthVectorsEnabled() {
return displayZeroLengthVectorsEnabled;
}
/**
* @param displayZeroLengthVectorsEnabled the
* displayZeroLengthVectorsEnabled to set
*/
public void setDisplayZeroLengthVectorsEnabled(boolean displayZeroLengthVectorsEnabled) {
this.displayZeroLengthVectorsEnabled = displayZeroLengthVectorsEnabled;
putBoolean("displayZeroLengthVectorsEnabled", displayZeroLengthVectorsEnabled);
}
// /**
// * @return the outlierMotionFilteringEnabled
// */
// public boolean isOutlierMotionFilteringEnabled() {
// return outlierMotionFilteringEnabled;
// }
//
// /**
// * @param outlierMotionFilteringEnabled the outlierMotionFilteringEnabled to
// * set
// */
// public void setOutlierMotionFilteringEnabled(boolean outlierMotionFilteringEnabled) {
// this.outlierMotionFilteringEnabled = outlierMotionFilteringEnabled;
// }
/**
* @return the displayVectorsAsColorDots
*/
public boolean isDisplayVectorsAsColorDots() {
return displayVectorsAsColorDots;
}
/**
* @param displayVectorsAsColorDots the displayVectorsAsColorDots to set
*/
public void setDisplayVectorsAsColorDots(boolean displayVectorsAsColorDots) {
this.displayVectorsAsColorDots = displayVectorsAsColorDots;
putBoolean("displayVectorsAsColorDots", displayVectorsAsColorDots);
}
public boolean isDisplayMotionFieldColorBlobs() {
return motionField.isDisplayMotionFieldColorBlobs();
}
public void setDisplayMotionFieldColorBlobs(boolean displayMotionFieldColorBlobs) {
motionField.setDisplayMotionFieldColorBlobs(displayMotionFieldColorBlobs);
}
public boolean isDisplayMotionFieldUsingColor() {
return motionField.isDisplayMotionFieldUsingColor();
}
public void setDisplayMotionFieldUsingColor(boolean displayMotionFieldUsingColor) {
motionField.setDisplayMotionFieldUsingColor(displayMotionFieldUsingColor);
}
public boolean isMotionFieldDiffusionEnabled() {
return motionField.isMotionFieldDiffusionEnabled();
}
public void setMotionFieldDiffusionEnabled(boolean motionFieldDiffusionEnabled) {
motionField.setMotionFieldDiffusionEnabled(motionFieldDiffusionEnabled);
}
public boolean isDecayTowardsZeroPeridiclly() {
return motionField.isDecayTowardsZeroPeridiclly();
}
public void setDecayTowardsZeroPeridiclly(boolean decayTowardsZeroPeridiclly) {
motionField.setDecayTowardsZeroPeridiclly(decayTowardsZeroPeridiclly);
}
/**
* @return the displayVectorsAsUnitVectors
*/
public boolean isDisplayVectorsAsUnitVectors() {
return displayVectorsAsUnitVectors;
}
/**
* @param displayVectorsAsUnitVectors the displayVectorsAsUnitVectors to set
*/
public void setDisplayVectorsAsUnitVectors(boolean displayVectorsAsUnitVectors) {
this.displayVectorsAsUnitVectors = displayVectorsAsUnitVectors;
putBoolean("displayVectorsAsUnitVectors", displayVectorsAsUnitVectors);
}
/**
* @return the ppsScaleDisplayRelativeOFLength
*/
public boolean isPpsScaleDisplayRelativeOFLength() {
return ppsScaleDisplayRelativeOFLength;
}
/**
* @param ppsScaleDisplayRelativeOFLength the
* ppsScaleDisplayRelativeOFLength to set
*/
public void setPpsScaleDisplayRelativeOFLength(boolean ppsScaleDisplayRelativeOFLength) {
boolean old = this.ppsScaleDisplayRelativeOFLength;
this.ppsScaleDisplayRelativeOFLength = ppsScaleDisplayRelativeOFLength;
putBoolean("ppsScaleDisplayRelativeOFLength", ppsScaleDisplayRelativeOFLength);
getSupport().firePropertyChange("ppsScaleDisplayRelativeOFLength", old, ppsScaleDisplayRelativeOFLength);
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
super.setFilterEnabled(yes);
if (cameraCalibration != null) {
cameraCalibration.setFilterEnabled(false); // disable camera cameraCalibration; force user to enable it every time
}
}
/**
* @return the statisticsWindowSize
*/
public int getStatisticsWindowSize() {
return statisticsWindowSize;
}
/**
* @param statisticsWindowSize the statisticsWindowSize to set
*/
public void setStatisticsWindowSize(int statisticsWindowSize) {
this.statisticsWindowSize = statisticsWindowSize;
putInt("statisticsWindowSize", statisticsWindowSize);
motionFlowStatistics.setWindowSize(this.statisticsWindowSize);
}
/**
* @return the randomScatterOnFlowVectorOrigins
*/
public boolean isRandomScatterOnFlowVectorOrigins() {
return randomScatterOnFlowVectorOrigins;
}
/**
* @param randomScatterOnFlowVectorOrigins the
* randomScatterOnFlowVectorOrigins to set
*/
public void setRandomScatterOnFlowVectorOrigins(boolean randomScatterOnFlowVectorOrigins) {
this.randomScatterOnFlowVectorOrigins = randomScatterOnFlowVectorOrigins;
putBoolean("randomScatterOnFlowVectorOrigins", randomScatterOnFlowVectorOrigins);
}
/**
* @return the motionVectorTransparencyAlpha
*/
public float getMotionVectorTransparencyAlpha() {
return motionVectorTransparencyAlpha;
}
/**
* @param motionVectorTransparencyAlpha the motionVectorTransparencyAlpha to
* set
*/
public void setMotionVectorTransparencyAlpha(float motionVectorTransparencyAlpha) {
if (motionVectorTransparencyAlpha < 0) {
motionVectorTransparencyAlpha = 0;
} else if (motionVectorTransparencyAlpha > 1) {
motionVectorTransparencyAlpha = 1;
}
this.motionVectorTransparencyAlpha = motionVectorTransparencyAlpha;
putFloat("motionVectorTransparencyAlpha", motionVectorTransparencyAlpha);
}
@Override
public void mouseMoved(MouseEvent mouseEvent) {
if (!measureAccuracy) {
return;
}
Point2D p = getMousePixel(mouseEvent);
if (p == null || p.getX() < 0 || p.getY() < 0 || p.getX() >= chip.getSizeX() || p.getY() >= chip.getSizeY()) {
return;
}
ApsDvsMotionOrientationEvent e = new ApsDvsMotionOrientationEvent();
e.x = (short) p.getX();
e.y = (short) p.getY();
e.timestamp = ts;
x = e.x;
y = e.y; // must set stupid globals to compute the GT flow in calculateImuFlow
imuFlowEstimator.calculateImuFlow(e);
if (imuFlowEstimator.getV() > 0) {
e.velocity.x = imuFlowEstimator.vx;
e.velocity.y = imuFlowEstimator.vy;
e.speed = (float) Math.sqrt(e.velocity.x * e.velocity.x + e.velocity.y * e.velocity.y);
mouseVectorString = String.format("GT: [vx,vy,v]=[%.1f,%.1f,%.1f] for [x,y]=[%d,%d]", e.velocity.x, e.velocity.y, e.speed, e.x, e.y);
log.info(mouseVectorString);
mouseVectorEvent = e;
} else {
mouseVectorEvent = null;
mouseVectorString = null;
}
super.mouseMoved(mouseEvent); //repaints
}
@Override
public void mouseExited(MouseEvent e) {
mouseVectorString = null;
mouseVectorEvent = null;
}
}
| src/ch/unizh/ini/jaer/projects/rbodo/opticalflow/AbstractMotionFlowIMU.java | package ch.unizh.ini.jaer.projects.rbodo.opticalflow;
import ch.unizh.ini.jaer.projects.davis.calibration.SingleCameraCalibration;
import ch.unizh.ini.jaer.projects.minliu.PatchMatchFlow;
import com.jmatio.io.MatFileReader;
import com.jmatio.io.MatFileWriter;
import com.jmatio.types.MLDouble;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.gl2.GLUT;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.event.orientation.ApsDvsMotionOrientationEvent;
import net.sf.jaer.event.orientation.DvsMotionOrientationEvent;
import net.sf.jaer.event.orientation.MotionOrientationEventInterface;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventio.ros.RosbagFileInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import net.sf.jaer.util.WarningDialogWithDontShowPreference;
import net.sf.jaer.util.filter.LowpassFilter3D;
import net.sf.jaer.util.filter.LowpassFilter3D.Point3D;
import org.jetbrains.bio.npy.NpyArray;
import org.jetbrains.bio.npy.NpyFile;
/**
* Abstract base class for motion flow filters. The filters that extend this
* class use different methods to compute the optical flow vectors and override
* the filterPacket method in this class. Several methods were taken from
* AbstractDirectionSelectiveFilter and Steadicam and slightly modified.
*
* @author rbodo
*/
@Description("Abstract base class for motion optical flow.")
@DevelopmentStatus(DevelopmentStatus.Status.Abstract)
abstract public class AbstractMotionFlowIMU extends EventFilter2DMouseAdaptor implements FrameAnnotater, PropertyChangeListener {
// Observed motion flow.
public static float vx, vy, v;
public int numInputTypes;
/**
* Basic event information. Type is event polarity value, 0=OFF and 1=ON,
* typically but not always
*/
public int x, y, ts, type, lastTs;
/**
* (Subsampled) chip sizes.
*/
protected int sizex, sizey, subSizeX, subSizeY;
/**
* Subsampling
*/
private int subSampleShift = getInt("subSampleShift", 0);
protected boolean[][] subsampledPixelIsSet;
// Map of input orientation event times
// [x][y][type] where type is mixture of orienation and polarity.
protected int[][][] lastTimesMap;
// xyFilter.
private int xMin = getInt("xMin", 0);
private static final int DEFAULT_XYMAX = 1000;
private int xMax = getInt("xMax", DEFAULT_XYMAX); // (tobi) set to large value to make sure any chip will have full area processed by default
private int yMin = getInt("yMin", 0);
private int yMax = getInt("yMax", DEFAULT_XYMAX);
// Display
private boolean displayVectorsEnabled = getBoolean("displayVectorsEnabled", true);
private boolean displayVectorsAsUnitVectors = getBoolean("displayVectorsAsUnitVectors", false);
private boolean displayVectorsAsColorDots = getBoolean("displayVectorsAsColorDots", false);
private boolean displayZeroLengthVectorsEnabled = getBoolean("displayZeroLengthVectorsEnabled", true);
private boolean displayRawInput = getBoolean("displayRawInput", true);
private boolean displayColorWheelLegend = getBoolean("displayColorWheelLegend", true);
private boolean randomScatterOnFlowVectorOrigins = getBoolean("randomScatterOnFlowVectorOrigins", true);
private static final float RANDOM_SCATTER_PIXELS = 1;
private Random random = new Random();
protected float motionVectorTransparencyAlpha = getFloat("motionVectorTransparencyAlpha", .7f);
private float ppsScale = getFloat("ppsScale", 0.1f);
private boolean ppsScaleDisplayRelativeOFLength = getBoolean("ppsScaleDisplayRelativeOFLength", false);
// A pixel can fire an event only after this period. Used for smoother flow
// and speedup.
private int refractoryPeriodUs = getInt("refractoryPeriodUs", 0);
// Global translation, rotation and expansion.
private boolean displayGlobalMotion = getBoolean("displayGlobalMotion", true);
protected int statisticsWindowSize = getInt("statisticsWindowSize", 10000);
protected EngineeringFormat engFmt = new EngineeringFormat();
/**
* The output events, also used for rendering output events.
*/
protected EventPacket dirPacket;
/**
* The output packet iterator
*/
protected OutputEventIterator outItr;
/**
* The current input event
*/
protected PolarityEvent e;
/**
* The current output event
*/
protected ApsDvsMotionOrientationEvent eout;
/**
* Use IMU gyro values to estimate motion flow.
*/
public ImuFlowEstimator imuFlowEstimator;
// Focal length of camera lens in mm needed to convert rad/s to pixel/s.
// Conversion factor is atan(pixelWidth/focalLength).
private float lensFocalLengthMm = 4.5f;
// Focal length of camera lens needed to convert rad/s to pixel/s.
// Conversion factor is atan(pixelWidth/focalLength).
private float radPerPixel;
private boolean addedViewerPropertyChangeListener = false; // TODO promote these to base EventFilter class
private boolean addTimeStampsResetPropertyChangeListener = false;
// Performing statistics and logging results. lastLoggingFolder starts off
// at user.dir which is startup folder "host/java" where .exe launcher lives
private String loggingFolder = getPrefs().get("DataLogger.loggingFolder", System.getProperty("user.dir"));
public boolean measureAccuracy = getBoolean("measureAccuracy", true);
boolean measureProcessingTime = getBoolean("measureProcessingTime", false);
public int countIn, countOut, countOutliers;
protected MotionFlowStatistics motionFlowStatistics;
double[][] vxGTframe, vyGTframe, tsGTframe;
public float vxGT, vyGT, vGT;
private boolean importedGTfromMatlab;
private boolean importedGTfromNPZ = false;
private String npzFilePath = getString("npzFilePath", "");
// Discard events that are considerably faster than average
private float avgSpeed = 0;
boolean speedControlEnabled = getBoolean("speedControlEnabled", true);
private float speedMixingFactor = getFloat("speedMixingFactor", 1e-3f);
private float excessSpeedRejectFactor = getFloat("excessSpeedRejectFactor", 2f);
// Motion flow vectors can be filtered out if the angle between the observed
// optical flow and ground truth is greater than a certain threshold.
// At the moment, this option is not included in the jAER filter settings
// and defaults to false.
protected boolean discardOutliersForStatisticalMeasurementEnabled = false;
// Threshold angle in degree. Discard measured optical flow vector if it
// deviates from ground truth by more than discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg.
protected float discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg = 10f;
// outlier filtering that only allows through motion events that agree with at least N most-recent neigbor events
// in max angle difference
// private boolean outlierMotionFilteringEnabled = getBoolean("outlierMotionFilteringEnabled", false);
protected float outlierMotionFilteringMaxAngleDifferenceDeg = getFloat("outlierMotionFilteringMaxAngleDifferenceDeg", 30f);
protected int outlierMotionFilteringSubsampleShift = getInt("outlierMotionFilteringSubsampleShift", 1);
protected int outlierMotionFilteringMinSameAngleInNeighborhood = getInt("outlierMotionFilteringMinSameAngleInNeighborhood", 2);
protected int[][] outlierMotionFilteringLastAngles = null;
private float motionVectorLineWidthPixels = getFloat("motionVectorLineWidthPixels", 4);
// MotionField that aggregates motion
protected MotionField motionField = new MotionField();
/**
* Relative scale of displayed global flow vector
*/
protected static final float GLOBAL_MOTION_DRAWING_SCALE = 1;
/**
* Used for logging motion vector events to a text log file
*/
protected TobiLogger motionVectorEventLogger = null;
final String filterClassName;
private boolean exportedFlowToMatlab;
private double[][] vxOut = null;
private double[][] vyOut = null;
public Iterator inItr;
protected static String dispTT = "Display";
protected static String measureTT = "Measure";
protected static String imuTT = "IMU";
protected static String smoothingTT = "Smoothing";
protected static String motionFieldTT = "Motion field";
protected SingleCameraCalibration cameraCalibration = null;
int uidx;
protected boolean useColorForMotionVectors = getBoolean("useColorForMotionVectors", true);
// NPZ ground truth data files from MVSEC
float MVSEC_FPS = 45; // of the MVSEC frames
private double[] tsDataS; // timestamp of frames in MVSEC GT in seconds (to avoid roundoff problems in us
private float[] xOFData;
private float[] yOFData;
private int[] gtOFArrayShape;
// for computing offset to find corresponding GT data for DVS events
private double aeInputStartTimeS = Double.NaN;
private double gtInputStartTimeS = Double.NaN;
private double offsetTimeThatGTStartsAfterRosbagS = Double.NaN;
// for drawing GT flow at a point
private volatile MotionOrientationEventInterface mouseVectorEvent = new ApsDvsMotionOrientationEvent();
private volatile String mouseVectorString = null;
public AbstractMotionFlowIMU(AEChip chip) {
super(chip);
imuFlowEstimator = new ImuFlowEstimator();
dirPacket = new EventPacket(ApsDvsMotionOrientationEvent.class);
filterClassName = getClass().getSimpleName();
FilterChain chain = new FilterChain(chip);
try {
cameraCalibration = new SingleCameraCalibration(chip);
cameraCalibration.setRealtimePatternDetectionEnabled(false);
cameraCalibration.setFilterEnabled(false);
getSupport().addPropertyChangeListener(SingleCameraCalibration.EVENT_NEW_CALIBRATION, this);
chain.add(cameraCalibration);
} catch (Exception e) {
log.warning("could not add calibration for DVS128");
}
setEnclosedFilterChain(chain);
// Labels for setPropertyTooltip.
setPropertyTooltip("LogMotionVectorEvents", "toggles saving motion vector events to a human readable file; auto stops on rewind");
setPropertyTooltip("LogAccuracyStatistics", "toggles logging accuracy statisticcs; automatically stops on rewind");
setPropertyTooltip("logGlobalMotionFlows", "toggle saving global motion flow vectors to a human readable file; auto stops on rewind");
setPropertyTooltip("printStatistics", "<html> Prints to console as log output a single instance of statistics collected since <b>measureAccuracy</b> was selected. (These statistics are reset when the filter is reset, e.g. at rewind.)");
setPropertyTooltip("reseetStatistics", "Reset (clear) statistics collected");
setPropertyTooltip(measureTT, "measureAccuracy", "<html> Writes a txt file with various motion statistics, by comparing the ground truth <br>(either estimated online using an embedded IMUFlow or loaded from file) <br> with the measured optical flow events. <br>This measurment function is called for every event to assign the local ground truth<br> (vxGT,vyGT) at location (x,y) a value from the imported ground truth field (vxGTframe,vyGTframe).");
setPropertyTooltip(measureTT, "measureProcessingTime", "writes a text file with timestamp filename with the packet's mean processing time of an event. Processing time is also logged to console.");
setPropertyTooltip(measureTT, "loggingFolder", "directory to store logged data files");
setPropertyTooltip(measureTT, "statisticsWindowSize", "Window in samples for measuring statistics of global flow, optical flow errors, and processing times");
setPropertyTooltip(dispTT, "ppsScale", "<html>When <i>ppsScaleDisplayRelativeOFLength=false</i>, then this is <br>scale of screen pixels per px/s flow to draw local motion vectors; <br>global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE + "<p>"
+ "When <i>ppsScaleDisplayRelativeOFLength=true</i>, then local motion vectors are scaled by average speed of flow");
setPropertyTooltip(dispTT, "ppsScaleDisplayRelativeOFLength", "<html>Display flow vector lengths relative to global average speed");
setPropertyTooltip(dispTT, "displayVectorsEnabled", "shows local motion vector evemts as arrows");
setPropertyTooltip(dispTT, "displayVectorsAsColorDots", "shows local motion vector events as color dots, rather than arrows");
setPropertyTooltip(dispTT, "displayVectorsAsUnitVectors", "shows local motion vector events with unit vector length");
setPropertyTooltip(dispTT, "displayZeroLengthVectorsEnabled", "shows local motion vector evemts even if they indicate zero motion (stationary features)");
setPropertyTooltip(dispTT, "displayColorWheelLegend", "Plots a color wheel to show flow direction colors.");
setPropertyTooltip(dispTT, "displayGlobalMotion", "shows global tranlational, rotational, and expansive motion. These vectors are scaled by ppsScale * " + GLOBAL_MOTION_DRAWING_SCALE + " pixels/second per chip pixel");
setPropertyTooltip(dispTT, "displayRawInput", "shows the input events, instead of the motion types");
setPropertyTooltip(dispTT, "randomScatterOnFlowVectorOrigins", "scatters flow vectors a bit to show density better");
setPropertyTooltip(dispTT, "xMin", "events with x-coordinate below this are filtered out.");
setPropertyTooltip(dispTT, "xMax", "events with x-coordinate above this are filtered out.");
setPropertyTooltip(dispTT, "yMin", "events with y-coordinate below this are filtered out.");
setPropertyTooltip(dispTT, "yMax", "events with y-coordinate above this are filtered out.");
setPropertyTooltip(dispTT, "motionVectorLineWidthPixels", "line width to draw motion vectors");
setPropertyTooltip(dispTT, "motionVectorTransparencyAlpha", "transparency alpha setting for motion vector rendering");
setPropertyTooltip(dispTT, "useColorForMotionVectors", "display the output motion vectors in color");
setPropertyTooltip(smoothingTT, "subSampleShift", "shift subsampled timestamp map stores by this many bits");
setPropertyTooltip(smoothingTT, "refractoryPeriodUs", "compute no flow vector if a flow vector has already been computed within this period at the same location.");
setPropertyTooltip(smoothingTT, "speedControlEnabled", "enables filtering of excess speeds");
setPropertyTooltip(smoothingTT, "speedControl_ExcessSpeedRejectFactor", "local speeds this factor higher than average are rejected as non-physical");
setPropertyTooltip(smoothingTT, "speedControl_speedMixingFactor", "speeds computed are mixed with old values with this factor");
// setPropertyTooltip(imuTT, "discardOutliersForStatisticalMeasurementEnabled", "discard measured local motion vector if it deviates from IMU estimate");
// setPropertyTooltip(imuTT, "discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg", "threshold angle in degree. Discard measured optical flow vector if it deviates from IMU-estimate by more than discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg");
setPropertyTooltip(imuTT, "lensFocalLengthMm", "lens focal length in mm. Used for computing the IMU flow from pan and tilt camera rotations. 4.5mm is focal length for dataset data.");
setPropertyTooltip(imuTT, "calibrationSamples", "number of IMU samples to average over for measuring IMU offset.");
setPropertyTooltip(imuTT, "startIMUCalibration", "<html> Starts estimating the IMU offsets based on next calibrationSamples samples. Should be used only with stationary recording to store these offsets in the preferences. <p> <b>measureAccuracy</b> must be selected as well to actually do the calibration.");
setPropertyTooltip(imuTT, "eraseIMUCalibration", "Erases the IMU offsets to zero. Can be used to observe effect of these offsets on a stationary recording in the IMUFlow filter.");
setPropertyTooltip(imuTT, "importGTfromMatlab", "Allows importing two 2D-arrays containing the x-/y- components of the motion flow field used as ground truth.");
setPropertyTooltip(imuTT, "importGTfromNPZ", "Allows importing ground truth from numpy uncompressed zip archive of multiple variables file (NPZ); only used for MVSEC dataset.");
setPropertyTooltip(imuTT, "clearGroundTruth", "Clears the ground truth optical flow that was imported from matlab or NPZ files. Used in the measureAccuracy option.");
setPropertyTooltip(imuTT, "selectLoggingFolder", "Allows selection of the folder to store the measured accuracies and optical flow events.");
// setPropertyTooltip(motionFieldTT, "motionFieldMixingFactor", "Flow events are mixed with the motion field with this factor. Use 1 to replace field content with each event, or e.g. 0.01 to update only by 1%.");
setPropertyTooltip(motionFieldTT, "displayMotionField", "computes and shows the average motion field (see MotionField section)");
setPropertyTooltip(motionFieldTT, "motionFieldSubsamplingShift", "The motion field is computed at this subsampled resolution, e.g. 1 means 1 motion field vector for each 2x2 pixel area.");
setPropertyTooltip(motionFieldTT, "maxAgeUs", "Maximum age of motion field value for display and for unconditionally replacing with latest flow event");
setPropertyTooltip(motionFieldTT, "minSpeedPpsToDrawMotionField", "Motion field locations where speed in pixels/second is less than this quantity are not drawn");
setPropertyTooltip(motionFieldTT, "consistentWithNeighbors", "Motion field value must be consistent with several neighbors if this option is selected.");
setPropertyTooltip(motionFieldTT, "consistentWithCurrentAngle", "Motion field value is only updated if flow event angle is in same half plane as current estimate, i.e. has non-negative dot product.");
setPropertyTooltip(motionFieldTT, "motionFieldTimeConstantMs", "Motion field low pass filter time constant in ms.");
setPropertyTooltip(motionFieldTT, "displayMotionFieldColorBlobs", "Shows color blobs for motion field as well as the flow vector arrows");
setPropertyTooltip(motionFieldTT, "displayMotionFieldUsingColor", "Shows motion field flow vectors in color; otherwise shown as monochrome color arrows");
setPropertyTooltip(motionFieldTT, "motionFieldDiffusionEnabled", "Enables an event-driven diffusive averaging of motion field values");
setPropertyTooltip(motionFieldTT, "decayTowardsZeroPeridiclly", "Decays motion field values periodically (with update interval of the time constant) towards zero velocity, i.e. enforce zero flow prior");
File lf = new File(loggingFolder);
if (!lf.exists() || !lf.isDirectory()) {
log.log(Level.WARNING, "loggingFolder {0} doesn't exist or isn't a directory, defaulting to {1}", new Object[]{lf, lf});
setLoggingFolder(System.getProperty("user.dir"));
}
}
synchronized public void doSelectLoggingFolder() {
if (loggingFolder == null || loggingFolder.isEmpty()) {
loggingFolder = System.getProperty("user.dir");
}
JFileChooser chooser = new JFileChooser(loggingFolder);
chooser.setDialogTitle("Choose data logging folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setMultiSelectionEnabled(false);
if (chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame()) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (f != null && f.isDirectory()) {
setLoggingFolder(f.toString());
log.log(Level.INFO, "Selected data logging folder {0}", loggingFolder);
} else {
log.log(Level.WARNING, "Tried to select invalid logging folder named {0}", f);
}
}
}
// Allows importing two 2D-arrays containing the x-/y- components of the
// motion flow field used as ground truth.
synchronized public void doImportGTfromMatlab() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose ground truth file");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(false);
if (chooser.showOpenDialog(chip.getAeViewer().getFilterFrame()) == JFileChooser.APPROVE_OPTION) {
try {
vxGTframe = ((MLDouble) (new MatFileReader(chooser.getSelectedFile().getPath())).getMLArray("vxGT")).getArray();
vyGTframe = ((MLDouble) (new MatFileReader(chooser.getSelectedFile().getPath())).getMLArray("vyGT")).getArray();
tsGTframe = ((MLDouble) (new MatFileReader(chooser.getSelectedFile().getPath())).getMLArray("ts")).getArray();
importedGTfromMatlab = true;
log.info("Imported ground truth file");
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
}
}
}
/**
* Read numpy timestamps of ground truth flow information as provided by
* MVSEC
*
* @param filePath The file full path
* @param scale set scale to scale all value (for flow vector scaling from
* pix to px/s)
* @param progressMonitor a progress monitor to show progress
* @return the final double[] times array
*/
private double[] readNpyTsArray(String filePath, ProgressMonitor progressMonitor) {
if (filePath == null) {
return null;
}
Path p = new File(filePath).toPath();
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
progressMonitor.setMaximum(3);
progressMonitor.setProgress(0);
long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String msg = String.format("<html>Loading Numpy NdArray <br>%s; <p>Free RAM %.1f GB", p.toString(), 1e-9 * presumableFreeMemory);
log.info(msg);
progressMonitor.setNote(msg);
progressMonitor.setProgress(1);
NpyArray a = NpyFile.read(p, 1 << 18);
String err = null;
int[] sh = a.getShape();
if (sh.length != 1) {
err = String.format("Shape of input NpyArray is wrong, got %d dimensions and not 1", sh.length);
}
if (err != null) {
showWarningDialogInSwingThread(err, "Bad timestamp file?");
}
progressMonitor.setProgress(2);
double[] d = a.asDoubleArray();
return d;
}
/**
* Read numpy file with ground truth flow information as provided by MVSEC
*
* @param filePath The file full path
* @param scale set scale to scale all value (for flow vector scaling from
* pix to px/s)
* @param progressMonitor a progress monitor to show progress
* @return the final float[] array which is flattened for the flow u and v
* matrices
*/
private float[] readNpyOFArray(String filePath, float scale, ProgressMonitor progressMonitor) {
if (filePath == null) {
return null;
}
Path p = new File(filePath).toPath();
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
progressMonitor.setMaximum(3);
progressMonitor.setProgress(0);
long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String msg = String.format("<html>Loading Numpy NdArray <br>%s; <p>Free RAM %.1f GB", p.toString(), 1e-9 * presumableFreeMemory);
log.info(msg);
progressMonitor.setNote(msg);
progressMonitor.setProgress(1);
NpyArray a = NpyFile.read(p, 1 << 20); // make it large enough to hold really big array of frames of flow component data
String err = null;
int[] sh = a.getShape();
if (sh.length != 3) {
err = String.format("Shape of input NpyArray is wrong, got %d dimensions and not 3", sh.length);
} else if (sh[1] != chip.getSizeY() || sh[2] != chip.getSizeX()) {
err = String.format("<html>Dimension of NpyArray flow matrix is wrong, got [H=%d,W=%d] pixels, but this chip has [H=%d,W=%d] pixels.<p>Did you choose the correct AEChip and GT file to match?<p>Will assume this array is centered on the AEChip.", sh[1], sh[2], chip.getSizeY(), chip.getSizeX());
}
if (err != null) {
showWarningDialogInSwingThread(err, "Wrong AEChip or wrong GT file?");
}
gtOFArrayShape = a.getShape(); // hack, save the shape of whatever the last flow data to look up values in float[] later.
progressMonitor.setProgress(2);
double[] d = a.asDoubleArray();
allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String msg2 = String.format("<html>Converting %s to float[]<p>Free RAM %.1f GB", p, 1e-9 * presumableFreeMemory);
progressMonitor.setNote(msg2);
float[] f = new float[d.length];
progressMonitor.setMaximum(d.length);
final int checkInterval = 10000;
for (int i = 0; i < d.length; i++) {
f[i] = (float) (scale * (d[i]));
if (i % checkInterval == 0) {
if (progressMonitor.isCanceled()) {
return null;
}
progressMonitor.setProgress(i);
}
}
return f;
}
// Allows importing two 2D-arrays containing the x-/y- components of the
// motion flow field used as ground truth from numpy file .npz.
// Primarily used for MVSEC dataset.
synchronized public void doImportGTfromNPZ() {
// check to ensure a rosbag file is playing already, so that we have starting time of the file
JFileChooser chooser = new JFileChooser(npzFilePath);
chooser.setDialogTitle("Choose ground truth MVSEC extracted folder that has the timestamps, vx and vy .npy files");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// FileFilter filter = new FileNameExtensionFilter("NPZ folder", "npz", "NPZ");
// chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
Component comp = chip.getAeViewer().getFilterFrame();
if (chooser.showOpenDialog(comp) == JFileChooser.APPROVE_OPTION) {
String fileName = chooser.getSelectedFile().getPath();
File dir = new File(fileName);
npzFilePath = dir.toString();
putString("npzFilePath", npzFilePath);
final ProgressMonitor progressMonitor = new ProgressMonitor(comp, "Opening " + npzFilePath, "Reading npy files", 0, 100);
progressMonitor.setMillisToPopup(0);
progressMonitor.setMillisToDecideToPopup(0);
final SwingWorker<Void, Void> worker = new SwingWorker() {
private String checkPaths(String f1, String f2) {
String s = null;
s = npzFilePath + File.separator + f1;
if (Files.isReadable(new File(s).toPath())) {
return s;
}
s = npzFilePath + File.separator + f2;
if (Files.isReadable(new File(s).toPath())) {
return s;
}
return null;
}
@Override
protected Object doInBackground() throws Exception {
try {
chip.getAeViewer().getAePlayer().setPaused(true); // to speed up disk access
System.gc();
if (comp != null) {
comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
tsDataS = readNpyTsArray(checkPaths("timestamps.npy", "ts.npy"), progressMonitor); // don't check size for timestamp array
if (tsDataS == null) {
throw new IOException("could not read timestamps for flow data from " + npzFilePath);
}
gtInputStartTimeS = tsDataS[0];
offsetTimeThatGTStartsAfterRosbagS = ((gtInputStartTimeS - aeInputStartTimeS)); // pos if GT later than DVS
MVSEC_FPS = (float) (1 / (tsDataS[1] - tsDataS[0]));
for (int i = 0; i < tsDataS.length; i++) { // subtract first time from all others
tsDataS[i] -= gtInputStartTimeS;
}
xOFData = readNpyOFArray(checkPaths("x_flow_dist.npy", "x_flow_tensor.npy"), MVSEC_FPS, progressMonitor); // check size for vx, vy arrays
if (xOFData == null) {
throw new IOException("could not read vx flow data from " + npzFilePath);
}
yOFData = readNpyOFArray(checkPaths("y_flow_dist.npy", "y_flow_tensor.npy"), MVSEC_FPS, progressMonitor);
if (yOFData == null) {
throw new IOException("could not read vy flow data from " + npzFilePath);
}
progressMonitor.setMinimum(0);
progressMonitor.setMaximum(2);
progressMonitor.setProgress(0);
progressMonitor.setNote("Running garbage collection and finalization");
System.gc();
progressMonitor.setProgress(1);
System.runFinalization();
progressMonitor.setProgress(2);
progressMonitor.close();
String s = String.format("<html>Imported %,d frames spanning t=[%,g]s<br>from %s. <p>Frame rate is %.1fHz. <p>GT flow starts %.3fs later than rosbag",
tsDataS.length,
(tsDataS[tsDataS.length - 1] - tsDataS[0]), npzFilePath,
MVSEC_FPS,
offsetTimeThatGTStartsAfterRosbagS);
log.info(s);
log.info(String.format("NPZ starts at epoch timestamp %,.3fs", tsDataS[0]));
showPlainMessageDialogInSwingThread(s, "NPZ import succeeded");
importedGTfromNPZ = true;
return true;
} catch (Exception e) {
log.warning("Could not parse, caught " + e.toString());
showWarningDialogInSwingThread("Could not parse, caught " + e.toString(), "NPZ load error");
return e;
} catch (OutOfMemoryError e) {
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
final String s = "<html>Ran out of memory: " + e.toString() + "; increase VM with e.g. -Xmx10000m for 10GB VM in JVM startup"
+ "<p> Presumable free memory now is " + String.format("%,fGB", (float) presumableFreeMemory * 1e-9f);
log.warning(s);
showWarningDialogInSwingThread(s, "Out of memory");
return e;
} finally {
chip.getAeViewer().getAePlayer().setPaused(false); // to speed up disk access
comp.setCursor(Cursor.getDefaultCursor());
}
}
@Override
protected void done() {
progressMonitor.close();
}
};
worker.execute();
}
}
// Allows exporting flow vectors that were accumulated between tmin and tmax
// to a mat-file which can be processed in MATLAB.
public void exportFlowToMatlab(final int tmin, final int tmax) {
if (!exportedFlowToMatlab) {
int firstTs = dirPacket.getFirstTimestamp();
if (firstTs > tmin && firstTs < tmax) {
if (vxOut == null) {
vxOut = new double[sizey][sizex];
vyOut = new double[sizey][sizex];
}
for (Object o : dirPacket) {
ApsDvsMotionOrientationEvent ev = (ApsDvsMotionOrientationEvent) o;
if (ev.hasDirection) {
vxOut[ev.y][ev.x] = ev.velocity.x;
vyOut[ev.y][ev.x] = ev.velocity.y;
}
}
}
if (firstTs > tmax && vxOut != null) {
ArrayList list = new ArrayList();
list.add(new MLDouble("vx", vxOut));
list.add(new MLDouble("vy", vyOut));
try {
MatFileWriter matFileWriter = new MatFileWriter(loggingFolder + "/flowExport.mat", list);
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
}
log.log(Level.INFO, "Exported motion flow to {0}/flowExport.mat", loggingFolder);
exportedFlowToMatlab = true;
vxOut = null;
vyOut = null;
}
}
}
void clearGroundTruth() {
importedGTfromMatlab = false;
vxGTframe = null;
vyGTframe = null;
tsGTframe = null;
vxGT = 0;
vyGT = 0;
vGT = 0;
tsDataS = null;
xOFData = null;
yOFData = null;
importedGTfromNPZ = false;
}
synchronized public void doClearGroundTruth() {
clearGroundTruth();
}
/**
* @return the useColorForMotionVectors
*/
public boolean isUseColorForMotionVectors() {
return useColorForMotionVectors;
}
/**
* @param useColorForMotionVectors the useColorForMotionVectors to set
*/
public void setUseColorForMotionVectors(boolean useColorForMotionVectors) {
this.useColorForMotionVectors = useColorForMotionVectors;
putBoolean("useColorForMotionVectors", useColorForMotionVectors);
}
// <editor-fold defaultstate="collapsed" desc="ImuFlowEstimator Class">
public class ImuFlowEstimator {
// Motion flow from IMU gyro values or GT file
private float vx;
private float vy;
private float v;
// Highpass filters for angular rates.
private float panRateDps, tiltRateDps, rollRateDps; // In deg/s
// Calibration
private boolean calibrating = false; // used to flag cameraCalibration state
private int calibrationSamples = getInt("calibrationSamples", 100); // number of samples, typically they come at 1kHz
private final Measurand panCalibrator, tiltCalibrator, rollCalibrator;
private float panOffset;
private float tiltOffset;
private float rollOffset;
private boolean calibrated = false;
// Deal with leftover IMU data after timestamps reset
private static final int FLUSH_COUNT = 1;
private int flushCounter;
protected ImuFlowEstimator() {
panCalibrator = new Measurand();
tiltCalibrator = new Measurand();
rollCalibrator = new Measurand();
// Some initial IMU cameraCalibration values.
// Will be overwritten when calibrating IMU
panOffset = getFloat("panOffset", 0);
tiltOffset = getFloat("tiltOffset", 0);
rollOffset = getFloat("rollOffset", 0); // tobi set back to zero rather than using hard coded values.
if (panOffset != 0 || rollOffset != 0 || tiltOffset != 0) {
log.warning("using existing calibration (offset) IMU rate gyro values stored in preferences: " + this.toString());
calibrated = true;
}
reset();
}
protected final synchronized void reset() {
flushCounter = FLUSH_COUNT;
panRateDps = 0;
tiltRateDps = 0;
rollRateDps = 0;
radPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * lensFocalLengthMm));
vx = 0;
vy = 0;
v = 0;
}
float getVx() {
return vx;
}
float getVy() {
return vy;
}
float getV() {
return v;
}
boolean isCalibrationSet() {
return calibrated;
}
private int imuFlowGTWarnings = 0;
final private int GT_Flow_WarningsPrintedInterval = 100000;
/**
* Calculate GT motion flow from IMU sample.
*
* @param o event
* @return true if flow is computed, either from IMU sample or GT flow
* loaded from file. If event is an IMU event, so enclosing loop can
* continue to next event, skipping flow processing of this IMU event.
*
* Return false if event is real event or no flow available. Return true
* if IMU event or calibration loaded that lables every time with GT
* flow for x,y address.
*/
public boolean calculateImuFlow(Object o) {
if (importedGTfromMatlab) {
if (ts >= tsGTframe[0][0] && ts < tsGTframe[0][1]) {
vx = (float) vxGTframe[y][x];
vy = (float) vyGTframe[y][x];
v = (float) Math.sqrt(vx * vx + vy * vy);
} else {
vx = 0;
vy = 0;
}
return false;
} else if (importedGTfromNPZ) {
if (!(o instanceof ApsDvsEvent)) {
return true; // continue processing this event outside
}
ApsDvsEvent e = (ApsDvsEvent) o;
if (getChip().getAeViewer().getAePlayer().getAEInputStream() == null) {
return false;
}
double tsRelativeToStartS = 1e-6 * ((e.timestamp - getChip().getAeViewer().getAePlayer().getAEInputStream().getFirstTimestamp()));
if (Double.isNaN(offsetTimeThatGTStartsAfterRosbagS)) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("Offset between starting times of GT flow and rosbag input not available"));
}
return false;
}
if (tsRelativeToStartS - offsetTimeThatGTStartsAfterRosbagS < 0 || tsRelativeToStartS - offsetTimeThatGTStartsAfterRosbagS >= (tsDataS[tsDataS.length - 1] - tsDataS[0])) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("Cannot find NPZ file flow for time relative to rosbag start of %.3fs in tsData from NPZ GT; data starts at offset %.3fs",
tsRelativeToStartS, offsetTimeThatGTStartsAfterRosbagS));
}
return false;
}
// int frameIdx = (int) (ts / (MVSEC_FPS * 1000)); // MVSEC's OF is updated at 45 MVSEC_FPS
int frameIdx = Math.abs(Arrays.binarySearch(tsDataS, tsRelativeToStartS - offsetTimeThatGTStartsAfterRosbagS)) - 2;
// minus 2 is because for timestamps less than the 2nd time (the first time is zero),
// the insertion point would be 1, so binarySearch returns -1-1=-2 but we want 0 for the frameIdx
/* binarySearch Returns:
index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).
The insertion point is defined as the point at which the key would be inserted into the array:
the index of the first element greater than the key, or a.length if all elements in the array are
less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
*/
if (frameIdx < 0 || frameIdx >= tsDataS.length) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("Cannot find GT flow for relative to start ts=%,.6fs in tsData from NPZ GT, resulting frameIdx=%,d is outside tsData times array bounds [%,.0f,%,.0f] s", tsRelativeToStartS, frameIdx, tsDataS[0], tsDataS[tsDataS.length - 1]));
}
vx = 0;
vy = 0;
v = 0;
return false;
}
final int cpix = chip.getNumPixels();
final int cx = chip.getSizeX(), cy = chip.getSizeY();
final int sx = gtOFArrayShape[2], sy = gtOFArrayShape[1], npix = sx * sy; // the loaded GT or EV-Flownet shape is used to look up values
// now find the GT flow. Assume the GT array is centered on the chip
// subtract from the event address half of the difference in width and height
final int ex = e.x - ((cx - sx) / 2), ey = e.y - ((cy - sy) / 2);
if (ex < 0 || ex >= sx || ey < 0 || ey >= sy) {
vx = 0;
vy = 0;
v = 0;
return false;
}
final int idx = (frameIdx * npix) + ((sy - 1 - ey) * sx) + ex;
if (idx < 0 || idx > xOFData.length) {
if (imuFlowGTWarnings++ % GT_Flow_WarningsPrintedInterval == 0) {
log.warning(String.format("idx=%,d is outside bounds of the flow arrays", idx));
}
return false;
}
vx = (float) xOFData[idx];
vy = (float) yOFData[idx];
vy = -vy; // flip for jAER coordinate frame starting at LL corner
v = (float) Math.sqrt(vx * vx + vy * vy);
return false;
}
if (!(o instanceof ApsDvsEvent)) {
return true; // continue processing this event outside
}
ApsDvsEvent e = (ApsDvsEvent) o;
if (e.isImuSample()) {
IMUSample imuSample = e.getImuSample();
float panRateDpsSample = imuSample.getGyroYawY(); // update pan tilt roll state from IMU
float tiltRateDpsSample = imuSample.getGyroTiltX();
float rollRateDpsSample = imuSample.getGyroRollZ();
if (calibrating) {
if (panCalibrator.getN() > getCalibrationSamples()) {
calibrating = false;
panOffset = (float) panCalibrator.getMean();
tiltOffset = (float) tiltCalibrator.getMean();
rollOffset = (float) rollCalibrator.getMean();
log.info(String.format("calibration finished. %,d samples averaged"
+ " to (pan,tilt,roll)=(%.3f,%.3f,%.3f)", getCalibrationSamples(), panOffset, tiltOffset, rollOffset));
calibrated = true;
putFloat("panOffset", panOffset);
putFloat("tiltOffset", tiltOffset);
putFloat("rollOffset", rollOffset);
} else {
panCalibrator.addValue(panRateDpsSample);
tiltCalibrator.addValue(tiltRateDpsSample);
rollCalibrator.addValue(rollRateDpsSample);
}
return false;
}
panRateDps = panRateDpsSample - panOffset;
tiltRateDps = tiltRateDpsSample - tiltOffset;
rollRateDps = rollRateDpsSample - rollOffset;
return true;
} else {
// otherwise, if not IMU sample, use last IMU sample to compute GT flow from last IMU sample and event location
// then transform, then move them back to their origin.
//
// The flow is computed from trigonometry assuming a pinhole lens. This lens projects points at larger angular distance with
// smaller pixel spacing. i.e. the math is the following.
// If the distance of the pixel from the middle of the image is l, the angle to the point is w, the focal length is f, then
// tan(w)=l/f,
// and dl/dt=f dw/dt (sec^2(w))
int nx = e.x - sizex / 2; // TODO assumes principal point is at center of image
int ny = e.y - sizey / 2;
// panRateDps=0; tiltRateDps=0; // debug
final float rrrad = -(float) (rollRateDps * Math.PI / 180);
final float radfac = (float) (Math.PI / 180);
final float pixfac = radfac / radPerPixel;
final float pixdim = chip.getPixelWidthUm() * 1e-3f;
final float thetax = (float) Math.atan2(nx * pixdim, lensFocalLengthMm);
final float secx = (float) (1f / Math.cos(thetax));
final float xprojfac = (float) (secx * secx);
final float thetay = (float) Math.atan2(ny * pixdim, lensFocalLengthMm);
final float secy = (float) (1f / Math.cos(thetay));
final float yprojfac = (float) (secy * secy);
vx = -(float) (-ny * rrrad + panRateDps * pixfac) * xprojfac;
vy = -(float) (nx * rrrad - tiltRateDps * pixfac) * yprojfac;
v = (float) Math.sqrt(vx * vx + vy * vy);
}
return false;
}
/**
* @return the calibrationSamples
*/
public int getCalibrationSamples() {
return calibrationSamples;
}
/**
* @param calibrationSamples the calibrationSamples to set
*/
public void setCalibrationSamples(int calibrationSamples) {
this.calibrationSamples = calibrationSamples;
}
@Override
public String toString() {
return "ImuFlowEstimator{" + "panOffset=" + panOffset + ", tiltOffset=" + tiltOffset + ", rollOffset=" + rollOffset + ", flushCounter=" + flushCounter + '}';
}
private void eraseIMUCalibration() {
panOffset = 0;
tiltOffset = 0;
rollOffset = 0;
calibrated = false;
putFloat("panOffset", panOffset);
putFloat("tiltOffset", tiltOffset);
putFloat("rollOffset", rollOffset);
log.info("IMU calibration erased (all offsets set to zero)");
}
/**
*
* @return the panRateDps in deg/s
*/
public float getPanRateDps() {
return panRateDps;
}
/**
* @return the tiltRateDps in deg/s
*/
public float getTiltRateDps() {
return tiltRateDps;
}
/**
* @return the rollRateDps in deg/s
*/
public float getRollRateDps() {
return rollRateDps;
}
}
// </editor-fold>
@Override
public abstract EventPacket filterPacket(EventPacket in);
synchronized void allocateMaps() {
subsampledPixelIsSet = new boolean[subSizeX][subSizeY];
lastTimesMap = new int[subSizeX][subSizeY][numInputTypes];
resetMaps();
}
protected void resetMaps() {
for (boolean[] a : subsampledPixelIsSet) {
Arrays.fill(a, false);
}
for (int[][] a : lastTimesMap) {
for (int[] b : a) {
Arrays.fill(b, Integer.MIN_VALUE);
}
}
}
@Override
public synchronized void resetFilter() {
if (measureAccuracy || measureProcessingTime && (motionFlowStatistics != null && motionFlowStatistics.getSampleCount() > 0)) {
doPrintStatistics();
}
resetMaps();
imuFlowEstimator.reset();
exportedFlowToMatlab = false;
motionField.reset();
motionFlowStatistics.reset(subSizeX, subSizeY, statisticsWindowSize);
if ("DirectionSelectiveFlow".equals(filterClassName) && getEnclosedFilter() != null) {
getEnclosedFilter().resetFilter();
}
setXMax(chip.getSizeX());
setYMax(chip.getSizeY());
}
@Override
public void initFilter() {
sizex = chip.getSizeX();
sizey = chip.getSizeY();
subSizeX = sizex >> subSampleShift;
subSizeY = sizey >> subSampleShift;
motionFlowStatistics = new MotionFlowStatistics(filterClassName, subSizeX, subSizeY, statisticsWindowSize);
if (chip.getAeViewer() != null) {
chip.getAeViewer().getSupport().addPropertyChangeListener(this); // AEViewer refires these events for convenience
}
allocateMaps();
setMeasureAccuracy(getBoolean("measureAccuracy", true));
setMeasureProcessingTime(getBoolean("measureProcessingTime", false));
setDisplayGlobalMotion(getBoolean("displayGlobalMotion", true));// these setters set other flags, so call them to set these flags to default values
resetFilter();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case AEViewer.EVENT_TIMESTAMPS_RESET:
if (isFilterEnabled()) {
resetFilter();
}
break;
case AEInputStream.EVENT_REWOUND:
case AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP:
case AEInputStream.EVENT_REPOSITIONED:
if (isFilterEnabled()) {
log.info(evt.toString() + ": resetting filter after printing collected statistics if measurement enabled");
doToggleOffLogGlobalMotionFlows();
doToggleOffLogMotionVectorEvents();
doToggleOffLogAccuracyStatistics();
}
break;
case AEViewer.EVENT_FILEOPEN:
log.info("EVENT_FILEOPEN=" + evt.toString());
if ((chip.getAeViewer() != null) && (chip.getAeViewer().getAePlayer().getAEInputStream() instanceof RosbagFileInputStream)) {
RosbagFileInputStream rosbag = (RosbagFileInputStream) chip.getAeViewer().getAePlayer().getAEInputStream();
aeInputStartTimeS = rosbag.getStartAbsoluteTimeS();
offsetTimeThatGTStartsAfterRosbagS = ((gtInputStartTimeS - aeInputStartTimeS)); // pos if GT later than DVS
// showPlainMessageDialogInSwingThread("Opened a rosbag file input stream", "Opened Rosbag first");
}
if (isFilterEnabled()) {
resetFilter();
}
break;
case AEViewer.EVENT_CHIP:
clearGroundTruth(); // save a lot of memory
break;
}
super.propertyChange(evt); // call super.propertyChange() after we have processed event here first, to e.g. print statistics
}
/**
* Draw a motion vector at location x,y with velocity vx, vy
*
* @param gl GL2 context
* @param x x location
* @param y y location
* @param vx x component of velocity in px/s
* @param vy y component in px/s
* @return the float[] RGBA color used to draw the vector
*/
protected float[] drawMotionVector(GL2 gl, int x, int y, float vx, float vy) {
float[] rgba = null;
if (useColorForMotionVectors) {
rgba = motionColor(vx, vy, 1, 1);
} else {
rgba = new float[]{0, 0, 1, motionVectorTransparencyAlpha};
}
gl.glColor4fv(rgba, 0);
float scale = ppsScale;
if (ppsScaleDisplayRelativeOFLength && displayGlobalMotion) {
scale = 100 * ppsScale / motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
}
if (displayVectorsEnabled) {
gl.glPushMatrix();
gl.glLineWidth(motionVectorLineWidthPixels);
// start arrow from event
// DrawGL.drawVector(gl, e.getX() + .5f, e.getY() + .5f, e.getVelocity().x, e.getVelocity().y, motionVectorLineWidthPixels, ppsScale);
// center arrow on location, rather that start from event location
float dx, dy;
dx = vx * scale;
dy = vy * scale;
if (displayVectorsAsUnitVectors) {
float s = 100 * scale / (float) Math.sqrt(dx * dx + dy * dy);
dx *= s;
dy *= s;
}
float x0 = x - (dx / 2) + .5f, y0 = y - (dy / 2) + .5f;
float rx = 0, ry = 0;
if (randomScatterOnFlowVectorOrigins) {
rx = RANDOM_SCATTER_PIXELS * (random.nextFloat() - .5f);
ry = RANDOM_SCATTER_PIXELS * (random.nextFloat() - .5f);
}
DrawGL.drawVector(gl, x0 + rx, y0 + ry, dx, dy, motionVectorLineWidthPixels / 2, 1);
gl.glPopMatrix();
}
if (displayVectorsAsColorDots) {
gl.glPointSize(motionVectorLineWidthPixels * 5);
gl.glEnable(GL2.GL_POINT_SMOOTH);
gl.glBegin(GL.GL_POINTS);
gl.glVertex2f(e.getX(), e.getY());
gl.glEnd();
}
return rgba;
}
/**
* Plots a single motion vector which is the number of pixels per second
* times scaling. Color vectors by angle to x-axis.
*
* @param gl the OpenGL context
* @return the float[] RGBA color used to draw the vector
*/
protected float[] drawMotionVector(GL2 gl, MotionOrientationEventInterface e) {
return drawMotionVector(gl, e.getX(), e.getY(), (float) e.getVelocity().getX(), (float) e.getVelocity().getY());
}
protected float[] motionColor(float angle) {
return motionColor((float) Math.cos(angle), (float) Math.sin(angle), 1, 1);
}
protected float[] motionColor(float angle, float saturation, float brightness) {
return motionColor((float) Math.cos(angle), (float) Math.sin(angle), saturation, brightness);
}
protected float[] motionColor(MotionOrientationEventInterface e1) {
return motionColor(e1.getVelocity().x, e1.getVelocity().y, 1, 1);
}
/**
* Returns a motion barb vector color including transparency
*
* @param x x component of velocity
* @param y y component of velocity
* @param saturation
* @param brightness
* @return float[] with 4 components RGBA
*/
protected float[] motionColor(float x, float y, float saturation, float brightness) {
float angle01 = (float) (Math.atan2(y, x) / (2 * Math.PI) + 0.5);
// atan2 returns -pi to +pi, so dividing by 2*pi gives -.5 to +.5. Adding .5 gives range 0 to 1.
// angle01=.5f; // debug
int rgbValue = Color.HSBtoRGB(angle01, saturation, brightness);
Color color = new Color(rgbValue);
float[] c = color.getRGBComponents(null);
return new float[]{c[0], c[1], c[2], motionVectorTransparencyAlpha};
}
@Override
public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
GL2 gl = drawable.getGL().getGL2();
if (gl == null) {
return;
}
// Draw individual motion vectors
if (dirPacket != null && (displayVectorsEnabled || displayVectorsAsColorDots)) {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_DST_COLOR);
gl.glBlendEquation(GL.GL_FUNC_ADD);
for (Object o : dirPacket) {
MotionOrientationEventInterface ei = (MotionOrientationEventInterface) o;
// If we passAllEvents then the check is needed to not annotate
// the events without a real direction.
if (ei.isHasDirection()) {
drawMotionVector(gl, ei);
} else if (displayZeroLengthVectorsEnabled) {
gl.glPushMatrix();
gl.glTranslatef(ei.getX(), ei.getY(), 0);
gl.glPointSize(motionVectorLineWidthPixels * 2);
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_POINTS);
gl.glVertex2i(0, 0);
gl.glEnd();
gl.glPopMatrix();
}
}
gl.glDisable(GL.GL_BLEND);
// draw scale bar vector at bottom
gl.glPushMatrix();
float speed = (chip.getSizeX() / 2);
if (displayGlobalMotion) {
speed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
}
DvsMotionOrientationEvent e = new DvsMotionOrientationEvent();
final int px = 10, py = -10;
float[] rgba = drawMotionVector(gl, px, py, speed, 0);
gl.glRasterPos2f(px + 100 * ppsScale, py); // use same scaling
String s = null;
if (displayGlobalMotion) {
s = String.format("%.1f px/s avg. speed and OF vector scale", speed);
} else {
s = String.format("%.1f px/s OF scale", speed);
}
// gl.glColor3f(1, 1, 1);
DrawGL.drawString(gl, 10, px, py, 0, new Color(rgba[0], rgba[1], rgba[2], rgba[3]), s);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glPopMatrix();
}
if (isDisplayGlobalMotion()) {
gl.glLineWidth(getMotionVectorLineWidthPixels() * 4);
gl.glColor3f(1, 1, 1);
// Draw global translation vector
gl.glPushMatrix();
DrawGL.drawVector(gl, sizex / 2, sizey / 2,
motionFlowStatistics.getGlobalMotion().meanGlobalVx,
motionFlowStatistics.getGlobalMotion().meanGlobalVy,
4, ppsScale * GLOBAL_MOTION_DRAWING_SCALE);
gl.glRasterPos2i(2, 10);
String flowMagPps = engFmt.format(motionFlowStatistics.getGlobalMotion().meanGlobalTrans);
chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
String.format("glob. trans.=%s px/s (local: %s)", flowMagPps, ppsScaleDisplayRelativeOFLength ? "rel." : "abs."));
gl.glPopMatrix();
// System.out.println(String.format("%5.3f\t%5.2f",ts*1e-6f, motionFlowStatistics.getGlobalMotion().meanGlobalTrans)); // debug
// draw quartiles statistics ellipse
gl.glPushMatrix();
gl.glTranslatef(sizex / 2 + motionFlowStatistics.getGlobalMotion().meanGlobalVx * ppsScale,
sizey / 2 + motionFlowStatistics.getGlobalMotion().meanGlobalVy * ppsScale,
0);
DrawGL.drawEllipse(gl, 0, 0, (float) motionFlowStatistics.getGlobalMotion().sdGlobalVx * ppsScale,
(float) motionFlowStatistics.getGlobalMotion().sdGlobalVy * ppsScale,
0, 16);
gl.glPopMatrix();
// Draw global rotation vector as line left/right
gl.glPushMatrix();
DrawGL.drawLine(gl,
sizex / 2,
sizey * 3 / 4,
(float) (-motionFlowStatistics.getGlobalMotion().getGlobalRotation().getMean()),
0, ppsScale * GLOBAL_MOTION_DRAWING_SCALE);
gl.glPopMatrix();
// Draw global expansion as circle with radius proportional to
// expansion metric, smaller for contraction, larger for expansion
gl.glPushMatrix();
DrawGL.drawCircle(gl, sizex / 2, sizey / 2, ppsScale * GLOBAL_MOTION_DRAWING_SCALE
* (1 + motionFlowStatistics.getGlobalMotion().meanGlobalExpansion), 15);
gl.glPopMatrix();
}
if (displayColorWheelLegend) {
final int segments = 16;
final float scale = 15;
gl.glPushMatrix();
gl.glTranslatef(-20, chip.getSizeY() / 2, 0);
gl.glScalef(scale, scale, 1);
for (float val01 = 0; val01 < 1; val01 += 1f / segments) {
float[] rgb = motionColor((float) ((val01 - .5f) * 2 * Math.PI), 1f, .5f);
gl.glColor3fv(rgb, 0);
// gl.glLineWidth(motionVectorLineWidthPixels);
// final double angleRad = 2*Math.PI*(val01-.5f);
// DrawGL.drawVector(gl, 0,0,(float)Math.cos(angleRad), (float)Math.sin(angleRad),.3f,2);
final float angle0 = (val01 - .5f) * 2 * (float) Math.PI;
final float angle1 = ((val01 - .5f) + 1f / segments) * 2 * (float) Math.PI;
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor4f(rgb[0], rgb[1], rgb[2], 1f);
gl.glVertex3d(0, 0, 0);
gl.glVertex3d(Math.cos(angle0), Math.sin(angle0), 0);
gl.glVertex3d(Math.cos(angle1), Math.sin(angle1), 0);
gl.glEnd();
}
gl.glPopMatrix();
}
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 1);
// Display statistics
if (measureProcessingTime) {
gl.glPushMatrix();
gl.glRasterPos2i(chip.getSizeX(), 0);
chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
String.format("%4.2f +/- %5.2f us", new Object[]{
motionFlowStatistics.processingTime.getMean(),
motionFlowStatistics.processingTime.getStandardDeviation()}));
gl.glPopMatrix();
}
if (measureAccuracy) {
MultilineAnnotationTextRenderer.resetToYPositionPixels(-20);
// MultilineAnnotationTextRenderer.setDefaultScale();
MultilineAnnotationTextRenderer.setScale(.4f);
// MultilineAnnotationTextRenderer.setFontSize(24);
String s = String.format("Accuracy statistics:%n%s%n%s%n%s",
motionFlowStatistics.endpointErrorAbs.graphicsString("AEE:", "px/s"),
motionFlowStatistics.endpointErrorRel.graphicsString("AREE:", "%"),
motionFlowStatistics.angularError.graphicsString("AAE:", "deg"),
String.format("Outliers (>%.0f px/s error): %.1f%%", motionFlowStatistics.OUTLIER_ABS_PPS, motionFlowStatistics.getOutlierPercentage()));
MultilineAnnotationTextRenderer.renderMultilineString(s);
// gl.glPushMatrix();
// final int ystart = -15, yoffset = -10, xoffset = 10;
// gl.glRasterPos2i(xoffset, ystart + yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.endpointErrorAbs.graphicsString("AEE(abs):", "px/s"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 2 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.endpointErrorRel.graphicsString("AEE(rel):", "%"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 3 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.angularError.graphicsString("AAE:", "deg"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 4 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// motionFlowStatistics.eventDensity.graphicsString("Density:", "%"));
// gl.glPopMatrix();
// gl.glPushMatrix();
// gl.glRasterPos2i(xoffset, ystart + 5 * yoffset);
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18,
// String.format("Outliers (>%.0f px/s error): %.1f%%", motionFlowStatistics.OUTLIER_ABS_PPS, motionFlowStatistics.getOutlierPercentage()));
// gl.glPopMatrix();
}
motionField.draw(gl);
// draw the mouse vector GT flow event
if (mouseVectorEvent != null && mouseVectorString != null) {
gl.glPushMatrix();
drawMotionVector(gl, mouseVectorEvent);
DrawGL.drawString(drawable, 20, (float) mouseVectorEvent.getX() / chip.getSizeX(), (float) mouseVectorEvent.getY() / chip.getSizeY(), .5f, Color.yellow, mouseVectorString);
gl.glPopMatrix();
}
}
synchronized public void setupFilter(EventPacket in) {
maybeAddListeners(chip);
inItr = in.iterator();
outItr = dirPacket.outputIterator();
subsampledPixelIsSet = new boolean[subSizeX][subSizeY];
countIn = 0;
countOut = 0;
countOutliers = 0;
if (measureProcessingTime) {
motionFlowStatistics.processingTime.startTime = System.nanoTime();
}
motionField.checkArrays();
getEnclosedFilterChain().filterPacket(in);
}
/**
* @return true if ... 1) the event lies outside the chip. 2) the event's
* subsampled address falls on a pixel location that has already had an
* event within this packet. We don't want to process or render it.
* Important: This prevents events to acccumulate at the same pixel
* location, which is an essential part of the Lucas-Kanade method.
* Therefore, subsampling should be avoided in LucasKanadeFlow when the goal
* is to optimize accuracy.
* @param d equals the spatial search distance plus some extra spacing
* needed for applying finite differences to calculate gradients.
*/
protected synchronized boolean isInvalidAddress(int d) {
if (x >= d && y >= d && x < subSizeX - d && y < subSizeY - d) {
if (subSampleShift > 0 && !subsampledPixelIsSet[x][y]) {
subsampledPixelIsSet[x][y] = true;
}
return false;
}
return true;
}
// Returns true if the event lies outside certain spatial bounds.
protected boolean xyFilter() {
return x < xMin || x >= xMax || y < yMin || y >= yMax;
}
/**
* returns true if timestamp is invalid, e.g. if the timestamp is LATER
* (nonmonotonic) or is too soon after the last event from the same pixel
* |refractoryPeriodUs). Does NOT check for events that are too old relative
* to the current event.
* <p>
* If the event is nonmonotonic, triggers a resetFilter()
*
* @return true if invalid timestamp, older than refractoryPeriodUs ago
*/
protected synchronized boolean isInvalidTimestamp() {
lastTs = lastTimesMap[x][y][type];
lastTimesMap[x][y][type] = ts;
if (ts < lastTs) {
log.warning(String.format("invalid timestamp ts=%,d < lastTs=%,d, resetting filter", ts, lastTs));
resetFilter(); // For NonMonotonicTimeException.
}
return ts < lastTs + refractoryPeriodUs;
}
/**
* extracts the event into to fields e, x,y,ts,type. x and y are in
* subsampled address space
*
* @param ein input event
* @return true if result is in-bounds, false if not, which can occur when
* the camera cameraCalibration magnifies the address beyond the sensor
* coordinates
*/
protected synchronized boolean extractEventInfo(Object ein) {
e = (PolarityEvent) ein;
// If camera calibrated, undistort pixel locations
x = e.x >> subSampleShift;
y = e.y >> subSampleShift;
ts = e.getTimestamp();
type = e.getPolarity() == PolarityEvent.Polarity.Off ? 0 : 1;
return true;
}
/**
* Takes output event eout and logs it
*
*/
synchronized public void processGoodEvent() {
// Copy the input event to a new output event and appendCopy the computed optical flow properties
eout = (ApsDvsMotionOrientationEvent) outItr.nextOutput();
eout.copyFrom(e);
eout.x = (short) (x << subSampleShift);
eout.y = (short) (y << subSampleShift);
eout.velocity.x = vx;
eout.velocity.y = vy;
eout.speed = v;
eout.hasDirection = v != 0;
if (v != 0) {
countOut++;
}
if (measureAccuracy) {
vxGT = imuFlowEstimator.getVx();
vyGT = imuFlowEstimator.getVy();
vGT = imuFlowEstimator.getV();
getMotionFlowStatistics().update(vx, vy, v, vxGT, vyGT, vGT);
}
if (displayGlobalMotion || ppsScaleDisplayRelativeOFLength) {
motionFlowStatistics.getGlobalMotion().update(vx, vy, v, eout.x, eout.y);
}
if (motionVectorEventLogger != null && motionVectorEventLogger.isEnabled()) {
if (getClass().getSimpleName().equals("PatchMatchFlow")) {
try {
Method sliceIndexMethod;
sliceIndexMethod = getClass().getDeclaredMethod("sliceIndex", Integer.TYPE);
sliceIndexMethod.setAccessible(true);
Object currentSliceIdxObj = sliceIndexMethod.invoke(this, 1);
int currentSliceIdx = (int) currentSliceIdxObj;
Field startTimeFiled = getClass().getDeclaredField("sliceStartTimeUs");
startTimeFiled.setAccessible(true);
Object sliceTminus1StartTime = startTimeFiled.get((PatchMatchFlow) this);
int[] sliceStartTimeUs = (int[]) sliceTminus1StartTime;
Field endTimeFiled = getClass().getDeclaredField("sliceEndTimeUs");
endTimeFiled.setAccessible(true);
Object sliceTminus1EndTime = endTimeFiled.get((PatchMatchFlow) this);
int[] sliceEndTimeUs = (int[]) sliceTminus1EndTime;
String s = String.format("%d %d %d %d %d %d %.3g %.3g %.3g %d", eout.timestamp,
sliceStartTimeUs[currentSliceIdx], sliceEndTimeUs[currentSliceIdx],
eout.x, eout.y, eout.type, eout.velocity.x, eout.velocity.y, eout.speed, eout.hasDirection ? 1 : 0);
motionVectorEventLogger.log(s);
} catch (NoSuchFieldException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(AbstractMotionFlowIMU.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String s = String.format("%d %d %d %d %.3g %.3g %.3g %d", eout.timestamp, eout.x, eout.y, eout.type, eout.velocity.x, eout.velocity.y, eout.speed, eout.hasDirection ? 1 : 0);
motionVectorEventLogger.log(s);
}
}
motionField.update(ts, x, y, vx, vy, v);
}
/**
* Returns true if motion event passes accuracy tests
*
* @return true if event is accurate enough, false if it should be rejected.
*/
synchronized public boolean accuracyTests() {
// 1.) Filter out events with speed high above average.
// 2.) Filter out events whose velocity deviates from IMU estimate by a
// certain degree.
return speedControlEnabled && isSpeeder() || discardOutliersForStatisticalMeasurementEnabled
&& Math.abs(motionFlowStatistics.angularError.calculateError(vx, vy, v, vxGT, vyGT, vGT))
> discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg;
}
// <editor-fold defaultstate="collapsed" desc="Speed Control">
protected boolean isSpeeder() {
// Discard events if velocity is too far above average
avgSpeed = (1 - speedMixingFactor) * avgSpeed + speedMixingFactor * v;
return v > avgSpeed * excessSpeedRejectFactor;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="IMUCalibration Start and Reset buttons">
synchronized public void doStartIMUCalibration() {
imuFlowEstimator.calibrating = true;
imuFlowEstimator.calibrated = false;
imuFlowEstimator.panCalibrator.clear();
imuFlowEstimator.tiltCalibrator.clear();
imuFlowEstimator.rollCalibrator.clear();
if (measureAccuracy) {
log.info("IMU calibration started");
} else {
log.warning("IMU calibration flagged, but will not start until measureAccuracy is selected");
}
}
synchronized public void doEraseIMUCalibration() {
imuFlowEstimator.eraseIMUCalibration();
}
// </editor-fold>
WarningDialogWithDontShowPreference imuWarningDialog;
synchronized public void doResetStatistics() {
if (motionFlowStatistics != null) {
motionFlowStatistics.reset(subSizeX, subSizeY, statisticsWindowSize);
}
}
// <editor-fold defaultstate="collapsed" desc="Statistics logging trigger button">
synchronized public void doPrintStatistics() {
if (motionFlowStatistics.getSampleCount() == 0) {
log.warning("No samples collected");
return;
}
log.log(Level.INFO, "{0}\n{1}", new Object[]{this.getClass().getSimpleName(), motionFlowStatistics.toString()});
if (!imuFlowEstimator.isCalibrationSet()) {
log.warning("IMU has not been calibrated yet! Load a file with no camera motion and hit the StartIMUCalibration button");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (imuWarningDialog != null) {
imuWarningDialog.setVisible(false);
imuWarningDialog.dispose();
}
imuWarningDialog = new WarningDialogWithDontShowPreference(null, false, "Uncalibrated IMU",
"<html>IMU has not been calibrated yet! <p>Load a file with no camera motion and hit the StartIMUCalibration button");
imuWarningDialog.setVisible(true);
}
});
} else if (imuWarningDialog != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (imuWarningDialog != null) {
imuWarningDialog.setVisible(false);
imuWarningDialog.dispose();
}
}
});
}
}
// </editor-fold>
synchronized public void doToggleOnLogMotionVectorEvents() {
if (motionVectorEventLogger != null && motionVectorEventLogger.isEnabled()) {
log.info("logging already started");
return;
}
String filename = null, filepath = null;
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(getString("lastFile", System.getProperty("user.dir")))); // defaults to startup runtime folder
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
fc.setDialogTitle("Select folder and base file name for the logged motion vector event data");
int ret = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putString("lastFile", file.toString());
motionVectorEventLogger = new TobiLogger(file.getPath(), "Motion vector events output from normal optical flow method");
motionVectorEventLogger.setNanotimeEnabled(false);
if (getClass().getSimpleName().equals("PatchMatchFlow")) {
motionVectorEventLogger.setColumnHeaderLine("timestamp(us) sliceStartTime(us) sliceEndTime(us) x y type vx(pps) vy(pps) speed(pps) validity");
motionVectorEventLogger.setSeparator(" ");
} else {
motionVectorEventLogger.setColumnHeaderLine("timestamp(us) x y type vx(pps) vy(pps) speed(pps) validity");
motionVectorEventLogger.setSeparator(" ");
}
motionVectorEventLogger.setEnabled(true);
} else {
log.info("Cancelled logging motion vectors");
}
}
synchronized public void doToggleOffLogMotionVectorEvents() {
if (motionVectorEventLogger == null) {
return;
}
log.info("stopping motion vector logging from " + motionVectorEventLogger);
motionVectorEventLogger.setEnabled(false);
motionVectorEventLogger = null;
}
synchronized public void doToggleOnLogGlobalMotionFlows() {
if (motionFlowStatistics.globalMotionVectorLogger != null && motionFlowStatistics.globalMotionVectorLogger.isEnabled()) {
log.info("logging already started");
return;
}
String filename = null, filepath = null;
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(getString("lastFile", System.getProperty("user.dir")))); // defaults to startup runtime folder
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
fc.setDialogTitle("Select folder and base file name for the logged global flows data");
int ret = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putString("lastFile", file.toString());
motionFlowStatistics.globalMotionVectorLogger = new TobiLogger(file.getPath(), "Global flows output from optical flow method");
motionFlowStatistics.globalMotionVectorLogger.setNanotimeEnabled(false);
motionFlowStatistics.globalMotionVectorLogger.setColumnHeaderLine("system_time(ms) timestamp(us) meanGlobalVx(pps) meanGlobalVy(pps)");
motionFlowStatistics.globalMotionVectorLogger.setSeparator(" ");
motionFlowStatistics.globalMotionVectorLogger.setEnabled(true);
} else {
log.info("Cancelled logging global flows");
}
}
synchronized public void doToggleOffLogGlobalMotionFlows() {
if (motionFlowStatistics.globalMotionVectorLogger == null) {
return;
}
log.info("Stopping global motion logging from " + motionFlowStatistics.globalMotionVectorLogger);
motionFlowStatistics.globalMotionVectorLogger.setEnabled(false);
motionFlowStatistics.globalMotionVectorLogger = null;
}
synchronized public void doToggleOnLogAccuracyStatistics() {
if (motionFlowStatistics.accuracyStatisticsLogger != null && motionFlowStatistics.accuracyStatisticsLogger.isEnabled()) {
log.info("logging already started");
return;
}
String filename = null, filepath = null;
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(getString("lastFile", System.getProperty("user.dir")))); // defaults to startup runtime folder
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setSelectedFile(new File(getString("lastFile", System.getProperty("user.dir"))));
fc.setDialogTitle("Select folder and base file name for the logged motionFlowStatistics.accuracyStatisticsLogger");
int ret = fc.showOpenDialog(chip.getAeViewer() != null && chip.getAeViewer().getFilterFrame() != null ? chip.getAeViewer().getFilterFrame() : null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
putString("lastFile", file.toString());
motionFlowStatistics.accuracyStatisticsLogger = new TobiLogger(file.getPath(), "Accuracy statistics");
motionFlowStatistics.accuracyStatisticsLogger.setNanotimeEnabled(false);
motionFlowStatistics.accuracyStatisticsLogger.setColumnHeaderLine("system_time(ms) timestamp(us) AEE(px/s) AREE(%) AAE(deg) N");
motionFlowStatistics.accuracyStatisticsLogger.setSeparator(" ");
motionFlowStatistics.accuracyStatisticsLogger.setEnabled(true);
} else {
log.info("Cancelled logging motionFlowStatistics.accuracyStatisticsLogger");
}
}
synchronized public void doToggleOffLogAccuracyStatistics() {
if (motionFlowStatistics.accuracyStatisticsLogger == null) {
return;
}
log.info("Stopping motionFlowStatistics.accuracyStatisticsLogger logging from " + motionFlowStatistics.accuracyStatisticsLogger);
motionFlowStatistics.accuracyStatisticsLogger.setEnabled(false);
motionFlowStatistics.accuracyStatisticsLogger = null;
}
// <editor-fold defaultstate="collapsed" desc="getter/setter for --speedControlEnabled--">
public boolean isSpeedControlEnabled() {
return speedControlEnabled;
}
public void setSpeedControlEnabled(boolean speedControlEnabled) {
support.firePropertyChange("speedControlEnabled", this.speedControlEnabled, speedControlEnabled);
this.speedControlEnabled = speedControlEnabled;
putBoolean("speedControlEnabled", speedControlEnabled);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --speedControl_speedMixingFactor--">
public float getSpeedControl_SpeedMixingFactor() {
return speedMixingFactor;
}
public void setSpeedControl_SpeedMixingFactor(float speedMixingFactor) {
if (speedMixingFactor > 1) {
speedMixingFactor = 1;
} else if (speedMixingFactor < Float.MIN_VALUE) {
speedMixingFactor = Float.MIN_VALUE;
}
this.speedMixingFactor = speedMixingFactor;
putFloat("speedMixingFactor", speedMixingFactor);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --speedControl_excessSpeedRejectFactor--">
public float getSpeedControl_ExcessSpeedRejectFactor() {
return excessSpeedRejectFactor;
}
public void setSpeedControl_ExcessSpeedRejectFactor(float excessSpeedRejectFactor) {
this.excessSpeedRejectFactor = excessSpeedRejectFactor;
putFloat("excessSpeedRejectFactor", excessSpeedRejectFactor);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg--">
// public float getEpsilon() {
// return discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg;
// }
//
// synchronized public void setEpsilon(float discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg) {
// if (discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg > 180) {
// discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg = 180;
// }
// this.discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg = discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg;
// putFloat("discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg", discardOutliersForStatisticalMeasurementMaxAngleDifferenceDeg);
// }
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --discardOutliersForStatisticalMeasurementEnabled--">
// public boolean getDiscardOutliersEnabled() {
// return this.discardOutliersForStatisticalMeasurementEnabled;
// }
//
// public void setDiscardOutliersEnabled(final boolean discardOutliersForStatisticalMeasurementEnabled) {
// support.firePropertyChange("discardOutliersForStatisticalMeasurementEnabled", this.discardOutliersForStatisticalMeasurementEnabled, discardOutliersForStatisticalMeasurementEnabled);
// this.discardOutliersForStatisticalMeasurementEnabled = discardOutliersForStatisticalMeasurementEnabled;
// putBoolean("discardOutliersForStatisticalMeasurementEnabled", discardOutliersForStatisticalMeasurementEnabled);
// }
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --loggingFolder--">
public String getLoggingFolder() {
return loggingFolder;
}
private void setLoggingFolder(String loggingFolder) {
getSupport().firePropertyChange("loggingFolder", this.loggingFolder, loggingFolder);
this.loggingFolder = loggingFolder;
getPrefs().put("DataLogger.loggingFolder", loggingFolder);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --measureAccuracy--">
public synchronized boolean isMeasureAccuracy() {
return measureAccuracy;
}
public synchronized void setMeasureAccuracy(boolean measureAccuracy) {
support.firePropertyChange("measureAccuracy", this.measureAccuracy, measureAccuracy);
this.measureAccuracy = measureAccuracy;
putBoolean("measureAccuracy", measureAccuracy);
motionFlowStatistics.setMeasureAccuracy(measureAccuracy);
if (measureAccuracy) {
//setMeasureProcessingTime(false);
resetFilter();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --measureProcessingTime--">
public synchronized boolean isMeasureProcessingTime() {
return measureProcessingTime;
}
public synchronized void setMeasureProcessingTime(boolean measureProcessingTime) {
motionFlowStatistics.setMeasureProcessingTime(measureProcessingTime);
if (measureProcessingTime) {
setRefractoryPeriodUs(1);
//support.firePropertyChange("measureAccuracy",this.measureAccuracy,false);
//this.measureAccuracy = false;
resetFilter();
this.measureProcessingTime = measureProcessingTime;
//motionFlowStatistics.processingTime.openLog(loggingFolder);
} //else motionFlowStatistics.processingTime.closeLog(loggingFolder,searchDistance);
support.firePropertyChange("measureProcessingTime", this.measureProcessingTime, measureProcessingTime);
this.measureProcessingTime = measureProcessingTime;
putBoolean("measureProcessingTime", measureProcessingTime);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --displayGlobalMotion--">
public boolean isDisplayGlobalMotion() {
return displayGlobalMotion;
}
public void setDisplayGlobalMotion(boolean displayGlobalMotion) {
boolean old = this.displayGlobalMotion;
motionFlowStatistics.setMeasureGlobalMotion(displayGlobalMotion);
this.displayGlobalMotion = displayGlobalMotion;
putBoolean("displayGlobalMotion", displayGlobalMotion);
if (displayGlobalMotion) {
resetFilter();
}
getSupport().firePropertyChange("displayGlobalMotion", old, displayGlobalMotion);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --displayVectorsEnabled--">
public boolean isDisplayVectorsEnabled() {
return displayVectorsEnabled;
}
public void setDisplayVectorsEnabled(boolean displayVectorsEnabled) {
boolean old = this.displayVectorsEnabled;
this.displayVectorsEnabled = displayVectorsEnabled;
putBoolean("displayVectorsEnabled", displayVectorsEnabled);
getSupport().firePropertyChange("displayVectorsEnabled", old, displayVectorsEnabled);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --ppsScale--">
public float getPpsScale() {
return ppsScale;
}
/**
* scale for drawn motion vectors, pixels per second per pixel
*
* @param ppsScale
*/
public void setPpsScale(float ppsScale) {
float old = this.ppsScale;
this.ppsScale = ppsScale;
putFloat("ppsScale", ppsScale);
getSupport().firePropertyChange("ppsScale", old, this.ppsScale);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --showRawInputEnable--">
public boolean isDisplayRawInput() {
return displayRawInput;
}
public void setDisplayRawInput(boolean displayRawInput) {
this.displayRawInput = displayRawInput;
putBoolean("displayRawInput", displayRawInput);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --subSampleShift--">
public int getSubSampleShift() {
return subSampleShift;
}
/**
* Sets the number of spatial bits to subsample events times by. Setting
* this equal to 1, for example, subsamples into an event time map with
* halved spatial resolution, aggregating over more space at coarser
* resolution but increasing the search range by a factor of two at no
* additional cost
*
* @param subSampleShift the number of bits, 0 means no subsampling
*/
synchronized public void setSubSampleShift(int subSampleShift) {
if (subSampleShift < 0) {
subSampleShift = 0;
} else if (subSampleShift > 4) {
subSampleShift = 4;
}
this.subSampleShift = subSampleShift;
putInt("subSampleShift", subSampleShift);
subSizeX = sizex >> subSampleShift;
subSizeY = sizey >> subSampleShift;
allocateMaps();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --refractoryPeriodUs--">
public int getRefractoryPeriodUs() {
return refractoryPeriodUs;
}
public void setRefractoryPeriodUs(int refractoryPeriodUs) {
support.firePropertyChange("refractoryPeriodUs", this.refractoryPeriodUs, refractoryPeriodUs);
this.refractoryPeriodUs = refractoryPeriodUs;
putInt("refractoryPeriodUs", refractoryPeriodUs);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --xMin--">
public int getXMin() {
return xMin;
}
public void setXMin(int xMin) {
if (xMin > xMax) {
xMin = xMax;
}
this.xMin = xMin;
putInt("xMin", xMin);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --xMax--">
public int getXMax() {
return xMax;
}
public void setXMax(int xMax) {
int old = this.xMax;
if (xMax > subSizeX) {
xMax = subSizeX;
}
this.xMax = xMax;
putInt("xMax", xMax);
getSupport().firePropertyChange("xMax", old, this.xMax);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --yMin--">
public int getYMin() {
return yMin;
}
public void setYMin(int yMin) {
if (yMin > yMax) {
yMin = yMax;
}
this.yMin = yMin;
putInt("yMin", yMin);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="getter/setter for --yMax--">
public int getYMax() {
return yMax;
}
public void setYMax(int yMax) {
int old = this.yMax;
if (yMax > subSizeY) {
yMax = subSizeY;
}
this.yMax = yMax;
putInt("yMax", yMax);
getSupport().firePropertyChange("yMax", old, this.yMax);
}
// </editor-fold>
/**
* @return the lensFocalLengthMm
*/
public float getLensFocalLengthMm() {
return lensFocalLengthMm;
}
/**
* @param aLensFocalLengthMm the lensFocalLengthMm to set
*/
public void setLensFocalLengthMm(float aLensFocalLengthMm) {
lensFocalLengthMm = aLensFocalLengthMm;
radPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * lensFocalLengthMm));
}
protected boolean outlierMotionFilteringKeepThisEvent(MotionOrientationEventInterface e) {
if (outlierMotionFilteringLastAngles == null) {
outlierMotionFilteringLastAngles = new int[chip.getSizeX()][chip.getSizeY()];
}
return true;
}
/**
* returns unsigned angle difference that is in range 0-180
*
* @param a
* @param b
* @return unsigned angle difference that is in range 0-180
*/
private int angleDiff(int a, int b) {
int d = Math.abs(a - b) % 360;
int r = d > 180 ? 360 - d : d;
return r;
}
/**
* Encapsulates the computed motion field that is estimated from the flow
* events, with outlier rejection etc.
*
*/
protected class MotionField {
int sx = 0, sy = 0; // size of arrays
private LowpassFilter3D[][] velocities;
// private LowpassFilter[][] speeds;
private int[][] lastTs;
private int lastDecayTimestamp = Integer.MAX_VALUE;
private int motionFieldSubsamplingShift = getInt("motionFieldSubsamplingShift", 3);
// private float motionFieldMixingFactor = getFloat("motionFieldMixingFactor", 1e-1f);
private int motionFieldTimeConstantMs = getInt("motionFieldTimeConstantMs", 100);
private int maxAgeUs = getInt("motionFieldMaxAgeUs", 100000);
private float minSpeedPpsToDrawMotionField = getFloat("minVelocityPps", 1);
private boolean consistentWithNeighbors = getBoolean("motionFieldConsistentWithNeighbors", false);
private boolean consistentWithCurrentAngle = getBoolean("motionFieldConsistentWithCurrentAngle", false);
private boolean displayMotionField = getBoolean("displayMotionField", false);
private boolean displayMotionFieldColorBlobs = getBoolean("displayMotionFieldColorBlobs", false);
;
private boolean displayMotionFieldUsingColor = getBoolean("displayMotionFieldUsingColor", true);
;
private boolean motionFieldDiffusionEnabled = getBoolean("motionFieldDiffusionEnabled", false);
private boolean decayTowardsZeroPeridiclly = getBoolean("decayTowardsZeroPeridiclly", false);
public MotionField() {
}
public void checkArrays() {
if (chip.getNumPixels() == 0) {
return;
}
int newsx = (chip.getSizeX() >> motionFieldSubsamplingShift);
int newsy = (chip.getSizeY() >> motionFieldSubsamplingShift);
if (newsx == 0 || newsy == 0) {
return; // not yet
}
if (sx == 0 || sy == 0 || sx != newsx || sy != newsy || lastTs == null || lastTs.length != sx
|| velocities == null || velocities.length != sx) {
sx = newsx;
sy = newsy;
lastTs = new int[sx][sy];
velocities = new LowpassFilter3D[sx][sy];
// speeds = new LowpassFilter[sx][sy];
for (x = 0; x < sx; x++) {
for (y = 0; y < sy; y++) {
velocities[x][y] = new LowpassFilter3D(motionFieldTimeConstantMs);
// speeds[x][y]=new LowpassFilter(motionFieldTimeConstantMs);
}
}
}
}
public void reset() {
if (chip.getNumPixels() == 0) {
return;
}
lastDecayTimestamp = Integer.MIN_VALUE;
checkArrays();
for (int[] a : lastTs) {
Arrays.fill(a, Integer.MAX_VALUE);
}
for (LowpassFilter3D[] a : velocities) {
for (LowpassFilter3D f : a) {
f.reset();
f.setInitialized(true); // start out with zero motion
}
}
// for (LowpassFilter[] a : speeds) {
// for (LowpassFilter f : a) {
// f.reset();
// }
// }
}
/**
* Decays all values towards zero
*
* @param timestamp current time in us
*/
public void decayAllTowardsZero(int timestamp) {
for (LowpassFilter3D[] a : velocities) {
for (LowpassFilter3D f : a) {
f.filter(0, 0, 0, timestamp);
}
}
}
/**
* updates motion field
*
* @param timestamp in us
* @param x1 location pixel x before subsampling
* @param y1
* @param vx flow vx, pps
* @param vy
*/
synchronized public void update(int timestamp, int x, int y, float vx, float vy, float speed) {
if (!displayMotionField) {
return;
}
int dtDecay = timestamp - lastDecayTimestamp;
if (decayTowardsZeroPeridiclly && dtDecay > motionFieldTimeConstantMs * 1000 || dtDecay < 0) {
decayAllTowardsZero(timestamp);
lastDecayTimestamp = timestamp;
}
int x1 = x >> motionFieldSubsamplingShift, y1 = y >> motionFieldSubsamplingShift;
if (x1 < 0 || x1 >= velocities.length || y1 < 0 || y1 >= velocities[0].length) {
return;
}
if (checkConsistent(timestamp, x1, y1, vx, vy)) {
velocities[x1][y1].filter(vx, vy, speed, timestamp);
if (motionFieldDiffusionEnabled) {
// diffuse by average of neighbors and ourselves
int n = 0;
float dvx = 0, dvy = 0, dvs = 0;
for (int dx = -1; dx <= 1; dx++) {
int x2 = x1 + dx;
if (x2 >= 0 && x2 < velocities.length) {
for (int dy = -1; dy <= 1; dy++) {
int y2 = y1 + dy;
if (dx == 0 && dy == 0) {
continue; // don't count ourselves
}
if (y2 >= 0 && y2 < velocities[0].length) {
n++;
Point3D p = velocities[x2][y2].getValue3D();
dvx += p.x;
dvy += p.y;
dvs += p.z;
}
}
}
}
float r = 1f / n; // recip of sum to compute average
LowpassFilter3D v = velocities[x1][y1];
Point3D c = v.getValue3D();
v.setInternalValue3D(.5f * (c.x + r * dvx), .5f * (c.y + r * dvy), .5f * (c.z + r * dvs));
}
}
lastTs[x1][y1] = ts;
}
/**
* Checks if new flow event is consistent sufficiently with motion field
*
* @param timestamp in us
* @param x1 location pixel x after subsampling
* @param y1
* @param vx flow vx, pps
* @param vy
* @return true if sufficiently consistent
*/
private boolean checkConsistent(int timestamp, int x1, int y1, float vx, float vy) {
int dt = timestamp - lastTs[x1][y1];
if (dt > maxAgeUs) {
return false;
}
boolean thisAngleConsistentWithCurrentAngle = true;
if (consistentWithCurrentAngle) {
Point3D p = velocities[x1][y1].getValue3D();
float dot = vx * p.x + vy * p.y;
thisAngleConsistentWithCurrentAngle = (dot >= 0);
}
boolean thisAngleConsistentWithNeighbors = true;
if (consistentWithNeighbors) {
int countConsistent = 0, count = 0;
final int[] xs = {-1, 0, 1, 0}, ys = {0, 1, 0, -1}; // 4 neigbors
int nNeighbors = xs.length;
for (int i = 0; i < nNeighbors; i++) {
int x = xs[i], y = ys[i];
int x2 = x1 + x, y2 = y1 + y;
if (x2 < 0 || x2 >= velocities.length || y2 < 0 || y2 >= velocities[0].length) {
continue;
}
count++;
Point3D p = velocities[x2][y2].getValue3D();
float dot2 = vx * p.x + vy * p.y;
if (dot2 >= 0) {
countConsistent++;
}
}
if (countConsistent > count / 2) {
thisAngleConsistentWithNeighbors = true;
} else {
thisAngleConsistentWithNeighbors = false;
}
}
return thisAngleConsistentWithCurrentAngle && thisAngleConsistentWithNeighbors;
}
public void draw(GL2 gl) {
if (!displayMotionField || velocities == null) {
return;
}
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
e.printStackTrace();
}
float shift = ((1 << motionFieldSubsamplingShift) * .5f);
final float saturationSpeedScaleInversePixels = ppsScale * 0.1f; // this length of vector in pixels makes full brightness
for (int ix = 0; ix < sx; ix++) {
float x = (ix << motionFieldSubsamplingShift) + shift;
for (int iy = 0; iy < sy; iy++) {
final float y = (iy << motionFieldSubsamplingShift) + shift;
final int dt = ts - lastTs[ix][iy]; // use last timestamp of any event that is processed by extractEventInfo
gl.glColor4f(0, 0, 1, 1f);
final float dotRadius = .75f;
gl.glRectf(x - dotRadius, y - dotRadius, x + dotRadius, y + dotRadius);
if (dt > maxAgeUs || dt < 0) {
continue;
}
final float speed = velocities[ix][iy].getValue3D().z;
if (speed < minSpeedPpsToDrawMotionField) {
continue;
}
final Point3D p = velocities[ix][iy].getValue3D();
final float vx = p.x, vy = p.y;
float brightness = p.z * saturationSpeedScaleInversePixels;
if (brightness > 1) {
brightness = 1;
}
// TODO use motionColor()
float[] rgb;
if (displayMotionFieldUsingColor) {
rgb = motionColor(vx, vy, 1, 1);
} else {
rgb = new float[]{0, 0, 1};
}
gl.glColor4f(rgb[0], rgb[1], rgb[2], 1f);
gl.glLineWidth(motionVectorLineWidthPixels);
// gl.glColor4f(angle, 1 - angle, 1 / (1 + 10 * angle), .5f);
gl.glPushMatrix();
DrawGL.drawVector(gl, x, y, vx * ppsScale, vy * ppsScale, motionVectorLineWidthPixels, 1);
gl.glPopMatrix();
if (displayMotionFieldColorBlobs) {
gl.glColor4f(rgb[0], rgb[1], rgb[2], .01f);
final float s = shift / 4;
// draw a blurred square showing motion field direction
// TODO appendCopy brightness to show magnitude somehow
for (float dxx = -shift; dxx < shift; dxx += s) {
for (float dyy = -shift; dyy < shift; dyy += s) {
gl.glRectf(x - shift + dxx, y - shift + dyy, x + shift + dxx, y + shift + dyy);
}
}
}
}
}
}
private boolean isDisplayMotionField() {
return displayMotionField;
}
private void setDisplayMotionField(boolean yes) {
displayMotionField = yes;
putBoolean("displayMotionField", yes);
}
/**
* @return the motionFieldSubsamplingShift
*/
public int getMotionFieldSubsamplingShift() {
return motionFieldSubsamplingShift;
}
/**
* @param motionFieldSubsamplingShift the motionFieldSubsamplingShift to
* set
*/
synchronized public void setMotionFieldSubsamplingShift(int motionFieldSubsamplingShift) {
if (motionFieldSubsamplingShift < 0) {
motionFieldSubsamplingShift = 0;
} else if (motionFieldSubsamplingShift > 5) {
motionFieldSubsamplingShift = 5;
}
this.motionFieldSubsamplingShift = motionFieldSubsamplingShift;
putInt("motionFieldSubsamplingShift", motionFieldSubsamplingShift);
reset();
}
// /**
// * @return the motionFieldMixingFactor
// */
// public float getMotionFieldMixingFactor() {
// return motionFieldMixingFactor;
// }
//
// /**
// * @param motionFieldMixingFactor the motionFieldMixingFactor to set
// */
// public void setMotionFieldMixingFactor(float motionFieldMixingFactor) {
// if (motionFieldMixingFactor < 1e-6f) {
// this.motionFieldMixingFactor = 1e-6f;
// } else if (motionFieldMixingFactor > 1) {
// this.motionFieldMixingFactor = 1;
// }
// this.motionFieldMixingFactor = motionFieldMixingFactor;
// putFloat("motionFieldMixingFactor", motionFieldMixingFactor);
// }
/**
* @return the maxAgeUs
*/
public int getMaxAgeUs() {
return maxAgeUs;
}
/**
* @param maxAgeUs the maxAgeUs to set
*/
public void setMaxAgeUs(int maxAgeUs) {
this.maxAgeUs = maxAgeUs;
putInt("motionFieldMaxAgeUs", maxAgeUs);
}
/**
* @return the consistentWithNeighbors
*/
public boolean isConsistentWithNeighbors() {
return consistentWithNeighbors;
}
/**
* @param consistentWithNeighbors the consistentWithNeighbors to set
*/
public void setConsistentWithNeighbors(boolean consistentWithNeighbors) {
this.consistentWithNeighbors = consistentWithNeighbors;
putBoolean("motionFieldConsistentWithNeighbors", consistentWithNeighbors);
}
/**
* @return the consistentWithCurrentAngle
*/
public boolean isConsistentWithCurrentAngle() {
return consistentWithCurrentAngle;
}
/**
* @param consistentWithCurrentAngle the consistentWithCurrentAngle to
* set
*/
public void setConsistentWithCurrentAngle(boolean consistentWithCurrentAngle) {
this.consistentWithCurrentAngle = consistentWithCurrentAngle;
putBoolean("motionFieldConsistentWithCurrentAngle", consistentWithCurrentAngle);
}
/**
* @return the minSpeedPpsToDrawMotionField
*/
public float getMinSpeedPpsToDrawMotionField() {
return minSpeedPpsToDrawMotionField;
}
/**
* @param minSpeedPpsToDrawMotionField the minSpeedPpsToDrawMotionField
* to set
*/
public void setMinSpeedPpsToDrawMotionField(float minSpeedPpsToDrawMotionField) {
this.minSpeedPpsToDrawMotionField = minSpeedPpsToDrawMotionField;
putFloat("minSpeedPpsToDrawMotionField", minSpeedPpsToDrawMotionField);
}
/**
* @return the motionFieldTimeConstantMs
*/
public int getMotionFieldTimeConstantMs() {
return motionFieldTimeConstantMs;
}
/**
* @param motionFieldTimeConstantMs the motionFieldTimeConstantMs to set
*/
public void setMotionFieldTimeConstantMs(int motionFieldTimeConstantMs) {
this.motionFieldTimeConstantMs = motionFieldTimeConstantMs;
putInt("motionFieldTimeConstantMs", motionFieldTimeConstantMs);
setTimeConstant(motionFieldTimeConstantMs);
}
private void setTimeConstant(int motionFieldTimeConstantMs) {
if (sx == 0 || sy == 0) {
return;
}
for (LowpassFilter3D[] a : velocities) {
for (LowpassFilter3D f : a) {
f.setTauMs(motionFieldTimeConstantMs);
}
}
// for (LowpassFilter[] a : speeds) {
// for (LowpassFilter f : a) {
// f.setTauMs(motionFieldTimeConstantMs);
// }
// }
}
/**
* @return the displayMotionFieldColorBlobs
*/
public boolean isDisplayMotionFieldColorBlobs() {
return displayMotionFieldColorBlobs;
}
/**
* @param displayMotionFieldColorBlobs the displayMotionFieldColorBlobs
* to set
*/
public void setDisplayMotionFieldColorBlobs(boolean displayMotionFieldColorBlobs) {
this.displayMotionFieldColorBlobs = displayMotionFieldColorBlobs;
putBoolean("displayMotionFieldColorBlobs", displayMotionFieldColorBlobs);
}
/**
* @return the displayMotionFieldUsingColor
*/
public boolean isDisplayMotionFieldUsingColor() {
return displayMotionFieldUsingColor;
}
/**
* @param displayMotionFieldUsingColor the displayMotionFieldUsingColor
* to set
*/
public void setDisplayMotionFieldUsingColor(boolean displayMotionFieldUsingColor) {
this.displayMotionFieldUsingColor = displayMotionFieldUsingColor;
putBoolean("displayMotionFieldUsingColor", displayMotionFieldUsingColor);
}
/**
* @return the motionFieldDiffusionEnabled
*/
public boolean isMotionFieldDiffusionEnabled() {
return motionFieldDiffusionEnabled;
}
/**
* @param motionFieldDiffusionEnabled the motionFieldDiffusionEnabled to
* set
*/
public void setMotionFieldDiffusionEnabled(boolean motionFieldDiffusionEnabled) {
this.motionFieldDiffusionEnabled = motionFieldDiffusionEnabled;
putBoolean("motionFieldDiffusionEnabled", motionFieldDiffusionEnabled);
}
/**
* @return the decayTowardsZeroPeridiclly
*/
public boolean isDecayTowardsZeroPeridiclly() {
return decayTowardsZeroPeridiclly;
}
/**
* @param decayTowardsZeroPeridiclly the decayTowardsZeroPeridiclly to
* set
*/
public void setDecayTowardsZeroPeridiclly(boolean decayTowardsZeroPeridiclly) {
this.decayTowardsZeroPeridiclly = decayTowardsZeroPeridiclly;
putBoolean("decayTowardsZeroPeridiclly", decayTowardsZeroPeridiclly);
}
} // MotionField
public boolean isDisplayMotionField() {
return motionField.isDisplayMotionField();
}
public void setDisplayMotionField(boolean yes) {
motionField.setDisplayMotionField(yes);
}
public int getMotionFieldSubsamplingShift() {
return motionField.getMotionFieldSubsamplingShift();
}
public void setMotionFieldSubsamplingShift(int motionFieldSubsamplingShift) {
motionField.setMotionFieldSubsamplingShift(motionFieldSubsamplingShift);
}
// public float getMotionFieldMixingFactor() {
// return motionField.getMotionFieldMixingFactor();
// }
//
// public void setMotionFieldMixingFactor(float motionFieldMixingFactor) {
// motionField.setMotionFieldMixingFactor(motionFieldMixingFactor);
// }
public int getMotionFieldTimeConstantMs() {
return motionField.getMotionFieldTimeConstantMs();
}
public void setMotionFieldTimeConstantMs(int motionFieldTimeConstantMs) {
motionField.setMotionFieldTimeConstantMs(motionFieldTimeConstantMs);
}
public int getMaxAgeUs() {
return motionField.getMaxAgeUs();
}
public void setMaxAgeUs(int maxAgeUs) {
motionField.setMaxAgeUs(maxAgeUs);
}
public boolean isConsistentWithNeighbors() {
return motionField.isConsistentWithNeighbors();
}
public void setConsistentWithNeighbors(boolean consistentWithNeighbors) {
motionField.setConsistentWithNeighbors(consistentWithNeighbors);
}
public boolean isConsistentWithCurrentAngle() {
return motionField.isConsistentWithCurrentAngle();
}
public void setConsistentWithCurrentAngle(boolean consistentWithCurrentAngle) {
motionField.setConsistentWithCurrentAngle(consistentWithCurrentAngle);
}
public float getMinSpeedPpsToDrawMotionField() {
return motionField.getMinSpeedPpsToDrawMotionField();
}
public void setMinSpeedPpsToDrawMotionField(float minSpeedPpsToDrawMotionField) {
motionField.setMinSpeedPpsToDrawMotionField(minSpeedPpsToDrawMotionField);
}
/**
* Returns the object holding flow statistics.
*
* @return the motionFlowStatistics
*/
public MotionFlowStatistics getMotionFlowStatistics() {
return motionFlowStatistics;
}
public int getCalibrationSamples() {
return imuFlowEstimator.getCalibrationSamples();
}
public void setCalibrationSamples(int calibrationSamples) {
imuFlowEstimator.setCalibrationSamples(calibrationSamples);
}
public boolean isDisplayColorWheelLegend() {
return this.displayColorWheelLegend;
}
public void setDisplayColorWheelLegend(boolean displayColorWheelLegend) {
this.displayColorWheelLegend = displayColorWheelLegend;
putBoolean("displayColorWheelLegend", displayColorWheelLegend);
}
/**
* @return the motionVectorLineWidthPixels
*/
public float getMotionVectorLineWidthPixels() {
return motionVectorLineWidthPixels;
}
/**
* @param motionVectorLineWidthPixels the motionVectorLineWidthPixels to set
*/
public void setMotionVectorLineWidthPixels(float motionVectorLineWidthPixels) {
if (motionVectorLineWidthPixels < .1f) {
motionVectorLineWidthPixels = .1f;
} else if (motionVectorLineWidthPixels > 10) {
motionVectorLineWidthPixels = 10;
}
this.motionVectorLineWidthPixels = motionVectorLineWidthPixels;
putFloat("motionVectorLineWidthPixels", motionVectorLineWidthPixels);
}
/**
* @return the displayZeroLengthVectorsEnabled
*/
public boolean isDisplayZeroLengthVectorsEnabled() {
return displayZeroLengthVectorsEnabled;
}
/**
* @param displayZeroLengthVectorsEnabled the
* displayZeroLengthVectorsEnabled to set
*/
public void setDisplayZeroLengthVectorsEnabled(boolean displayZeroLengthVectorsEnabled) {
this.displayZeroLengthVectorsEnabled = displayZeroLengthVectorsEnabled;
putBoolean("displayZeroLengthVectorsEnabled", displayZeroLengthVectorsEnabled);
}
// /**
// * @return the outlierMotionFilteringEnabled
// */
// public boolean isOutlierMotionFilteringEnabled() {
// return outlierMotionFilteringEnabled;
// }
//
// /**
// * @param outlierMotionFilteringEnabled the outlierMotionFilteringEnabled to
// * set
// */
// public void setOutlierMotionFilteringEnabled(boolean outlierMotionFilteringEnabled) {
// this.outlierMotionFilteringEnabled = outlierMotionFilteringEnabled;
// }
/**
* @return the displayVectorsAsColorDots
*/
public boolean isDisplayVectorsAsColorDots() {
return displayVectorsAsColorDots;
}
/**
* @param displayVectorsAsColorDots the displayVectorsAsColorDots to set
*/
public void setDisplayVectorsAsColorDots(boolean displayVectorsAsColorDots) {
this.displayVectorsAsColorDots = displayVectorsAsColorDots;
putBoolean("displayVectorsAsColorDots", displayVectorsAsColorDots);
}
public boolean isDisplayMotionFieldColorBlobs() {
return motionField.isDisplayMotionFieldColorBlobs();
}
public void setDisplayMotionFieldColorBlobs(boolean displayMotionFieldColorBlobs) {
motionField.setDisplayMotionFieldColorBlobs(displayMotionFieldColorBlobs);
}
public boolean isDisplayMotionFieldUsingColor() {
return motionField.isDisplayMotionFieldUsingColor();
}
public void setDisplayMotionFieldUsingColor(boolean displayMotionFieldUsingColor) {
motionField.setDisplayMotionFieldUsingColor(displayMotionFieldUsingColor);
}
public boolean isMotionFieldDiffusionEnabled() {
return motionField.isMotionFieldDiffusionEnabled();
}
public void setMotionFieldDiffusionEnabled(boolean motionFieldDiffusionEnabled) {
motionField.setMotionFieldDiffusionEnabled(motionFieldDiffusionEnabled);
}
public boolean isDecayTowardsZeroPeridiclly() {
return motionField.isDecayTowardsZeroPeridiclly();
}
public void setDecayTowardsZeroPeridiclly(boolean decayTowardsZeroPeridiclly) {
motionField.setDecayTowardsZeroPeridiclly(decayTowardsZeroPeridiclly);
}
/**
* @return the displayVectorsAsUnitVectors
*/
public boolean isDisplayVectorsAsUnitVectors() {
return displayVectorsAsUnitVectors;
}
/**
* @param displayVectorsAsUnitVectors the displayVectorsAsUnitVectors to set
*/
public void setDisplayVectorsAsUnitVectors(boolean displayVectorsAsUnitVectors) {
this.displayVectorsAsUnitVectors = displayVectorsAsUnitVectors;
putBoolean("displayVectorsAsUnitVectors", displayVectorsAsUnitVectors);
}
/**
* @return the ppsScaleDisplayRelativeOFLength
*/
public boolean isPpsScaleDisplayRelativeOFLength() {
return ppsScaleDisplayRelativeOFLength;
}
/**
* @param ppsScaleDisplayRelativeOFLength the
* ppsScaleDisplayRelativeOFLength to set
*/
public void setPpsScaleDisplayRelativeOFLength(boolean ppsScaleDisplayRelativeOFLength) {
boolean old = this.ppsScaleDisplayRelativeOFLength;
this.ppsScaleDisplayRelativeOFLength = ppsScaleDisplayRelativeOFLength;
putBoolean("ppsScaleDisplayRelativeOFLength", ppsScaleDisplayRelativeOFLength);
getSupport().firePropertyChange("ppsScaleDisplayRelativeOFLength", old, ppsScaleDisplayRelativeOFLength);
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
super.setFilterEnabled(yes);
if (cameraCalibration != null) {
cameraCalibration.setFilterEnabled(false); // disable camera cameraCalibration; force user to enable it every time
}
}
/**
* @return the statisticsWindowSize
*/
public int getStatisticsWindowSize() {
return statisticsWindowSize;
}
/**
* @param statisticsWindowSize the statisticsWindowSize to set
*/
public void setStatisticsWindowSize(int statisticsWindowSize) {
this.statisticsWindowSize = statisticsWindowSize;
putInt("statisticsWindowSize", statisticsWindowSize);
motionFlowStatistics.setWindowSize(this.statisticsWindowSize);
}
/**
* @return the randomScatterOnFlowVectorOrigins
*/
public boolean isRandomScatterOnFlowVectorOrigins() {
return randomScatterOnFlowVectorOrigins;
}
/**
* @param randomScatterOnFlowVectorOrigins the
* randomScatterOnFlowVectorOrigins to set
*/
public void setRandomScatterOnFlowVectorOrigins(boolean randomScatterOnFlowVectorOrigins) {
this.randomScatterOnFlowVectorOrigins = randomScatterOnFlowVectorOrigins;
putBoolean("randomScatterOnFlowVectorOrigins", randomScatterOnFlowVectorOrigins);
}
/**
* @return the motionVectorTransparencyAlpha
*/
public float getMotionVectorTransparencyAlpha() {
return motionVectorTransparencyAlpha;
}
/**
* @param motionVectorTransparencyAlpha the motionVectorTransparencyAlpha to
* set
*/
public void setMotionVectorTransparencyAlpha(float motionVectorTransparencyAlpha) {
if (motionVectorTransparencyAlpha < 0) {
motionVectorTransparencyAlpha = 0;
} else if (motionVectorTransparencyAlpha > 1) {
motionVectorTransparencyAlpha = 1;
}
this.motionVectorTransparencyAlpha = motionVectorTransparencyAlpha;
putFloat("motionVectorTransparencyAlpha", motionVectorTransparencyAlpha);
}
@Override
public void mouseMoved(MouseEvent mouseEvent) {
if (!measureAccuracy) {
return;
}
Point2D p = getMousePixel(mouseEvent);
if (p == null || p.getX() < 0 || p.getY() < 0 || p.getX() >= chip.getSizeX() || p.getY() >= chip.getSizeY()) {
return;
}
ApsDvsMotionOrientationEvent e = new ApsDvsMotionOrientationEvent();
e.x = (short) p.getX();
e.y = (short) p.getY();
e.timestamp = ts;
x = e.x;
y = e.y; // must set stupid globals to compute the GT flow in calculateImuFlow
imuFlowEstimator.calculateImuFlow(e);
if (imuFlowEstimator.getV() > 0) {
e.velocity.x = imuFlowEstimator.vx;
e.velocity.y = imuFlowEstimator.vy;
e.speed = (float) Math.sqrt(e.velocity.x * e.velocity.x + e.velocity.y * e.velocity.y);
mouseVectorString = String.format("GT: [vx,vy,v]=[%.1f,%.1f,%.1f] for [x,y]=[%d,%d]", e.velocity.x, e.velocity.y, e.speed, e.x, e.y);
log.info(mouseVectorString);
mouseVectorEvent = e;
} else {
mouseVectorEvent = null;
mouseVectorString = null;
}
super.mouseMoved(mouseEvent); //repaints
}
@Override
public void mouseExited(MouseEvent e) {
mouseVectorString = null;
mouseVectorEvent = null;
}
}
| improved placement of text rendering and global flow line width | src/ch/unizh/ini/jaer/projects/rbodo/opticalflow/AbstractMotionFlowIMU.java | improved placement of text rendering and global flow line width | <ide><path>rc/ch/unizh/ini/jaer/projects/rbodo/opticalflow/AbstractMotionFlowIMU.java
<ide> s = String.format("%.1f px/s OF scale", speed);
<ide> }
<ide> // gl.glColor3f(1, 1, 1);
<del> DrawGL.drawString(gl, 10, px, py, 0, new Color(rgba[0], rgba[1], rgba[2], rgba[3]), s);
<add> DrawGL.drawString(gl, 10, px+20, py, 0, new Color(rgba[0], rgba[1], rgba[2], rgba[3]), s);
<ide> // chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
<ide> gl.glPopMatrix();
<ide>
<ide> }
<ide>
<ide> if (isDisplayGlobalMotion()) {
<del> gl.glLineWidth(getMotionVectorLineWidthPixels() * 4);
<add> gl.glLineWidth(getMotionVectorLineWidthPixels());
<ide> gl.glColor3f(1, 1, 1);
<ide>
<ide> // Draw global translation vector |
|
Java | apache-2.0 | 8d131df3dafad49e5f9b702cfdfdee4c2b079f63 | 0 | BrunoEberhard/minimal-j,BrunoEberhard/minimal-j,BrunoEberhard/minimal-j | package org.minimalj.rest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.minimalj.frontend.impl.json.JsonReader;
import org.minimalj.model.Code;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.Codes;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.GenericUtils;
import org.minimalj.util.StringUtils;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class EntityJsonReader {
public static <T> T read(Class<T> clazz, String input) {
if (StringUtils.isEmpty(input)) {
return null;
}
Map<String, Object> values = (Map<String, Object>) JsonReader.read(input);
return convert(clazz, values);
}
public static <T> T read(Class<T> clazz, InputStream inputStream) {
Map<String, Object> values = (Map<String, Object>) JsonReader.read(inputStream);
return convert(clazz, values);
}
public static <T> T read(T entity, String input) {
if (StringUtils.isEmpty(input)) {
return entity;
}
Map<String, Object> values = (Map<String, Object>) JsonReader.read(input);
return convert(entity, values);
}
public static <T> T read(T entity, InputStream inputStream) {
Map<String, Object> values = (Map<String, Object>) JsonReader.read(inputStream);
return convert(entity, values);
}
private static <T> List<T> convertList(Class<T> clazz, List list) {
List convertedList = new ArrayList<>();
for (Object item : list) {
convertedList.add(convert(clazz, (Map<String, Object>) item));
}
return convertedList;
}
private static <T extends Enum> void convertEnumSet(Set<T> set, Class<T> clazz, List list) {
set.clear();
for (Object item : list) {
set.add(Enum.valueOf(clazz, (String) item));
}
}
private static <T> T convert(Class<T> clazz, Map<String, Object> values) {
T entity = CloneHelper.newInstance(clazz);
return convert(entity, values);
}
private static <T> T convert(T entity, Map<String, Object> values) {
Map<String, PropertyInterface> properties = FlatProperties.getProperties(entity.getClass());
for (Map.Entry<String, Object> entry : values.entrySet()) {
PropertyInterface property = properties.get(entry.getKey());
if (property == null) {
continue;
}
Object value = entry.getValue();
if (property.getClazz() == List.class) {
List list = (List) value;
value = convertList(GenericUtils.getGenericClass(property.getType()), list);
property.setValue(entity, value);
} else if (property.getClazz() == Set.class) {
Set set = (Set) property.getValue(entity);
convertEnumSet(set, (Class<? extends Enum>) GenericUtils.getGenericClass(property.getType()), (List)value);
} else if (value instanceof String) {
String string = (String) value;
if (!"id".equals(property.getName()) || property.getClazz() != Object.class) {
Class<?> propertyClazz = property.getClazz();
if (propertyClazz != String.class) {
if (Code.class.isAssignableFrom(propertyClazz)) {
value = Codes.findCode((Class) propertyClazz, value);
} else {
value = FieldUtils.parse(string, propertyClazz);
}
}
}
property.setValue(entity, value);
} else if (value instanceof BigDecimal) {
if (property.getClazz() == BigDecimal.class) {
property.setValue(entity, value);
} else if (property.getClazz() == Long.class) {
property.setValue(entity, ((BigDecimal) value).longValue());
} else if (property.getClazz() == Integer.class) {
property.setValue(entity, ((BigDecimal) value).intValue());
}
} else if (value instanceof Long) {
// Integer.Type for version
if (property.getClazz() == Integer.class || property.getClazz() == Integer.TYPE) {
property.setValue(entity, ((Long) value).intValue());
} else if (property.getClazz() == Long.class) {
property.setValue(entity, value);
} else if (property.getClazz() == BigDecimal.class) {
property.setValue(entity, BigDecimal.valueOf((Long) value));
}
} else if (value instanceof Boolean) {
property.setValue(entity, value);
} else if (value instanceof Map) {
Map map = (Map) value;
Class c2 = property.getClazz();
value = convert(c2, map);
property.setValue(entity, value);
}
}
return entity;
}
}
| ext/rest/src/main/java/org/minimalj/rest/EntityJsonReader.java | package org.minimalj.rest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.minimalj.frontend.impl.json.JsonReader;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.GenericUtils;
import org.minimalj.util.StringUtils;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class EntityJsonReader {
public static <T> T read(Class<T> clazz, String input) {
if (StringUtils.isEmpty(input)) {
return null;
}
Map<String, Object> values = (Map<String, Object>) JsonReader.read(input);
return convert(clazz, values);
}
public static <T> T read(Class<T> clazz, InputStream inputStream) {
Map<String, Object> values = (Map<String, Object>) JsonReader.read(inputStream);
return convert(clazz, values);
}
public static <T> T read(T entity, String input) {
if (StringUtils.isEmpty(input)) {
return entity;
}
Map<String, Object> values = (Map<String, Object>) JsonReader.read(input);
return convert(entity, values);
}
public static <T> T read(T entity, InputStream inputStream) {
Map<String, Object> values = (Map<String, Object>) JsonReader.read(inputStream);
return convert(entity, values);
}
private static <T> List<T> convertList(Class<T> clazz, List list) {
List convertedList = new ArrayList<>();
for (Object item : list) {
convertedList.add(convert(clazz, (Map<String, Object>) item));
}
return convertedList;
}
private static <T extends Enum> void convertEnumSet(Set<T> set, Class<T> clazz, List list) {
set.clear();
for (Object item : list) {
set.add(Enum.valueOf(clazz, (String) item));
}
}
private static <T> T convert(Class<T> clazz, Map<String, Object> values) {
T entity = CloneHelper.newInstance(clazz);
return convert(entity, values);
}
private static <T> T convert(T entity, Map<String, Object> values) {
Map<String, PropertyInterface> properties = FlatProperties.getProperties(entity.getClass());
for (Map.Entry<String, Object> entry : values.entrySet()) {
PropertyInterface property = properties.get(entry.getKey());
if (property == null) {
continue;
}
Object value = entry.getValue();
if (property.getClazz() == List.class) {
List list = (List) value;
value = convertList(GenericUtils.getGenericClass(property.getType()), list);
property.setValue(entity, value);
} else if (property.getClazz() == Set.class) {
Set set = (Set) property.getValue(entity);
convertEnumSet(set, (Class<? extends Enum>) GenericUtils.getGenericClass(property.getType()), (List)value);
} else if (value instanceof String) {
String string = (String) value;
if ("version".equals(property.getName())) {
value = Integer.parseInt(string);
} else if (!"id".equals(property.getName()) || property.getClazz() != Object.class) {
Class<?> propertyClazz = property.getClazz();
if (propertyClazz != String.class) {
value = FieldUtils.parse(string, propertyClazz);
}
}
property.setValue(entity, value);
} else if (value instanceof BigDecimal) {
if (property.getClazz() == BigDecimal.class) {
property.setValue(entity, value);
} else if (property.getClazz() == Long.class) {
property.setValue(entity, ((BigDecimal) value).longValue());
} else if (property.getClazz() == Integer.class) {
property.setValue(entity, ((BigDecimal) value).intValue());
}
} else if (value instanceof Long) {
if (property.getClazz() == Integer.class) {
property.setValue(entity, ((Long) value).intValue());
} else if (property.getClazz() == Long.class) {
property.setValue(entity, value);
} else if (property.getClazz() == BigDecimal.class) {
property.setValue(entity, BigDecimal.valueOf((Long) value));
}
} else if (value instanceof Boolean) {
property.setValue(entity, value);
} else if (value instanceof Map) {
Map map = (Map) value;
Class c2 = property.getClazz();
value = convert(c2, map);
property.setValue(entity, value);
}
}
return entity;
}
}
| EntityJsonReader: support codes | ext/rest/src/main/java/org/minimalj/rest/EntityJsonReader.java | EntityJsonReader: support codes | <ide><path>xt/rest/src/main/java/org/minimalj/rest/EntityJsonReader.java
<ide> import java.util.Set;
<ide>
<ide> import org.minimalj.frontend.impl.json.JsonReader;
<add>import org.minimalj.model.Code;
<ide> import org.minimalj.model.properties.FlatProperties;
<ide> import org.minimalj.model.properties.PropertyInterface;
<ide> import org.minimalj.util.CloneHelper;
<add>import org.minimalj.util.Codes;
<ide> import org.minimalj.util.FieldUtils;
<ide> import org.minimalj.util.GenericUtils;
<ide> import org.minimalj.util.StringUtils;
<ide> convertEnumSet(set, (Class<? extends Enum>) GenericUtils.getGenericClass(property.getType()), (List)value);
<ide> } else if (value instanceof String) {
<ide> String string = (String) value;
<del> if ("version".equals(property.getName())) {
<del> value = Integer.parseInt(string);
<del> } else if (!"id".equals(property.getName()) || property.getClazz() != Object.class) {
<add> if (!"id".equals(property.getName()) || property.getClazz() != Object.class) {
<ide> Class<?> propertyClazz = property.getClazz();
<ide> if (propertyClazz != String.class) {
<del> value = FieldUtils.parse(string, propertyClazz);
<add> if (Code.class.isAssignableFrom(propertyClazz)) {
<add> value = Codes.findCode((Class) propertyClazz, value);
<add> } else {
<add> value = FieldUtils.parse(string, propertyClazz);
<add> }
<ide> }
<ide> }
<ide> property.setValue(entity, value);
<ide> property.setValue(entity, ((BigDecimal) value).intValue());
<ide> }
<ide> } else if (value instanceof Long) {
<del> if (property.getClazz() == Integer.class) {
<add> // Integer.Type for version
<add> if (property.getClazz() == Integer.class || property.getClazz() == Integer.TYPE) {
<ide> property.setValue(entity, ((Long) value).intValue());
<ide> } else if (property.getClazz() == Long.class) {
<ide> property.setValue(entity, value); |
|
Java | apache-2.0 | 5a501a4ab762c7da283ee59e10630b48f7383d79 | 0 | jitsi/jitsi-meet-torture,jitsi/jitsi-meet-torture,jitsi/jitsi-meet-torture,jitsi/jitsi-meet-torture,jitsi/jitsi-meet-torture | /*
* Copyright @ 2017 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.meet.test;
import junit.framework.*;
import org.jitsi.meet.test.util.*;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
/**
* Tests 1-on-1 remote video thumbnail display in the filmstrip.
*
* @author Leonard Kim
*/
public class OneOnOneTest
extends TestCase
{
/**
* The duration to wait, in seconds, remote videos in filmstrip to display
* and complete animations.
*/
private final int filmstripVisibilityWait = 5;
/**
* Parameters to attach to the meeting url to enable One-On-One behavior
* and have toolbars dismiss faster, as remote video visibility is also
* tied to toolbar visibility.
*/
private final String oneOnOneConfigOverrides
= "config.disable1On1Mode=false"
+ "&interfaceConfig.TOOLBAR_TIMEOUT=500"
+ "&interfaceConfig.INITIAL_TOOLBAR_TIMEOUT=500"
+ "&config.alwaysVisibleToolbar=false";
/**
* Constructs test
* @param name the method name for the test.
*/
public OneOnOneTest(String name)
{
super(name);
}
/**
* Orders the tests.
* @return the suite with order tests.
*/
public static junit.framework.Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new OneOnOneTest("testFilmstripHiddenInOneOnOne"));
suite.addTest(new OneOnOneTest("testFilmstripVisibleWithMoreThanTwo"));
suite.addTest(
new OneOnOneTest("testFilmstripDisplayWhenReturningToOneOnOne"));
suite.addTest(new OneOnOneTest("testFilmstripVisibleOnSelfViewFocus"));
suite.addTest(new OneOnOneTest("testFilmstripHoverShowsVideos"));
suite.addTest(new OneOnOneTest("testStopOneOnOneTest"));
return suite;
}
/**
* Tests remote videos in filmstrip do not display in a 1-on-1 call.
*/
public void testFilmstripHiddenInOneOnOne()
{
WebDriver owner = ConferenceFixture.getOwner();
WebDriver secondParticipant = ConferenceFixture.getSecondParticipant();
// Close the browsers first and then load the meeting so hash changes to
// the config are detected by the browser.
ConferenceFixture.close(owner);
ConferenceFixture.close(secondParticipant);
ConferenceFixture.startOwner(oneOnOneConfigOverrides);
ConferenceFixture.startSecondParticipant(oneOnOneConfigOverrides);
// Prevent toolbar from being always displayed as filmstrip visibility
// is tied to toolbar visibility.
stopDockingToolbar(owner);
stopDockingToolbar(secondParticipant);
verifyRemoteVideosDisplay(owner, false);
verifyRemoteVideosDisplay(secondParticipant, false);
}
/**
* Tests remote videos in filmstrip do display when in a call with more than
* two total participants.
*/
public void testFilmstripVisibleWithMoreThanTwo() {
// Close the third participant's browser and reopen so hash changes to
// the config are detected by the browser.
WebDriver thirdParticipant = ConferenceFixture.getThirdParticipant();
ConferenceFixture.waitForThirdParticipantToConnect();
ConferenceFixture.close(thirdParticipant);
ConferenceFixture.startThirdParticipant(oneOnOneConfigOverrides);
stopDockingToolbar(thirdParticipant);
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
verifyRemoteVideosDisplay(
ConferenceFixture.getSecondParticipant(), true);
verifyRemoteVideosDisplay(thirdParticipant, true);
}
/**
* Tests remote videos in filmstrip do not display after transitioning to
* 1-on-1 mode. Also tests remote videos in filmstrip do display when
* focused on self and transitioning back to 1-on-1 mode.
*/
public void testFilmstripDisplayWhenReturningToOneOnOne() {
MeetUIUtils.clickOnLocalVideo(ConferenceFixture.getSecondParticipant());
ConferenceFixture.closeThirdParticipant();
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), false);
verifyRemoteVideosDisplay(
ConferenceFixture.getSecondParticipant(), true);
}
/**
* Tests remote videos in filmstrip become visible when focused on self view
* while in a 1-on-1 call.
*/
public void testFilmstripVisibleOnSelfViewFocus() {
MeetUIUtils.clickOnLocalVideo(ConferenceFixture.getOwner());
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
MeetUIUtils.clickOnLocalVideo(ConferenceFixture.getOwner());
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), false);
}
/**
* Tests remote videos in filmstrip stay visible when hovering over when the
* filmstrip is hovered over.
*/
public void testFilmstripHoverShowsVideos() {
WebDriver owner = ConferenceFixture.getOwner();
WebElement toolbar = owner.findElement(By.id("remoteVideos"));
Actions hoverOnToolbar = new Actions(owner);
hoverOnToolbar.moveToElement(toolbar);
hoverOnToolbar.perform();
verifyRemoteVideosDisplay(owner, true);
}
/**
* Ensures participants reopen their browsers without 1-on-1 mode enabled.
*/
public void testStopOneOnOneTest() {
ConferenceFixture.restartParticipants();
}
/**
* Check if remote videos in filmstrip are visible.
*
* @param testee the <tt>WebDriver</tt> of the participant for whom we're
* checking the status of filmstrip remote video visibility.
* @param isDisplayed whether or not filmstrip remote videos should be
* visible
*/
private void verifyRemoteVideosDisplay(
WebDriver testee, boolean isDisplayed)
{
waitForToolbarsHidden(testee);
String filmstripRemoteVideosXpath
= "//div[@id='filmstripRemoteVideosContainer']";
TestUtils.waitForDisplayedOrNotByXPath(
testee,
filmstripRemoteVideosXpath,
filmstripVisibilityWait,
isDisplayed);
}
/**
* Disables permanent display (docking) of the toolbars.
*
* @param testee the <tt>WebDriver</tt> of the participant for whom we're
* no longer want to dock toolbars.
*/
private void stopDockingToolbar(WebDriver testee) {
((JavascriptExecutor) testee)
.executeScript("APP.UI.dockToolbar(false);");
}
/**
* Waits until the toolbars are no longer displayed.
*
* @param testee the <tt>WebDriver</tt> of the participant for whom we're
* waiting to no longer see toolbars.
*/
private void waitForToolbarsHidden(WebDriver testee) {
// Wait for the visible filmstrip to no longer be displayed.
String visibleToolbarXpath
= "//*[contains(@class, 'toolbar_secondary')"
+ "and contains(@class ,'slideInExtX')]";
TestUtils.waitForElementNotPresentByXPath(
testee,
visibleToolbarXpath,
filmstripVisibilityWait);
}
}
| src/test/java/org/jitsi/meet/test/OneOnOneTest.java | /*
* Copyright @ 2017 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.meet.test;
import junit.framework.*;
import org.jitsi.meet.test.util.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
/**
* Tests 1-on-1 remote video thumbnail display in the filmstrip.
*
* @author Leonard Kim
*/
public class OneOnOneTest
extends TestCase
{
private final static String filmstripRemoteVideosXpath
= "//div[@id='filmstripRemoteVideosContainer']";
private final int filmstripVisibilityWait = 5;
/**
* Constructs test
* @param name the method name for the test.
*/
public OneOnOneTest(String name)
{
super(name);
}
/**
* Orders the tests.
* @return the suite with order tests.
*/
public static junit.framework.Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new OneOnOneTest("testFilmstripHiddenInOneOnOne"));
suite.addTest(new OneOnOneTest("testFilmstripVisibleWithMoreThanTwo"));
suite.addTest(
new OneOnOneTest("testFilmstripDisplayWhenReturningToOneOnOne"));
suite.addTest(new OneOnOneTest("testFilmstripVisibleOnSelfViewFocus"));
suite.addTest(new OneOnOneTest("testShareVideoShowsRemoteVideos"));
suite.addTest(new OneOnOneTest("testStopOneOnOneTest"));
return suite;
}
/**
* Tests remote videos in filmstrip do not display in a 1-on-1 call.
*/
public void testFilmstripHiddenInOneOnOne()
{
// Close the browsers first and then load the meeting so hash changes to
// the config are detected by the browser.
ConferenceFixture.close(ConferenceFixture.getOwner());
ConferenceFixture.close(ConferenceFixture.getSecondParticipant());
ConferenceFixture.startOwner("config.disable1On1Mode=false");
ConferenceFixture.startSecondParticipant(
"config.disable1On1Mode=false");
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), false);
verifyRemoteVideosDisplay(
ConferenceFixture.getSecondParticipant(), false);
}
/**
* Tests remote videos in filmstrip do display when in a call with more than
* two total participants.
*/
public void testFilmstripVisibleWithMoreThanTwo() {
// Close the third participant's browser and reopen so hash changes to
// the config are detected by the browser.
ConferenceFixture.waitForThirdParticipantToConnect();
ConferenceFixture.close(ConferenceFixture.getThirdParticipant());
ConferenceFixture.startThirdParticipant("config.disable1On1Mode=false");
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
verifyRemoteVideosDisplay(
ConferenceFixture.getSecondParticipant(), true);
verifyRemoteVideosDisplay(
ConferenceFixture.getThirdParticipant(), true);
}
/**
* Tests remote videos in filmstrip do not display after transitioning to
* 1-on-1 mode. Also tests remote videos in filmstrip do display when
* focused on self and transitioning back to 1-on-1 mode.
*/
public void testFilmstripDisplayWhenReturningToOneOnOne() {
MeetUIUtils.clickOnLocalVideo(ConferenceFixture.getSecondParticipant());
ConferenceFixture.closeThirdParticipant();
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), false);
verifyRemoteVideosDisplay(
ConferenceFixture.getSecondParticipant(), true);
}
/**
* Tests remote videos in filmstrip become visible when focused on self view
* while in a 1-on-1 call.
*/
public void testFilmstripVisibleOnSelfViewFocus() {
MeetUIUtils.clickOnLocalVideo(ConferenceFixture.getOwner());
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
MeetUIUtils.clickOnLocalVideo(ConferenceFixture.getOwner());
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), false);
}
/**
* Tests remote videos in filmstrip become visible when sharing video, even
* when in a lonely call.
*/
public void testShareVideoShowsRemoteVideos() {
SharedVideoTest sharedVideoTest = new SharedVideoTest("startSharingVideo");
sharedVideoTest.startSharingVideo();
ConferenceFixture.closeSecondParticipant();
WebDriver owner = ConferenceFixture.getOwner();
TestUtils.waitForCondition(owner, 5,
new ExpectedCondition<Boolean>()
{
public Boolean apply(WebDriver d)
{
return MeetUIUtils.getRemoteVideos(d).size() == 0;
}
});
verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
}
/**
* Ensures participants reopen their browsers without 1-on-1 mode enabled.
*/
public void testStopOneOnOneTest() {
ConferenceFixture.restartParticipants();
}
/**
* Check if remote videos in filmstrip are visible.
*
* @param testee the <tt>WebDriver</tt> of the participant for whom we're
* checking the status of filmstrip remote video visibility.
* @param isDisplayed whether or not filmstrip remote videos should be
* visible
*/
private void verifyRemoteVideosDisplay(
WebDriver testee, boolean isDisplayed)
{
TestUtils.waitForDisplayedOrNotByXPath(
testee,
filmstripRemoteVideosXpath,
filmstripVisibilityWait,
isDisplayed);
}
}
| fix(1-on-1): update tests for displaying videos with toolbar
jitsi-meet will have changes that have the remote videos of
the filmstrip display with the toolbars. The 1-on-1 tests have
to make sure the toolbars are not set to show all the time
and also wait for them to disappear. The test for showing
remote videos while sharing video was removed because sharing
video docks the toolbar, so remote videos always display. That
test has been replaced with a test to ensure remote videos
stay displayed while being hovered over.
| src/test/java/org/jitsi/meet/test/OneOnOneTest.java | fix(1-on-1): update tests for displaying videos with toolbar | <ide><path>rc/test/java/org/jitsi/meet/test/OneOnOneTest.java
<ide> import junit.framework.*;
<ide> import org.jitsi.meet.test.util.*;
<ide> import org.openqa.selenium.*;
<del>import org.openqa.selenium.support.ui.ExpectedCondition;
<add>import org.openqa.selenium.interactions.Actions;
<ide>
<ide> /**
<ide> * Tests 1-on-1 remote video thumbnail display in the filmstrip.
<ide> public class OneOnOneTest
<ide> extends TestCase
<ide> {
<del> private final static String filmstripRemoteVideosXpath
<del> = "//div[@id='filmstripRemoteVideosContainer']";
<add> /**
<add> * The duration to wait, in seconds, remote videos in filmstrip to display
<add> * and complete animations.
<add> */
<ide> private final int filmstripVisibilityWait = 5;
<add>
<add> /**
<add> * Parameters to attach to the meeting url to enable One-On-One behavior
<add> * and have toolbars dismiss faster, as remote video visibility is also
<add> * tied to toolbar visibility.
<add> */
<add> private final String oneOnOneConfigOverrides
<add> = "config.disable1On1Mode=false"
<add> + "&interfaceConfig.TOOLBAR_TIMEOUT=500"
<add> + "&interfaceConfig.INITIAL_TOOLBAR_TIMEOUT=500"
<add> + "&config.alwaysVisibleToolbar=false";
<ide>
<ide> /**
<ide> * Constructs test
<ide> suite.addTest(
<ide> new OneOnOneTest("testFilmstripDisplayWhenReturningToOneOnOne"));
<ide> suite.addTest(new OneOnOneTest("testFilmstripVisibleOnSelfViewFocus"));
<del> suite.addTest(new OneOnOneTest("testShareVideoShowsRemoteVideos"));
<add> suite.addTest(new OneOnOneTest("testFilmstripHoverShowsVideos"));
<ide> suite.addTest(new OneOnOneTest("testStopOneOnOneTest"));
<ide>
<ide> return suite;
<ide> */
<ide> public void testFilmstripHiddenInOneOnOne()
<ide> {
<add> WebDriver owner = ConferenceFixture.getOwner();
<add> WebDriver secondParticipant = ConferenceFixture.getSecondParticipant();
<add>
<ide> // Close the browsers first and then load the meeting so hash changes to
<ide> // the config are detected by the browser.
<del> ConferenceFixture.close(ConferenceFixture.getOwner());
<del> ConferenceFixture.close(ConferenceFixture.getSecondParticipant());
<del>
<del> ConferenceFixture.startOwner("config.disable1On1Mode=false");
<del> ConferenceFixture.startSecondParticipant(
<del> "config.disable1On1Mode=false");
<del>
<del> verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), false);
<del> verifyRemoteVideosDisplay(
<del> ConferenceFixture.getSecondParticipant(), false);
<add> ConferenceFixture.close(owner);
<add> ConferenceFixture.close(secondParticipant);
<add>
<add> ConferenceFixture.startOwner(oneOnOneConfigOverrides);
<add> ConferenceFixture.startSecondParticipant(oneOnOneConfigOverrides);
<add>
<add> // Prevent toolbar from being always displayed as filmstrip visibility
<add> // is tied to toolbar visibility.
<add> stopDockingToolbar(owner);
<add> stopDockingToolbar(secondParticipant);
<add>
<add> verifyRemoteVideosDisplay(owner, false);
<add> verifyRemoteVideosDisplay(secondParticipant, false);
<ide> }
<ide>
<ide> /**
<ide> public void testFilmstripVisibleWithMoreThanTwo() {
<ide> // Close the third participant's browser and reopen so hash changes to
<ide> // the config are detected by the browser.
<add> WebDriver thirdParticipant = ConferenceFixture.getThirdParticipant();
<add>
<ide> ConferenceFixture.waitForThirdParticipantToConnect();
<del> ConferenceFixture.close(ConferenceFixture.getThirdParticipant());
<del> ConferenceFixture.startThirdParticipant("config.disable1On1Mode=false");
<add> ConferenceFixture.close(thirdParticipant);
<add> ConferenceFixture.startThirdParticipant(oneOnOneConfigOverrides);
<add> stopDockingToolbar(thirdParticipant);
<ide>
<ide> verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
<ide> verifyRemoteVideosDisplay(
<ide> ConferenceFixture.getSecondParticipant(), true);
<del> verifyRemoteVideosDisplay(
<del> ConferenceFixture.getThirdParticipant(), true);
<add> verifyRemoteVideosDisplay(thirdParticipant, true);
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<del> * Tests remote videos in filmstrip become visible when sharing video, even
<del> * when in a lonely call.
<del> */
<del> public void testShareVideoShowsRemoteVideos() {
<del> SharedVideoTest sharedVideoTest = new SharedVideoTest("startSharingVideo");
<del>
<del> sharedVideoTest.startSharingVideo();
<del>
<del> ConferenceFixture.closeSecondParticipant();
<del>
<add> * Tests remote videos in filmstrip stay visible when hovering over when the
<add> * filmstrip is hovered over.
<add> */
<add> public void testFilmstripHoverShowsVideos() {
<ide> WebDriver owner = ConferenceFixture.getOwner();
<del> TestUtils.waitForCondition(owner, 5,
<del> new ExpectedCondition<Boolean>()
<del> {
<del> public Boolean apply(WebDriver d)
<del> {
<del> return MeetUIUtils.getRemoteVideos(d).size() == 0;
<del> }
<del> });
<del>
<del> verifyRemoteVideosDisplay(ConferenceFixture.getOwner(), true);
<add>
<add> WebElement toolbar = owner.findElement(By.id("remoteVideos"));
<add> Actions hoverOnToolbar = new Actions(owner);
<add> hoverOnToolbar.moveToElement(toolbar);
<add> hoverOnToolbar.perform();
<add>
<add> verifyRemoteVideosDisplay(owner, true);
<ide> }
<ide>
<ide> /**
<ide> private void verifyRemoteVideosDisplay(
<ide> WebDriver testee, boolean isDisplayed)
<ide> {
<add> waitForToolbarsHidden(testee);
<add>
<add> String filmstripRemoteVideosXpath
<add> = "//div[@id='filmstripRemoteVideosContainer']";
<add>
<ide> TestUtils.waitForDisplayedOrNotByXPath(
<ide> testee,
<ide> filmstripRemoteVideosXpath,
<ide> filmstripVisibilityWait,
<ide> isDisplayed);
<ide> }
<add>
<add> /**
<add> * Disables permanent display (docking) of the toolbars.
<add> *
<add> * @param testee the <tt>WebDriver</tt> of the participant for whom we're
<add> * no longer want to dock toolbars.
<add>
<add> */
<add> private void stopDockingToolbar(WebDriver testee) {
<add> ((JavascriptExecutor) testee)
<add> .executeScript("APP.UI.dockToolbar(false);");
<add> }
<add>
<add> /**
<add> * Waits until the toolbars are no longer displayed.
<add> *
<add> * @param testee the <tt>WebDriver</tt> of the participant for whom we're
<add> * waiting to no longer see toolbars.
<add> */
<add> private void waitForToolbarsHidden(WebDriver testee) {
<add> // Wait for the visible filmstrip to no longer be displayed.
<add> String visibleToolbarXpath
<add> = "//*[contains(@class, 'toolbar_secondary')"
<add> + "and contains(@class ,'slideInExtX')]";
<add>
<add> TestUtils.waitForElementNotPresentByXPath(
<add> testee,
<add> visibleToolbarXpath,
<add> filmstripVisibilityWait);
<add> }
<ide> } |
|
Java | apache-2.0 | 0cc6715cc7629d568c32c07db54c7c6171b4c40c | 0 | SoltauFintel/xmldocument | package de.mwvb.base.xml;
import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.DOMReader;
import org.dom4j.io.DOMWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* XML document
*
* <p>Wrapper of DOM4J for easy DOM- and XPath-based XML access.
*
* <p>Advantages:<ul>
* <li>easy navigation through XML document</li>
* <li>getValue(attributeName) returns "" if attribute does not exist</li>
* <li>add(elementName) creates and appends new XML element in one operation</li>
* <li>easy XMLDocument to/from XML conversions</li>
* <li>many ways to save and load XMLDocument</li>
* <li>easy XPath access using selectNodes() or selectSingleNode()</li>
* <li>and some more special functions.</li>
* </ul>
*
* @author Marcus Warm
* @since 2008
*/
public class XMLDocument implements Closeable {
private Document doc;
/**
* Default constructor
* <p>Document will not be initialized.
*/
public XMLDocument() {
}
/**
* XML String constructor
*
* @param xml valid XML String
*/
public XMLDocument(final String xml) {
if (xml == null) {
throw new IllegalArgumentException("XMLDocument argument xml must not be null!");
}
try {
doc = DocumentHelper.parseText(xml);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
/**
* Load XML file constructor
*
* @param isResource true if it is a resource file in a package,<br>false if it is a file in file system
* @param fileName file name incl. path
* <br>File name can begin with "file:" or "http:". In that case the isResource option will be ignored.
*/
public XMLDocument(final boolean isResource, final String fileName) {
if (fileName.startsWith("file:") || fileName.startsWith("http:")) {
try {
URL url = new URL(fileName);
loadStream(url.openConnection().getInputStream());
} catch (Throwable e) {
throw new RuntimeException("Error loading XML file '" + fileName + "'!", e);
}
} else if (isResource) {
loadResource(fileName);
} else {
loadFile(fileName);
}
}
/**
* Load XML file constructor
*
* @param file file in file system
*/
public XMLDocument(final File file) {
this(false, file.getPath());
}
/**
* XML stream constructor
*
* @param stream InputStream
*/
public XMLDocument(final InputStream stream) {
loadStream(stream);
}
/**
* Load XML file constructor
*
* @param clazz class to get package path
* @param resourceName file name of the resource without path
*/
public XMLDocument(final Class<?> clazz, final String resourceName) {
final char slash = '/';
final String path = clazz.getPackage().getName().replace('.', slash);
loadResource(slash + path + slash + resourceName);
}
/**
* org.w3c.dom.Document to XMLDocument constructor
*
* @param w3cDoc org.w3c.dom.Document
*/
public XMLDocument(final org.w3c.dom.Document w3cDoc) {
final DOMReader reader = new DOMReader();
doc = reader.read(w3cDoc);
}
/**
* Load XML file
*
* @param fileName name of file in file system
* @return XMLDocument
*/
public static XMLDocument load(final String fileName) {
final XMLDocument ret = new XMLDocument();
ret.loadFile(fileName);
return ret;
}
/**
* Load XML file
*
* @param fileName name of file in file system
* @return XML String
*/
public static String loadXML(final String fileName) {
final XMLDocument ret = new XMLDocument();
try {
ret.loadFile(fileName);
return ret.getXML();
} finally {
ret.close();
}
}
/**
* Load XML file
*
* @param fileName name of in file system
*/
public void loadFile(final String fileName) {
try {
final SAXReader r = new SAXReader();
doc = r.read(fileName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Load XML file
*
* @param resourceName name of resource file, incl. path
*/
public void loadResource(final String resourceName) {
InputStream stream = getClass().getResourceAsStream(resourceName);
if (stream == null) {
throw new RuntimeException("Error loading resource file '" + resourceName + "'!");
}
loadStream(stream); // <- closes stream
}
/**
* Load XML file
*
* @param stream InputStream
*/
public void loadStream(final InputStream stream) {
try {
final SAXReader r = new SAXReader();
doc = r.read(stream);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
}
/**
* Save XML document to file using pretty print format
*
* @param fileName name of file in file system
*/
public void saveFile(final String fileName) {
saveFile(fileName, OutputFormat.createPrettyPrint());
}
/**
* Save XML document to file using compact format
*
* @param fileName name of file in file system
*/
public void saveFileCompact(final String fileName) {
saveFile(fileName, OutputFormat.createCompactFormat());
}
private void saveFile(final String fileName, final OutputFormat format) {
try {
final FileWriter writer = new FileWriter(fileName);
try {
format.setEncoding(getEncoding());
new XMLWriter(writer, format).write(doc);
} finally {
writer.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected String getEncoding() {
return "windows-1252";
}
/**
* @return true if document is valid and root element has child elements
*/
public boolean isOkay() {
return doc != null
&& doc.getRootElement() != null
&& doc.getRootElement().elements() != null
&& doc.getRootElement().elements().size() > 0;
}
/**
* @return root element, null if document was not initialized
*/
public XMLElement getElement() {
return doc == null ? null : XMLElementImpl.create(doc.getRootElement());
}
/**
* Returns XML child elements
*
* @return XMLElement list
*/
public List<XMLElement> getChildren() {
return XMLElementImpl.getChildElements(doc.getRootElement().elements());
}
/**
* XML element selection using XPath (Dokumentebene)
* <p>An exception will be thrown if the XPath statement is incorrect.
*
* @param pXPath XPath String, e.g. "//addresses/person[@surname='Doe']"
* @return XMLElement Liste
*/
public List<XMLElement> selectNodes(final String pXPath) {
return XMLElementImpl.getChildElements(doc.selectNodes(pXPath));
}
/**
* XML element selection using XPath (Dokumentebene)
* <p>An exception will be thrown if the XPath statement is incorrect.
*
* @param pXPath XPath String, e.g. "//addresses/person[@id='4711']"
* <br>The XPath String should deliver only one element.
* @return XMLElement or null if no element was found
*/
public XMLElement selectSingleNode(final String pXPath) {
final Node node = doc.selectSingleNode(pXPath);
if (node == null) {
return null;
} else {
return XMLElementImpl.create((Element) node);
}
}
/**
* Returns a element which has the given value in attribute "id".
* It is assumed that there is only one element with that id.
*
* @param id id value
* @return XMLElement or null if no element was found
*/
public XMLElement byId(final String id) {
return selectSingleNode("//*[@id='" + id + "']");
}
/**
* Removes a non-root-element in the whole document with given value in attribute "id".
*
* @param id id value
* @return true: element was removed, false: element was not found
*/
public boolean removeChildById(final String id) {
final String xpath = "*[@id='" + id + "']";
XMLElement p = selectSingleNode("//" + xpath + "/..");
if (p != null) {
p.removeChildren(xpath);
}
return p != null;
}
/**
* @return XML String
*/
public String getXML() {
return doc.asXML();
}
@Override
public String toString() {
return getXML();
}
/**
* Converts this DOM4J-based Document to org.w3c.dom.Document
*
* @return org.w3c.dom.Document
* @throws DocumentException -
*/
public org.w3c.dom.Document getW3CDocument() throws DocumentException {
return new DOMWriter().write(doc);
}
@Override
public void close() {
doc = null; // frees memory
}
}
| xmldocument/src/main/java/de/mwvb/base/xml/XMLDocument.java | package de.mwvb.base.xml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.DOMReader;
import org.dom4j.io.DOMWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* XML document
*
* <p>Wrapper of DOM4J for easy DOM- and XPath-based XML access.
*
* <p>Advantages:<ul>
* <li>easy navigation through XML document</li>
* <li>getValue(attributeName) returns "" if attribute does not exist</li>
* <li>add(elementName) creates and appends new XML element in one operation</li>
* <li>easy XMLDocument to/from XML conversions</li>
* <li>many ways to save and load XMLDocument</li>
* <li>easy XPath access using selectNodes() or selectSingleNode()</li>
* <li>and some more special functions.</li>
* </ul>
*
* @author Marcus Warm
* @since 2008
*/
public class XMLDocument {
private Document doc;
/**
* Default constructor
* <p>Document will not be initialized.
*/
public XMLDocument() {
}
/**
* XML String constructor
*
* @param xml valid XML String
*/
public XMLDocument(final String xml) {
if (xml == null) {
throw new IllegalArgumentException("XMLDocument argument xml must not be null!");
}
try {
doc = DocumentHelper.parseText(xml);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
/**
* Load XML file constructor
*
* @param isResource true if it is a resource file in a package,<br>false if it is a file in file system
* @param fileName file name incl. path
* <br>File name can begin with "file:" or "http:". In that case the isResource option will be ignored.
*/
public XMLDocument(final boolean isResource, final String fileName) {
if (fileName.startsWith("file:") || fileName.startsWith("http:")) {
try {
URL url = new URL(fileName);
loadStream(url.openConnection().getInputStream());
} catch (Throwable e) {
throw new RuntimeException("Error loading XML file '" + fileName + "'!", e);
}
} else if (isResource) {
loadResource(fileName);
} else {
loadFile(fileName);
}
}
/**
* Load XML file constructor
*
* @param file file in file system
*/
public XMLDocument(final File file) {
this(false, file.getPath());
}
/**
* XML stream constructor
*
* @param stream InputStream
*/
public XMLDocument(final InputStream stream) {
loadStream(stream);
}
/**
* Load XML file constructor
*
* @param clazz class to get package path
* @param resourceName file name of the resource without path
*/
public XMLDocument(final Class<?> clazz, final String resourceName) {
final char slash = '/';
final String path = clazz.getPackage().getName().replace('.', slash);
loadResource(slash + path + slash + resourceName);
}
/**
* org.w3c.dom.Document to XMLDocument constructor
*
* @param w3cDoc org.w3c.dom.Document
*/
public XMLDocument(final org.w3c.dom.Document w3cDoc) {
final DOMReader reader = new DOMReader();
doc = reader.read(w3cDoc);
}
/**
* Load XML file
*
* @param fileName name of file in file system
* @return XMLDocument
*/
public static XMLDocument load(final String fileName) {
final XMLDocument ret = new XMLDocument();
ret.loadFile(fileName);
return ret;
}
/**
* Load XML file
*
* @param fileName name of file in file system
* @return XML String
*/
public static String loadXML(final String fileName) {
final XMLDocument ret = new XMLDocument();
ret.loadFile(fileName);
return ret.getXML();
}
/**
* Load XML file
*
* @param fileName name of in file system
*/
public void loadFile(final String fileName) {
try {
final SAXReader r = new SAXReader();
doc = r.read(fileName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Load XML file
*
* @param resourceName name of resource file, incl. path
*/
public void loadResource(final String resourceName) {
InputStream stream = getClass().getResourceAsStream(resourceName);
if (stream == null) {
throw new RuntimeException("Error loading resource file '" + resourceName + "'!");
}
loadStream(stream); // <- closes stream
}
/**
* Load XML file
*
* @param stream InputStream
*/
public void loadStream(final InputStream stream) {
try {
final SAXReader r = new SAXReader();
doc = r.read(stream);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
}
/**
* Save XML document to file using pretty print format
*
* @param fileName name of file in file system
*/
public void saveFile(final String fileName) {
saveFile(fileName, OutputFormat.createPrettyPrint());
}
/**
* Save XML document to file using compact format
*
* @param fileName name of file in file system
*/
public void saveFileCompact(final String fileName) {
saveFile(fileName, OutputFormat.createCompactFormat());
}
private void saveFile(final String fileName, final OutputFormat format) {
try {
final FileWriter writer = new FileWriter(fileName);
try {
format.setEncoding(getEncoding());
new XMLWriter(writer, format).write(doc);
} finally {
writer.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected String getEncoding() {
return "windows-1252";
}
/**
* @return true if document is valid and root element has child elements
*/
public boolean isOkay() {
return doc != null
&& doc.getRootElement() != null
&& doc.getRootElement().elements() != null
&& doc.getRootElement().elements().size() > 0;
}
/**
* @return root element, null if document was not initialized
*/
public XMLElement getElement() {
return doc == null ? null : XMLElementImpl.create(doc.getRootElement());
}
/**
* Returns XML child elements
*
* @return XMLElement list
*/
public List<XMLElement> getChildren() {
return XMLElementImpl.getChildElements(doc.getRootElement().elements());
}
/**
* XML element selection using XPath (Dokumentebene)
* <p>An exception will be thrown if the XPath statement is incorrect.
*
* @param pXPath XPath String, e.g. "//addresses/person[@surname='Doe']"
* @return XMLElement Liste
*/
public List<XMLElement> selectNodes(final String pXPath) {
return XMLElementImpl.getChildElements(doc.selectNodes(pXPath));
}
/**
* XML element selection using XPath (Dokumentebene)
* <p>An exception will be thrown if the XPath statement is incorrect.
*
* @param pXPath XPath String, e.g. "//addresses/person[@id='4711']"
* <br>The XPath String should deliver only one element.
* @return XMLElement or null if no element was found
*/
public XMLElement selectSingleNode(final String pXPath) {
final Node node = doc.selectSingleNode(pXPath);
if (node == null) {
return null;
} else {
return XMLElementImpl.create((Element) node);
}
}
/**
* Returns a element which has the given value in attribute "id".
* It is assumed that there is only one element with that id.
*
* @param id id value
* @return XMLElement or null if no element was found
*/
public XMLElement byId(final String id) {
return selectSingleNode("//*[@id='" + id + "']");
}
/**
* Removes a non-root-element in the whole document with given value in attribute "id".
*
* @param id id value
* @return true: element was removed, false: element was not found
*/
public boolean removeChildById(final String id) {
final String xpath = "*[@id='" + id + "']";
XMLElement p = selectSingleNode("//" + xpath + "/..");
if (p != null) {
p.removeChildren(xpath);
}
return p != null;
}
/**
* @return XML String
*/
public String getXML() {
return doc.asXML();
}
@Override
public String toString() {
return getXML();
}
/**
* Converts this DOM4J-based Document to org.w3c.dom.Document
*
* @return org.w3c.dom.Document
* @throws DocumentException -
*/
public org.w3c.dom.Document getW3CDocument() throws DocumentException {
return new DOMWriter().write(doc);
}
}
| XMLDocument implements Closeable | xmldocument/src/main/java/de/mwvb/base/xml/XMLDocument.java | XMLDocument implements Closeable | <ide><path>mldocument/src/main/java/de/mwvb/base/xml/XMLDocument.java
<ide> package de.mwvb.base.xml;
<ide>
<add>import java.io.Closeable;
<ide> import java.io.File;
<ide> import java.io.FileWriter;
<ide> import java.io.IOException;
<ide> * @author Marcus Warm
<ide> * @since 2008
<ide> */
<del>public class XMLDocument {
<add>public class XMLDocument implements Closeable {
<ide> private Document doc;
<ide>
<ide> /**
<ide> */
<ide> public static String loadXML(final String fileName) {
<ide> final XMLDocument ret = new XMLDocument();
<del> ret.loadFile(fileName);
<del> return ret.getXML();
<add> try {
<add> ret.loadFile(fileName);
<add> return ret.getXML();
<add> } finally {
<add> ret.close();
<add> }
<ide> }
<ide>
<ide> /**
<ide> public org.w3c.dom.Document getW3CDocument() throws DocumentException {
<ide> return new DOMWriter().write(doc);
<ide> }
<add>
<add> @Override
<add> public void close() {
<add> doc = null; // frees memory
<add> }
<ide> } |
|
Java | apache-2.0 | 2648862cf279367bb4d430bc7a52a53fcc80d125 | 0 | amith01994/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,adedayo/intellij-community,da1z/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,da1z/intellij-community,hurricup/intellij-community,samthor/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,petteyg/intellij-community,vladmm/intellij-community,adedayo/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,fitermay/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,semonte/intellij-community,vvv1559/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,fnouama/intellij-community,robovm/robovm-studio,amith01994/intellij-community,ibinti/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,da1z/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,supersven/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ernestp/consulo,diorcety/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,consulo/consulo,semonte/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,kool79/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,jexp/idea2,akosyakov/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,amith01994/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,slisson/intellij-community,signed/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,da1z/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,dslomov/intellij-community,holmes/intellij-community,samthor/intellij-community,caot/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ernestp/consulo,ol-loginov/intellij-community,caot/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,adedayo/intellij-community,izonder/intellij-community,adedayo/intellij-community,da1z/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,supersven/intellij-community,supersven/intellij-community,FHannes/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ryano144/intellij-community,kool79/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,ryano144/intellij-community,robovm/robovm-studio,petteyg/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,diorcety/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,signed/intellij-community,jagguli/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,ahb0327/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,xfournet/intellij-community,izonder/intellij-community,ryano144/intellij-community,robovm/robovm-studio,asedunov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ahb0327/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,allotria/intellij-community,hurricup/intellij-community,amith01994/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,jexp/idea2,ftomassetti/intellij-community,consulo/consulo,retomerz/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,robovm/robovm-studio,diorcety/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,jagguli/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,allotria/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,amith01994/intellij-community,supersven/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,fitermay/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,izonder/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,dslomov/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,kool79/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,holmes/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,petteyg/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,joewalnes/idea-community,asedunov/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,vladmm/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,kool79/intellij-community,clumsy/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,jexp/idea2,youdonghai/intellij-community,asedunov/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,vladmm/intellij-community,kool79/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,signed/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,samthor/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,slisson/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,clumsy/intellij-community,asedunov/intellij-community,diorcety/intellij-community,hurricup/intellij-community,allotria/intellij-community,vladmm/intellij-community,caot/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,semonte/intellij-community,diorcety/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,allotria/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,ernestp/consulo,signed/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ryano144/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,holmes/intellij-community,asedunov/intellij-community,jagguli/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,semonte/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,ahb0327/intellij-community,slisson/intellij-community,retomerz/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ibinti/intellij-community,jagguli/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,fitermay/intellij-community,kool79/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,fitermay/intellij-community,xfournet/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,samthor/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,caot/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,robovm/robovm-studio,fnouama/intellij-community,samthor/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,slisson/intellij-community,asedunov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,slisson/intellij-community,holmes/intellij-community,apixandru/intellij-community,jexp/idea2,ryano144/intellij-community,adedayo/intellij-community,signed/intellij-community,blademainer/intellij-community,xfournet/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,clumsy/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,joewalnes/idea-community,izonder/intellij-community,retomerz/intellij-community,supersven/intellij-community,semonte/intellij-community,kool79/intellij-community,caot/intellij-community,jexp/idea2,blademainer/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,allotria/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,consulo/consulo,supersven/intellij-community,petteyg/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,da1z/intellij-community,adedayo/intellij-community,signed/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,consulo/consulo,apixandru/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,clumsy/intellij-community,apixandru/intellij-community,kdwink/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,caot/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,izonder/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,supersven/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,wreckJ/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,consulo/consulo,vvv1559/intellij-community,signed/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fitermay/intellij-community,robovm/robovm-studio,FHannes/intellij-community,Distrotech/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,samthor/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,adedayo/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,signed/intellij-community,fitermay/intellij-community,caot/intellij-community,jexp/idea2,ol-loginov/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,xfournet/intellij-community,joewalnes/idea-community,blademainer/intellij-community,amith01994/intellij-community,ibinti/intellij-community,kool79/intellij-community,vladmm/intellij-community,allotria/intellij-community,allotria/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,supersven/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,ryano144/intellij-community,izonder/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,allotria/intellij-community,hurricup/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,izonder/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,TangHao1987/intellij-community,caot/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,da1z/intellij-community,adedayo/intellij-community,apixandru/intellij-community,robovm/robovm-studio,vladmm/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,joewalnes/idea-community,diorcety/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ryano144/intellij-community | package com.intellij.formatting;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.FormattingDocumentModelImpl;
import com.intellij.psi.formatter.ReadOnlyBlockInformationProvider;
import com.intellij.psi.formatter.xml.SyntheticBlock;
import com.intellij.psi.impl.DebugUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class InitialInfoBuilder {
private static final Logger LOG = Logger.getInstance("#com.intellij.formatting.InitialInfoBuilder");
private WhiteSpace myCurrentWhiteSpace;
private final FormattingDocumentModel myModel;
private TextRange myAffectedRange;
private final int myPositionOfInterest;
private boolean myProcessHeadingWhitespace;
private final Map<AbstractBlockWrapper, Block> myResult = new THashMap<AbstractBlockWrapper, Block>();
private CompositeBlockWrapper myRootBlockWrapper;
private LeafBlockWrapper myPreviousBlock;
private LeafBlockWrapper myFirstTokenBlock;
private LeafBlockWrapper myLastTokenBlock;
private SpacingImpl myCurrentSpaceProperty;
private final CodeStyleSettings.IndentOptions myOptions;
private ReadOnlyBlockInformationProvider myReadOnlyBlockInformationProvider;
private InitialInfoBuilder(final FormattingDocumentModel model,
final TextRange affectedRange,
final CodeStyleSettings.IndentOptions options,
final boolean processHeadingWhitespace,
final int positionOfInterest
) {
myModel = model;
myAffectedRange = affectedRange;
myProcessHeadingWhitespace = processHeadingWhitespace;
myCurrentWhiteSpace = new WhiteSpace(0, true);
myOptions = options;
myPositionOfInterest = positionOfInterest;
}
public static InitialInfoBuilder buildBlocks(Block root,
FormattingDocumentModel model,
final TextRange affectedRange,
final CodeStyleSettings.IndentOptions options,
final boolean processHeadingWhitespace, int interestingOffset) {
final InitialInfoBuilder builder = new InitialInfoBuilder(model, affectedRange, options, processHeadingWhitespace, interestingOffset);
final AbstractBlockWrapper wrapper = builder.buildFrom(root, 0, null, null, root.getTextRange(), null, true);
wrapper.setIndent((IndentImpl)Indent.getNoneIndent());
return builder;
}
private AbstractBlockWrapper buildFrom(final Block rootBlock,
final int index,
final AbstractBlockWrapper parent,
WrapImpl currentWrapParent,
final TextRange textRange,
final Block parentBlock,
boolean rootBlockIsRightBlock
) {
final WrapImpl wrap = (WrapImpl)rootBlock.getWrap();
if (wrap != null) {
wrap.registerParent(currentWrapParent);
currentWrapParent = wrap;
}
final int blockStartOffset = textRange.getStartOffset();
if (parent != null) {
if (textRange.getStartOffset() < parent.getStartOffset()) {
assertInvalidRanges(
textRange.getStartOffset(),
parent.getStartOffset(),
myModel,
"child block start is less than parent block start"
);
}
if (textRange.getEndOffset() > parent.getEndOffset()) {
assertInvalidRanges(
textRange.getEndOffset(),
parent.getEndOffset(),
myModel,
"child block end is after parent block end"
);
}
}
myCurrentWhiteSpace.append(blockStartOffset, myModel, myOptions);
boolean isReadOnly = isReadOnly(textRange, rootBlockIsRightBlock);
ReadOnlyBlockInformationProvider previousProvider = myReadOnlyBlockInformationProvider;
try {
if (rootBlock instanceof ReadOnlyBlockInformationProvider) {
myReadOnlyBlockInformationProvider = (ReadOnlyBlockInformationProvider)rootBlock;
}
if (isReadOnly) {
return processSimpleBlock(rootBlock, parent, isReadOnly, textRange, index, parentBlock);
}
else {
final List<Block> subBlocks = rootBlock.getSubBlocks();
if (subBlocks.isEmpty() || myReadOnlyBlockInformationProvider != null &&
myReadOnlyBlockInformationProvider.isReadOnly(rootBlock)) {
final AbstractBlockWrapper wrapper = processSimpleBlock(rootBlock, parent, isReadOnly, textRange, index, parentBlock);
if (subBlocks.size() > 0) {
wrapper.setIndent((IndentImpl)subBlocks.get(0).getIndent());
}
return wrapper;
}
else {
return processCompositeBlock(rootBlock, parent, textRange, index, subBlocks, currentWrapParent, rootBlockIsRightBlock);
}
}
} finally {
myReadOnlyBlockInformationProvider = previousProvider;
}
}
private AbstractBlockWrapper processCompositeBlock(final Block rootBlock,
final AbstractBlockWrapper parent,
final TextRange textRange,
final int index,
final List<Block> subBlocks,
final WrapImpl currentWrapParent,
boolean rootBlockIsRightBlock
) {
final CompositeBlockWrapper info = new CompositeBlockWrapper(rootBlock, myCurrentWhiteSpace, parent, textRange);
if (index == 0) {
info.arrangeParentTextRange();
}
if (myRootBlockWrapper == null) myRootBlockWrapper = info;
boolean blocksMayBeOfInterest = false;
if (myPositionOfInterest != -1) {
myResult.put(info, rootBlock);
blocksMayBeOfInterest = true;
}
Block previous = null;
final int subBlocksCount = subBlocks.size();
List<AbstractBlockWrapper> list = new ArrayList<AbstractBlockWrapper>(subBlocksCount);
final boolean blocksAreReadOnly = rootBlock instanceof SyntheticBlock || blocksMayBeOfInterest;
for (int i = 0; i < subBlocksCount; i++) {
final Block block = subBlocks.get(i);
if (previous != null) {
myCurrentSpaceProperty = (SpacingImpl)rootBlock.getSpacing(previous, block);
}
final TextRange blockRange = block.getTextRange();
boolean childBlockIsRightBlock = false;
if (i == subBlocksCount - 1 && rootBlockIsRightBlock) {
childBlockIsRightBlock = true;
}
final AbstractBlockWrapper wrapper = buildFrom(block, i, info, currentWrapParent, blockRange,rootBlock,childBlockIsRightBlock);
list.add(wrapper);
if (wrapper.getIndent() == null) {
wrapper.setIndent((IndentImpl)block.getIndent());
}
previous = block;
if (!blocksAreReadOnly) subBlocks.set(i, null); // to prevent extra strong refs during model building
}
setDefaultIndents(list);
info.setChildren(list);
return info;
}
private static void setDefaultIndents(final List<AbstractBlockWrapper> list) {
if (!list.isEmpty()) {
for (AbstractBlockWrapper wrapper : list) {
if (wrapper.getIndent() == null) {
wrapper.setIndent((IndentImpl)Indent.getContinuationWithoutFirstIndent());
}
}
}
}
private AbstractBlockWrapper processSimpleBlock(final Block rootBlock,
final AbstractBlockWrapper parent,
final boolean readOnly,
final TextRange textRange,
final int index,
Block parentBlock
) {
final LeafBlockWrapper info = new LeafBlockWrapper(rootBlock, parent, myCurrentWhiteSpace, myModel, myPreviousBlock, readOnly,
textRange);
if (index == 0) {
info.arrangeParentTextRange();
}
if (textRange.getLength() == 0) {
assertInvalidRanges(
textRange.getStartOffset(),
textRange.getEndOffset(),
myModel,
"empty block"
);
}
if (myPreviousBlock != null) {
myPreviousBlock.setNextBlock(info);
}
if (myFirstTokenBlock == null) {
myFirstTokenBlock = info;
}
myLastTokenBlock = info;
if (currentWhiteSpaceIsReadOnly()) {
myCurrentWhiteSpace.setReadOnly(true);
}
if (myCurrentSpaceProperty != null) {
myCurrentWhiteSpace.setIsSafe(myCurrentSpaceProperty.isSafe());
myCurrentWhiteSpace.setKeepFirstColumn(myCurrentSpaceProperty.shouldKeepFirstColumn());
}
info.setSpaceProperty(myCurrentSpaceProperty);
myCurrentWhiteSpace = new WhiteSpace(textRange.getEndOffset(), false);
myPreviousBlock = info;
if (myPositionOfInterest != -1 && (textRange.contains(myPositionOfInterest) || textRange.getEndOffset() == myPositionOfInterest)) {
myResult.put(info, rootBlock);
if (parent != null) myResult.put(parent, parentBlock);
}
return info;
}
private boolean currentWhiteSpaceIsReadOnly() {
if (myCurrentSpaceProperty != null && myCurrentSpaceProperty.isReadOnly()) {
return true;
}
else {
if (myAffectedRange == null) return false;
if (myCurrentWhiteSpace.getStartOffset() >= myAffectedRange.getEndOffset()) return true;
if (myProcessHeadingWhitespace) {
return myCurrentWhiteSpace.getEndOffset() < myAffectedRange.getStartOffset();
}
else {
return myCurrentWhiteSpace.getEndOffset() <= myAffectedRange.getStartOffset();
}
}
}
private boolean isReadOnly(final TextRange textRange, boolean rootIsRightBlock) {
if (myAffectedRange == null) return false;
if (myAffectedRange.getStartOffset() >= textRange.getEndOffset() && rootIsRightBlock) {
return false;
}
if (textRange.getStartOffset() > myAffectedRange.getEndOffset()) return true;
return textRange.getEndOffset() < myAffectedRange.getStartOffset();
}
public Map<AbstractBlockWrapper,Block> getBlockToInfoMap() {
return myResult;
}
public CompositeBlockWrapper getRootBlockWrapper() {
return myRootBlockWrapper;
}
public LeafBlockWrapper getFirstTokenBlock() {
return myFirstTokenBlock;
}
public LeafBlockWrapper getLastTokenBlock() {
return myLastTokenBlock;
}
public static void assertInvalidRanges(final int startOffset, final int newEndOffset, FormattingDocumentModel model, String message) {
@NonNls final StringBuffer buffer = new StringBuffer();
buffer.append("Invalid formatting blocks:").append(message).append("\n");
buffer.append("Start offset:");
buffer.append(startOffset);
buffer.append(" end offset:");
buffer.append(newEndOffset);
buffer.append("\n");
int minOffset = Math.max(Math.min(startOffset, newEndOffset) - 20, 0);
int maxOffset = Math.min(Math.max(startOffset, newEndOffset) + 20, model.getTextLength());
buffer.append("Affected text fragment:[").append(minOffset).append(",").append(maxOffset).append("] - '")
.append(model.getText(new TextRange(minOffset, maxOffset))).append("'\n");
if (model instanceof FormattingDocumentModelImpl) {
buffer.append("in ").append(((FormattingDocumentModelImpl)model).getFile().getLanguage()).append("\n");
}
buffer.append("File text:(" + model.getTextLength()+")\n'");
buffer.append(model.getText(new TextRange(0, model.getTextLength())).toString());
buffer.append("'\n");
if (model instanceof FormattingDocumentModelImpl) {
final FormattingDocumentModelImpl modelImpl = (FormattingDocumentModelImpl)model;
buffer.append("Psi Tree:\n");
final PsiFile file = modelImpl.getFile();
final PsiFile[] roots = file.getPsiRoots();
for (PsiFile root : roots) {
buffer.append("Root ");
DebugUtil.treeToBuffer(buffer, root.getNode(), 0, false, true, true);
}
buffer.append('\n');
}
LOG.error(buffer.toString());
}
}
| lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java | package com.intellij.formatting;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.FormattingDocumentModelImpl;
import com.intellij.psi.formatter.xml.SyntheticBlock;
import com.intellij.psi.formatter.xml.ReadOnlyBlockInformationProvider;
import com.intellij.psi.impl.DebugUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class InitialInfoBuilder {
private static final Logger LOG = Logger.getInstance("#com.intellij.formatting.InitialInfoBuilder");
private WhiteSpace myCurrentWhiteSpace;
private final FormattingDocumentModel myModel;
private TextRange myAffectedRange;
private final int myPositionOfInterest;
private boolean myProcessHeadingWhitespace;
private final Map<AbstractBlockWrapper, Block> myResult = new THashMap<AbstractBlockWrapper, Block>();
private CompositeBlockWrapper myRootBlockWrapper;
private LeafBlockWrapper myPreviousBlock;
private LeafBlockWrapper myFirstTokenBlock;
private LeafBlockWrapper myLastTokenBlock;
private SpacingImpl myCurrentSpaceProperty;
private final CodeStyleSettings.IndentOptions myOptions;
private ReadOnlyBlockInformationProvider myReadOnlyBlockInformationProvider;
private InitialInfoBuilder(final FormattingDocumentModel model,
final TextRange affectedRange,
final CodeStyleSettings.IndentOptions options,
final boolean processHeadingWhitespace,
final int positionOfInterest
) {
myModel = model;
myAffectedRange = affectedRange;
myProcessHeadingWhitespace = processHeadingWhitespace;
myCurrentWhiteSpace = new WhiteSpace(0, true);
myOptions = options;
myPositionOfInterest = positionOfInterest;
}
public static InitialInfoBuilder buildBlocks(Block root,
FormattingDocumentModel model,
final TextRange affectedRange,
final CodeStyleSettings.IndentOptions options,
final boolean processHeadingWhitespace, int interestingOffset) {
final InitialInfoBuilder builder = new InitialInfoBuilder(model, affectedRange, options, processHeadingWhitespace, interestingOffset);
final AbstractBlockWrapper wrapper = builder.buildFrom(root, 0, null, null, root.getTextRange(), null, true);
wrapper.setIndent((IndentImpl)Indent.getNoneIndent());
return builder;
}
private AbstractBlockWrapper buildFrom(final Block rootBlock,
final int index,
final AbstractBlockWrapper parent,
WrapImpl currentWrapParent,
final TextRange textRange,
final Block parentBlock,
boolean rootBlockIsRightBlock
) {
final WrapImpl wrap = (WrapImpl)rootBlock.getWrap();
if (wrap != null) {
wrap.registerParent(currentWrapParent);
currentWrapParent = wrap;
}
final int blockStartOffset = textRange.getStartOffset();
if (parent != null) {
if (textRange.getStartOffset() < parent.getStartOffset()) {
assertInvalidRanges(
textRange.getStartOffset(),
parent.getStartOffset(),
myModel,
"child block start is less than parent block start"
);
}
if (textRange.getEndOffset() > parent.getEndOffset()) {
assertInvalidRanges(
textRange.getEndOffset(),
parent.getEndOffset(),
myModel,
"child block end is after parent block end"
);
}
}
myCurrentWhiteSpace.append(blockStartOffset, myModel, myOptions);
boolean isReadOnly = isReadOnly(textRange, rootBlockIsRightBlock);
ReadOnlyBlockInformationProvider previousProvider = myReadOnlyBlockInformationProvider;
try {
if (rootBlock instanceof ReadOnlyBlockInformationProvider) {
myReadOnlyBlockInformationProvider = (ReadOnlyBlockInformationProvider)rootBlock;
}
if (isReadOnly) {
return processSimpleBlock(rootBlock, parent, isReadOnly, textRange, index, parentBlock);
}
else {
final List<Block> subBlocks = rootBlock.getSubBlocks();
if (subBlocks.isEmpty() || myReadOnlyBlockInformationProvider != null &&
myReadOnlyBlockInformationProvider.isReadOnly(rootBlock)) {
final AbstractBlockWrapper wrapper = processSimpleBlock(rootBlock, parent, isReadOnly, textRange, index, parentBlock);
if (subBlocks.size() > 0) {
wrapper.setIndent((IndentImpl)subBlocks.get(0).getIndent());
}
return wrapper;
}
else {
return processCompositeBlock(rootBlock, parent, textRange, index, subBlocks, currentWrapParent, rootBlockIsRightBlock);
}
}
} finally {
myReadOnlyBlockInformationProvider = previousProvider;
}
}
private AbstractBlockWrapper processCompositeBlock(final Block rootBlock,
final AbstractBlockWrapper parent,
final TextRange textRange,
final int index,
final List<Block> subBlocks,
final WrapImpl currentWrapParent,
boolean rootBlockIsRightBlock
) {
final CompositeBlockWrapper info = new CompositeBlockWrapper(rootBlock, myCurrentWhiteSpace, parent, textRange);
if (index == 0) {
info.arrangeParentTextRange();
}
if (myRootBlockWrapper == null) myRootBlockWrapper = info;
boolean blocksMayBeOfInterest = false;
if (myPositionOfInterest != -1) {
myResult.put(info, rootBlock);
blocksMayBeOfInterest = true;
}
Block previous = null;
final int subBlocksCount = subBlocks.size();
List<AbstractBlockWrapper> list = new ArrayList<AbstractBlockWrapper>(subBlocksCount);
final boolean blocksAreReadOnly = rootBlock instanceof SyntheticBlock || blocksMayBeOfInterest;
for (int i = 0; i < subBlocksCount; i++) {
final Block block = subBlocks.get(i);
if (previous != null) {
myCurrentSpaceProperty = (SpacingImpl)rootBlock.getSpacing(previous, block);
}
final TextRange blockRange = block.getTextRange();
boolean childBlockIsRightBlock = false;
if (i == subBlocksCount - 1 && rootBlockIsRightBlock) {
childBlockIsRightBlock = true;
}
final AbstractBlockWrapper wrapper = buildFrom(block, i, info, currentWrapParent, blockRange,rootBlock,childBlockIsRightBlock);
list.add(wrapper);
if (wrapper.getIndent() == null) {
wrapper.setIndent((IndentImpl)block.getIndent());
}
previous = block;
if (!blocksAreReadOnly) subBlocks.set(i, null); // to prevent extra strong refs during model building
}
setDefaultIndents(list);
info.setChildren(list);
return info;
}
private static void setDefaultIndents(final List<AbstractBlockWrapper> list) {
if (!list.isEmpty()) {
for (AbstractBlockWrapper wrapper : list) {
if (wrapper.getIndent() == null) {
wrapper.setIndent((IndentImpl)Indent.getContinuationWithoutFirstIndent());
}
}
}
}
private AbstractBlockWrapper processSimpleBlock(final Block rootBlock,
final AbstractBlockWrapper parent,
final boolean readOnly,
final TextRange textRange,
final int index,
Block parentBlock
) {
final LeafBlockWrapper info = new LeafBlockWrapper(rootBlock, parent, myCurrentWhiteSpace, myModel, myPreviousBlock, readOnly,
textRange);
if (index == 0) {
info.arrangeParentTextRange();
}
if (textRange.getLength() == 0) {
assertInvalidRanges(
textRange.getStartOffset(),
textRange.getEndOffset(),
myModel,
"empty block"
);
}
if (myPreviousBlock != null) {
myPreviousBlock.setNextBlock(info);
}
if (myFirstTokenBlock == null) {
myFirstTokenBlock = info;
}
myLastTokenBlock = info;
if (currentWhiteSpaceIsReadOnly()) {
myCurrentWhiteSpace.setReadOnly(true);
}
if (myCurrentSpaceProperty != null) {
myCurrentWhiteSpace.setIsSafe(myCurrentSpaceProperty.isSafe());
myCurrentWhiteSpace.setKeepFirstColumn(myCurrentSpaceProperty.shouldKeepFirstColumn());
}
info.setSpaceProperty(myCurrentSpaceProperty);
myCurrentWhiteSpace = new WhiteSpace(textRange.getEndOffset(), false);
myPreviousBlock = info;
if (myPositionOfInterest != -1 && (textRange.contains(myPositionOfInterest) || textRange.getEndOffset() == myPositionOfInterest)) {
myResult.put(info, rootBlock);
if (parent != null) myResult.put(parent, parentBlock);
}
return info;
}
private boolean currentWhiteSpaceIsReadOnly() {
if (myCurrentSpaceProperty != null && myCurrentSpaceProperty.isReadOnly()) {
return true;
}
else {
if (myAffectedRange == null) return false;
if (myCurrentWhiteSpace.getStartOffset() >= myAffectedRange.getEndOffset()) return true;
if (myProcessHeadingWhitespace) {
return myCurrentWhiteSpace.getEndOffset() < myAffectedRange.getStartOffset();
}
else {
return myCurrentWhiteSpace.getEndOffset() <= myAffectedRange.getStartOffset();
}
}
}
private boolean isReadOnly(final TextRange textRange, boolean rootIsRightBlock) {
if (myAffectedRange == null) return false;
if (myAffectedRange.getStartOffset() >= textRange.getEndOffset() && rootIsRightBlock) {
return false;
}
if (textRange.getStartOffset() > myAffectedRange.getEndOffset()) return true;
return textRange.getEndOffset() < myAffectedRange.getStartOffset();
}
public Map<AbstractBlockWrapper,Block> getBlockToInfoMap() {
return myResult;
}
public CompositeBlockWrapper getRootBlockWrapper() {
return myRootBlockWrapper;
}
public LeafBlockWrapper getFirstTokenBlock() {
return myFirstTokenBlock;
}
public LeafBlockWrapper getLastTokenBlock() {
return myLastTokenBlock;
}
public static void assertInvalidRanges(final int startOffset, final int newEndOffset, FormattingDocumentModel model, String message) {
@NonNls final StringBuffer buffer = new StringBuffer();
buffer.append("Invalid formatting blocks:").append(message).append("\n");
buffer.append("Start offset:");
buffer.append(startOffset);
buffer.append(" end offset:");
buffer.append(newEndOffset);
buffer.append("\n");
int minOffset = Math.max(Math.min(startOffset, newEndOffset) - 20, 0);
int maxOffset = Math.min(Math.max(startOffset, newEndOffset) + 20, model.getTextLength());
buffer.append("Affected text fragment:[").append(minOffset).append(",").append(maxOffset).append("] - '")
.append(model.getText(new TextRange(minOffset, maxOffset))).append("'\n");
if (model instanceof FormattingDocumentModelImpl) {
buffer.append("in ").append(((FormattingDocumentModelImpl)model).getFile().getLanguage()).append("\n");
}
buffer.append("File text:(" + model.getTextLength()+")\n'");
buffer.append(model.getText(new TextRange(0, model.getTextLength())).toString());
buffer.append("'\n");
if (model instanceof FormattingDocumentModelImpl) {
final FormattingDocumentModelImpl modelImpl = (FormattingDocumentModelImpl)model;
buffer.append("Psi Tree:\n");
final PsiFile file = modelImpl.getFile();
final PsiFile[] roots = file.getPsiRoots();
for (PsiFile root : roots) {
buffer.append("Root ");
DebugUtil.treeToBuffer(buffer, root.getNode(), 0, false, true, true);
}
buffer.append('\n');
}
LOG.error(buffer.toString());
}
}
| compile fix
| lang-impl/src/com/intellij/formatting/InitialInfoBuilder.java | compile fix | <ide><path>ang-impl/src/com/intellij/formatting/InitialInfoBuilder.java
<ide> import com.intellij.psi.PsiFile;
<ide> import com.intellij.psi.codeStyle.CodeStyleSettings;
<ide> import com.intellij.psi.formatter.FormattingDocumentModelImpl;
<add>import com.intellij.psi.formatter.ReadOnlyBlockInformationProvider;
<ide> import com.intellij.psi.formatter.xml.SyntheticBlock;
<del>import com.intellij.psi.formatter.xml.ReadOnlyBlockInformationProvider;
<ide> import com.intellij.psi.impl.DebugUtil;
<ide> import gnu.trove.THashMap;
<ide> import org.jetbrains.annotations.NonNls; |
|
Java | apache-2.0 | 254332516593d14865c2103cd898ea088efa2137 | 0 | mtransitapps/ca-montreal-amt-bus-parser,mtransitapps/ca-montreal-amt-bus-parser | package org.mtransit.parser.ca_montreal_amt_bus;
import java.util.HashSet;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MSpec;
import org.mtransit.parser.mt.data.MTrip;
// http://www.amt.qc.ca/developers/
// http://www.amt.qc.ca/xdata/express/google_transit.zip
public class MontrealAMTBusAgencyTools extends DefaultAgencyTools {
public static final String ROUTE_TYPE_FILTER = "3"; // bus only
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-montreal-amt-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new MontrealAMTBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("Generating AMT bus data...\n");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("Generating AMT bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
if (ROUTE_TYPE_FILTER != null && !gRoute.route_type.equals(ROUTE_TYPE_FILTER)) {
return true;
}
return super.excludeRoute(gRoute);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip) {
String stationName = cleanTripHeadsign(gTrip.trip_headsign);
int directionId = Integer.valueOf(gTrip.direction_id);
mTrip.setHeadsignString(stationName, directionId);
}
private static final String DIRECTION = "Direction ";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
return MSpec.cleanLabel(tripHeadsign.substring(DIRECTION.length()));
}
@Override
public String cleanStopName(String gStopName) {
return super.cleanStopNameFR(gStopName);
}
@Override
public int getStopId(GStop gStop) {
return Integer.valueOf(getStopCode(gStop)); // using stop code as stop ID
}
}
| src/org/mtransit/parser/ca_montreal_amt_bus/MontrealAMTBusAgencyTools.java | package org.mtransit.parser.ca_montreal_amt_bus;
import java.util.HashSet;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MSpec;
import org.mtransit.parser.mt.data.MTrip;
// http://www.amt.qc.ca/developers/
// http://www.amt.qc.ca/xdata/express/google_transit.zip
public class MontrealAMTBusAgencyTools extends DefaultAgencyTools {
public static final String ROUTE_TYPE_FILTER = "3"; // bus only
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-montreal-amt-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new MontrealAMTBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("Generating AMT bus data...\n");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("Generating AMT bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
if (ROUTE_TYPE_FILTER != null && !gRoute.route_type.equals(ROUTE_TYPE_FILTER)) {
return true;
}
return super.excludeRoute(gRoute);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip) {
String stationName = cleanTripHeadsign(gTrip.trip_headsign);
int directionId = Integer.valueOf(gTrip.direction_id);
mTrip.setHeadsignString(stationName, directionId);
}
private static final String DIRECTION = "Direction ";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
return MSpec.cleanLabel(tripHeadsign.substring(DIRECTION.length()));
}
@Override
public String cleanStopName(String gStopName) {
return super.cleanStopNameFR(gStopName);
}
@Override
public int getStopId(GStop gStop) {
return Integer.valueOf(getStopCode(gStop)); // using stop code as stop ID
}
}
| Minor cleanup
| src/org/mtransit/parser/ca_montreal_amt_bus/MontrealAMTBusAgencyTools.java | Minor cleanup | <ide><path>rc/org/mtransit/parser/ca_montreal_amt_bus/MontrealAMTBusAgencyTools.java
<ide> @Override
<ide> public boolean excludeTrip(GTrip gTrip) {
<ide> if (this.serviceIds != null) {
<del> return excludeUselessTrip(gTrip, serviceIds);
<add> return excludeUselessTrip(gTrip, this.serviceIds);
<ide> }
<ide> return super.excludeTrip(gTrip);
<ide> } |
|
Java | apache-2.0 | a6627aeeae3229c7f672518f246cfb0d74d005a4 | 0 | greenadex/timetable-builder | package utils;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;
import com.google.api.services.calendar.model.Calendar;
import model.Activity;
import model.FromDayToInteger;
import model.Timetable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.File;
import java.lang.reflect.Array;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* Created on 26.09.2016
*/
public class TimetableBuilder {
/**
* Application name.
*/
private static final String APPLICATION_NAME =
"TimetableBuilder";
/**
* Directory to store user credentials for this application.
*/
private static final File DATA_STORE_DIR = new File(
System.getProperty("user.home"), ".credentials/timetable-builder");
/**
* Global instance of the {@link FileDataStoreFactory}.
*/
private static FileDataStoreFactory DATA_STORE_FACTORY;
/**
* Global instance of the JSON factory.
*/
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/**
* Global instance of the HTTP transport.
*/
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the Calendar service.
*/
private static com.google.api.services.calendar.Calendar service;
/**
* Global instance of the scopes required by this application.
* <p>
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/timetable-builder
*/
private static final List<String> SCOPES =
Collections.singletonList(CalendarScopes.CALENDAR);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
service = getCalendarService();
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
private static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
TimetableBuilder.class.getResourceAsStream("/client.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("online")
.build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
/**
* Build and return an authorized Calendar client service.
*
* @return an authorized Calendar client service
* @throws IOException
*/
private static com.google.api.services.calendar.Calendar getCalendarService() throws IOException {
Credential credential = authorize();
return new com.google.api.services.calendar.Calendar.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
private static LocalDate getStartingDateOfActivity(Activity activity, int semester) {
String startingDate = SemesterInfo.getStartingDate(semester);
LocalDate localStartingDate = LocalDate.of(Integer.parseInt(startingDate.substring(0, 4)),
Integer.parseInt(startingDate.substring(5, 7)),
Integer.parseInt(startingDate.substring(8)));
localStartingDate = localStartingDate.plus(FromDayToInteger.getInteger(activity.getDay()), ChronoUnit.DAYS);
return localStartingDate;
}
private static void setSummary(Event event, Activity activity) {
String title = activity.getNameOfActivity();
if (activity.getTypeOfActivity().equals("Laborator") && activity.getGroup().contains("/"))
title += " " + activity.getGroup();
event.setSummary(title);
}
private static void setLocation(Event event, Activity activity) {
event.setLocation(activity.getActivityRoom());
}
private static void setDescription(Event event, Activity activity) {
event.setDescription(activity.getTypeOfActivity() + ' ' + activity.getNameOfActivity() + " - "
+ activity.getProfessor());
}
private static void setColor(Event event, Activity activity) {
int colorId = 4; //light red
//11 for dark red
if (activity.getTypeOfActivity().equals("Seminar"))
colorId = 10; //green
if (activity.getTypeOfActivity().equals("Laborator"))
colorId = 5; //yellow
event.setColorId(Integer.toString(colorId));
}
private static void setStartAndEndDate(Event event, Activity activity, int semester) {
String startingDate = getStartingDateOfActivity(activity, semester).toString(),
timeZone = (semester == 1 ? ":00.000+03:00" : ":00.000+02:00");
DateTime start = DateTime.parseRfc3339(startingDate + "T" + activity.getStartingHour() + timeZone);
DateTime end = DateTime.parseRfc3339(startingDate + "T" + activity.getEndingHour() + timeZone);
event.setStart(new EventDateTime().setDateTime(start).setTimeZone("Europe/Bucharest"));
event.setEnd(new EventDateTime().setDateTime(end).setTimeZone("Europe/Bucharest"));
}
private static void setRecurrence(Event event, int semester) {
String recurrence = "RRULE:FREQ=WEEKLY;COUNT=" + SemesterInfo.getNoOfWeeks(semester);
event.setRecurrence(Collections.singletonList(recurrence));
}
private static void deleteExtraEvents(String calendarID, Activity activity, List<Event> items, int semester)
throws IOException {
int holidayLength = SemesterInfo.getHolidayLength(semester),
startingWeekHoliday = SemesterInfo.getHolidayStartingWeek(semester);
for (int week = 0; week < holidayLength; week++) {
service.events().delete(calendarID, items.get(startingWeekHoliday + week).getId()).execute();
}
if (activity.getFrequency().isEmpty()) {
return;
}
int activityParity = activity.getFrequency().contains("1") ? 1 : 0;
for (int week = activityParity; week < startingWeekHoliday; week += 2) {
service.events().delete(calendarID, items.get(week).getId()).execute();
}
if (holidayLength % 2 != 0) {
activityParity = 1 - activityParity;
}
for (int week = startingWeekHoliday + holidayLength + activityParity;
week < SemesterInfo.getNoOfWeeks(semester); week += 2) {
service.events().delete(calendarID, items.get(week).getId()).execute();
}
}
private static void deleteExtraEvents(String calendarID, Activity activity, String eventID, int semester)
throws IOException {
String pageToken = null;
do {
Events events =
service.events().instances(calendarID, eventID).setPageToken(pageToken).execute();
List<Event> items = events.getItems();
deleteExtraEvents(calendarID, activity, items, semester);
pageToken = events.getNextPageToken();
} while (pageToken != null);
}
/**
* Adds a new class (a new event) of the timetable to the calendar
*
* @param calendarId - the id of the calendar where the new event will be added
* @param activity - the Activity object holding the information of the class to be added
* @param semester - the activity's semester
* @throws IOException
*/
private static void addActivity(String calendarId, Activity activity, int semester) throws IOException {
Event event = new Event();
setSummary(event, activity);
setLocation(event, activity);
setDescription(event, activity);
setColor(event, activity);
setStartAndEndDate(event, activity, semester);
setRecurrence(event, semester);
System.out.println("Generating event for " + event.getSummary() + " " + activity.getTypeOfActivity());
event = service.events().insert(calendarId, event).execute();
deleteExtraEvents(calendarId, activity, event.getId(), semester);
}
/**
* Adds the timetable to the calendar
*
* @param calendarId - the id of the calendar where the timetable will be added
* @param timetable - the Timetable object which holds all the information of the calendar to be added
* @throws IOException
*/
public static void addTimetable(String calendarId, Timetable timetable) throws IOException {
List<Activity> allActivities = timetable.getAllActivities();
for (Activity nextActivity : allActivities) {
addActivity(calendarId, nextActivity, timetable.getSemester());
}
}
/**
* Creates a new calendar with an appropriate description for a timetable
*
* @param timetable - the timetable to be added in the newly created calendar
* @return the id of the calendar created
* @throws IOException
*/
public static String createCalendar(Timetable timetable) throws IOException {
Calendar newCalendar = new Calendar();
String summary = timetable.getSemiGroup().equals("*") ?
timetable.getGroup() + " Sem." + timetable.getSemester() :
timetable.getGroup() + "/" + timetable.getSemiGroup() + " Sem." + timetable.getSemester();
newCalendar.setSummary(summary);
String description = "Timetable for group " + timetable.getGroup() + " for the semester " +
timetable.getSemester() + "\n\n\tRed - Course\n\tGreen - Seminar\n\tYellow - Laboratory";
newCalendar.setDescription(description);
newCalendar.setTimeZone("Europe/Bucharest");
return service.calendars().insert(newCalendar).execute().getId();
}
public static void deleteCalendar(String calendarID) throws IOException {
service.calendars().delete(calendarID).execute();
}
}
| src/main/java/utils/TimetableBuilder.java | package utils;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;
import com.google.api.services.calendar.model.Calendar;
import model.Activity;
import model.FromDayToInteger;
import model.Timetable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.File;
import java.lang.reflect.Array;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* Created on 26.09.2016
*/
public class TimetableBuilder {
/**
* Application name.
*/
private static final String APPLICATION_NAME =
"TimetableBuilder";
/**
* Directory to store user credentials for this application.
*/
private static final File DATA_STORE_DIR = new File(
System.getProperty("user.home"), ".credentials/timetable-builder");
/**
* Global instance of the {@link FileDataStoreFactory}.
*/
private static FileDataStoreFactory DATA_STORE_FACTORY;
/**
* Global instance of the JSON factory.
*/
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/**
* Global instance of the HTTP transport.
*/
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the Calendar service.
*/
private static com.google.api.services.calendar.Calendar service;
/**
* Global instance of the scopes required by this application.
* <p>
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/timetable-builder
*/
private static final List<String> SCOPES =
Collections.singletonList(CalendarScopes.CALENDAR);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
service = getCalendarService();
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
private static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
TimetableBuilder.class.getResourceAsStream("/client.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("online")
.build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
/**
* Build and return an authorized Calendar client service.
*
* @return an authorized Calendar client service
* @throws IOException
*/
private static com.google.api.services.calendar.Calendar getCalendarService() throws IOException {
Credential credential = authorize();
return new com.google.api.services.calendar.Calendar.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
private static LocalDate getStartingDateOfActivity(Activity activity, int semester) {
String startingDate = SemesterInfo.getStartingDate(semester);
LocalDate localStartingDate = LocalDate.of(Integer.parseInt(startingDate.substring(0, 4)),
Integer.parseInt(startingDate.substring(5, 7)),
Integer.parseInt(startingDate.substring(8)));
localStartingDate = localStartingDate.plus(FromDayToInteger.getInteger(activity.getDay()), ChronoUnit.DAYS);
return localStartingDate;
}
private static void setSummary(Event event, Activity activity) {
String title = activity.getNameOfActivity();
if (activity.getTypeOfActivity().equals("Laborator") && activity.getGroup().contains("/"))
title += " " + activity.getGroup();
event.setSummary(title);
}
private static void setLocation(Event event, Activity activity) {
event.setLocation(activity.getActivityRoom());
}
private static void setDescription(Event event, Activity activity) {
event.setDescription(activity.getTypeOfActivity() + ' ' + activity.getNameOfActivity() + " - "
+ activity.getProfessor());
}
private static void setColor(Event event, Activity activity) {
int colorId = 4; //light red
//11 for dark red
if (activity.getTypeOfActivity().equals("Seminar"))
colorId = 10; //green
if (activity.getTypeOfActivity().equals("Laborator"))
colorId = 5; //yellow
event.setColorId(Integer.toString(colorId));
}
private static void setStartAndEndDate(Event event, Activity activity, int semester) {
String startingDate = getStartingDateOfActivity(activity,semester).toString(),
timeZone = (semester == 1 ? ":00.000+03:00" : ":00.000+02:00");
DateTime start = DateTime.parseRfc3339(startingDate + "T" + activity.getStartingHour() + timeZone);
DateTime end = DateTime.parseRfc3339(startingDate + "T" + activity.getEndingHour() + timeZone);
event.setStart(new EventDateTime().setDateTime(start).setTimeZone("Europe/Bucharest"));
event.setEnd(new EventDateTime().setDateTime(end).setTimeZone("Europe/Bucharest"));
}
private static void setRecurrence(Event event, Activity activity, int semester) {
String recurrence = "RRULE:FREQ=WEEKLY;COUNT=" + SemesterInfo.getNoOfWeeks(semester);
event.setRecurrence(Collections.singletonList(recurrence));
}
private static void deleteExtraEvents(String calendarID, Activity activity, List<Event> items, int semester)
throws IOException {
int holidayLength = SemesterInfo.getHolidayLength(semester),
startingWeekHoliday = SemesterInfo.getHolidayStartingWeek(semester);
for (int week = 0; week < holidayLength; week++) {
service.events().delete(calendarID, items.get(startingWeekHoliday + week).getId()).execute();
}
if (activity.getFrequency().isEmpty()) {
return;
}
int activityParity = activity.getFrequency().contains("1") ? 1 : 0;
for (int week = activityParity; week < startingWeekHoliday; week += 2) {
service.events().delete(calendarID, items.get(week).getId()).execute();
}
if (holidayLength % 2 != 0) {
activityParity = 1 - activityParity;
}
for (int week = startingWeekHoliday + holidayLength + activityParity;
week < SemesterInfo.getNoOfWeeks(semester); week += 2) {
service.events().delete(calendarID, items.get(week).getId()).execute();
}
}
private static void deleteExtraEvents(String calendarID, Activity activity, String eventID, int semester)
throws IOException {
String pageToken = null;
do {
Events events =
service.events().instances(calendarID, eventID).setPageToken(pageToken).execute();
List<Event> items = events.getItems();
deleteExtraEvents(calendarID, activity, items, semester);
pageToken = events.getNextPageToken();
} while (pageToken != null);
}
/**
* Adds a new class (a new event) of the timetable to the calendar
*
* @param calendarId - the id of the calendar where the new event will be added
* @param activity - the Activity object holding the information of the class to be added
* @param semester - the activity's semester
* @throws IOException
*/
private static void addActivity(String calendarId, Activity activity, int semester) throws IOException {
Event event = new Event();
setSummary(event, activity);
setLocation(event, activity);
setDescription(event, activity);
setColor(event, activity);
setStartAndEndDate(event, activity, semester);
setRecurrence(event, activity, semester);
System.out.println("Generating event for " + event.getSummary() + " " + activity.getTypeOfActivity());
event = service.events().insert(calendarId, event).execute();
deleteExtraEvents(calendarId, activity, event.getId(), semester);
}
/**
* Adds the timetable to the calendar
*
* @param calendarId - the id of the calendar where the timetable will be added
* @param timetable - the Timetable object which holds all the information of the calendar to be added
* @throws IOException
*/
public static void addTimetable(String calendarId, Timetable timetable) throws IOException {
List<Activity> allActivities = timetable.getAllActivities();
for (Activity nextActivity : allActivities) {
addActivity(calendarId, nextActivity, timetable.getSemester());
}
}
/**
* Creates a new calendar with an appropriate description for a timetable
*
* @param timetable - the timetable to be added in the newly created calendar
* @return the id of the calendar created
* @throws IOException
*/
public static String createCalendar(Timetable timetable) throws IOException {
Calendar newCalendar = new Calendar();
String summary = timetable.getSemiGroup().equals("*") ?
timetable.getGroup() + " Sem." + timetable.getSemester() :
timetable.getGroup() + "/" + timetable.getSemiGroup() + " Sem." + timetable.getSemester();
newCalendar.setSummary(summary);
String description = "Timetable for group " + timetable.getGroup() + " for the semester " +
timetable.getSemester() + "\n\n\tRed - Course\n\tGreen - Seminar\n\tYellow - Laboratory";
newCalendar.setDescription(description);
newCalendar.setTimeZone("Europe/Bucharest");
return service.calendars().insert(newCalendar).execute().getId();
}
public static void deleteCalendar(String calendarID) throws IOException {
service.calendars().delete(calendarID).execute();
}
}
| Reformat
| src/main/java/utils/TimetableBuilder.java | Reformat | <ide><path>rc/main/java/utils/TimetableBuilder.java
<ide> }
<ide>
<ide> private static void setStartAndEndDate(Event event, Activity activity, int semester) {
<del> String startingDate = getStartingDateOfActivity(activity,semester).toString(),
<del> timeZone = (semester == 1 ? ":00.000+03:00" : ":00.000+02:00");
<add> String startingDate = getStartingDateOfActivity(activity, semester).toString(),
<add> timeZone = (semester == 1 ? ":00.000+03:00" : ":00.000+02:00");
<ide>
<ide> DateTime start = DateTime.parseRfc3339(startingDate + "T" + activity.getStartingHour() + timeZone);
<ide> DateTime end = DateTime.parseRfc3339(startingDate + "T" + activity.getEndingHour() + timeZone);
<ide> event.setEnd(new EventDateTime().setDateTime(end).setTimeZone("Europe/Bucharest"));
<ide> }
<ide>
<del> private static void setRecurrence(Event event, Activity activity, int semester) {
<add> private static void setRecurrence(Event event, int semester) {
<ide> String recurrence = "RRULE:FREQ=WEEKLY;COUNT=" + SemesterInfo.getNoOfWeeks(semester);
<ide> event.setRecurrence(Collections.singletonList(recurrence));
<ide> }
<ide> private static void deleteExtraEvents(String calendarID, Activity activity, List<Event> items, int semester)
<ide> throws IOException {
<ide> int holidayLength = SemesterInfo.getHolidayLength(semester),
<del> startingWeekHoliday = SemesterInfo.getHolidayStartingWeek(semester);
<add> startingWeekHoliday = SemesterInfo.getHolidayStartingWeek(semester);
<ide>
<ide> for (int week = 0; week < holidayLength; week++) {
<ide> service.events().delete(calendarID, items.get(startingWeekHoliday + week).getId()).execute();
<ide> /**
<ide> * Adds a new class (a new event) of the timetable to the calendar
<ide> *
<del> * @param calendarId - the id of the calendar where the new event will be added
<del> * @param activity - the Activity object holding the information of the class to be added
<del> * @param semester - the activity's semester
<add> * @param calendarId - the id of the calendar where the new event will be added
<add> * @param activity - the Activity object holding the information of the class to be added
<add> * @param semester - the activity's semester
<ide> * @throws IOException
<ide> */
<ide> private static void addActivity(String calendarId, Activity activity, int semester) throws IOException {
<ide> setDescription(event, activity);
<ide> setColor(event, activity);
<ide> setStartAndEndDate(event, activity, semester);
<del> setRecurrence(event, activity, semester);
<del>
<add> setRecurrence(event, semester);
<ide>
<ide> System.out.println("Generating event for " + event.getSummary() + " " + activity.getTypeOfActivity());
<ide> event = service.events().insert(calendarId, event).execute();
<ide> Calendar newCalendar = new Calendar();
<ide>
<ide> String summary = timetable.getSemiGroup().equals("*") ?
<del> timetable.getGroup() + " Sem." + timetable.getSemester() :
<del> timetable.getGroup() + "/" + timetable.getSemiGroup() + " Sem." + timetable.getSemester();
<add> timetable.getGroup() + " Sem." + timetable.getSemester() :
<add> timetable.getGroup() + "/" + timetable.getSemiGroup() + " Sem." + timetable.getSemester();
<ide> newCalendar.setSummary(summary);
<ide>
<ide> String description = "Timetable for group " + timetable.getGroup() + " for the semester " + |
|
JavaScript | mit | 52c81845aadea0d355957a0f7f100b6aa8da28e3 | 0 | mcanthony/p2.js,beni55/p2.js,GoodBoyDigital/p2.js,psalaets/p2.js,markware/p2.js,mcanthony/p2.js,koopero/p2.js,koopero/p2.js,jaggedsoft/p2.js,modulexcite/p2.js,GoodBoyDigital/p2.js,markware/p2.js,beni55/p2.js,psalaets/p2.js,modulexcite/p2.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify : {
test : {
src : ["src/p2.js"],
dest : 'build/p2.js',
options : {
standalone : "p2"
}
}
},
uglify : {
build : {
src : ['build/p2.js'],
dest : 'build/p2.min.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['browserify','uglify']);
};
| Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify : {
test : {
src : ["src/p2.js"],
dest : 'build/p2.js',
options : {
standalone : "p2"
}
}
},
uglify : {
build : {
src : ['build/p2.js'],
dest : 'build/p2.min.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['uglify', 'browserify']);
};
| gruntfile default build order fix
| Gruntfile.js | gruntfile default build order fix | <ide><path>runtfile.js
<ide>
<ide> grunt.loadNpmTasks('grunt-contrib-uglify');
<ide> grunt.loadNpmTasks('grunt-browserify');
<del> grunt.registerTask('default', ['uglify', 'browserify']);
<add> grunt.registerTask('default', ['browserify','uglify']);
<ide>
<ide> }; |
|
Java | mit | 8918ef97e435fe1d986e705e0eea81a0b295f2b6 | 0 | kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper,kbase/njs_wrapper | package us.kbase.narrativejobservice.sdkjobs;
import java.io.*;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.time.Instant;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.util.Hash;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Volume;
import com.google.common.html.HtmlEscapers;
import us.kbase.auth.AuthConfig;
import us.kbase.auth.AuthToken;
import us.kbase.auth.ConfigurableAuthService;
import us.kbase.catalog.CatalogClient;
import us.kbase.catalog.GetSecureConfigParamsInput;
import us.kbase.catalog.ModuleVersion;
import us.kbase.catalog.SecureConfigParameter;
import us.kbase.catalog.SelectModuleVersion;
import us.kbase.catalog.VolumeMount;
import us.kbase.catalog.VolumeMountConfig;
import us.kbase.catalog.VolumeMountFilter;
import us.kbase.common.executionengine.CallbackServer;
import us.kbase.common.executionengine.CallbackServerConfigBuilder;
import us.kbase.common.executionengine.JobRunnerConstants;
import us.kbase.common.executionengine.LineLogger;
import us.kbase.common.executionengine.ModuleMethod;
import us.kbase.common.executionengine.ModuleRunVersion;
import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig;
import us.kbase.common.service.JsonServerServlet;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.Tuple2;
import us.kbase.common.service.UObject;
import us.kbase.common.service.UnauthorizedException;
import us.kbase.common.utils.NetUtils;
import us.kbase.narrativejobservice.CancelJobParams;
import us.kbase.narrativejobservice.CheckJobCanceledResult;
import us.kbase.narrativejobservice.FinishJobParams;
import us.kbase.narrativejobservice.JobState;
import us.kbase.narrativejobservice.JsonRpcError;
import us.kbase.narrativejobservice.LogLine;
import us.kbase.narrativejobservice.MethodCall;
import us.kbase.narrativejobservice.NarrativeJobServiceClient;
import us.kbase.narrativejobservice.NarrativeJobServiceServer;
import us.kbase.narrativejobservice.RpcContext;
import us.kbase.narrativejobservice.RunJobParams;
import us.kbase.narrativejobservice.UpdateJobParams;
import us.kbase.narrativejobservice.subjobs.NJSCallbackServer;
import us.kbase.narrativejobservice.sdkjobs.DockerRunner;
import us.kbase.narrativejobservice.sdkjobs.ShifterRunner;
public class SDKLocalMethodRunner {
private final static DateTimeFormatter DATE_FORMATTER =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC();
public static final String DEV = JobRunnerConstants.DEV;
public static final String BETA = JobRunnerConstants.BETA;
public static final String RELEASE = JobRunnerConstants.RELEASE;
public static final Set<String> RELEASE_TAGS = JobRunnerConstants.RELEASE_TAGS;
private static final long MAX_OUTPUT_SIZE = JobRunnerConstants.MAX_IO_BYTE_SIZE;
public static final String JOB_CONFIG_FILE = JobRunnerConstants.JOB_CONFIG_FILE;
public static final String CFG_PROP_EE_SERVER_VERSION =
JobRunnerConstants.CFG_PROP_EE_SERVER_VERSION;
public static final String CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS =
JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS;
public static long milliSecondsToLive(String token, Map<String, String> config) throws Exception {
String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2);
if (authUrl == null) {
throw new IllegalStateException("Deployment configuration parameter is not defined: " +
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2) ;
}
//Check to see if http links are allowed
String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
if (! "true".equals(authAllowInsecure) && ! authUrl.startsWith("https://")) {
throw new Exception("Only https links are allowed: " + authUrl);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet request = new HttpGet(authUrl);
request.setHeader(HttpHeaders.AUTHORIZATION, token);
InputStream response = httpclient.execute(request).getEntity().getContent();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(response, Map.class);
Object expire = jsonMap.getOrDefault("expires", null);
//Calculate ms till expiration
if (expire != null) {
return (Long.parseLong((String) expire) - Instant.now().toEpochMilli());
}
throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString());
}
public static void canceljob(NarrativeJobServiceClient jobSrvClient, String jobId) throws Exception{
jobSrvClient.cancelJob(new CancelJobParams().withJobId(jobId));
}
public static void main(String[] args) throws Exception {
System.out.println("Starting docker runner EDIT EDIT EDIT with args " +
StringUtils.join(args, ", "));
if (args.length != 2) {
System.err.println("Usage: <program> <job_id> <job_service_url>");
for (int i = 0; i < args.length; i++)
System.err.println("\tArgument[" + i + "]: " + args[i]);
System.exit(1);
}
Thread shutdownHook = new Thread()
{
@Override
public void run()
{
try {
DockerRunner.killSubJobs();
}
catch (Exception e){
e.printStackTrace();
}
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
String[] hostnameAndIP = getHostnameAndIP();
final String jobId = args[0];
String jobSrvUrl = args[1];
String tokenStr = System.getenv("KB_AUTH_TOKEN");
if (tokenStr == null || tokenStr.isEmpty())
tokenStr = System.getProperty("KB_AUTH_TOKEN"); // For tests
if (tokenStr == null || tokenStr.isEmpty())
throw new IllegalStateException("Token is not defined");
// We should skip token validation now because we don't have auth service URL yet.
final AuthToken tempToken = new AuthToken(tokenStr, "<unknown>");
final NarrativeJobServiceClient jobSrvClient = getJobClient(
jobSrvUrl, tempToken);
Thread logFlusher = null;
final List<LogLine> logLines = new ArrayList<LogLine>();
final LineLogger log = new LineLogger() {
@Override
public void logNextLine(String line, boolean isError) {
addLogLine(jobSrvClient, jobId, logLines,
new LogLine().withLine(line)
.withIsError(isError ? 1L : 0L));
}
};
Server callbackServer = null;
try {
JobState jobState = jobSrvClient.checkJob(jobId);
if (jobState.getFinished() != null && jobState.getFinished() == 1L) {
if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) {
log.logNextLine("Job was canceled", false);
} else {
log.logNextLine("Job was already done before", true);
}
flushLog(jobSrvClient, jobId, logLines);
return;
}
Tuple2<RunJobParams, Map<String,String>> jobInput = jobSrvClient.getJobParams(jobId);
Map<String, String> config = jobInput.getE2();
if (System.getenv("CALLBACK_INTERFACE")!=null)
config.put(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS, System.getenv("CALLBACK_INTERFACE"));
if (System.getenv("REFDATA_DIR")!=null)
config.put(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE, System.getenv("REFDATA_DIR"));
ConfigurableAuthService auth = getAuth(config);
// We couldn't validate token earlier because we didn't have auth service URL.
AuthToken token = auth.validateToken(tokenStr);
final URL catalogURL = getURL(config,
NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL);
final URI dockerURI = getURI(config,
NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_DOCKER_URI,
true);
RunJobParams job = jobInput.getE1();
for (String msg : jobSrvClient.updateJob(new UpdateJobParams().withJobId(jobId)
.withIsStarted(1L)).getMessages()) {
log.logNextLine(msg, false);
}
File jobDir = getJobDir(jobInput.getE2(), jobId);
if (!mountExists()) {
log.logNextLine("Cannot find mount point as defined in condor-submit-workdir",true);
throw new IOException("Cannot find mount point condor-submit-workdir");
}
final ModuleMethod modMeth = new ModuleMethod(job.getMethod());
RpcContext context = job.getRpcContext();
if (context == null)
context = new RpcContext().withRunId("");
if (context.getCallStack() == null)
context.setCallStack(new ArrayList<MethodCall>());
context.getCallStack().add(new MethodCall().withJobId(jobId).withMethod(job.getMethod())
.withTime(DATE_FORMATTER.print(new DateTime())));
Map<String, Object> rpc = new LinkedHashMap<String, Object>();
rpc.put("version", "1.1");
rpc.put("method", job.getMethod());
rpc.put("params", job.getParams());
rpc.put("context", context);
File workDir = new File(jobDir, "workdir");
if (!workDir.exists())
workDir.mkdir();
File scratchDir = new File(workDir, "tmp");
if (!scratchDir.exists())
scratchDir.mkdir();
File inputFile = new File(workDir, "input.json");
UObject.getMapper().writeValue(inputFile, rpc);
File outputFile = new File(workDir, "output.json");
File configFile = new File(workDir, JOB_CONFIG_FILE);
String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT);
String clientDetails = hostnameAndIP[1];
String clientName = System.getenv("AWE_CLIENTNAME");
if (clientName != null && !clientName.isEmpty()) {
clientDetails += ", client-name=" + clientName;
}
log.logNextLine("Running on " + hostnameAndIP[0] + " (" + clientDetails + "), in " +
new File(".").getCanonicalPath(), false);
String clientGroup = System.getenv("AWE_CLIENTGROUP");
if (clientGroup == null)
clientGroup = "<unknown>";
log.logNextLine("Client group: " + clientGroup, false);
String codeEeVer = NarrativeJobServiceServer.VERSION;
String runtimeEeVersion = config.get(CFG_PROP_EE_SERVER_VERSION);
if (runtimeEeVersion == null)
runtimeEeVersion = "<unknown>";
if (codeEeVer.equals(runtimeEeVersion)) {
log.logNextLine("Server version of Execution Engine: " +
runtimeEeVersion + " (matches to version of runner script)", false);
} else {
log.logNextLine("WARNING: Server version of Execution Engine (" +
runtimeEeVersion + ") doesn't match to version of runner script " +
"(" + codeEeVer + ")", true);
}
CatalogClient catClient = new CatalogClient(catalogURL, token);
catClient.setIsInsecureHttpConnectionAllowed(true);
catClient.setAllSSLCertificatesTrusted(true);
// the NJSW always passes the githash in service ver
final String imageVersion = job.getServiceVer();
final String requestedRelease = (String) job
.getAdditionalProperties().get(SDKMethodRunner.REQ_REL);
final ModuleVersion mv;
try {
mv = catClient.getModuleVersion(new SelectModuleVersion()
.withModuleName(modMeth.getModule())
.withVersion(imageVersion));
} catch (ServerException se) {
throw new IllegalArgumentException(String.format(
"Error looking up module %s with version %s: %s",
modMeth.getModule(), imageVersion,
se.getLocalizedMessage()));
}
String imageName = mv.getDockerImgName();
File refDataDir = null;
String refDataBase = config.get(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE);
if (mv.getDataFolder() != null && mv.getDataVersion() != null) {
if (refDataBase == null)
throw new IllegalStateException("Reference data parameters are defined for image but " +
NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE + " property isn't set in configuration");
refDataDir = new File(new File(refDataBase, mv.getDataFolder()), mv.getDataVersion());
if (!refDataDir.exists())
throw new IllegalStateException("Reference data directory doesn't exist: " + refDataDir);
}
if (imageName == null) {
throw new IllegalStateException("Image is not stored in catalog");
} else {
log.logNextLine("Image name received from catalog: " + imageName, false);
}
logFlusher = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
break;
}
flushLog(jobSrvClient, jobId, logLines);
if (Thread.currentThread().isInterrupted())
break;
}
}
});
logFlusher.setDaemon(true);
logFlusher.start();
// Let's check if there are some volume mount rules or secure configuration parameters
// set up for this module
List<Bind> additionalBinds = null;
Map<String, String> envVars = null;
List<SecureConfigParameter> secureCfgParams = null;
String adminTokenStr = System.getenv("KB_ADMIN_AUTH_TOKEN");
if (adminTokenStr == null || adminTokenStr.isEmpty())
adminTokenStr = System.getProperty("KB_ADMIN_AUTH_TOKEN"); // For tests
String miniKB = System.getenv("MINI_KB");
boolean useVolumeMounts = true;
if (miniKB != null && !miniKB.isEmpty() && miniKB.equals("true") ){
useVolumeMounts = false;
}
if (adminTokenStr != null && !adminTokenStr.isEmpty() && useVolumeMounts) {
final AuthToken adminToken = auth.validateToken(adminTokenStr);
final CatalogClient adminCatClient = new CatalogClient(catalogURL, adminToken);
adminCatClient.setIsInsecureHttpConnectionAllowed(true);
adminCatClient.setAllSSLCertificatesTrusted(true);
List<VolumeMountConfig> vmc = null;
try {
vmc = adminCatClient.listVolumeMounts(new VolumeMountFilter().withModuleName(
modMeth.getModule()).withClientGroup(clientGroup)
.withFunctionName(modMeth.getMethod()));
} catch (Exception ex) {
log.logNextLine("Error requesing volume mounts from Catalog: " + ex.getMessage(), true);
}
if (vmc != null && vmc.size() > 0) {
if (vmc.size() > 1)
throw new IllegalStateException("More than one rule for Docker volume mounts was found");
additionalBinds = new ArrayList<Bind>();
for (VolumeMount vm : vmc.get(0).getVolumeMounts()) {
boolean isReadOnly = vm.getReadOnly() != null && vm.getReadOnly() != 0L;
File hostDir = new File(processHostPathForVolumeMount(vm.getHostDir(),
token.getUserName()));
if (!hostDir.exists()) {
if (isReadOnly) {
throw new IllegalStateException("Volume mount directory doesn't exist: " +
hostDir);
} else {
hostDir.mkdirs();
}
}
String contDir = vm.getContainerDir();
AccessMode am = isReadOnly ?
AccessMode.ro : AccessMode.rw;
additionalBinds.add(new Bind(hostDir.getCanonicalPath(), new Volume(contDir), am));
}
}
secureCfgParams = adminCatClient.getSecureConfigParams(
new GetSecureConfigParamsInput().withModuleName(modMeth.getModule())
.withVersion(mv.getGitCommitHash()).withLoadAllVersions(0L));
envVars = new TreeMap<String, String>();
for (SecureConfigParameter param : secureCfgParams) {
envVars.put("KBASE_SECURE_CONFIG_PARAM_" + param.getParamName(),
param.getParamValue());
}
}
PrintWriter pw = new PrintWriter(configFile);
pw.println("[global]");
if (kbaseEndpoint != null)
pw.println("kbase_endpoint = " + kbaseEndpoint);
pw.println("job_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL));
pw.println("workspace_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL));
pw.println("shock_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SHOCK_URL));
pw.println("handle_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_HANDLE_SRV_URL));
pw.println("srv_wiz_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SRV_WIZ_URL));
pw.println("njsw_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL));
pw.println("auth_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL));
pw.println("auth_service_url_allow_insecure = " +
config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM));
if (secureCfgParams != null) {
for (SecureConfigParameter param : secureCfgParams) {
pw.println(param.getParamName() + " = " + param.getParamValue());
}
}
pw.close();
// Cancellation checker
CancellationChecker cancellationChecker = new CancellationChecker() {
Boolean canceled = null;
@Override
public boolean isJobCanceled() {
if (canceled != null)
return canceled;
try {
final CheckJobCanceledResult jobState = jobSrvClient.checkJobCanceled(
new CancelJobParams().withJobId(jobId));
if (jobState.getFinished() != null && jobState.getFinished() == 1L) {
canceled = true;
if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) {
// Print cancellation message after DockerRunner is done
} else {
log.logNextLine("Job was registered as finished by another worker",
true);
}
flushLog(jobSrvClient, jobId, logLines);
return true;
}
} catch (Exception ex) {
log.logNextLine("Non-critical error checking for job cancelation - " +
String.format("Will check again in %s seconds. ",
DockerRunner.CANCELLATION_CHECK_PERIOD_SEC) +
"Error reported by execution engine was: " +
HtmlEscapers.htmlEscaper().escape(ex.getMessage()), true);
}
return false;
}
};
// Starting up callback server
String[] callbackNetworks = null;
String callbackNetworksText = config.get(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS);
if (callbackNetworksText != null) {
callbackNetworks = callbackNetworksText.trim().split("\\s*,\\s*");
}
final int callbackPort = NetUtils.findFreePort();
final URL callbackUrl = CallbackServer.
getCallbackUrl(callbackPort, callbackNetworks);
if (callbackUrl != null) {
log.logNextLine("Job runner recieved callback URL: " +
callbackUrl, false);
final ModuleRunVersion runver = new ModuleRunVersion(
new URL(mv.getGitUrl()), modMeth,
mv.getGitCommitHash(), mv.getVersion(),
requestedRelease);
final CallbackServerConfig cbcfg =
new CallbackServerConfigBuilder(config, callbackUrl,
jobDir.toPath(), Paths.get(refDataBase), log).build();
final JsonServerServlet callback = new NJSCallbackServer(
token, cbcfg, runver, job.getParams(),
job.getSourceWsObjects(), additionalBinds, cancellationChecker);
callbackServer = new Server(callbackPort);
final ServletContextHandler srvContext =
new ServletContextHandler(
ServletContextHandler.SESSIONS);
srvContext.setContextPath("/");
callbackServer.setHandler(srvContext);
srvContext.addServlet(new ServletHolder(callback),"/*");
callbackServer.start();
} else {
if (callbackNetworks != null && callbackNetworks.length > 0) {
throw new IllegalStateException("No proper callback IP was found, " +
"please check 'awe.client.callback.networks' parameter in " +
"execution engine configuration");
}
log.logNextLine("WARNING: No callback URL was recieved " +
"by the job runner. Local callbacks are disabled.",
true);
}
Map<String,String> labels = new HashMap<>();
labels.put("job_id",""+jobId);
labels.put("image_name",imageName);
String method = job.getMethod();
String[] appNameMethodName = method.split("\\.");
if(appNameMethodName.length == 2){
labels.put("app_name",appNameMethodName[0]);
labels.put("method_name",appNameMethodName[1]);
}
else{
labels.put("app_name",method);
labels.put("method_name",method);
}
labels.put("parent_job_id",job.getParentJobId());
labels.put("image_version",imageVersion);
labels.put("wsid",""+job.getWsid());
labels.put("app_id",""+job.getAppId());
labels.put("user_name",token.getUserName());
Map<String,String> resourceRequirements = new HashMap<String,String>();
String[] resourceStrings = {"request_cpus", "request_memory", "request_disk"};
for (String resourceKey : resourceStrings) {
String resourceValue = System.getenv(resourceKey);
if (resourceValue != null && !resourceKey.isEmpty()) {
resourceRequirements.put(resourceKey, resourceValue);
}
}
if (resourceRequirements.isEmpty()) {
resourceRequirements = null;
log.logNextLine("Resource Requirements are not specified.", false);
} else {
log.logNextLine("Resource Requirements are:", false);
log.logNextLine(resourceRequirements.toString(), false);
}
//Get number of milliseconds to live for this token
//Set a timer before job is cancelled for having an expired token to the expiration time minus 10 minutes
//
final long msToLive = milliSecondsToLive(tokenStr,config);
Thread tokenExpirationHook = new Thread()
{
@Override
public void run()
{
try {
long tenMinutesBeforeExpiration = msToLive - 600000;
if(tenMinutesBeforeExpiration > 0){
Thread.sleep(tenMinutesBeforeExpiration);
canceljob(jobSrvClient,jobId);
log.logNextLine("Job was canceled due to token expiration", false);
}
else{
canceljob(jobSrvClient,jobId);
log.logNextLine("Job was canceled due to invalid token expiration state:" + tenMinutesBeforeExpiration, false);
}
}
catch (Exception e){
e.printStackTrace();
}
}
};
tokenExpirationHook.start();
// Calling Runner
if (System.getenv("USE_SHIFTER") != null) {
new ShifterRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log,
outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds,
cancellationChecker, envVars, labels);
} else {
new DockerRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log,
outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds,
cancellationChecker, envVars, labels, resourceRequirements);
}
if (cancellationChecker.isJobCanceled()) {
log.logNextLine("Job was canceled", false);
flushLog(jobSrvClient, jobId, logLines);
logFlusher.interrupt();
return;
}
if (outputFile.length() > MAX_OUTPUT_SIZE) {
Reader r = new FileReader(outputFile);
char[] chars = new char[1000];
r.read(chars);
r.close();
String error = "Method " + job.getMethod() + " returned value longer than " + MAX_OUTPUT_SIZE +
" bytes. This may happen as a result of returning actual data instead of saving it to " +
"kbase data stores (Workspace, Shock, ...) and returning reference to it. Returned " +
"value starts with \"" + new String(chars) + "...\"";
throw new IllegalStateException(error);
}
FinishJobParams result = UObject.getMapper().readValue(outputFile, FinishJobParams.class);
// flush logs to execution engine
if (result.getError() != null) {
String err = "";
if (notNullOrEmpty(result.getError().getName())) {
err = result.getError().getName();
}
if (notNullOrEmpty(result.getError().getMessage())) {
if (!err.isEmpty()) {
err += ": ";
}
err += result.getError().getMessage();
}
if (notNullOrEmpty(result.getError().getError())) {
if (!err.isEmpty()) {
err += "\n";
}
err += result.getError().getError();
}
if (err == "")
err = "Unknown error (please ask administrator for details providing full output log)";
log.logNextLine("Error: " + err, true);
} else {
log.logNextLine("Job is done", false);
}
flushLog(jobSrvClient, jobId, logLines);
// push results to execution engine
jobSrvClient.finishJob(jobId, result);
logFlusher.interrupt();
//Turn off cancellation hook
tokenExpirationHook.interrupt();
} catch (Exception ex) {
ex.printStackTrace();
try {
flushLog(jobSrvClient, jobId, logLines);
} catch (Exception ignore) {}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.close();
String err = "Fatal error: " + sw.toString();
if (ex instanceof ServerException) {
err += "\nServer exception:\n" +
((ServerException)ex).getData();
}
try {
log.logNextLine(err, true);
flushLog(jobSrvClient, jobId, logLines);
logFlusher.interrupt();
} catch (Exception ignore) {}
try {
FinishJobParams result = new FinishJobParams().withError(
new JsonRpcError().withCode(-1L).withName("JSONRPCError")
.withMessage("Job service side error: " + ex.getMessage())
.withError(err));
jobSrvClient.finishJob(jobId, result);
} catch (Exception ex2) {
ex2.printStackTrace();
}
} finally {
if (callbackServer != null)
try {
callbackServer.stop();
System.out.println("Callback server was shutdown");
} catch (Exception ignore) {
System.err.println("Error shutting down callback server: " + ignore.getMessage());
}
}
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
public static String processHostPathForVolumeMount(String path, String username) {
return path.replace("${username}", username);
}
private static boolean notNullOrEmpty(final String s) {
return s != null && !s.isEmpty();
}
private static synchronized void addLogLine(NarrativeJobServiceClient jobSrvClient,
String jobId, List<LogLine> logLines, LogLine line) {
logLines.add(line);
if (line.getIsError() != null && line.getIsError() == 1L) {
System.err.println(line.getLine());
} else {
System.out.println(line.getLine());
}
}
private static synchronized void flushLog(NarrativeJobServiceClient jobSrvClient,
String jobId, List<LogLine> logLines) {
if (logLines.isEmpty())
return;
try {
jobSrvClient.addJobLogs(jobId, logLines);
logLines.clear();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String decamelize(final String s) {
final Matcher m = Pattern.compile("([A-Z])").matcher(s.substring(1));
return (s.substring(0, 1) + m.replaceAll("_$1")).toLowerCase();
}
private static File getJobDir(Map<String, String> config, String jobId) {
String rootDirPath = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_SCRATCH);
File rootDir = new File(rootDirPath == null ? "." : rootDirPath);
if (!rootDir.exists())
rootDir.mkdirs();
File ret = new File(rootDir, "job_" + jobId);
if (!ret.exists())
ret.mkdir();
return ret;
}
/**
* Check to see if the basedir exists, which is in
* a format similar to /mnt/condor/<username>
* @return
*/
private static boolean mountExists() {
File mountPath = new File(System.getenv("BASE_DIR"));
return mountPath.exists() && mountPath.canWrite();
}
public static NarrativeJobServiceClient getJobClient(String jobSrvUrl,
AuthToken token) throws UnauthorizedException, IOException,
MalformedURLException {
final NarrativeJobServiceClient jobSrvClient =
new NarrativeJobServiceClient(new URL(jobSrvUrl), token);
jobSrvClient.setIsInsecureHttpConnectionAllowed(true);
return jobSrvClient;
}
private static ConfigurableAuthService getAuth(final Map<String, String> config)
throws Exception {
String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL);
if (authUrl == null) {
throw new IllegalStateException("Deployment configuration parameter is not defined: " +
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL);
}
String authAllowInsecure = config.get(
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
final AuthConfig c = new AuthConfig().withKBaseAuthServerURL(new URL(authUrl));
if ("true".equals(authAllowInsecure)) {
c.withAllowInsecureURLs(true);
}
return new ConfigurableAuthService(c);
}
private static URL getURL(final Map<String, String> config,
final String param) {
final String urlStr = config.get(param);
if (urlStr == null || urlStr.isEmpty()) {
throw new IllegalStateException("Parameter '" + param +
"' is not defined in configuration");
}
try {
return new URL(urlStr);
} catch (MalformedURLException mal) {
throw new IllegalStateException("The configuration parameter '" +
param + " = " + urlStr + "' is not a valid URL");
}
}
private static URI getURI(final Map<String, String> config,
final String param, boolean allowAbsent) {
final String urlStr = config.get(param);
if (urlStr == null || urlStr.isEmpty()) {
if (allowAbsent) {
return null;
}
throw new IllegalStateException("Parameter '" + param +
"' is not defined in configuration");
}
try {
return new URI(urlStr);
} catch (URISyntaxException use) {
throw new IllegalStateException("The configuration parameter '" +
param + " = " + urlStr + "' is not a valid URI");
}
}
public static String[] getHostnameAndIP() {
String hostname = null;
String ip = null;
try {
InetAddress ia = InetAddress.getLocalHost();
ip = ia.getHostAddress();
hostname = ia.getHostName();
} catch (Throwable ignore) {}
if (hostname == null) {
try {
hostname = System.getenv("HOSTNAME");
if (hostname != null && hostname.isEmpty())
hostname = null;
} catch (Throwable ignore) {}
}
if (ip == null && hostname != null) {
try {
ip = InetAddress.getByName(hostname).getHostAddress();
} catch (Throwable ignore) {}
}
return new String[] {hostname == null ? "unknown" : hostname,
ip == null ? "unknown" : ip};
}
}
| src/us/kbase/narrativejobservice/sdkjobs/SDKLocalMethodRunner.java | package us.kbase.narrativejobservice.sdkjobs;
import java.io.*;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.time.Instant;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.util.Hash;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Volume;
import com.google.common.html.HtmlEscapers;
import us.kbase.auth.AuthConfig;
import us.kbase.auth.AuthToken;
import us.kbase.auth.ConfigurableAuthService;
import us.kbase.catalog.CatalogClient;
import us.kbase.catalog.GetSecureConfigParamsInput;
import us.kbase.catalog.ModuleVersion;
import us.kbase.catalog.SecureConfigParameter;
import us.kbase.catalog.SelectModuleVersion;
import us.kbase.catalog.VolumeMount;
import us.kbase.catalog.VolumeMountConfig;
import us.kbase.catalog.VolumeMountFilter;
import us.kbase.common.executionengine.CallbackServer;
import us.kbase.common.executionengine.CallbackServerConfigBuilder;
import us.kbase.common.executionengine.JobRunnerConstants;
import us.kbase.common.executionengine.LineLogger;
import us.kbase.common.executionengine.ModuleMethod;
import us.kbase.common.executionengine.ModuleRunVersion;
import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig;
import us.kbase.common.service.JsonServerServlet;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.Tuple2;
import us.kbase.common.service.UObject;
import us.kbase.common.service.UnauthorizedException;
import us.kbase.common.utils.NetUtils;
import us.kbase.narrativejobservice.CancelJobParams;
import us.kbase.narrativejobservice.CheckJobCanceledResult;
import us.kbase.narrativejobservice.FinishJobParams;
import us.kbase.narrativejobservice.JobState;
import us.kbase.narrativejobservice.JsonRpcError;
import us.kbase.narrativejobservice.LogLine;
import us.kbase.narrativejobservice.MethodCall;
import us.kbase.narrativejobservice.NarrativeJobServiceClient;
import us.kbase.narrativejobservice.NarrativeJobServiceServer;
import us.kbase.narrativejobservice.RpcContext;
import us.kbase.narrativejobservice.RunJobParams;
import us.kbase.narrativejobservice.UpdateJobParams;
import us.kbase.narrativejobservice.subjobs.NJSCallbackServer;
import us.kbase.narrativejobservice.sdkjobs.DockerRunner;
import us.kbase.narrativejobservice.sdkjobs.ShifterRunner;
public class SDKLocalMethodRunner {
private final static DateTimeFormatter DATE_FORMATTER =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC();
public static final String DEV = JobRunnerConstants.DEV;
public static final String BETA = JobRunnerConstants.BETA;
public static final String RELEASE = JobRunnerConstants.RELEASE;
public static final Set<String> RELEASE_TAGS = JobRunnerConstants.RELEASE_TAGS;
private static final long MAX_OUTPUT_SIZE = JobRunnerConstants.MAX_IO_BYTE_SIZE;
public static final String JOB_CONFIG_FILE = JobRunnerConstants.JOB_CONFIG_FILE;
public static final String CFG_PROP_EE_SERVER_VERSION =
JobRunnerConstants.CFG_PROP_EE_SERVER_VERSION;
public static final String CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS =
JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS;
public static long miliSecondsToLive(String token, Map<String, String> config) throws Exception {
String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2);
// if (authUrl == null) {
// throw new IllegalStateException("Deployment configuration parameter is not defined: " +
// NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2);
// }
authUrl = "http://auth:8080/api/V2/token";
//TODO
// String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
// if ("true".equals(authAllowInsecure)) {
//
// }
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet request = new HttpGet(authUrl);
request.setHeader(HttpHeaders.AUTHORIZATION, token);
InputStream response = httpclient.execute(request).getEntity().getContent();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(response, Map.class);
Object expire = jsonMap.getOrDefault("expires", null);
if (expire != null) {
System.out.println("TOKEN EXPIRATION IS:" + expire);
long expiration = 1533767010265L;
long current_time = Instant.now().toEpochMilli();
long seconds_to_expire = (expiration - current_time);
return seconds_to_expire;
}
throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString());
}
public static void canceljob(NarrativeJobServiceClient jobSrvClient, String jobId) throws Exception{
jobSrvClient.cancelJob(new CancelJobParams().withJobId(jobId));
}
public static void main(String[] args) throws Exception {
System.out.println("Starting docker runner EDIT EDIT EDIT with args " +
StringUtils.join(args, ", "));
if (args.length != 2) {
System.err.println("Usage: <program> <job_id> <job_service_url>");
for (int i = 0; i < args.length; i++)
System.err.println("\tArgument[" + i + "]: " + args[i]);
System.exit(1);
}
Thread shutdownHook = new Thread()
{
@Override
public void run()
{
try {
DockerRunner.killSubJobs();
}
catch (Exception e){
e.printStackTrace();
}
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
String[] hostnameAndIP = getHostnameAndIP();
final String jobId = args[0];
String jobSrvUrl = args[1];
String tokenStr = System.getenv("KB_AUTH_TOKEN");
if (tokenStr == null || tokenStr.isEmpty())
tokenStr = System.getProperty("KB_AUTH_TOKEN"); // For tests
if (tokenStr == null || tokenStr.isEmpty())
throw new IllegalStateException("Token is not defined");
// We should skip token validation now because we don't have auth service URL yet.
final AuthToken tempToken = new AuthToken(tokenStr, "<unknown>");
final NarrativeJobServiceClient jobSrvClient = getJobClient(
jobSrvUrl, tempToken);
Thread logFlusher = null;
final List<LogLine> logLines = new ArrayList<LogLine>();
final LineLogger log = new LineLogger() {
@Override
public void logNextLine(String line, boolean isError) {
addLogLine(jobSrvClient, jobId, logLines,
new LogLine().withLine(line)
.withIsError(isError ? 1L : 0L));
}
};
Server callbackServer = null;
try {
JobState jobState = jobSrvClient.checkJob(jobId);
if (jobState.getFinished() != null && jobState.getFinished() == 1L) {
if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) {
log.logNextLine("Job was canceled", false);
} else {
log.logNextLine("Job was already done before", true);
}
flushLog(jobSrvClient, jobId, logLines);
return;
}
Tuple2<RunJobParams, Map<String,String>> jobInput = jobSrvClient.getJobParams(jobId);
Map<String, String> config = jobInput.getE2();
if (System.getenv("CALLBACK_INTERFACE")!=null)
config.put(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS, System.getenv("CALLBACK_INTERFACE"));
if (System.getenv("REFDATA_DIR")!=null)
config.put(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE, System.getenv("REFDATA_DIR"));
ConfigurableAuthService auth = getAuth(config);
// We couldn't validate token earlier because we didn't have auth service URL.
AuthToken token = auth.validateToken(tokenStr);
final URL catalogURL = getURL(config,
NarrativeJobServiceServer.CFG_PROP_CATALOG_SRV_URL);
final URI dockerURI = getURI(config,
NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_DOCKER_URI,
true);
RunJobParams job = jobInput.getE1();
for (String msg : jobSrvClient.updateJob(new UpdateJobParams().withJobId(jobId)
.withIsStarted(1L)).getMessages()) {
log.logNextLine(msg, false);
}
File jobDir = getJobDir(jobInput.getE2(), jobId);
if (!mountExists()) {
log.logNextLine("Cannot find mount point as defined in condor-submit-workdir",true);
throw new IOException("Cannot find mount point condor-submit-workdir");
}
final ModuleMethod modMeth = new ModuleMethod(job.getMethod());
RpcContext context = job.getRpcContext();
if (context == null)
context = new RpcContext().withRunId("");
if (context.getCallStack() == null)
context.setCallStack(new ArrayList<MethodCall>());
context.getCallStack().add(new MethodCall().withJobId(jobId).withMethod(job.getMethod())
.withTime(DATE_FORMATTER.print(new DateTime())));
Map<String, Object> rpc = new LinkedHashMap<String, Object>();
rpc.put("version", "1.1");
rpc.put("method", job.getMethod());
rpc.put("params", job.getParams());
rpc.put("context", context);
File workDir = new File(jobDir, "workdir");
if (!workDir.exists())
workDir.mkdir();
File scratchDir = new File(workDir, "tmp");
if (!scratchDir.exists())
scratchDir.mkdir();
File inputFile = new File(workDir, "input.json");
UObject.getMapper().writeValue(inputFile, rpc);
File outputFile = new File(workDir, "output.json");
File configFile = new File(workDir, JOB_CONFIG_FILE);
String kbaseEndpoint = config.get(NarrativeJobServiceServer.CFG_PROP_KBASE_ENDPOINT);
String clientDetails = hostnameAndIP[1];
String clientName = System.getenv("AWE_CLIENTNAME");
if (clientName != null && !clientName.isEmpty()) {
clientDetails += ", client-name=" + clientName;
}
log.logNextLine("Running on " + hostnameAndIP[0] + " (" + clientDetails + "), in " +
new File(".").getCanonicalPath(), false);
String clientGroup = System.getenv("AWE_CLIENTGROUP");
if (clientGroup == null)
clientGroup = "<unknown>";
log.logNextLine("Client group: " + clientGroup, false);
String codeEeVer = NarrativeJobServiceServer.VERSION;
String runtimeEeVersion = config.get(CFG_PROP_EE_SERVER_VERSION);
if (runtimeEeVersion == null)
runtimeEeVersion = "<unknown>";
if (codeEeVer.equals(runtimeEeVersion)) {
log.logNextLine("Server version of Execution Engine: " +
runtimeEeVersion + " (matches to version of runner script)", false);
} else {
log.logNextLine("WARNING: Server version of Execution Engine (" +
runtimeEeVersion + ") doesn't match to version of runner script " +
"(" + codeEeVer + ")", true);
}
CatalogClient catClient = new CatalogClient(catalogURL, token);
catClient.setIsInsecureHttpConnectionAllowed(true);
catClient.setAllSSLCertificatesTrusted(true);
// the NJSW always passes the githash in service ver
final String imageVersion = job.getServiceVer();
final String requestedRelease = (String) job
.getAdditionalProperties().get(SDKMethodRunner.REQ_REL);
final ModuleVersion mv;
try {
mv = catClient.getModuleVersion(new SelectModuleVersion()
.withModuleName(modMeth.getModule())
.withVersion(imageVersion));
} catch (ServerException se) {
throw new IllegalArgumentException(String.format(
"Error looking up module %s with version %s: %s",
modMeth.getModule(), imageVersion,
se.getLocalizedMessage()));
}
String imageName = mv.getDockerImgName();
File refDataDir = null;
String refDataBase = config.get(NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE);
if (mv.getDataFolder() != null && mv.getDataVersion() != null) {
if (refDataBase == null)
throw new IllegalStateException("Reference data parameters are defined for image but " +
NarrativeJobServiceServer.CFG_PROP_REF_DATA_BASE + " property isn't set in configuration");
refDataDir = new File(new File(refDataBase, mv.getDataFolder()), mv.getDataVersion());
if (!refDataDir.exists())
throw new IllegalStateException("Reference data directory doesn't exist: " + refDataDir);
}
if (imageName == null) {
throw new IllegalStateException("Image is not stored in catalog");
} else {
log.logNextLine("Image name received from catalog: " + imageName, false);
}
logFlusher = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
break;
}
flushLog(jobSrvClient, jobId, logLines);
if (Thread.currentThread().isInterrupted())
break;
}
}
});
logFlusher.setDaemon(true);
logFlusher.start();
// Let's check if there are some volume mount rules or secure configuration parameters
// set up for this module
List<Bind> additionalBinds = null;
Map<String, String> envVars = null;
List<SecureConfigParameter> secureCfgParams = null;
String adminTokenStr = System.getenv("KB_ADMIN_AUTH_TOKEN");
if (adminTokenStr == null || adminTokenStr.isEmpty())
adminTokenStr = System.getProperty("KB_ADMIN_AUTH_TOKEN"); // For tests
String miniKB = System.getenv("MINI_KB");
boolean useVolumeMounts = true;
if (miniKB != null && !miniKB.isEmpty() && miniKB.equals("true") ){
useVolumeMounts = false;
}
if (adminTokenStr != null && !adminTokenStr.isEmpty() && useVolumeMounts) {
final AuthToken adminToken = auth.validateToken(adminTokenStr);
final CatalogClient adminCatClient = new CatalogClient(catalogURL, adminToken);
adminCatClient.setIsInsecureHttpConnectionAllowed(true);
adminCatClient.setAllSSLCertificatesTrusted(true);
List<VolumeMountConfig> vmc = null;
try {
vmc = adminCatClient.listVolumeMounts(new VolumeMountFilter().withModuleName(
modMeth.getModule()).withClientGroup(clientGroup)
.withFunctionName(modMeth.getMethod()));
} catch (Exception ex) {
log.logNextLine("Error requesing volume mounts from Catalog: " + ex.getMessage(), true);
}
if (vmc != null && vmc.size() > 0) {
if (vmc.size() > 1)
throw new IllegalStateException("More than one rule for Docker volume mounts was found");
additionalBinds = new ArrayList<Bind>();
for (VolumeMount vm : vmc.get(0).getVolumeMounts()) {
boolean isReadOnly = vm.getReadOnly() != null && vm.getReadOnly() != 0L;
File hostDir = new File(processHostPathForVolumeMount(vm.getHostDir(),
token.getUserName()));
if (!hostDir.exists()) {
if (isReadOnly) {
throw new IllegalStateException("Volume mount directory doesn't exist: " +
hostDir);
} else {
hostDir.mkdirs();
}
}
String contDir = vm.getContainerDir();
AccessMode am = isReadOnly ?
AccessMode.ro : AccessMode.rw;
additionalBinds.add(new Bind(hostDir.getCanonicalPath(), new Volume(contDir), am));
}
}
secureCfgParams = adminCatClient.getSecureConfigParams(
new GetSecureConfigParamsInput().withModuleName(modMeth.getModule())
.withVersion(mv.getGitCommitHash()).withLoadAllVersions(0L));
envVars = new TreeMap<String, String>();
for (SecureConfigParameter param : secureCfgParams) {
envVars.put("KBASE_SECURE_CONFIG_PARAM_" + param.getParamName(),
param.getParamValue());
}
}
PrintWriter pw = new PrintWriter(configFile);
pw.println("[global]");
if (kbaseEndpoint != null)
pw.println("kbase_endpoint = " + kbaseEndpoint);
pw.println("job_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_JOBSTATUS_SRV_URL));
pw.println("workspace_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_WORKSPACE_SRV_URL));
pw.println("shock_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SHOCK_URL));
pw.println("handle_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_HANDLE_SRV_URL));
pw.println("srv_wiz_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SRV_WIZ_URL));
pw.println("njsw_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_SELF_EXTERNAL_URL));
pw.println("auth_service_url = " + config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL));
pw.println("auth_service_url_allow_insecure = " +
config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM));
if (secureCfgParams != null) {
for (SecureConfigParameter param : secureCfgParams) {
pw.println(param.getParamName() + " = " + param.getParamValue());
}
}
pw.close();
// Cancellation checker
CancellationChecker cancellationChecker = new CancellationChecker() {
Boolean canceled = null;
@Override
public boolean isJobCanceled() {
if (canceled != null)
return canceled;
try {
final CheckJobCanceledResult jobState = jobSrvClient.checkJobCanceled(
new CancelJobParams().withJobId(jobId));
if (jobState.getFinished() != null && jobState.getFinished() == 1L) {
canceled = true;
if (jobState.getCanceled() != null && jobState.getCanceled() == 1L) {
// Print cancellation message after DockerRunner is done
} else {
log.logNextLine("Job was registered as finished by another worker",
true);
}
flushLog(jobSrvClient, jobId, logLines);
return true;
}
} catch (Exception ex) {
log.logNextLine("Non-critical error checking for job cancelation - " +
String.format("Will check again in %s seconds. ",
DockerRunner.CANCELLATION_CHECK_PERIOD_SEC) +
"Error reported by execution engine was: " +
HtmlEscapers.htmlEscaper().escape(ex.getMessage()), true);
}
return false;
}
};
// Starting up callback server
String[] callbackNetworks = null;
String callbackNetworksText = config.get(CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS);
if (callbackNetworksText != null) {
callbackNetworks = callbackNetworksText.trim().split("\\s*,\\s*");
}
final int callbackPort = NetUtils.findFreePort();
final URL callbackUrl = CallbackServer.
getCallbackUrl(callbackPort, callbackNetworks);
if (callbackUrl != null) {
log.logNextLine("Job runner recieved callback URL: " +
callbackUrl, false);
final ModuleRunVersion runver = new ModuleRunVersion(
new URL(mv.getGitUrl()), modMeth,
mv.getGitCommitHash(), mv.getVersion(),
requestedRelease);
final CallbackServerConfig cbcfg =
new CallbackServerConfigBuilder(config, callbackUrl,
jobDir.toPath(), Paths.get(refDataBase), log).build();
final JsonServerServlet callback = new NJSCallbackServer(
token, cbcfg, runver, job.getParams(),
job.getSourceWsObjects(), additionalBinds, cancellationChecker);
callbackServer = new Server(callbackPort);
final ServletContextHandler srvContext =
new ServletContextHandler(
ServletContextHandler.SESSIONS);
srvContext.setContextPath("/");
callbackServer.setHandler(srvContext);
srvContext.addServlet(new ServletHolder(callback),"/*");
callbackServer.start();
} else {
if (callbackNetworks != null && callbackNetworks.length > 0) {
throw new IllegalStateException("No proper callback IP was found, " +
"please check 'awe.client.callback.networks' parameter in " +
"execution engine configuration");
}
log.logNextLine("WARNING: No callback URL was recieved " +
"by the job runner. Local callbacks are disabled.",
true);
}
Map<String,String> labels = new HashMap<>();
labels.put("job_id",""+jobId);
labels.put("image_name",imageName);
String method = job.getMethod();
String[] appNameMethodName = method.split("\\.");
if(appNameMethodName.length == 2){
labels.put("app_name",appNameMethodName[0]);
labels.put("method_name",appNameMethodName[1]);
}
else{
labels.put("app_name",method);
labels.put("method_name",method);
}
labels.put("parent_job_id",job.getParentJobId());
labels.put("image_version",imageVersion);
labels.put("wsid",""+job.getWsid());
labels.put("app_id",""+job.getAppId());
labels.put("user_name",token.getUserName());
Map<String,String> resourceRequirements = new HashMap<String,String>();
String[] resourceStrings = {"request_cpus", "request_memory", "request_disk"};
for (String resourceKey : resourceStrings) {
String resourceValue = System.getenv(resourceKey);
if (resourceValue != null && !resourceKey.isEmpty()) {
resourceRequirements.put(resourceKey, resourceValue);
}
}
if (resourceRequirements.isEmpty()) {
resourceRequirements = null;
log.logNextLine("Resource Requirements are not specified.", false);
} else {
log.logNextLine("Resource Requirements are:", false);
log.logNextLine(resourceRequirements.toString(), false);
}
final long msToLive = miliSecondsToLive(tokenStr,config);
Thread tokenExpirationHook = new Thread()
{
@Override
public void run()
{
try {
long tenMinutesBeforeExpiration = msToLive - 600000;
tenMinutesBeforeExpiration=1000;
if(tenMinutesBeforeExpiration > 0){
Thread.sleep(tenMinutesBeforeExpiration);
canceljob(jobSrvClient,jobId);
log.logNextLine("Job was canceled due to token expiration", false);
}
else{
canceljob(jobSrvClient,jobId);
log.logNextLine("Job was canceled due to invalid token expiration state:" + tenMinutesBeforeExpiration, false);
}
}
catch (Exception e){
e.printStackTrace();
}
}
};
tokenExpirationHook.start();
// Calling Runner
if (System.getenv("USE_SHIFTER") != null) {
new ShifterRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log,
outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds,
cancellationChecker, envVars, labels);
} else {
new DockerRunner(dockerURI).run(imageName, modMeth.getModule(), inputFile, token, log,
outputFile, false, refDataDir, null, callbackUrl, jobId, additionalBinds,
cancellationChecker, envVars, labels, resourceRequirements);
}
if (cancellationChecker.isJobCanceled()) {
log.logNextLine("Job was canceled", false);
flushLog(jobSrvClient, jobId, logLines);
logFlusher.interrupt();
return;
}
if (outputFile.length() > MAX_OUTPUT_SIZE) {
Reader r = new FileReader(outputFile);
char[] chars = new char[1000];
r.read(chars);
r.close();
String error = "Method " + job.getMethod() + " returned value longer than " + MAX_OUTPUT_SIZE +
" bytes. This may happen as a result of returning actual data instead of saving it to " +
"kbase data stores (Workspace, Shock, ...) and returning reference to it. Returned " +
"value starts with \"" + new String(chars) + "...\"";
throw new IllegalStateException(error);
}
FinishJobParams result = UObject.getMapper().readValue(outputFile, FinishJobParams.class);
// flush logs to execution engine
if (result.getError() != null) {
String err = "";
if (notNullOrEmpty(result.getError().getName())) {
err = result.getError().getName();
}
if (notNullOrEmpty(result.getError().getMessage())) {
if (!err.isEmpty()) {
err += ": ";
}
err += result.getError().getMessage();
}
if (notNullOrEmpty(result.getError().getError())) {
if (!err.isEmpty()) {
err += "\n";
}
err += result.getError().getError();
}
if (err == "")
err = "Unknown error (please ask administrator for details providing full output log)";
log.logNextLine("Error: " + err, true);
} else {
log.logNextLine("Job is done", false);
}
flushLog(jobSrvClient, jobId, logLines);
// push results to execution engine
jobSrvClient.finishJob(jobId, result);
logFlusher.interrupt();
//Turn off cancellation hook
tokenExpirationHook.interrupt();
} catch (Exception ex) {
ex.printStackTrace();
try {
flushLog(jobSrvClient, jobId, logLines);
} catch (Exception ignore) {}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.close();
String err = "Fatal error: " + sw.toString();
if (ex instanceof ServerException) {
err += "\nServer exception:\n" +
((ServerException)ex).getData();
}
try {
log.logNextLine(err, true);
flushLog(jobSrvClient, jobId, logLines);
logFlusher.interrupt();
} catch (Exception ignore) {}
try {
FinishJobParams result = new FinishJobParams().withError(
new JsonRpcError().withCode(-1L).withName("JSONRPCError")
.withMessage("Job service side error: " + ex.getMessage())
.withError(err));
jobSrvClient.finishJob(jobId, result);
} catch (Exception ex2) {
ex2.printStackTrace();
}
} finally {
if (callbackServer != null)
try {
callbackServer.stop();
System.out.println("Callback server was shutdown");
} catch (Exception ignore) {
System.err.println("Error shutting down callback server: " + ignore.getMessage());
}
}
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
public static String processHostPathForVolumeMount(String path, String username) {
return path.replace("${username}", username);
}
private static boolean notNullOrEmpty(final String s) {
return s != null && !s.isEmpty();
}
private static synchronized void addLogLine(NarrativeJobServiceClient jobSrvClient,
String jobId, List<LogLine> logLines, LogLine line) {
logLines.add(line);
if (line.getIsError() != null && line.getIsError() == 1L) {
System.err.println(line.getLine());
} else {
System.out.println(line.getLine());
}
}
private static synchronized void flushLog(NarrativeJobServiceClient jobSrvClient,
String jobId, List<LogLine> logLines) {
if (logLines.isEmpty())
return;
try {
jobSrvClient.addJobLogs(jobId, logLines);
logLines.clear();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String decamelize(final String s) {
final Matcher m = Pattern.compile("([A-Z])").matcher(s.substring(1));
return (s.substring(0, 1) + m.replaceAll("_$1")).toLowerCase();
}
private static File getJobDir(Map<String, String> config, String jobId) {
String rootDirPath = config.get(NarrativeJobServiceServer.CFG_PROP_AWE_CLIENT_SCRATCH);
File rootDir = new File(rootDirPath == null ? "." : rootDirPath);
if (!rootDir.exists())
rootDir.mkdirs();
File ret = new File(rootDir, "job_" + jobId);
if (!ret.exists())
ret.mkdir();
return ret;
}
/**
* Check to see if the basedir exists, which is in
* a format similar to /mnt/condor/<username>
* @return
*/
private static boolean mountExists() {
File mountPath = new File(System.getenv("BASE_DIR"));
return mountPath.exists() && mountPath.canWrite();
}
public static NarrativeJobServiceClient getJobClient(String jobSrvUrl,
AuthToken token) throws UnauthorizedException, IOException,
MalformedURLException {
final NarrativeJobServiceClient jobSrvClient =
new NarrativeJobServiceClient(new URL(jobSrvUrl), token);
jobSrvClient.setIsInsecureHttpConnectionAllowed(true);
return jobSrvClient;
}
private static ConfigurableAuthService getAuth(final Map<String, String> config)
throws Exception {
String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL);
if (authUrl == null) {
throw new IllegalStateException("Deployment configuration parameter is not defined: " +
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL);
}
String authAllowInsecure = config.get(
NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
final AuthConfig c = new AuthConfig().withKBaseAuthServerURL(new URL(authUrl));
if ("true".equals(authAllowInsecure)) {
c.withAllowInsecureURLs(true);
}
return new ConfigurableAuthService(c);
}
private static URL getURL(final Map<String, String> config,
final String param) {
final String urlStr = config.get(param);
if (urlStr == null || urlStr.isEmpty()) {
throw new IllegalStateException("Parameter '" + param +
"' is not defined in configuration");
}
try {
return new URL(urlStr);
} catch (MalformedURLException mal) {
throw new IllegalStateException("The configuration parameter '" +
param + " = " + urlStr + "' is not a valid URL");
}
}
private static URI getURI(final Map<String, String> config,
final String param, boolean allowAbsent) {
final String urlStr = config.get(param);
if (urlStr == null || urlStr.isEmpty()) {
if (allowAbsent) {
return null;
}
throw new IllegalStateException("Parameter '" + param +
"' is not defined in configuration");
}
try {
return new URI(urlStr);
} catch (URISyntaxException use) {
throw new IllegalStateException("The configuration parameter '" +
param + " = " + urlStr + "' is not a valid URI");
}
}
public static String[] getHostnameAndIP() {
String hostname = null;
String ip = null;
try {
InetAddress ia = InetAddress.getLocalHost();
ip = ia.getHostAddress();
hostname = ia.getHostName();
} catch (Throwable ignore) {}
if (hostname == null) {
try {
hostname = System.getenv("HOSTNAME");
if (hostname != null && hostname.isEmpty())
hostname = null;
} catch (Throwable ignore) {}
}
if (ip == null && hostname != null) {
try {
ip = InetAddress.getByName(hostname).getHostAddress();
} catch (Throwable ignore) {}
}
return new String[] {hostname == null ? "unknown" : hostname,
ip == null ? "unknown" : ip};
}
}
| Creates a thread that dies 10 minutes before the token expires
| src/us/kbase/narrativejobservice/sdkjobs/SDKLocalMethodRunner.java | Creates a thread that dies 10 minutes before the token expires | <ide><path>rc/us/kbase/narrativejobservice/sdkjobs/SDKLocalMethodRunner.java
<ide> JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS;
<ide>
<ide>
<del> public static long miliSecondsToLive(String token, Map<String, String> config) throws Exception {
<add> public static long milliSecondsToLive(String token, Map<String, String> config) throws Exception {
<ide> String authUrl = config.get(NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2);
<del>// if (authUrl == null) {
<del>// throw new IllegalStateException("Deployment configuration parameter is not defined: " +
<del>// NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2);
<del>// }
<del> authUrl = "http://auth:8080/api/V2/token";
<del> //TODO
<del>// String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
<del>// if ("true".equals(authAllowInsecure)) {
<del>//
<del>// }
<del>
<del>
<add> if (authUrl == null) {
<add> throw new IllegalStateException("Deployment configuration parameter is not defined: " +
<add> NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_URL_V2) ;
<add> }
<add>
<add> //Check to see if http links are allowed
<add> String authAllowInsecure = config.get( NarrativeJobServiceServer.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM);
<add> if (! "true".equals(authAllowInsecure) && ! authUrl.startsWith("https://")) {
<add> throw new Exception("Only https links are allowed: " + authUrl);
<add> }
<ide> CloseableHttpClient httpclient = HttpClients.createDefault();
<del>
<ide> HttpGet request = new HttpGet(authUrl);
<ide> request.setHeader(HttpHeaders.AUTHORIZATION, token);
<ide> InputStream response = httpclient.execute(request).getEntity().getContent();
<ide> ObjectMapper mapper = new ObjectMapper();
<ide> Map<String, Object> jsonMap = mapper.readValue(response, Map.class);
<ide> Object expire = jsonMap.getOrDefault("expires", null);
<add> //Calculate ms till expiration
<ide> if (expire != null) {
<del> System.out.println("TOKEN EXPIRATION IS:" + expire);
<del> long expiration = 1533767010265L;
<del> long current_time = Instant.now().toEpochMilli();
<del> long seconds_to_expire = (expiration - current_time);
<del> return seconds_to_expire;
<add> return (Long.parseLong((String) expire) - Instant.now().toEpochMilli());
<ide> }
<ide> throw new Exception("Unable to get expiry date of token, we should cancel it now" + jsonMap.toString());
<ide> }
<ide> log.logNextLine(resourceRequirements.toString(), false);
<ide> }
<ide>
<del>
<del> final long msToLive = miliSecondsToLive(tokenStr,config);
<add> //Get number of milliseconds to live for this token
<add> //Set a timer before job is cancelled for having an expired token to the expiration time minus 10 minutes
<add> //
<add> final long msToLive = milliSecondsToLive(tokenStr,config);
<ide> Thread tokenExpirationHook = new Thread()
<ide> {
<ide> @Override
<ide> {
<ide> try {
<ide> long tenMinutesBeforeExpiration = msToLive - 600000;
<del>
<del> tenMinutesBeforeExpiration=1000;
<del>
<del> if(tenMinutesBeforeExpiration > 0){
<add> if(tenMinutesBeforeExpiration > 0){
<ide> Thread.sleep(tenMinutesBeforeExpiration);
<ide> canceljob(jobSrvClient,jobId);
<ide> log.logNextLine("Job was canceled due to token expiration", false);
<ide> };
<ide>
<ide> tokenExpirationHook.start();
<del>
<del>
<ide>
<ide>
<ide> // Calling Runner |
|
Java | agpl-3.0 | 3e9ae3efa6cbcd42bf3338e0b9866e22dece49a3 | 0 | UniversityOfHawaii/kfs,smith750/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,kuali/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kuali/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,quikkian-ua-devops/will-financials,kuali/kfs,ua-eas/kfs,kkronenb/kfs,bhutchinson/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs | /*
* Copyright (c) 2004, 2005 The National Association of College and University Business Officers,
* Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees,
* Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on
* behalf of the University of Arizona, and the r*smart group.
*
* Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining,
* using and/or copying this Original Work, you agree that you have read, understand, and will
* comply with the terms and conditions of the Educational Community License.
*
* You may obtain a copy of the License at:
*
* http://kualiproject.org/license.html
*
* 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 org.kuali.module.chart.rules;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.kuali.KeyConstants;
import org.kuali.core.bo.PostalZipCode;
import org.kuali.core.bo.State;
import org.kuali.core.bo.user.KualiUser;
import org.kuali.core.document.MaintenanceDocument;
import org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase;
import org.kuali.core.service.BusinessObjectService;
import org.kuali.core.util.GlobalVariables;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.util.SpringServiceLocator;
import org.kuali.module.chart.bo.Account;
import org.kuali.module.chart.bo.AccountGuideline;
import org.kuali.module.chart.bo.Campus;
/**
* Business rule(s) applicable to AccountMaintenance documents.
*
* @author Kuali Nervous System Team ([email protected])
*/
public class AccountRule extends MaintenanceDocumentRuleBase {
private static Set validBudgetCodes;
static {
initializeBudgetCodes();
}
Account oldAccount;
Account newAccount;
AccountGuideline oldAccountGuideline;
AccountGuideline newAccountGuideline;
MaintenanceDocument maintenanceDocument;
private static void initializeBudgetCodes() {
validBudgetCodes = new TreeSet();
validBudgetCodes.add("A");
validBudgetCodes.add("C");
validBudgetCodes.add("L");
validBudgetCodes.add("N");
validBudgetCodes.add("O");
}
/**
*
* This method sets the convenience objects like newAccount and oldAccount, so you
* have short and easy handles to the new and old objects contained in the
* maintenance document.
*
* @param document - the maintenanceDocument being evaluated
*
*/
private void setupConvenienceObjects(MaintenanceDocument document) {
// set the global reference of the maint doc
maintenanceDocument = document;
// setup oldAccount convenience objects
oldAccount = (Account) document.getOldMaintainableObject().getBusinessObject();
oldAccountGuideline = oldAccount.getAccountGuideline();
// setup newAccount convenience objects
newAccount = (Account) document.getNewMaintainableObject().getBusinessObject();
newAccountGuideline = newAccount.getAccountGuideline();
}
protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) {
setupConvenienceObjects(document);
// default to success
boolean success = true;
success &= checkEmptyValues(document);
return success;
}
protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) {
setupConvenienceObjects(document);
// default to success
boolean success = true;
success &= checkEmptyValues(document);
success &= checkGeneralRules(document);
success &= checkCloseAccount(document);
success &= checkContractsAndGrants(document);
success &= checkExpirationDate(document);
success &= checkFundGroup(document);
success &= checkSubFundGroup(document);
return success;
}
/**
*
* This method checks the basic rules for empty values in an account and associated
* objects with this account
* @param maintenanceDocument
* @return
*/
private boolean checkEmptyValues(MaintenanceDocument maintenanceDocument) {
boolean success = true;
//TODO: all of these strings need to be changed to propertyNames,
// ie: Chart of Accounts Code -> chartOfAccountsCode
success &= checkEmptyValue("Financial Document Description",
maintenanceDocument.getDocumentHeader().getFinancialDocumentDescription());
success &= checkEmptyValue("Chart of Accounts Code", newAccount.getChartOfAccountsCode());
success &= checkEmptyValue("Account Number", newAccount.getAccountNumber());
success &= checkEmptyValue("Account Name", newAccount.getAccountName());
success &= checkEmptyValue("OrganizationFromRules", newAccount.getOrganizationCode());
success &= checkEmptyValue("Campus Code", newAccount.getAccountPhysicalCampusCode());
success &= checkEmptyValue("Effective Date", newAccount.getAccountEffectiveDate());
success &= checkEmptyValue("City Name", newAccount.getAccountCityName());
success &= checkEmptyValue("State Code", newAccount.getAccountStateCode());
success &= checkEmptyValue("Address", newAccount.getAccountStreetAddress());
success &= checkEmptyValue("ZIP Code", newAccount.getAccountZipCode());
success &= checkEmptyValue("Account Manager", newAccount.getAccountManagerUser().getPersonUniversalIdentifier());
success &= checkEmptyValue("Account Supervisor", newAccount.getAccountSupervisoryUser().getPersonUniversalIdentifier());
success &= checkEmptyValue("Budget Recording Level", newAccount.getBudgetRecordingLevelCode());
success &= checkEmptyValue("Sufficient Funds Code", newAccount.getAccountSufficientFundsCode());
success &= checkEmptyValue("Sub Fund Group", newAccount.getSubFundGroupCode());
success &= checkEmptyValue("Higher Ed Function Code", newAccount.getFinancialHigherEdFunctionCd());
success &= checkEmptyValue("Restricted Status Code", newAccount.getAccountRestrictedStatusCode());
success &= checkEmptyValue("ICR Type Code", newAccount.getAcctIndirectCostRcvyTypeCd());
success &= checkEmptyValue("ICR Series Identifier", newAccount.getFinancialIcrSeriesIdentifier());
success &= checkEmptyValue("ICR Cost Recovery Account", newAccount.getIndirectCostRecoveryAcctNbr());
success &= checkEmptyValue("C&G Domestic Assistance Number", newAccount.getCgCatlfFedDomestcAssistNbr());
// Guidelines are only required on a 'new' maint doc
if (maintenanceDocument.isNew()) {
success &= checkEmptyValue("Expense Guideline", newAccount.getAccountGuideline().getAccountExpenseGuidelineText());
success &= checkEmptyValue("Income Guideline", newAccount.getAccountGuideline().getAccountIncomeGuidelineText());
success &= checkEmptyValue("Account Purpose", newAccount.getAccountGuideline().getAccountPurposeText());
}
return success;
}
/**
*
* This method checks some of the general business rules associated with this document
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkGeneralRules(MaintenanceDocument maintenanceDocument) {
boolean success = true;
GlobalVariables.getErrorMap().addToErrorPath("newMaintainableObject");
//if the account type code is left blank it will default to NA.
if(newAccount.getAccountTypeCode().equals("")) {
newAccount.setAccountTypeCode("NA");
}
//TODO: IU-specific rule?
//the account number cannot begin with a 3, or with 00.
if(newAccount.getAccountNumber().startsWith("3") || newAccount.getAccountNumber().startsWith("00")) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
}
//only a FIS supervisor can reopen a closed account. (This is the central super user, not an account supervisor).
//we need to get the old maintanable doc here
if (maintenanceDocument.isEdit()) {
Account oldAccount = (Account) maintenanceDocument.getOldMaintainableObject().getBusinessObject();
Account newAccount = (Account) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
if (oldAccount.isAccountClosedIndicator()) {
if (!newAccount.isAccountClosedIndicator()) {
KualiUser thisUser = GlobalVariables.getUserSession().getKualiUser();
if (!thisUser.isSupervisorUser()) {
success &= false;
putFieldError("accountClosedIndicator", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ONLY_SUPERVISORS_CAN_REOPEN);
}
}
}
}
//when a restricted status code of 'T' (temporarily restricted) is selected, a restricted status date must be supplied.
if(newAccount.getAccountRestrictedStatusCode().equalsIgnoreCase("T") && newAccount.getAccountRestrictedStatusDate() == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
}
// the fringe benefit account (otherwise known as the reportsToAccount) is required if
// the fringe benefit code is set to N.
// The fringe benefit code of the account designated to accept the fringes must be Y.
if(!newAccount.isAccountsFringesBnftIndicator()) {
if (StringUtils.isEmpty(newAccount.getReportsToAccountNumber()) ||
ObjectUtils.isNull(newAccount.getReportsToAccount())) { // proxy-safe null test
success &= false;
putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_REQUIRED_IF_FRINGEBENEFIT_FALSE);
}
else {
Account reportsToAccount = newAccount.getReportsToAccount();
if (!reportsToAccount.isAccountsFringesBnftIndicator()) {
success &= false;
putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_MUST_BE_FLAGGED_FRINGEBENEFIT, newAccount.getReportsToAccountNumber());
}
}
}
//the employee type for fiscal officer, account manager, and account supervisor must be 'P' professional.
KualiUser fiscalOfficer = newAccount.getAccountFiscalOfficerUser();
KualiUser acctMgr = newAccount.getAccountManagerUser();
KualiUser acctSvr = newAccount.getAccountSupervisoryUser();
if(fiscalOfficer == null || acctMgr == null || acctSvr == null) {
SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(newAccount);
if(fiscalOfficer == null || acctMgr == null || acctSvr == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
}
String fiscalOfficerEmpType = fiscalOfficer.getEmployeeTypeCode();
String acctMgrEmpType = acctMgr.getEmployeeTypeCode();
String acctSvrEmpType = acctSvr.getEmployeeTypeCode();
if(!fiscalOfficerEmpType.equalsIgnoreCase("P") ||
!acctMgrEmpType.equalsIgnoreCase("P") ||
!acctSvrEmpType.equalsIgnoreCase("P")) {
success &= false;
putFieldError("accountNumber", "GenericError", newAccount.getAccountNumber());
}
}
//the supervisor cannot be the same as the fiscal officer or account manager.
if(fiscalOfficer.equals(acctMgr) ||
fiscalOfficer.equals(acctSvr) ||
acctMgr.equals(acctSvr)) {
success &= false;
putFieldError("accountNumber", "GenericError", newAccount.getAccountNumber());
}
//valid values for the budget code are account, consolidation, level, object code, mixed, sub-account and no budget.
String budgetCode = newAccount.getBudgetRecordingLevelCode();
if (!validBudgetCodes.contains(budgetCode)) {
success &= false;
putFieldError("accountNumber", "GenericError", newAccount.getAccountNumber());
}
// If a document is enroute that affects the filled in account number then give the user an error indicating that
// the current account is locked for editing
//TODO: do it
//If acct_off_cmp_ind is not set when they route the document then default it to "N"
if(newAccount.isAccountOffCampusIndicator())
//TODO: do it
//org_cd must be a valid org and active in the ca_org_t table
if(!newAccount.getOrganization().isOrganizationActiveIndicator()) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
}
//acct_phys_cmp_cd must be valid campus in the acct_phys_cmp_cd table
String physicalCampusCode = newAccount.getAccountPhysicalCampusCode();
Campus campus = newAccount.getAccountPhysicalCampus();
if(campus == null && !physicalCampusCode.equals("")) {
SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(newAccount);
campus = newAccount.getAccountPhysicalCampus();
if(campus == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
}
}
//acct_state_cd must be valid in the sh_state_t table
String stateCode = newAccount.getAccountStateCode();
State state = newAccount.getAccountState();
if(state == null && !stateCode.equals("")) {
SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(newAccount);
state = newAccount.getAccountState();
if(state == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
}
}
//acct_zip_cd must be a valid in the sh_zip_code_t table
//if acct_typ_cd is left empty it is defaulted to "NA"
if(newAccount.getAccountTypeCode() == null) {
newAccount.setAccountTypeCode("NA");
}
return success;
/*
* These should never be null as they are boolean
* account.getAccountsFringesBnftIndicator() == null ||
* account.isPendingAcctSufficientFundsIndicator() == null ||
account.isExtrnlFinEncumSufficntFndIndicator() == null ||
account.isIntrnlFinEncumSufficntFndIndicator() == null ||
account.isFinPreencumSufficientFundIndicator() == null ||
account.getFinancialObjectivePrsctrlIndicator() == null ||
*/
}
/**
*
* This method checks to see if the user is trying to close the account and if so if any
* rules are being violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkCloseAccount(MaintenanceDocument maintenanceDocument) {
boolean success = true;
//TODO - should we move this up to the calling method?
boolean isClosed = newAccount.isAccountClosedIndicator();
if(!isClosed) {
return true;
}
//when closing an account, the account expiration date must be the current date or earlier
Timestamp closeDate = newAccount.getAccountExpirationDate();
Timestamp today = new Timestamp(Calendar.getInstance().getTimeInMillis());
if(isClosed && !closeDate.before(today)) {
//TODO - error message
success &= false;
}
//when closing an account, a continuation account is required error message - "When closing an Account a Continuation Account Number entered on the Responsibility screen is required."
if(isClosed && newAccount.getContinuationAccountNumber().equals("") ){
//TODO - error message
success &= false;
}
//in order to close an account, the account must either expire today or already be expired,
//must have no base budget, must have no pending ledger entries or pending labor ledger entries,
//must have no open encumbrances, must have no asset, liability or fund balance balances other than object code 9899
//(9899 is fund balance for us), and the process of closing income and expense into 9899 must take the 9899 balance to zero.
//budget first - no idea (maybe through Options? AccountBalance?)
//definitely looks like we need to pull AccountBalance
/*<field-descriptor name="universityFiscalYear" column="UNIV_FISCAL_YR" jdbc-type="INTEGER" primarykey="true"/>
<field-descriptor name="chartOfAccountsCode" column="FIN_COA_CD" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="accountNumber" column="ACCOUNT_NBR" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="subAccountNumber" column="SUB_ACCT_NBR" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="objectCode" column="FIN_OBJECT_CD" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="subObjectCode" column="FIN_SUB_OBJ_CD" jdbc-type="VARCHAR" primarykey="true" />
*/
String fiscalYear = "2005";
String coaCode = newAccount.getChartOfAccountsCode();
String acctNumber = newAccount.getAccountNumber();
String subAcctNumber = "";
String objectCode = ""; //not sure which object code it wants
String subObjectCode = "";
BusinessObjectService busObjService = SpringServiceLocator.getBusinessObjectService();
//pending ledger entries or pending labor ledger entries
//possibly use GeneralLedgerPendingEntryService to find, but what keys are used?
//no clue on how to check for balances in the other areas (encumbrances, asset, liability, fund balance [other than 9899])
//accounts can only be closed if they dont have balances or any pending ledger entries
return true;
}
/**
*
* This method checks to see if any Contracts and Grants business rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkContractsAndGrants(MaintenanceDocument maintenanceDocument) {
boolean success = true;
return success;
}
/**
*
* This method checks to see if any expiration date field rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkExpirationDate(MaintenanceDocument maintenanceDocument) {
boolean success = true;
//When updating an account expiration date, the date must be today or later (except for C&G accounts).
//a continuation account is required if the expiration date is completed.
//if the expiration date is earlier than today, guidelines are not required.
//If creating a new account if acct_expiration_dt is set and the fund_group is not "CG" then the acct_expiration_dt must be changed to a date that is today or later
//acct_expiration_dt can not be before acct_effect_dt
return success;
}
/**
*
* This method checks to see if any Fund Group rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkFundGroup(MaintenanceDocument maintenanceDocument) {
boolean success = true;
//on the account screen, if the fund group of the account is CG (contracts & grants) or
//RF (restricted funds), the restricted status code is set to 'R'.
//If the fund group is EN (endowment) or PF (plant fund) the value is not set by the system and
//must be set by the user, for all other fund groups the value is set to 'U'. R being restricted,
//U being unrestricted.
//TODO - not sure how to get the Fund Group
//an account in the general fund fund group cannot have a budget recording level of mixed.
return success;
}
/**
*
* This method checks to see if any SubFund Group rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkSubFundGroup(MaintenanceDocument maintenanceDocument) {
boolean success = true;
//sub_fund_grp_cd on the account must be set to a valid sub_fund_grp_cd that exists in the ca_sub_fund_grp_t table
newAccount.getSubFundGroupCode();
//if the sub fund group code is plant fund, construction and major remodeling (PFCMR), the campus and building are required on the description screen for CAMS.
newAccount.getSubFundGroupCode();
//if sub_fund_grp_cd is 'PFCMR' then campus_cd must be entered
//if sub_fund_grp_cd is 'PFCMR' then bldg_cd must be entered
if(newAccount.getSubFundGroupCode().equalsIgnoreCase("PFCMR")) {
if(newAccount.getAccountPhysicalCampusCode() == null ||
newAccount.getAccountPhysicalCampusCode().equals("")) {
//TODO - error message
success &= false;
}
if(newAccount.getAccountZipCode() != null && !newAccount.getAccountZipCode().equals("")) {
HashMap primaryKeys = new HashMap();
primaryKeys.put("postalZipCode", newAccount.getAccountZipCode());
PostalZipCode zip = (PostalZipCode)SpringServiceLocator.getBusinessObjectService().findByPrimaryKey(PostalZipCode.class, primaryKeys);
//now we can check the building code
if(zip.getBuildingCode() == null || zip.getBuildingCode().equals("")) {
//TODO - error message
success &= false;
}
}
}
return success;
}
} | work/src/org/kuali/kfs/coa/document/validation/impl/AccountRule.java | /*
* Copyright (c) 2004, 2005 The National Association of College and University Business Officers,
* Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees,
* Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on
* behalf of the University of Arizona, and the r*smart group.
*
* Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining,
* using and/or copying this Original Work, you agree that you have read, understand, and will
* comply with the terms and conditions of the Educational Community License.
*
* You may obtain a copy of the License at:
*
* http://kualiproject.org/license.html
*
* 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 org.kuali.module.chart.rules;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.kuali.KeyConstants;
import org.kuali.core.bo.PostalZipCode;
import org.kuali.core.bo.State;
import org.kuali.core.bo.user.KualiUser;
import org.kuali.core.document.MaintenanceDocument;
import org.kuali.core.maintenance.Maintainable;
import org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase;
import org.kuali.core.service.BusinessObjectService;
import org.kuali.core.util.GlobalVariables;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.util.SpringServiceLocator;
import org.kuali.module.chart.bo.Account;
import org.kuali.module.chart.bo.Campus;
/**
* Business rule(s) applicable to AccountMaintenance documents.
*
* @author Kuali Nervous System Team ([email protected])
*/
public class AccountRule extends MaintenanceDocumentRuleBase {
private static Set validBudgetCodes;
static {
initializeBudgetCodes();
}
private static void initializeBudgetCodes() {
validBudgetCodes = new TreeSet();
validBudgetCodes.add("A");
validBudgetCodes.add("C");
validBudgetCodes.add("L");
validBudgetCodes.add("N");
validBudgetCodes.add("O");
}
protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) {
boolean success = true;
success &= checkEmptyValues(document);
return success;
}
protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) {
boolean success = true;
success &= checkEmptyValues(document);
success &= checkGeneralRules(document);
success &= checkCloseAccount(document);
success &= checkContractsAndGrants(document);
success &= checkExpirationDate(document);
success &= checkFundGroup(document);
success &= checkSubFundGroup(document);
return success;
}
/**
*
* This method checks the basic rules for empty values in an account and associated
* objects with this account
* @param maintenanceDocument
* @return
*/
private boolean checkEmptyValues(MaintenanceDocument maintenanceDocument) {
boolean success = true;
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
success &= checkEmptyValue("Financial Document Description",
maintenanceDocument.getDocumentHeader().getFinancialDocumentDescription());
success &= checkEmptyValue("Chart of Accounts Code", account.getChartOfAccountsCode());
success &= checkEmptyValue("Account Number", account.getAccountNumber());
success &= checkEmptyValue("Account Name", account.getAccountName());
success &= checkEmptyValue("Organization", account.getOrganizationCode());
success &= checkEmptyValue("Campus Code", account.getAccountPhysicalCampusCode());
success &= checkEmptyValue("Effective Date", account.getAccountEffectiveDate());
success &= checkEmptyValue("City Name", account.getAccountCityName());
success &= checkEmptyValue("State Code", account.getAccountStateCode());
success &= checkEmptyValue("Address", account.getAccountStreetAddress());
success &= checkEmptyValue("ZIP Code", account.getAccountZipCode());
success &= checkEmptyValue("Account Manager", account.getAccountManagerUser().getPersonUniversalIdentifier());
success &= checkEmptyValue("Account Supervisor", account.getAccountSupervisoryUser().getPersonUniversalIdentifier());
success &= checkEmptyValue("Budget Recording Level", account.getBudgetRecordingLevelCode());
success &= checkEmptyValue("Sufficient Funds Code", account.getAccountSufficientFundsCode());
success &= checkEmptyValue("Sub Fund Group", account.getSubFundGroupCode());
success &= checkEmptyValue("Higher Ed Function Code", account.getFinancialHigherEdFunctionCd());
success &= checkEmptyValue("Restricted Status Code", account.getAccountRestrictedStatusCode());
success &= checkEmptyValue("ICR Type Code", account.getAcctIndirectCostRcvyTypeCd());
success &= checkEmptyValue("ICR Series Identifier", account.getFinancialIcrSeriesIdentifier());
success &= checkEmptyValue("ICR Cost Recovery Account", account.getIndirectCostRecoveryAcctNbr());
success &= checkEmptyValue("C&G Domestic Assistance Number", account.getCgCatlfFedDomestcAssistNbr());
success &= checkEmptyValue("Expense Guideline", account.getAccountGuideline().getAccountExpenseGuidelineText());
success &= checkEmptyValue("Income Guideline", account.getAccountGuideline().getAccountIncomeGuidelineText());
success &= checkEmptyValue("Account Purpose", account.getAccountGuideline().getAccountPurposeText());
return success;
}
/**
*
* This method checks some of the general business rules associated with this document
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkGeneralRules(MaintenanceDocument maintenanceDocument) {
boolean success = true;
GlobalVariables.getErrorMap().addToErrorPath("newMaintainableObject");
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
//if the account type code is left blank it will default to NA.
if(account.getAccountTypeCode().equals("")) {
account.setAccountTypeCode("NA");
}
//TODO: IU-specific rule?
//the account number cannot begin with a 3, or with 00.
if(account.getAccountNumber().startsWith("3") || account.getAccountNumber().startsWith("00")) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
}
//only a FIS supervisor can reopen a closed account. (This is the central super user, not an account supervisor).
//we need to get the old maintanable doc here
if (maintenanceDocument.isEdit()) {
Account oldAccount = (Account) maintenanceDocument.getOldMaintainableObject().getBusinessObject();
Account newAccount = (Account) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
if (oldAccount.isAccountClosedIndicator()) {
if (!newAccount.isAccountClosedIndicator()) {
KualiUser thisUser = GlobalVariables.getUserSession().getKualiUser();
if (!thisUser.isSupervisorUser()) {
success &= false;
putFieldError("accountClosedIndicator", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ONLY_SUPERVISORS_CAN_REOPEN);
}
}
}
}
//when a restricted status code of 'T' (temporarily restricted) is selected, a restricted status date must be supplied.
if(account.getAccountRestrictedStatusCode().equalsIgnoreCase("T") && account.getAccountRestrictedStatusDate() == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
}
// the fringe benefit account (otherwise known as the reportsToAccount) is required if
// the fringe benefit code is set to N.
// The fringe benefit code of the account designated to accept the fringes must be Y.
if(!account.isAccountsFringesBnftIndicator()) {
if (StringUtils.isEmpty(account.getReportsToAccountNumber()) ||
ObjectUtils.isNull(account.getReportsToAccount())) { // proxy-safe null test
success &= false;
putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_REQUIRED_IF_FRINGEBENEFIT_FALSE);
}
else {
Account reportsToAccount = account.getReportsToAccount();
if (!reportsToAccount.isAccountsFringesBnftIndicator()) {
success &= false;
putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_MUST_BE_FLAGGED_FRINGEBENEFIT, account.getReportsToAccountNumber());
}
}
}
//the employee type for fiscal officer, account manager, and account supervisor must be 'P' professional.
KualiUser fiscalOfficer = account.getAccountFiscalOfficerUser();
KualiUser acctMgr = account.getAccountManagerUser();
KualiUser acctSvr = account.getAccountSupervisoryUser();
if(fiscalOfficer == null || acctMgr == null || acctSvr == null) {
SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(account);
if(fiscalOfficer == null || acctMgr == null || acctSvr == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
}
String fiscalOfficerEmpType = fiscalOfficer.getEmployeeTypeCode();
String acctMgrEmpType = acctMgr.getEmployeeTypeCode();
String acctSvrEmpType = acctSvr.getEmployeeTypeCode();
if(!fiscalOfficerEmpType.equalsIgnoreCase("P") ||
!acctMgrEmpType.equalsIgnoreCase("P") ||
!acctSvrEmpType.equalsIgnoreCase("P")) {
success &= false;
putFieldError("accountNumber", "GenericError", account.getAccountNumber());
}
}
//the supervisor cannot be the same as the fiscal officer or account manager.
if(fiscalOfficer.equals(acctMgr) ||
fiscalOfficer.equals(acctSvr) ||
acctMgr.equals(acctSvr)) {
success &= false;
putFieldError("accountNumber", "GenericError", account.getAccountNumber());
}
//valid values for the budget code are account, consolidation, level, object code, mixed, sub-account and no budget.
String budgetCode = account.getBudgetRecordingLevelCode();
if (!validBudgetCodes.contains(budgetCode)) {
success &= false;
putFieldError("accountNumber", "GenericError", account.getAccountNumber());
}
//If a document is enroute that affects the filled in account number then give the user an error indicating that the current account is locked for editing
//If acct_off_cmp_ind is not set when they route the document then default it to "N"
if(account.isAccountOffCampusIndicator())
//org_cd must be a valid org and active in the ca_org_t table
if(!account.getOrganization().isOrganizationActiveIndicator()) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
}
//acct_phys_cmp_cd must be valid campus in the acct_phys_cmp_cd table
String physicalCampusCode = account.getAccountPhysicalCampusCode();
Campus campus = account.getAccountPhysicalCampus();
if(campus == null && !physicalCampusCode.equals("")) {
SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(account);
campus = account.getAccountPhysicalCampus();
if(campus == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
}
}
//acct_state_cd must be valid in the sh_state_t table
String stateCode = account.getAccountStateCode();
State state = account.getAccountState();
if(state == null && !stateCode.equals("")) {
SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(account);
state = account.getAccountState();
if(state == null) {
success &= false;
putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
}
}
//acct_zip_cd must be a valid in the sh_zip_code_t table
//if acct_typ_cd is left empty it is defaulted to "NA"
if(account.getAccountTypeCode() == null) {
account.setAccountTypeCode("NA");
}
return success;
/*
* These should never be null as they are boolean
* account.getAccountsFringesBnftIndicator() == null ||
* account.isPendingAcctSufficientFundsIndicator() == null ||
account.isExtrnlFinEncumSufficntFndIndicator() == null ||
account.isIntrnlFinEncumSufficntFndIndicator() == null ||
account.isFinPreencumSufficientFundIndicator() == null ||
account.getFinancialObjectivePrsctrlIndicator() == null ||
*/
}
/**
*
* This method checks to see if the user is trying to close the account and if so if any
* rules are being violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkCloseAccount(MaintenanceDocument maintenanceDocument) {
boolean success = true;
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
//TODO - should we move this up to the calling method?
boolean isClosed = account.isAccountClosedIndicator();
if(!isClosed) {
return true;
}
//when closing an account, the account expiration date must be the current date or earlier
Timestamp closeDate = account.getAccountExpirationDate();
Timestamp today = new Timestamp(Calendar.getInstance().getTimeInMillis());
if(isClosed && !closeDate.before(today)) {
//TODO - error message
success &= false;
}
//when closing an account, a continuation account is required error message - "When closing an Account a Continuation Account Number entered on the Responsibility screen is required."
if(isClosed && account.getContinuationAccountNumber().equals("") ){
//TODO - error message
success &= false;
}
//in order to close an account, the account must either expire today or already be expired,
//must have no base budget, must have no pending ledger entries or pending labor ledger entries,
//must have no open encumbrances, must have no asset, liability or fund balance balances other than object code 9899
//(9899 is fund balance for us), and the process of closing income and expense into 9899 must take the 9899 balance to zero.
//budget first - no idea (maybe through Options? AccountBalance?)
//definitely looks like we need to pull AccountBalance
/*<field-descriptor name="universityFiscalYear" column="UNIV_FISCAL_YR" jdbc-type="INTEGER" primarykey="true"/>
<field-descriptor name="chartOfAccountsCode" column="FIN_COA_CD" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="accountNumber" column="ACCOUNT_NBR" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="subAccountNumber" column="SUB_ACCT_NBR" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="objectCode" column="FIN_OBJECT_CD" jdbc-type="VARCHAR" primarykey="true" />
<field-descriptor name="subObjectCode" column="FIN_SUB_OBJ_CD" jdbc-type="VARCHAR" primarykey="true" />
*/
String fiscalYear = "2005";
String coaCode = account.getChartOfAccountsCode();
String acctNumber = account.getAccountNumber();
String subAcctNumber = "";
String objectCode = ""; //not sure which object code it wants
String subObjectCode = "";
BusinessObjectService busObjService = SpringServiceLocator.getBusinessObjectService();
//pending ledger entries or pending labor ledger entries
//possibly use GeneralLedgerPendingEntryService to find, but what keys are used?
//no clue on how to check for balances in the other areas (encumbrances, asset, liability, fund balance [other than 9899])
//accounts can only be closed if they dont have balances or any pending ledger entries
return true;
}
/**
*
* This method checks to see if any Contracts and Grants business rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkContractsAndGrants(MaintenanceDocument maintenanceDocument) {
boolean success = true;
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
return success;
}
/**
*
* This method checks to see if any expiration date field rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkExpirationDate(MaintenanceDocument maintenanceDocument) {
boolean success = true;
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
//When updating an account expiration date, the date must be today or later (except for C&G accounts).
//a continuation account is required if the expiration date is completed.
//if the expiration date is earlier than today, guidelines are not required.
//If creating a new account if acct_expiration_dt is set and the fund_group is not "CG" then the acct_expiration_dt must be changed to a date that is today or later
//acct_expiration_dt can not be before acct_effect_dt
return success;
}
/**
*
* This method checks to see if any Fund Group rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkFundGroup(MaintenanceDocument maintenanceDocument) {
boolean success = true;
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
//on the account screen, if the fund group of the account is CG (contracts & grants) or
//RF (restricted funds), the restricted status code is set to 'R'.
//If the fund group is EN (endowment) or PF (plant fund) the value is not set by the system and
//must be set by the user, for all other fund groups the value is set to 'U'. R being restricted,
//U being unrestricted.
//TODO - not sure how to get the Fund Group
//an account in the general fund fund group cannot have a budget recording level of mixed.
return success;
}
/**
*
* This method checks to see if any SubFund Group rules were violated
* @param maintenanceDocument
* @return false on rules violation
*/
private boolean checkSubFundGroup(MaintenanceDocument maintenanceDocument) {
boolean success = true;
Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
Account account = (Account) newMaintainable.getBusinessObject();
//sub_fund_grp_cd on the account must be set to a valid sub_fund_grp_cd that exists in the ca_sub_fund_grp_t table
account.getSubFundGroupCode();
//if the sub fund group code is plant fund, construction and major remodeling (PFCMR), the campus and building are required on the description screen for CAMS.
account.getSubFundGroupCode();
//if sub_fund_grp_cd is 'PFCMR' then campus_cd must be entered
//if sub_fund_grp_cd is 'PFCMR' then bldg_cd must be entered
if(account.getSubFundGroupCode().equalsIgnoreCase("PFCMR")) {
if(account.getAccountPhysicalCampusCode() == null ||
account.getAccountPhysicalCampusCode().equals("")) {
//TODO - error message
success &= false;
}
if(account.getAccountZipCode() != null && !account.getAccountZipCode().equals("")) {
HashMap primaryKeys = new HashMap();
primaryKeys.put("zipCode", account.getAccountZipCode());
PostalZipCode zip = (PostalZipCode)SpringServiceLocator.getBusinessObjectService().findByPrimaryKey(PostalZipCode.class, primaryKeys);
//now we can check the building code
if(zip.getBuildingCode() == null || zip.getBuildingCode().equals("")) {
//TODO - error message
success &= false;
}
}
}
return success;
}
} | created global handles for oldAccount and newAccount
fixed the ZipCode -> postalZipCode name change
| work/src/org/kuali/kfs/coa/document/validation/impl/AccountRule.java | created global handles for oldAccount and newAccount fixed the ZipCode -> postalZipCode name change | <ide><path>ork/src/org/kuali/kfs/coa/document/validation/impl/AccountRule.java
<ide> import org.kuali.core.bo.State;
<ide> import org.kuali.core.bo.user.KualiUser;
<ide> import org.kuali.core.document.MaintenanceDocument;
<del>import org.kuali.core.maintenance.Maintainable;
<ide> import org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase;
<ide> import org.kuali.core.service.BusinessObjectService;
<ide> import org.kuali.core.util.GlobalVariables;
<ide> import org.kuali.core.util.ObjectUtils;
<ide> import org.kuali.core.util.SpringServiceLocator;
<ide> import org.kuali.module.chart.bo.Account;
<add>import org.kuali.module.chart.bo.AccountGuideline;
<ide> import org.kuali.module.chart.bo.Campus;
<ide>
<ide> /**
<ide> static {
<ide> initializeBudgetCodes();
<ide> }
<add>
<add> Account oldAccount;
<add> Account newAccount;
<add> AccountGuideline oldAccountGuideline;
<add> AccountGuideline newAccountGuideline;
<add> MaintenanceDocument maintenanceDocument;
<ide>
<ide> private static void initializeBudgetCodes() {
<ide> validBudgetCodes = new TreeSet();
<ide> validBudgetCodes.add("O");
<ide> }
<ide>
<add> /**
<add> *
<add> * This method sets the convenience objects like newAccount and oldAccount, so you
<add> * have short and easy handles to the new and old objects contained in the
<add> * maintenance document.
<add> *
<add> * @param document - the maintenanceDocument being evaluated
<add> *
<add> */
<add> private void setupConvenienceObjects(MaintenanceDocument document) {
<add>
<add> // set the global reference of the maint doc
<add> maintenanceDocument = document;
<add>
<add> // setup oldAccount convenience objects
<add> oldAccount = (Account) document.getOldMaintainableObject().getBusinessObject();
<add> oldAccountGuideline = oldAccount.getAccountGuideline();
<add>
<add> // setup newAccount convenience objects
<add> newAccount = (Account) document.getNewMaintainableObject().getBusinessObject();
<add> newAccountGuideline = newAccount.getAccountGuideline();
<add> }
<add>
<ide> protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) {
<del> boolean success = true;
<add>
<add> setupConvenienceObjects(document);
<add>
<add> // default to success
<add> boolean success = true;
<add>
<ide> success &= checkEmptyValues(document);
<ide> return success;
<ide> }
<ide>
<ide> protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) {
<add>
<add> setupConvenienceObjects(document);
<add>
<add> // default to success
<ide> boolean success = true;
<ide>
<ide> success &= checkEmptyValues(document);
<ide> */
<ide> private boolean checkEmptyValues(MaintenanceDocument maintenanceDocument) {
<ide> boolean success = true;
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<del>
<add>
<add> //TODO: all of these strings need to be changed to propertyNames,
<add> // ie: Chart of Accounts Code -> chartOfAccountsCode
<ide> success &= checkEmptyValue("Financial Document Description",
<ide> maintenanceDocument.getDocumentHeader().getFinancialDocumentDescription());
<ide>
<del> success &= checkEmptyValue("Chart of Accounts Code", account.getChartOfAccountsCode());
<del>
<del> success &= checkEmptyValue("Account Number", account.getAccountNumber());
<del>
<del> success &= checkEmptyValue("Account Name", account.getAccountName());
<del>
<del> success &= checkEmptyValue("Organization", account.getOrganizationCode());
<del>
<del> success &= checkEmptyValue("Campus Code", account.getAccountPhysicalCampusCode());
<del>
<del> success &= checkEmptyValue("Effective Date", account.getAccountEffectiveDate());
<del>
<del> success &= checkEmptyValue("City Name", account.getAccountCityName());
<del>
<del> success &= checkEmptyValue("State Code", account.getAccountStateCode());
<del>
<del> success &= checkEmptyValue("Address", account.getAccountStreetAddress());
<del>
<del> success &= checkEmptyValue("ZIP Code", account.getAccountZipCode());
<del>
<del> success &= checkEmptyValue("Account Manager", account.getAccountManagerUser().getPersonUniversalIdentifier());
<del>
<del> success &= checkEmptyValue("Account Supervisor", account.getAccountSupervisoryUser().getPersonUniversalIdentifier());
<del>
<del> success &= checkEmptyValue("Budget Recording Level", account.getBudgetRecordingLevelCode());
<del>
<del> success &= checkEmptyValue("Sufficient Funds Code", account.getAccountSufficientFundsCode());
<del>
<del> success &= checkEmptyValue("Sub Fund Group", account.getSubFundGroupCode());
<del>
<del> success &= checkEmptyValue("Higher Ed Function Code", account.getFinancialHigherEdFunctionCd());
<del>
<del> success &= checkEmptyValue("Restricted Status Code", account.getAccountRestrictedStatusCode());
<del>
<del> success &= checkEmptyValue("ICR Type Code", account.getAcctIndirectCostRcvyTypeCd());
<del>
<del> success &= checkEmptyValue("ICR Series Identifier", account.getFinancialIcrSeriesIdentifier());
<del>
<del> success &= checkEmptyValue("ICR Cost Recovery Account", account.getIndirectCostRecoveryAcctNbr());
<del>
<del> success &= checkEmptyValue("C&G Domestic Assistance Number", account.getCgCatlfFedDomestcAssistNbr());
<del>
<del> success &= checkEmptyValue("Expense Guideline", account.getAccountGuideline().getAccountExpenseGuidelineText());
<del>
<del> success &= checkEmptyValue("Income Guideline", account.getAccountGuideline().getAccountIncomeGuidelineText());
<del>
<del> success &= checkEmptyValue("Account Purpose", account.getAccountGuideline().getAccountPurposeText());
<del>
<add> success &= checkEmptyValue("Chart of Accounts Code", newAccount.getChartOfAccountsCode());
<add>
<add> success &= checkEmptyValue("Account Number", newAccount.getAccountNumber());
<add>
<add> success &= checkEmptyValue("Account Name", newAccount.getAccountName());
<add>
<add> success &= checkEmptyValue("OrganizationFromRules", newAccount.getOrganizationCode());
<add>
<add> success &= checkEmptyValue("Campus Code", newAccount.getAccountPhysicalCampusCode());
<add>
<add> success &= checkEmptyValue("Effective Date", newAccount.getAccountEffectiveDate());
<add>
<add> success &= checkEmptyValue("City Name", newAccount.getAccountCityName());
<add>
<add> success &= checkEmptyValue("State Code", newAccount.getAccountStateCode());
<add>
<add> success &= checkEmptyValue("Address", newAccount.getAccountStreetAddress());
<add>
<add> success &= checkEmptyValue("ZIP Code", newAccount.getAccountZipCode());
<add>
<add> success &= checkEmptyValue("Account Manager", newAccount.getAccountManagerUser().getPersonUniversalIdentifier());
<add>
<add> success &= checkEmptyValue("Account Supervisor", newAccount.getAccountSupervisoryUser().getPersonUniversalIdentifier());
<add>
<add> success &= checkEmptyValue("Budget Recording Level", newAccount.getBudgetRecordingLevelCode());
<add>
<add> success &= checkEmptyValue("Sufficient Funds Code", newAccount.getAccountSufficientFundsCode());
<add>
<add> success &= checkEmptyValue("Sub Fund Group", newAccount.getSubFundGroupCode());
<add>
<add> success &= checkEmptyValue("Higher Ed Function Code", newAccount.getFinancialHigherEdFunctionCd());
<add>
<add> success &= checkEmptyValue("Restricted Status Code", newAccount.getAccountRestrictedStatusCode());
<add>
<add> success &= checkEmptyValue("ICR Type Code", newAccount.getAcctIndirectCostRcvyTypeCd());
<add>
<add> success &= checkEmptyValue("ICR Series Identifier", newAccount.getFinancialIcrSeriesIdentifier());
<add>
<add> success &= checkEmptyValue("ICR Cost Recovery Account", newAccount.getIndirectCostRecoveryAcctNbr());
<add>
<add> success &= checkEmptyValue("C&G Domestic Assistance Number", newAccount.getCgCatlfFedDomestcAssistNbr());
<add>
<add> // Guidelines are only required on a 'new' maint doc
<add> if (maintenanceDocument.isNew()) {
<add> success &= checkEmptyValue("Expense Guideline", newAccount.getAccountGuideline().getAccountExpenseGuidelineText());
<add> success &= checkEmptyValue("Income Guideline", newAccount.getAccountGuideline().getAccountIncomeGuidelineText());
<add> success &= checkEmptyValue("Account Purpose", newAccount.getAccountGuideline().getAccountPurposeText());
<add> }
<ide> return success;
<ide> }
<ide>
<ide>
<ide> GlobalVariables.getErrorMap().addToErrorPath("newMaintainableObject");
<ide>
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<del>
<ide> //if the account type code is left blank it will default to NA.
<del> if(account.getAccountTypeCode().equals("")) {
<del> account.setAccountTypeCode("NA");
<add> if(newAccount.getAccountTypeCode().equals("")) {
<add> newAccount.setAccountTypeCode("NA");
<ide> }
<ide>
<ide> //TODO: IU-specific rule?
<ide> //the account number cannot begin with a 3, or with 00.
<del> if(account.getAccountNumber().startsWith("3") || account.getAccountNumber().startsWith("00")) {
<del> success &= false;
<del> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
<add> if(newAccount.getAccountNumber().startsWith("3") || newAccount.getAccountNumber().startsWith("00")) {
<add> success &= false;
<add> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
<ide> }
<ide>
<ide> //only a FIS supervisor can reopen a closed account. (This is the central super user, not an account supervisor).
<ide> }
<ide>
<ide> //when a restricted status code of 'T' (temporarily restricted) is selected, a restricted status date must be supplied.
<del> if(account.getAccountRestrictedStatusCode().equalsIgnoreCase("T") && account.getAccountRestrictedStatusDate() == null) {
<del> success &= false;
<del> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
<add> if(newAccount.getAccountRestrictedStatusCode().equalsIgnoreCase("T") && newAccount.getAccountRestrictedStatusDate() == null) {
<add> success &= false;
<add> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
<ide> }
<ide>
<ide> // the fringe benefit account (otherwise known as the reportsToAccount) is required if
<ide> // the fringe benefit code is set to N.
<ide> // The fringe benefit code of the account designated to accept the fringes must be Y.
<del> if(!account.isAccountsFringesBnftIndicator()) {
<del> if (StringUtils.isEmpty(account.getReportsToAccountNumber()) ||
<del> ObjectUtils.isNull(account.getReportsToAccount())) { // proxy-safe null test
<add> if(!newAccount.isAccountsFringesBnftIndicator()) {
<add> if (StringUtils.isEmpty(newAccount.getReportsToAccountNumber()) ||
<add> ObjectUtils.isNull(newAccount.getReportsToAccount())) { // proxy-safe null test
<ide> success &= false;
<ide> putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_REQUIRED_IF_FRINGEBENEFIT_FALSE);
<ide> }
<ide> else {
<del> Account reportsToAccount = account.getReportsToAccount();
<add> Account reportsToAccount = newAccount.getReportsToAccount();
<ide> if (!reportsToAccount.isAccountsFringesBnftIndicator()) {
<ide> success &= false;
<del> putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_MUST_BE_FLAGGED_FRINGEBENEFIT, account.getReportsToAccountNumber());
<add> putFieldError("reportsToAccountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_RPTS_TO_ACCT_MUST_BE_FLAGGED_FRINGEBENEFIT, newAccount.getReportsToAccountNumber());
<ide> }
<ide> }
<ide> }
<ide>
<ide> //the employee type for fiscal officer, account manager, and account supervisor must be 'P' professional.
<del> KualiUser fiscalOfficer = account.getAccountFiscalOfficerUser();
<del> KualiUser acctMgr = account.getAccountManagerUser();
<del> KualiUser acctSvr = account.getAccountSupervisoryUser();
<add> KualiUser fiscalOfficer = newAccount.getAccountFiscalOfficerUser();
<add> KualiUser acctMgr = newAccount.getAccountManagerUser();
<add> KualiUser acctSvr = newAccount.getAccountSupervisoryUser();
<ide>
<ide> if(fiscalOfficer == null || acctMgr == null || acctSvr == null) {
<del> SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(account);
<add> SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(newAccount);
<ide> if(fiscalOfficer == null || acctMgr == null || acctSvr == null) {
<ide> success &= false;
<del> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
<add> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
<ide> }
<ide> String fiscalOfficerEmpType = fiscalOfficer.getEmployeeTypeCode();
<ide> String acctMgrEmpType = acctMgr.getEmployeeTypeCode();
<ide> !acctMgrEmpType.equalsIgnoreCase("P") ||
<ide> !acctSvrEmpType.equalsIgnoreCase("P")) {
<ide> success &= false;
<del> putFieldError("accountNumber", "GenericError", account.getAccountNumber());
<add> putFieldError("accountNumber", "GenericError", newAccount.getAccountNumber());
<ide>
<ide> }
<ide> }
<ide> fiscalOfficer.equals(acctSvr) ||
<ide> acctMgr.equals(acctSvr)) {
<ide> success &= false;
<del> putFieldError("accountNumber", "GenericError", account.getAccountNumber());
<add> putFieldError("accountNumber", "GenericError", newAccount.getAccountNumber());
<ide> }
<ide>
<ide> //valid values for the budget code are account, consolidation, level, object code, mixed, sub-account and no budget.
<del> String budgetCode = account.getBudgetRecordingLevelCode();
<add> String budgetCode = newAccount.getBudgetRecordingLevelCode();
<ide> if (!validBudgetCodes.contains(budgetCode)) {
<ide> success &= false;
<del> putFieldError("accountNumber", "GenericError", account.getAccountNumber());
<del> }
<del>
<del> //If a document is enroute that affects the filled in account number then give the user an error indicating that the current account is locked for editing
<add> putFieldError("accountNumber", "GenericError", newAccount.getAccountNumber());
<add> }
<add>
<add> // If a document is enroute that affects the filled in account number then give the user an error indicating that
<add> // the current account is locked for editing
<add> //TODO: do it
<ide>
<ide> //If acct_off_cmp_ind is not set when they route the document then default it to "N"
<del> if(account.isAccountOffCampusIndicator())
<add> if(newAccount.isAccountOffCampusIndicator())
<add> //TODO: do it
<ide>
<ide> //org_cd must be a valid org and active in the ca_org_t table
<del> if(!account.getOrganization().isOrganizationActiveIndicator()) {
<del> success &= false;
<del> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
<add> if(!newAccount.getOrganization().isOrganizationActiveIndicator()) {
<add> success &= false;
<add> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
<ide> }
<ide>
<ide> //acct_phys_cmp_cd must be valid campus in the acct_phys_cmp_cd table
<del> String physicalCampusCode = account.getAccountPhysicalCampusCode();
<del> Campus campus = account.getAccountPhysicalCampus();
<add> String physicalCampusCode = newAccount.getAccountPhysicalCampusCode();
<add> Campus campus = newAccount.getAccountPhysicalCampus();
<ide> if(campus == null && !physicalCampusCode.equals("")) {
<del> SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(account);
<del> campus = account.getAccountPhysicalCampus();
<add> SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(newAccount);
<add> campus = newAccount.getAccountPhysicalCampus();
<ide> if(campus == null) {
<ide> success &= false;
<del> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
<add> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
<ide> }
<ide> }
<ide>
<ide> //acct_state_cd must be valid in the sh_state_t table
<del> String stateCode = account.getAccountStateCode();
<del> State state = account.getAccountState();
<add> String stateCode = newAccount.getAccountStateCode();
<add> State state = newAccount.getAccountState();
<ide> if(state == null && !stateCode.equals("")) {
<del> SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(account);
<del> state = account.getAccountState();
<add> SpringServiceLocator.getPersistenceService().retrieveNonKeyFields(newAccount);
<add> state = newAccount.getAccountState();
<ide> if(state == null) {
<ide> success &= false;
<del> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, account.getAccountNumber());
<add> putFieldError("accountNumber", KeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_NMBR_NOT_ALLOWED, newAccount.getAccountNumber());
<ide> }
<ide> }
<ide>
<ide> //acct_zip_cd must be a valid in the sh_zip_code_t table
<ide>
<ide> //if acct_typ_cd is left empty it is defaulted to "NA"
<del> if(account.getAccountTypeCode() == null) {
<del> account.setAccountTypeCode("NA");
<add> if(newAccount.getAccountTypeCode() == null) {
<add> newAccount.setAccountTypeCode("NA");
<ide> }
<ide>
<ide> return success;
<ide> */
<ide> private boolean checkCloseAccount(MaintenanceDocument maintenanceDocument) {
<ide> boolean success = true;
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<ide>
<ide> //TODO - should we move this up to the calling method?
<del> boolean isClosed = account.isAccountClosedIndicator();
<add> boolean isClosed = newAccount.isAccountClosedIndicator();
<ide> if(!isClosed) {
<ide> return true;
<ide> }
<ide> //when closing an account, the account expiration date must be the current date or earlier
<del> Timestamp closeDate = account.getAccountExpirationDate();
<add> Timestamp closeDate = newAccount.getAccountExpirationDate();
<ide> Timestamp today = new Timestamp(Calendar.getInstance().getTimeInMillis());
<ide> if(isClosed && !closeDate.before(today)) {
<ide> //TODO - error message
<ide> }
<ide>
<ide> //when closing an account, a continuation account is required error message - "When closing an Account a Continuation Account Number entered on the Responsibility screen is required."
<del> if(isClosed && account.getContinuationAccountNumber().equals("") ){
<add> if(isClosed && newAccount.getContinuationAccountNumber().equals("") ){
<ide> //TODO - error message
<ide> success &= false;
<ide> }
<ide> <field-descriptor name="subObjectCode" column="FIN_SUB_OBJ_CD" jdbc-type="VARCHAR" primarykey="true" />
<ide> */
<ide> String fiscalYear = "2005";
<del> String coaCode = account.getChartOfAccountsCode();
<del> String acctNumber = account.getAccountNumber();
<add> String coaCode = newAccount.getChartOfAccountsCode();
<add> String acctNumber = newAccount.getAccountNumber();
<ide> String subAcctNumber = "";
<ide> String objectCode = ""; //not sure which object code it wants
<ide> String subObjectCode = "";
<ide> */
<ide> private boolean checkContractsAndGrants(MaintenanceDocument maintenanceDocument) {
<ide> boolean success = true;
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<ide>
<ide> return success;
<ide> }
<ide> */
<ide> private boolean checkExpirationDate(MaintenanceDocument maintenanceDocument) {
<ide> boolean success = true;
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<add>
<ide> //When updating an account expiration date, the date must be today or later (except for C&G accounts).
<ide>
<ide> //a continuation account is required if the expiration date is completed.
<ide> */
<ide> private boolean checkFundGroup(MaintenanceDocument maintenanceDocument) {
<ide> boolean success = true;
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<add>
<ide> //on the account screen, if the fund group of the account is CG (contracts & grants) or
<ide> //RF (restricted funds), the restricted status code is set to 'R'.
<ide> //If the fund group is EN (endowment) or PF (plant fund) the value is not set by the system and
<ide> */
<ide> private boolean checkSubFundGroup(MaintenanceDocument maintenanceDocument) {
<ide> boolean success = true;
<del> Maintainable newMaintainable = maintenanceDocument.getNewMaintainableObject();
<del> Account account = (Account) newMaintainable.getBusinessObject();
<ide>
<ide> //sub_fund_grp_cd on the account must be set to a valid sub_fund_grp_cd that exists in the ca_sub_fund_grp_t table
<del> account.getSubFundGroupCode();
<add> newAccount.getSubFundGroupCode();
<ide>
<ide> //if the sub fund group code is plant fund, construction and major remodeling (PFCMR), the campus and building are required on the description screen for CAMS.
<del> account.getSubFundGroupCode();
<add> newAccount.getSubFundGroupCode();
<ide>
<ide> //if sub_fund_grp_cd is 'PFCMR' then campus_cd must be entered
<ide> //if sub_fund_grp_cd is 'PFCMR' then bldg_cd must be entered
<del> if(account.getSubFundGroupCode().equalsIgnoreCase("PFCMR")) {
<del> if(account.getAccountPhysicalCampusCode() == null ||
<del> account.getAccountPhysicalCampusCode().equals("")) {
<add> if(newAccount.getSubFundGroupCode().equalsIgnoreCase("PFCMR")) {
<add> if(newAccount.getAccountPhysicalCampusCode() == null ||
<add> newAccount.getAccountPhysicalCampusCode().equals("")) {
<ide> //TODO - error message
<ide> success &= false;
<ide> }
<del> if(account.getAccountZipCode() != null && !account.getAccountZipCode().equals("")) {
<add> if(newAccount.getAccountZipCode() != null && !newAccount.getAccountZipCode().equals("")) {
<ide> HashMap primaryKeys = new HashMap();
<del> primaryKeys.put("zipCode", account.getAccountZipCode());
<add> primaryKeys.put("postalZipCode", newAccount.getAccountZipCode());
<ide> PostalZipCode zip = (PostalZipCode)SpringServiceLocator.getBusinessObjectService().findByPrimaryKey(PostalZipCode.class, primaryKeys);
<ide> //now we can check the building code
<ide> if(zip.getBuildingCode() == null || zip.getBuildingCode().equals("")) { |
|
Java | apache-2.0 | f44dc94ff5475b4ceb7c1c5a8a7377ee9102b7f0 | 0 | sivikt/cassandra,helena/cassandra,likaiwalkman/cassandra,joesiewert/cassandra,DavidHerzogTU-Berlin/cassandra,carlyeks/cassandra,knifewine/cassandra,WorksApplications/cassandra,likaiwalkman/cassandra,driftx/cassandra,belliottsmith/cassandra,nlalevee/cassandra,hhorii/cassandra,beobal/cassandra,nakomis/cassandra,stef1927/cassandra,sriki77/cassandra,aboudreault/cassandra,segfault/apache_cassandra,josh-mckenzie/cassandra,jasonstack/cassandra,blambov/cassandra,mheffner/cassandra-1,thelastpickle/cassandra,adelapena/cassandra,scylladb/scylla-tools-java,driftx/cassandra,fengshao0907/Cassandra-Research,snazy/cassandra,tjake/cassandra,aureagle/cassandra,yhnishi/cassandra,mt0803/cassandra,emolsson/cassandra,jeffjirsa/cassandra,newrelic-forks/cassandra,knifewine/cassandra,Stratio/stratio-cassandra,beobal/cassandra,juiceblender/cassandra,darach/cassandra,dprguiuc/Cassandra-Wasef,HidemotoNakada/cassandra-udf,iburmistrov/Cassandra,yangzhe1991/cassandra,bpupadhyaya/cassandra,Jaumo/cassandra,wreda/cassandra,christian-esken/cassandra,jrwest/cassandra,mike-tr-adamson/cassandra,jasobrown/cassandra,thelastpickle/cassandra,clohfink/cassandra,chbatey/cassandra-1,pcn/cassandra-1,regispl/cassandra,adelapena/cassandra,nakomis/cassandra,kgreav/cassandra,ollie314/cassandra,ejankan/cassandra,jrwest/cassandra,yanbit/cassandra,adelapena/cassandra,sluk3r/cassandra,belliottsmith/cassandra,yangzhe1991/cassandra,rackerlabs/cloudmetrics-cassandra,sedulam/CASSANDRA-12201,josh-mckenzie/cassandra,LatencyUtils/cassandra-stress2,qinjin/mdtc-cassandra,helena/cassandra,macintoshio/cassandra,Instagram/cassandra,strapdata/cassandra,sluk3r/cassandra,sayanh/ViewMaintenanceCassandra,jbellis/cassandra,adelapena/cassandra,nutbunnies/cassandra,driftx/cassandra,mklew/mmp,jasobrown/cassandra,vramaswamy456/cassandra,krummas/cassandra,strapdata/cassandra,carlyeks/cassandra,nitsanw/cassandra,modempachev4/kassandra,jeromatron/cassandra,ptuckey/cassandra,jbellis/cassandra,michaelmior/cassandra,pauloricardomg/cassandra,heiko-braun/cassandra,ibmsoe/cassandra,darach/cassandra,shookari/cassandra,ifesdjeen/cassandra,juiceblender/cassandra,hhorii/cassandra,pthomaid/cassandra,pallavi510/cassandra,scylladb/scylla-tools-java,bcoverston/cassandra,knifewine/cassandra,jbellis/cassandra,tjake/cassandra,matthewtt/cassandra_read,phact/cassandra,emolsson/cassandra,sedulam/CASSANDRA-12201,JeremiahDJordan/cassandra,tjake/cassandra,caidongyun/cassandra,JeremiahDJordan/cassandra,AtwooTM/cassandra,sbtourist/cassandra,aweisberg/cassandra,pbailis/cassandra-pbs,DikangGu/cassandra,weideng1/cassandra,michaelmior/cassandra,Bj0rnen/cassandra,kangkot/stratio-cassandra,scaledata/cassandra,mkjellman/cassandra,aarushi12002/cassandra,ptuckey/cassandra,iburmistrov/Cassandra,mike-tr-adamson/cassandra,jkni/cassandra,sayanh/ViewMaintenanceSupport,miguel0afd/cassandra-cqlMod,sedulam/CASSANDRA-12201,chaordic/cassandra,sivikt/cassandra,rmarchei/cassandra,spodkowinski/cassandra,sayanh/ViewMaintenanceCassandra,pcmanus/cassandra,JeremiahDJordan/cassandra,scaledata/cassandra,mheffner/cassandra-1,mgmuscari/cassandra-cdh4,newrelic-forks/cassandra,jeffjirsa/cassandra,pcn/cassandra-1,instaclustr/cassandra,Stratio/stratio-cassandra,blambov/cassandra,chbatey/cassandra-1,DICL/cassandra,weideng1/cassandra,nvoron23/cassandra,tommystendahl/cassandra,chbatey/cassandra-1,AtwooTM/cassandra,mashuai/Cassandra-Research,fengshao0907/Cassandra-Research,jrwest/cassandra,ben-manes/cassandra,weipinghe/cassandra,segfault/apache_cassandra,WorksApplications/cassandra,ollie314/cassandra,caidongyun/cassandra,asias/cassandra,rogerchina/cassandra,sriki77/cassandra,vramaswamy456/cassandra,nakomis/cassandra,boneill42/cassandra,Jollyplum/cassandra,yhnishi/cassandra,adejanovski/cassandra,kangkot/stratio-cassandra,mkjellman/cassandra,instaclustr/cassandra,weideng1/cassandra,thelastpickle/cassandra,michaelsembwever/cassandra,yanbit/cassandra,aureagle/cassandra,lalithsuresh/cassandra-c3,juiceblender/cassandra,mambocab/cassandra,jasonwee/cassandra,ejankan/cassandra,Bj0rnen/cassandra,gdusbabek/cassandra,jasonwee/cassandra,chaordic/cassandra,sbtourist/cassandra,bcoverston/cassandra,project-zerus/cassandra,segfault/apache_cassandra,aweisberg/cassandra,emolsson/cassandra,HidemotoNakada/cassandra-udf,yukim/cassandra,exoscale/cassandra,bcoverston/cassandra,mshuler/cassandra,mheffner/cassandra-1,rdio/cassandra,stef1927/cassandra,jsanda/cassandra,mambocab/cassandra,szhou1234/cassandra,michaelsembwever/cassandra,apache/cassandra,pofallon/cassandra,exoscale/cassandra,ptnapoleon/cassandra,jasonstack/cassandra,Stratio/stratio-cassandra,codefollower/Cassandra-Research,DavidHerzogTU-Berlin/cassandraToRun,DICL/cassandra,codefollower/Cassandra-Research,fengshao0907/Cassandra-Research,jeromatron/cassandra,mshuler/cassandra,WorksApplications/cassandra,jeffjirsa/cassandra,vaibhi9/cassandra,bdeggleston/cassandra,bcoverston/cassandra,cooldoger/cassandra,yukim/cassandra,taigetco/cassandra_read,pallavi510/cassandra,guanxi55nba/key-value-store,pauloricardomg/cassandra,ptuckey/cassandra,jeromatron/cassandra,mklew/mmp,ejankan/cassandra,aweisberg/cassandra,iburmistrov/Cassandra,ben-manes/cassandra,dkua/cassandra,joesiewert/cassandra,kangkot/stratio-cassandra,blambov/cassandra,a-buck/cassandra,pkdevbox/cassandra,mashuai/Cassandra-Research,jsanda/cassandra,adejanovski/cassandra,strapdata/cassandra,blerer/cassandra,qinjin/mdtc-cassandra,newrelic-forks/cassandra,DavidHerzogTU-Berlin/cassandra,tommystendahl/cassandra,LatencyUtils/cassandra-stress2,pbailis/cassandra-pbs,sharvanath/cassandra,Jollyplum/cassandra,macintoshio/cassandra,rmarchei/cassandra,josh-mckenzie/cassandra,bmel/cassandra,tommystendahl/cassandra,xiongzheng/Cassandra-Research,DikangGu/cassandra,iamaleksey/cassandra,dongjiaqiang/cassandra,pkdevbox/cassandra,blerer/cassandra,apache/cassandra,scylladb/scylla-tools-java,yangzhe1991/cassandra,aarushi12002/cassandra,blerer/cassandra,bdeggleston/cassandra,pofallon/cassandra,yonglehou/cassandra,vramaswamy456/cassandra,taigetco/cassandra_read,tongjixianing/projects,project-zerus/cassandra,bmel/cassandra,ptnapoleon/cassandra,asias/cassandra,guanxi55nba/db-improvement,stef1927/cassandra,macintoshio/cassandra,strapdata/cassandra,fengshao0907/cassandra-1,bcoverston/apache-hosted-cassandra,shawnkumar/cstargraph,fengshao0907/cassandra-1,ibmsoe/cassandra,asias/cassandra,jsanda/cassandra,ibmsoe/cassandra,heiko-braun/cassandra,belliottsmith/cassandra,weipinghe/cassandra,chaordic/cassandra,sbtourist/cassandra,wreda/cassandra,jeffjirsa/cassandra,pthomaid/cassandra,mt0803/cassandra,sayanh/ViewMaintenanceSupport,swps/cassandra,RyanMagnusson/cassandra,iamaleksey/cassandra,spodkowinski/cassandra,darach/cassandra,whitepages/cassandra,snazy/cassandra,josh-mckenzie/cassandra,guanxi55nba/key-value-store,nvoron23/cassandra,pcmanus/cassandra,shawnkumar/cstargraph,leomrocha/cassandra,pofallon/cassandra,EnigmaCurry/cassandra,christian-esken/cassandra,tongjixianing/projects,codefollower/Cassandra-Research,guard163/cassandra,aweisberg/cassandra,HidemotoNakada/cassandra-udf,GabrielNicolasAvellaneda/cassandra,regispl/cassandra,ben-manes/cassandra,iamaleksey/cassandra,DavidHerzogTU-Berlin/cassandra,Jaumo/cassandra,ifesdjeen/cassandra,shookari/cassandra,mambocab/cassandra,modempachev4/kassandra,spodkowinski/cassandra,EnigmaCurry/cassandra,GabrielNicolasAvellaneda/cassandra,nutbunnies/cassandra,whitepages/cassandra,whitepages/cassandra,jkni/cassandra,hhorii/cassandra,pbailis/cassandra-pbs,bcoverston/apache-hosted-cassandra,juiceblender/cassandra,hengxin/cassandra,ollie314/cassandra,RyanMagnusson/cassandra,caidongyun/cassandra,swps/cassandra,sharvanath/cassandra,mashuai/Cassandra-Research,michaelsembwever/cassandra,pcmanus/cassandra,scylladb/scylla-tools-java,Jollyplum/cassandra,yukim/cassandra,DICL/cassandra,nitsanw/cassandra,mgmuscari/cassandra-cdh4,nlalevee/cassandra,boneill42/cassandra,bpupadhyaya/cassandra,szhou1234/cassandra,scaledata/cassandra,fengshao0907/cassandra-1,WorksApplications/cassandra,DavidHerzogTU-Berlin/cassandraToRun,Bj0rnen/cassandra,yonglehou/cassandra,guanxi55nba/key-value-store,mike-tr-adamson/cassandra,rogerchina/cassandra,tjake/cassandra,ptnapoleon/cassandra,Instagram/cassandra,nvoron23/cassandra,clohfink/cassandra,stef1927/cassandra,dprguiuc/Cassandra-Wasef,pallavi510/cassandra,instaclustr/cassandra,adejanovski/cassandra,taigetco/cassandra_read,krummas/cassandra,Stratio/stratio-cassandra,DikangGu/cassandra,bpupadhyaya/cassandra,AtwooTM/cassandra,thelastpickle/cassandra,mt0803/cassandra,EnigmaCurry/cassandra,wreda/cassandra,hengxin/cassandra,pkdevbox/cassandra,LatencyUtils/cassandra-stress2,clohfink/cassandra,yukim/cassandra,mike-tr-adamson/cassandra,MasahikoSawada/cassandra,guard163/cassandra,aboudreault/cassandra,kangkot/stratio-cassandra,Instagram/cassandra,mshuler/cassandra,modempachev4/kassandra,Jaumo/cassandra,nutbunnies/cassandra,blerer/cassandra,mgmuscari/cassandra-cdh4,bmel/cassandra,a-buck/cassandra,phact/cassandra,lalithsuresh/cassandra-c3,regispl/cassandra,matthewtt/cassandra_read,apache/cassandra,michaelsembwever/cassandra,rackerlabs/cloudmetrics-cassandra,thobbs/cassandra,phact/cassandra,belliottsmith/cassandra,sriki77/cassandra,pauloricardomg/cassandra,rdio/cassandra,mkjellman/cassandra,mshuler/cassandra,xiongzheng/Cassandra-Research,tongjixianing/projects,snazy/cassandra,shookari/cassandra,dongjiaqiang/cassandra,ifesdjeen/cassandra,matthewtt/cassandra_read,driftx/cassandra,bdeggleston/cassandra,boneill42/cassandra,guard163/cassandra,cooldoger/cassandra,sivikt/cassandra,pauloricardomg/cassandra,MasahikoSawada/cassandra,miguel0afd/cassandra-cqlMod,RyanMagnusson/cassandra,leomrocha/cassandra,cooldoger/cassandra,tommystendahl/cassandra,Imran-C/cassandra,kgreav/cassandra,guanxi55nba/db-improvement,weipinghe/cassandra,bcoverston/apache-hosted-cassandra,helena/cassandra,krummas/cassandra,guanxi55nba/db-improvement,kangkot/stratio-cassandra,kgreav/cassandra,pcn/cassandra-1,blambov/cassandra,dongjiaqiang/cassandra,miguel0afd/cassandra-cqlMod,DavidHerzogTU-Berlin/cassandraToRun,yonglehou/cassandra,lalithsuresh/cassandra-c3,qinjin/mdtc-cassandra,iamaleksey/cassandra,yhnishi/cassandra,mklew/mmp,rackerlabs/cloudmetrics-cassandra,ifesdjeen/cassandra,instaclustr/cassandra,vaibhi9/cassandra,rmarchei/cassandra,jasobrown/cassandra,aboudreault/cassandra,project-zerus/cassandra,vaibhi9/cassandra,cooldoger/cassandra,yanbit/cassandra,nlalevee/cassandra,exoscale/cassandra,krummas/cassandra,rdio/cassandra,GabrielNicolasAvellaneda/cassandra,jasonwee/cassandra,dkua/cassandra,michaelmior/cassandra,hengxin/cassandra,thobbs/cassandra,pthomaid/cassandra,sharvanath/cassandra,shawnkumar/cstargraph,snazy/cassandra,Stratio/cassandra,Stratio/cassandra,apache/cassandra,jrwest/cassandra,mkjellman/cassandra,gdusbabek/cassandra,Imran-C/cassandra,gdusbabek/cassandra,MasahikoSawada/cassandra,jasobrown/cassandra,christian-esken/cassandra,leomrocha/cassandra,dkua/cassandra,jkni/cassandra,beobal/cassandra,dprguiuc/Cassandra-Wasef,szhou1234/cassandra,Instagram/cassandra,swps/cassandra,joesiewert/cassandra,a-buck/cassandra,kgreav/cassandra,heiko-braun/cassandra,rogerchina/cassandra,Imran-C/cassandra,likaiwalkman/cassandra,carlyeks/cassandra,thobbs/cassandra,beobal/cassandra,sluk3r/cassandra,xiongzheng/Cassandra-Research,Stratio/stratio-cassandra,spodkowinski/cassandra,aureagle/cassandra,Stratio/cassandra,jasonstack/cassandra,nitsanw/cassandra,aarushi12002/cassandra,szhou1234/cassandra,clohfink/cassandra,bdeggleston/cassandra,sayanh/ViewMaintenanceCassandra | /*
* 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.cassandra.utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLongArray;
import org.apache.cassandra.io.ICompactSerializer2;
public class EstimatedHistogram
{
public static EstimatedHistogramSerializer serializer = new EstimatedHistogramSerializer();
/**
* The series of values to which the counts in `buckets` correspond:
* 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 17, 20, etc.
* Thus, a `buckets` of [0, 0, 1, 10] would mean we had seen one value of 3 and 10 values of 4.
*
* The series starts at 1 and grows by 1.2 each time (rounding and removing duplicates). It goes from 1
* to around 36M by default (creating 90+1 buckets), which will give us timing resolution from microseconds to
* 36 seconds, with less precision as the numbers get larger.
*
* Each bucket represents values from (previous bucket offset, current offset].
*/
private long[] bucketOffsets;
// buckets is one element longer than bucketOffsets -- the last element is values greater than the last offset
final AtomicLongArray buckets;
public EstimatedHistogram()
{
this(90);
}
public EstimatedHistogram(int bucketCount)
{
makeOffsets(bucketCount);
buckets = new AtomicLongArray(bucketOffsets.length + 1);
}
public EstimatedHistogram(long[] offsets, long[] bucketData)
{
assert bucketData.length == offsets.length +1;
bucketOffsets = offsets;
buckets = new AtomicLongArray(bucketData);
}
private void makeOffsets(int size)
{
bucketOffsets = new long[size];
long last = 1;
bucketOffsets[0] = last;
for (int i = 1; i < size; i++)
{
long next = Math.round(last * 1.2);
if (next == last)
next++;
bucketOffsets[i] = next;
last = next;
}
}
/**
* @return the histogram values corresponding to each bucket index
*/
public long[] getBucketOffsets()
{
return bucketOffsets;
}
/**
* Increments the count of the bucket closest to n, rounding UP.
* @param n
*/
public void add(long n)
{
int index = Arrays.binarySearch(bucketOffsets, n);
if (index < 0)
{
// inexact match, take the first bucket higher than n
index = -index - 1;
}
// else exact match; we're good
buckets.incrementAndGet(index);
}
/**
* @return the count in the given bucket
*/
long get(int bucket)
{
return buckets.get(bucket);
}
/**
* @param reset: zero out buckets afterwards if true
* @return a long[] containing the current histogram buckets
*/
public long[] getBuckets(boolean reset)
{
long[] rv = new long[buckets.length()];
for (int i = 0; i < buckets.length(); i++)
rv[i] = buckets.get(i);
if (reset)
for (int i = 0; i < buckets.length(); i++)
buckets.set(i, 0L);
return rv;
}
/**
* @return the smallest value that could have been added to this histogram
*/
public long min()
{
for (int i = 0; i < buckets.length(); i++)
{
if (buckets.get(i) > 0)
return i == 0 ? 0 : 1 + bucketOffsets[i - 1];
}
return 0;
}
/**
* @return the largest value that could have been added to this histogram. If the histogram
* overflowed, returns Long.MAX_VALUE.
*/
public long max()
{
int lastBucket = buckets.length() - 1;
if (buckets.get(lastBucket) > 0)
return Long.MAX_VALUE;
for (int i = lastBucket - 1; i >= 0; i--)
{
if (buckets.get(i) > 0)
return bucketOffsets[i];
}
return 0;
}
/**
* @return the mean histogram value (average of bucket offsets, weighted by count)
* @throws IllegalStateException if any values were greater than the largest bucket threshold
*/
public long mean()
{
int lastBucket = buckets.length() - 1;
if (buckets.get(lastBucket) > 0)
throw new IllegalStateException("Unable to compute ceiling for max when histogram overflowed");
long elements = 0;
long sum = 0;
for (int i = 0; i < lastBucket; i++)
{
elements += buckets.get(i);
sum += buckets.get(i) * bucketOffsets[i];
}
return (long) Math.ceil((double) sum / elements);
}
/**
* @return true if this histogram has overflowed -- that is, a value larger than our largest bucket could bound was added
*/
public boolean isOverflowed()
{
return buckets.get(buckets.length() - 1) > 0;
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (!(o instanceof EstimatedHistogram))
return false;
EstimatedHistogram that = (EstimatedHistogram) o;
return Arrays.equals(getBucketOffsets(), that.getBucketOffsets()) &&
Arrays.equals(getBuckets(false), that.getBuckets(false));
}
public static class EstimatedHistogramSerializer implements ICompactSerializer2<EstimatedHistogram>
{
public void serialize(EstimatedHistogram eh, DataOutput dos) throws IOException
{
long[] offsets = eh.getBucketOffsets();
long[] buckets = eh.getBuckets(false);
dos.writeInt(buckets.length);
for (int i = 0; i < buckets.length; i++)
{
dos.writeLong(offsets[i == 0 ? 0 : i - 1]);
dos.writeLong(buckets[i]);
}
}
public EstimatedHistogram deserialize(DataInput dis) throws IOException
{
int size = dis.readInt();
long[] offsets = new long[size - 1];
long[] buckets = new long[size];
for (int i = 0; i < size; i++) {
offsets[i == 0 ? 0 : i - 1] = dis.readLong();
buckets[i] = dis.readLong();
}
return new EstimatedHistogram(offsets, buckets);
}
}
}
| src/java/org/apache/cassandra/utils/EstimatedHistogram.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.cassandra.utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLongArray;
import org.apache.cassandra.io.ICompactSerializer2;
public class EstimatedHistogram
{
public static EstimatedHistogramSerializer serializer = new EstimatedHistogramSerializer();
/**
* The series of values to which the counts in `buckets` correspond:
* 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 17, 20, etc.
* Thus, a `buckets` of [0, 0, 1, 10] would mean we had seen one value of 3 and 10 values of 4.
*
* The series starts at 1 and grows by 1.2 each time (rounding and removing duplicates). It goes from 1
* to around 36M by default (creating 90+1 buckets), which will give us timing resolution from microseconds to
* 36 seconds, with less precision as the numbers get larger.
*
* Each bucket represents values from (previous bucket offset, current offset].
*/
private long[] bucketOffsets;
// buckets is one element longer than bucketOffsets -- the last element is values greater than the last offset
final AtomicLongArray buckets;
public EstimatedHistogram()
{
this(90);
}
public EstimatedHistogram(int bucketCount)
{
makeOffsets(bucketCount);
buckets = new AtomicLongArray(bucketOffsets.length + 1);
}
public EstimatedHistogram(long[] offsets, long[] bucketData)
{
assert bucketData.length == offsets.length +1;
bucketOffsets = offsets;
buckets = new AtomicLongArray(bucketData);
}
private void makeOffsets(int size)
{
bucketOffsets = new long[size];
long last = 1;
bucketOffsets[0] = last;
for (int i = 1; i < size; i++)
{
long next = Math.round(last * 1.2);
if (next == last)
next++;
bucketOffsets[i] = next;
last = next;
}
}
/**
* @return the histogram values corresponding to each bucket index
*/
public long[] getBucketOffsets()
{
return bucketOffsets;
}
/**
* Increments the count of the bucket closest to n, rounding UP.
* @param n
*/
public void add(long n)
{
int index = Arrays.binarySearch(bucketOffsets, n);
if (index < 0)
{
// inexact match, take the first bucket higher than n
index = -index - 1;
}
// else exact match; we're good
buckets.incrementAndGet(index);
}
/**
* @return the count in the given bucket
*/
long get(int bucket)
{
return buckets.get(bucket);
}
/**
* @param reset: zero out buckets afterwards if true
* @return a long[] containing the current histogram buckets
*/
public long[] getBuckets(boolean reset)
{
long[] rv = new long[buckets.length()];
for (int i = 0; i < buckets.length(); i++)
rv[i] = buckets.get(i);
if (reset)
for (int i = 0; i < buckets.length(); i++)
buckets.set(i, 0L);
return rv;
}
/**
* @return the smallest value that could have been added to this histogram
*/
public long min()
{
for (int i = 0; i < buckets.length(); i++)
{
if (buckets.get(i) > 0)
return i == 0 ? 0 : 1 + bucketOffsets[i - 1];
}
return 0;
}
/**
* @return the largest value that could have been added to this histogram. If the histogram
* overflowed, returns Long.MAX_VALUE.
*/
public long max()
{
int lastBucket = buckets.length() - 1;
if (buckets.get(lastBucket) > 0)
return Long.MAX_VALUE;
for (int i = lastBucket - 1; i >= 0; i--)
{
if (buckets.get(i) > 0)
return bucketOffsets[i];
}
return 0;
}
/**
* @return the mean histogram value (average of bucket offsets, weighted by count)
* @throws IllegalStateException if any values were greater than the largest bucket threshold
*/
public long mean()
{
int lastBucket = buckets.length() - 1;
if (buckets.get(lastBucket) > 0)
throw new IllegalStateException("Unable to compute ceiling for max when histogram overflowed");
long elements = 0;
long sum = 0;
for (int i = 0; i < lastBucket; i++)
{
elements += buckets.get(i);
sum += buckets.get(i) * bucketOffsets[i];
}
return (long) Math.ceil((double) sum / elements);
}
/**
* @return true if this histogram has overflowed -- that is, a value larger than our largest bucket could bound was added
*/
public boolean isOverflowed()
{
return buckets.get(buckets.length() - 1) > 0;
}
public boolean equals(EstimatedHistogram o)
{
return Arrays.equals(getBucketOffsets(), o.getBucketOffsets()) &&
Arrays.equals(getBuckets(false), o.getBuckets(false));
}
public static class EstimatedHistogramSerializer implements ICompactSerializer2<EstimatedHistogram>
{
public void serialize(EstimatedHistogram eh, DataOutput dos) throws IOException
{
long[] offsets = eh.getBucketOffsets();
long[] buckets = eh.getBuckets(false);
dos.writeInt(buckets.length);
for (int i = 0; i < buckets.length; i++)
{
dos.writeLong(offsets[i == 0 ? 0 : i - 1]);
dos.writeLong(buckets[i]);
}
}
public EstimatedHistogram deserialize(DataInput dis) throws IOException
{
int size = dis.readInt();
long[] offsets = new long[size - 1];
long[] buckets = new long[size];
for (int i = 0; i < size; i++) {
offsets[i == 0 ? 0 : i - 1] = dis.readLong();
buckets[i] = dis.readLong();
}
return new EstimatedHistogram(offsets, buckets);
}
}
}
| update EH.equals to work with any Object
patch by Dave Brosius; reviewed by jbellis for CASSANDRA-3053
git-svn-id: af0234e1aff5c580ad966c5a1be7e5402979d927@1159374 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/cassandra/utils/EstimatedHistogram.java | update EH.equals to work with any Object patch by Dave Brosius; reviewed by jbellis for CASSANDRA-3053 | <ide><path>rc/java/org/apache/cassandra/utils/EstimatedHistogram.java
<ide> return buckets.get(buckets.length() - 1) > 0;
<ide> }
<ide>
<del> public boolean equals(EstimatedHistogram o)
<del> {
<del> return Arrays.equals(getBucketOffsets(), o.getBucketOffsets()) &&
<del> Arrays.equals(getBuckets(false), o.getBuckets(false));
<add> @Override
<add> public boolean equals(Object o)
<add> {
<add> if (this == o)
<add> return true;
<add>
<add> if (!(o instanceof EstimatedHistogram))
<add> return false;
<add>
<add> EstimatedHistogram that = (EstimatedHistogram) o;
<add> return Arrays.equals(getBucketOffsets(), that.getBucketOffsets()) &&
<add> Arrays.equals(getBuckets(false), that.getBuckets(false));
<ide> }
<ide>
<ide> public static class EstimatedHistogramSerializer implements ICompactSerializer2<EstimatedHistogram> |
|
Java | mit | error: pathspec 'new_cust.java' did not match any file(s) known to git
| c1056f5184d4c68791be358d57597c8e83871c24 | 1 | shiblibaig/Municipal-Complaint-Manager | /*
* 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 Project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
/**
*
* @author hp1
*/
public class New_cust extends javax.swing.JFrame {
//Static variables for global operations.
static int ag,i,j=0;
static int k;
String nm, occ,pn,dt;
/**
* Creates new form New_cust
*/
public New_cust() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup4 = new javax.swing.ButtonGroup();
buttonGroup5 = new javax.swing.ButtonGroup();
buttonGroup6 = new javax.swing.ButtonGroup();
buttonGroup7 = new javax.swing.ButtonGroup();
buttonGroup8 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
t1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
t2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
cb1 = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
t3 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
ta = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
b1 = new javax.swing.JRadioButton();
b2 = new javax.swing.JRadioButton();
b3 = new javax.swing.JRadioButton();
b4 = new javax.swing.JRadioButton();
b5 = new javax.swing.JRadioButton();
b6 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Name");
t1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t1ActionPerformed(evt);
}
});
jLabel2.setText("Age");
jLabel3.setText("Occupation");
cb1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--none--", "Self Employed", "Government Employee", "Corporate Employee", "Other" }));
cb1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cb1ActionPerformed(evt);
}
});
jLabel4.setText("Phone Number");
t3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t3ActionPerformed(evt);
}
});
jLabel5.setText("Complaint Category");
jLabel6.setText("Detail (255 characters)");
ta.setColumns(20);
ta.setRows(5);
jScrollPane1.setViewportView(ta);
jButton1.setText("Proceed");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
buttonGroup1.add(b1);
b1.setText("Water (1)");
buttonGroup1.add(b2);
b2.setText("Electricity (2)");
buttonGroup1.add(b3);
b3.setText("Communication (3)");
buttonGroup1.add(b4);
b4.setText("Municipal");
buttonGroup1.add(b5);
b5.setText("Criminal");
buttonGroup1.add(b6);
b6.setText("Stray Animal");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jButton1))
.addComponent(b1, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b2, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b3, javax.swing.GroupLayout.Alignment.LEADING))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(70, 70, 70)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b5)
.addComponent(b4)
.addComponent(b6))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(cb1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addComponent(jLabel2)))
.addGap(28, 28, 28)
.addComponent(t2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel5)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(t3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(t2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(cb1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(t3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b1)
.addComponent(b4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b2)
.addComponent(b5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b3)
.addComponent(b6))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(jButton1))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
nm = t1.getText();
ag = Integer.parseInt(t2.getText());
pn = t3.getText();
dt = ta.getText();
Select_type st1 = new Select_type();
Old_cust oc1 = new Old_cust();
check ck1 = new check();
Fee_coll fc = new Fee_coll();
i = cb1.getSelectedIndex();
//Check for detail's length.
if(dt.length()>255){
JOptionPane.showMessageDialog(null," Refill the form. Char length was more than 255.");
this.setVisible(false);
st1.setVisible(true);
}
else{
//Check for profession.
if(i==2){
occ = "Self Employed";
}
else if(i==3){
occ = "Govt. Employee";
}
else if(i==4){
occ = "Corporate Employee";
}
else if(i==5){
occ = "Other";
}
if(b1.isSelected()==true){
j=1;
}
if(b2.isSelected()==true){
j=2;
}
if(b3.isSelected()==true){
j=3;
}
if(b4.isSelected()==true){
j=4;
}
if(b5.isSelected()==true){
j=5;
}
if(b6.isSelected()==true){
j=6;
}
k++;
//Input of each new record happens here.
try {
Connection con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/comp","shibli","shibli");
Statement st = (Statement)con.createStatement();
st.executeUpdate("Insert into cmp values('"+nm+"',"+ag+",'"+occ+"','"+pn+"',"+j+",'"+dt+"',"+k+",NULL,0,0)");
JOptionPane.showMessageDialog(null,"Your unique complaint ID is " + k);
} catch (SQLException ex) {
Logger.getLogger(New_cust.class.getName()).log(Level.SEVERE, null, ex);
}
if(j==1 ||j==2||j==3){
//Entry in fee GUI.
fc.setVisible(true);
this.setVisible(false);
}
else{
st1.setVisible(true);
this.setVisible(false);
}
}
}//GEN-LAST:event_jButton1ActionPerformed
private void t3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_t3ActionPerformed
private void cb1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cb1ActionPerformed
private void t1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_t1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new New_cust().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JRadioButton b1;
private javax.swing.JRadioButton b2;
private javax.swing.JRadioButton b3;
private javax.swing.JRadioButton b4;
private javax.swing.JRadioButton b5;
private javax.swing.JRadioButton b6;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.ButtonGroup buttonGroup4;
private javax.swing.ButtonGroup buttonGroup5;
private javax.swing.ButtonGroup buttonGroup6;
private javax.swing.ButtonGroup buttonGroup7;
private javax.swing.ButtonGroup buttonGroup8;
private javax.swing.JComboBox cb1;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField t1;
private javax.swing.JTextField t2;
private javax.swing.JTextField t3;
private javax.swing.JTextArea ta;
// End of variables declaration//GEN-END:variables
}
| new_cust.java | Create new_cust.java
Form for a new complaint. | new_cust.java | Create new_cust.java | <ide><path>ew_cust.java
<add>/*
<add> * To change this license header, choose License Headers in Project Properties.
<add> * To change this template file, choose Tools | Templates
<add> * and open the template in the editor.
<add> */
<add>package Project;
<add>
<add>import java.sql.Connection;
<add>import java.sql.DriverManager;
<add>import java.sql.SQLException;
<add>import java.sql.Statement;
<add>import java.util.logging.Level;
<add>import java.util.logging.Logger;
<add>import javax.swing.ButtonGroup;
<add>import javax.swing.JOptionPane;
<add>
<add>/**
<add> *
<add> * @author hp1
<add> */
<add>public class New_cust extends javax.swing.JFrame {
<add> //Static variables for global operations.
<add> static int ag,i,j=0;
<add> static int k;
<add> String nm, occ,pn,dt;
<add> /**
<add> * Creates new form New_cust
<add> */
<add> public New_cust() {
<add> initComponents();
<add>
<add> }
<add>
<add> /**
<add> * This method is called from within the constructor to initialize the form.
<add> * WARNING: Do NOT modify this code. The content of this method is always
<add> * regenerated by the Form Editor.
<add> */
<add> @SuppressWarnings("unchecked")
<add> // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
<add> private void initComponents() {
<add>
<add> buttonGroup1 = new javax.swing.ButtonGroup();
<add> buttonGroup2 = new javax.swing.ButtonGroup();
<add> buttonGroup3 = new javax.swing.ButtonGroup();
<add> buttonGroup4 = new javax.swing.ButtonGroup();
<add> buttonGroup5 = new javax.swing.ButtonGroup();
<add> buttonGroup6 = new javax.swing.ButtonGroup();
<add> buttonGroup7 = new javax.swing.ButtonGroup();
<add> buttonGroup8 = new javax.swing.ButtonGroup();
<add> jLabel1 = new javax.swing.JLabel();
<add> t1 = new javax.swing.JTextField();
<add> jLabel2 = new javax.swing.JLabel();
<add> t2 = new javax.swing.JTextField();
<add> jLabel3 = new javax.swing.JLabel();
<add> cb1 = new javax.swing.JComboBox();
<add> jLabel4 = new javax.swing.JLabel();
<add> t3 = new javax.swing.JTextField();
<add> jLabel5 = new javax.swing.JLabel();
<add> jLabel6 = new javax.swing.JLabel();
<add> jScrollPane1 = new javax.swing.JScrollPane();
<add> ta = new javax.swing.JTextArea();
<add> jButton1 = new javax.swing.JButton();
<add> b1 = new javax.swing.JRadioButton();
<add> b2 = new javax.swing.JRadioButton();
<add> b3 = new javax.swing.JRadioButton();
<add> b4 = new javax.swing.JRadioButton();
<add> b5 = new javax.swing.JRadioButton();
<add> b6 = new javax.swing.JRadioButton();
<add>
<add> setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
<add>
<add> jLabel1.setText("Name");
<add>
<add> t1.addActionListener(new java.awt.event.ActionListener() {
<add> public void actionPerformed(java.awt.event.ActionEvent evt) {
<add> t1ActionPerformed(evt);
<add> }
<add> });
<add>
<add> jLabel2.setText("Age");
<add>
<add> jLabel3.setText("Occupation");
<add>
<add> cb1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--none--", "Self Employed", "Government Employee", "Corporate Employee", "Other" }));
<add> cb1.addActionListener(new java.awt.event.ActionListener() {
<add> public void actionPerformed(java.awt.event.ActionEvent evt) {
<add> cb1ActionPerformed(evt);
<add> }
<add> });
<add>
<add> jLabel4.setText("Phone Number");
<add>
<add> t3.addActionListener(new java.awt.event.ActionListener() {
<add> public void actionPerformed(java.awt.event.ActionEvent evt) {
<add> t3ActionPerformed(evt);
<add> }
<add> });
<add>
<add> jLabel5.setText("Complaint Category");
<add>
<add> jLabel6.setText("Detail (255 characters)");
<add>
<add> ta.setColumns(20);
<add> ta.setRows(5);
<add> jScrollPane1.setViewportView(ta);
<add>
<add> jButton1.setText("Proceed");
<add> jButton1.addActionListener(new java.awt.event.ActionListener() {
<add> public void actionPerformed(java.awt.event.ActionEvent evt) {
<add> jButton1ActionPerformed(evt);
<add> }
<add> });
<add>
<add> buttonGroup1.add(b1);
<add> b1.setText("Water (1)");
<add>
<add> buttonGroup1.add(b2);
<add> b2.setText("Electricity (2)");
<add>
<add> buttonGroup1.add(b3);
<add> b3.setText("Communication (3)");
<add>
<add> buttonGroup1.add(b4);
<add> b4.setText("Municipal");
<add>
<add> buttonGroup1.add(b5);
<add> b5.setText("Criminal");
<add>
<add> buttonGroup1.add(b6);
<add> b6.setText("Stray Animal");
<add>
<add> javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
<add> getContentPane().setLayout(layout);
<add> layout.setHorizontalGroup(
<add> layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addGroup(layout.createSequentialGroup()
<add> .addGap(41, 41, 41)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addGroup(layout.createSequentialGroup()
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addComponent(jLabel6)
<add> .addComponent(jButton1))
<add> .addComponent(b1, javax.swing.GroupLayout.Alignment.LEADING)
<add> .addComponent(b2, javax.swing.GroupLayout.Alignment.LEADING)
<add> .addComponent(b3, javax.swing.GroupLayout.Alignment.LEADING))
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addGroup(layout.createSequentialGroup()
<add> .addGap(36, 36, 36)
<add> .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE))
<add> .addGroup(layout.createSequentialGroup()
<add> .addGap(70, 70, 70)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addComponent(b5)
<add> .addComponent(b4)
<add> .addComponent(b6))
<add> .addGap(0, 0, Short.MAX_VALUE))))
<add> .addGroup(layout.createSequentialGroup()
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addGroup(layout.createSequentialGroup()
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addComponent(jLabel1)
<add> .addComponent(jLabel3))
<add> .addGap(34, 34, 34)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
<add> .addComponent(cb1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
<add> .addGroup(layout.createSequentialGroup()
<add> .addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
<add> .addGap(52, 52, 52)
<add> .addComponent(jLabel2)))
<add> .addGap(28, 28, 28)
<add> .addComponent(t2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
<add> .addComponent(jLabel5)
<add> .addGroup(layout.createSequentialGroup()
<add> .addComponent(jLabel4)
<add> .addGap(18, 18, 18)
<add> .addComponent(t3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
<add> .addGap(0, 0, Short.MAX_VALUE)))
<add> .addContainerGap())
<add> );
<add> layout.setVerticalGroup(
<add> layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addGroup(layout.createSequentialGroup()
<add> .addGap(21, 21, 21)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
<add> .addComponent(jLabel1)
<add> .addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
<add> .addComponent(jLabel2)
<add> .addComponent(t2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
<add> .addGap(18, 18, 18)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
<add> .addComponent(jLabel3)
<add> .addComponent(cb1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
<add> .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
<add> .addComponent(jLabel4)
<add> .addComponent(t3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
<add> .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
<add> .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
<add> .addGap(18, 18, 18)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
<add> .addComponent(b1)
<add> .addComponent(b4))
<add> .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
<add> .addComponent(b2)
<add> .addComponent(b5))
<add> .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
<add> .addComponent(b3)
<add> .addComponent(b6))
<add> .addGap(11, 11, 11)
<add> .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
<add> .addGroup(layout.createSequentialGroup()
<add> .addComponent(jLabel6)
<add> .addGap(18, 18, 18)
<add> .addComponent(jButton1))
<add> .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
<add> .addContainerGap(14, Short.MAX_VALUE))
<add> );
<add>
<add> pack();
<add> }// </editor-fold>//GEN-END:initComponents
<add>
<add> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
<add>
<add> nm = t1.getText();
<add> ag = Integer.parseInt(t2.getText());
<add> pn = t3.getText();
<add> dt = ta.getText();
<add> Select_type st1 = new Select_type();
<add> Old_cust oc1 = new Old_cust();
<add>check ck1 = new check();
<add>Fee_coll fc = new Fee_coll();
<add>i = cb1.getSelectedIndex();
<add>//Check for detail's length.
<add> if(dt.length()>255){
<add> JOptionPane.showMessageDialog(null," Refill the form. Char length was more than 255.");
<add> this.setVisible(false);
<add> st1.setVisible(true);
<add> }
<add> else{
<add> //Check for profession.
<add> if(i==2){
<add> occ = "Self Employed";
<add>}
<add>else if(i==3){
<add> occ = "Govt. Employee";
<add>}
<add>else if(i==4){
<add> occ = "Corporate Employee";
<add>}
<add>else if(i==5){
<add> occ = "Other";
<add>}
<add>if(b1.isSelected()==true){
<add> j=1;
<add>}
<add>if(b2.isSelected()==true){
<add> j=2;
<add>}
<add>if(b3.isSelected()==true){
<add> j=3;
<add>}
<add>if(b4.isSelected()==true){
<add> j=4;
<add>}
<add>if(b5.isSelected()==true){
<add> j=5;
<add> }
<add>if(b6.isSelected()==true){
<add> j=6;
<add>}
<add> k++;
<add> //Input of each new record happens here.
<add> try {
<add> Connection con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/comp","shibli","shibli");
<add> Statement st = (Statement)con.createStatement();
<add> st.executeUpdate("Insert into cmp values('"+nm+"',"+ag+",'"+occ+"','"+pn+"',"+j+",'"+dt+"',"+k+",NULL,0,0)");
<add> JOptionPane.showMessageDialog(null,"Your unique complaint ID is " + k);
<add> } catch (SQLException ex) {
<add> Logger.getLogger(New_cust.class.getName()).log(Level.SEVERE, null, ex);
<add> }
<add>if(j==1 ||j==2||j==3){
<add> //Entry in fee GUI.
<add> fc.setVisible(true);
<add> this.setVisible(false);
<add>}
<add>else{
<add> st1.setVisible(true);
<add>this.setVisible(false);
<add>}
<add>}
<add>
<add> }//GEN-LAST:event_jButton1ActionPerformed
<add>
<add> private void t3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t3ActionPerformed
<add> // TODO add your handling code here:
<add> }//GEN-LAST:event_t3ActionPerformed
<add>
<add> private void cb1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb1ActionPerformed
<add> // TODO add your handling code here:
<add> }//GEN-LAST:event_cb1ActionPerformed
<add>
<add> private void t1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t1ActionPerformed
<add> // TODO add your handling code here:
<add> }//GEN-LAST:event_t1ActionPerformed
<add>
<add> /**
<add> * @param args the command line arguments
<add> */
<add> public static void main(String args[]) {
<add> /* Set the Nimbus look and feel */
<add> //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
<add> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
<add> * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
<add> */
<add> try {
<add> for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
<add> if ("Nimbus".equals(info.getName())) {
<add> javax.swing.UIManager.setLookAndFeel(info.getClassName());
<add> break;
<add> }
<add> }
<add> } catch (ClassNotFoundException ex) {
<add> java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
<add> } catch (InstantiationException ex) {
<add> java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
<add> } catch (IllegalAccessException ex) {
<add> java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
<add> } catch (javax.swing.UnsupportedLookAndFeelException ex) {
<add> java.util.logging.Logger.getLogger(New_cust.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
<add> }
<add> //</editor-fold>
<add>
<add> /* Create and display the form */
<add> java.awt.EventQueue.invokeLater(new Runnable() {
<add> public void run() {
<add> new New_cust().setVisible(true);
<add> }
<add> });
<add> }
<add>
<add> // Variables declaration - do not modify//GEN-BEGIN:variables
<add> private javax.swing.JRadioButton b1;
<add> private javax.swing.JRadioButton b2;
<add> private javax.swing.JRadioButton b3;
<add> private javax.swing.JRadioButton b4;
<add> private javax.swing.JRadioButton b5;
<add> private javax.swing.JRadioButton b6;
<add> private javax.swing.ButtonGroup buttonGroup1;
<add> private javax.swing.ButtonGroup buttonGroup2;
<add> private javax.swing.ButtonGroup buttonGroup3;
<add> private javax.swing.ButtonGroup buttonGroup4;
<add> private javax.swing.ButtonGroup buttonGroup5;
<add> private javax.swing.ButtonGroup buttonGroup6;
<add> private javax.swing.ButtonGroup buttonGroup7;
<add> private javax.swing.ButtonGroup buttonGroup8;
<add> private javax.swing.JComboBox cb1;
<add> private javax.swing.JButton jButton1;
<add> private javax.swing.JLabel jLabel1;
<add> private javax.swing.JLabel jLabel2;
<add> private javax.swing.JLabel jLabel3;
<add> private javax.swing.JLabel jLabel4;
<add> private javax.swing.JLabel jLabel5;
<add> private javax.swing.JLabel jLabel6;
<add> private javax.swing.JScrollPane jScrollPane1;
<add> private javax.swing.JTextField t1;
<add> private javax.swing.JTextField t2;
<add> private javax.swing.JTextField t3;
<add> private javax.swing.JTextArea ta;
<add> // End of variables declaration//GEN-END:variables
<add>} |
|
JavaScript | mit | a45bc4f1b9339419496979555c8da04ac2657535 | 0 | alexdao/phonics-backend,alexdao/phonics-backend,alexdao/phonics-backend,alexdao/phonics-backend,alexdao/phonics-backend,alexdao/phonics-backend | 'use strict';
const app = require('express')();
const execSync = require('child_process').execSync;
const http = require('http').Server(app);
const io = require('socket.io')(http);
const fs = require('fs');
let buffer = '';
let prev = '';
app.get('/', function(req, res) {
res.send('<h1>Hello world</h1>');
});
io.origins('*:*');
io.on('connection', function(socket){
console.log('a user connected');
// Voice message came in
socket.on('message', function(msg){
if (msg === 'erase') {
erase();
}
else if (msg === 'analyze') {
analyze();
clear();
}
else if (msg === 'clear') {
clear();
}
else {
buffer += prev;
prev = msg + '. ';
}
});
socket.on('sending_image', function(msg){
decodeBase64(msg.image);
console.log('Received image!');
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
function decodeBase64(base64Data) {
fs.writeFile("out.png", base64Data, 'base64', function(err) {
if (error != null) {
console.log('Error ' + err);
}
});
}
// Speaker takes back his most recent sentence
function erase() {
prev = '';
}
// Speaker has finished speaking
function analyze() {
console.log('Voice: ' + buffer + prev);
}
function clear() {
buffer = '';
prev = '';
}
http.listen(3000, function(){
console.log('listening on *:3000');
});
| index.js | 'use strict';
const app = require('express')();
const execSync = require('child_process').execSync;
const http = require('http').Server(app);
const io = require('socket.io')(http);
let buffer = '';
let prev = '';
app.get('/', function(req, res) {
res.send('<h1>Hello world</h1>');
});
io.origins('*:*');
io.on('connection', function(socket){
console.log('a user connected');
// Voice message came in
socket.on('message', function(msg){
if (msg === 'erase') {
erase();
}
else if (msg === 'analyze') {
analyze();
clear();
}
else if (msg === 'clear') {
clear();
}
else {
buffer += prev;
prev = msg + '. ';
}
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
// Speaker takes back his most recent sentence
function erase() {
prev = '';
}
// Speaker has finished speaking
function analyze() {
console.log('Voice: ' + buffer + prev);
}
function clear() {
buffer = '';
prev = '';
}
http.listen(3000, function(){
console.log('listening on *:3000');
});
| Decode base 64 image
| index.js | Decode base 64 image | <ide><path>ndex.js
<ide> const execSync = require('child_process').execSync;
<ide> const http = require('http').Server(app);
<ide> const io = require('socket.io')(http);
<add>const fs = require('fs');
<ide>
<ide> let buffer = '';
<ide> let prev = '';
<ide> }
<ide> });
<ide>
<add> socket.on('sending_image', function(msg){
<add> decodeBase64(msg.image);
<add> console.log('Received image!');
<add> });
<add>
<ide> socket.on('disconnect', function(){
<ide> console.log('user disconnected');
<ide> });
<ide> });
<add>
<add>
<add>function decodeBase64(base64Data) {
<add> fs.writeFile("out.png", base64Data, 'base64', function(err) {
<add> if (error != null) {
<add> console.log('Error ' + err);
<add> }
<add> });
<add>}
<ide>
<ide> // Speaker takes back his most recent sentence
<ide> function erase() { |
|
Java | apache-2.0 | fc484c9bf07d05a04ea9a01113f3f5834f2ac13a | 0 | mafulafunk/wicket,Servoy/wicket,freiheit-com/wicket,topicusonderwijs/wicket,Servoy/wicket,topicusonderwijs/wicket,astrapi69/wicket,martin-g/wicket-osgi,zwsong/wicket,bitstorm/wicket,AlienQueen/wicket,bitstorm/wicket,mosoft521/wicket,klopfdreh/wicket,klopfdreh/wicket,zwsong/wicket,mosoft521/wicket,zwsong/wicket,AlienQueen/wicket,Servoy/wicket,astrapi69/wicket,klopfdreh/wicket,zwsong/wicket,klopfdreh/wicket,astrapi69/wicket,selckin/wicket,Servoy/wicket,bitstorm/wicket,mafulafunk/wicket,apache/wicket,aldaris/wicket,freiheit-com/wicket,freiheit-com/wicket,mafulafunk/wicket,freiheit-com/wicket,AlienQueen/wicket,topicusonderwijs/wicket,selckin/wicket,Servoy/wicket,apache/wicket,AlienQueen/wicket,selckin/wicket,AlienQueen/wicket,apache/wicket,topicusonderwijs/wicket,dashorst/wicket,topicusonderwijs/wicket,mosoft521/wicket,aldaris/wicket,dashorst/wicket,freiheit-com/wicket,apache/wicket,aldaris/wicket,astrapi69/wicket,klopfdreh/wicket,apache/wicket,martin-g/wicket-osgi,bitstorm/wicket,martin-g/wicket-osgi,bitstorm/wicket,mosoft521/wicket,mosoft521/wicket,dashorst/wicket,aldaris/wicket,dashorst/wicket,aldaris/wicket,selckin/wicket,dashorst/wicket,selckin/wicket | /*
* $Id$ $Revision:
* 1.235 $ $Date$
*
* ==============================================================================
* 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 wicket;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.authorization.AuthorizationException;
import wicket.authorization.UnauthorizedEnabledStateException;
import wicket.authorization.UnauthorizedInstantiationException;
import wicket.behavior.IBehavior;
import wicket.behavior.IBehaviorListener;
import wicket.feedback.FeedbackMessage;
import wicket.markup.ComponentTag;
import wicket.markup.MarkupException;
import wicket.markup.MarkupStream;
import wicket.markup.WicketTag;
import wicket.model.CompoundPropertyModel;
import wicket.model.ICompoundModel;
import wicket.model.IModel;
import wicket.model.IModelComparator;
import wicket.settings.IRequiredPageSettings;
import wicket.settings.Settings;
import wicket.util.convert.IConverter;
import wicket.util.lang.Classes;
import wicket.util.string.Strings;
import wicket.version.undo.Change;
/**
* Component serves as the highest level abstract base class for all components.
*
* <ul>
* <li><b>Identity </b>- All Components must have a non-null id which is
* retrieved by calling getId(). The id must be unique within the
* MarkupContainer that holds the Component, but does not have to be globally
* unique or unique within a Page's component hierarchy.
*
* <li><b>Hierarchy </b>- A component has a parent which can be retrieved with
* getParent(). If a component is an instance of MarkupContainer, it may have
* children. In this way it has a place in the hierarchy of components contained
* on a given page. The {@link Component#isAncestorOf(Component)} method returns
* true if this Component is an ancestor of the given Component.
*
* <li><b>Component Paths </b>- The path from the Page at the root of the
* component hierarchy to a given Component is simply the concatenation with dot
* separators of each id along the way. For example, the path "a.b.c" would
* refer to the component named "c" inside the MarkupContainer named "b" inside
* the container named "a". The path to a component can be retrieved by calling
* getPath(). This path is an absolute path beginning with the id of the Page at
* the root. Pages bear a PageMap/Session-relative identifier as their id, so
* each absolute path will begin with a number, such as "0.a.b.c". To get a
* Component path relative to the page that contains it, you can call
* getPageRelativePath().
*
* <li><b>LifeCycle </b>- Components participate in the following lifecycle
* phases:
* <ul>
* <li><b>Construction </b>- A Component is constructed with the Java language
* new operator. Children may be added during construction if the Component is a
* MarkupContainer.
*
* <li><b>Request Handling </b>- An incoming request is processed by a protocol
* request handler such as WicketServlet. An associated Application object
* creates Session, Request and Response objects for use by a given Component in
* updating its model and rendering a response. These objects are stored inside
* a container called {@link RequestCycle} which is accessible via
* {@link Component#getRequestCycle()}. The convenience methods
* {@link Component#getRequest()}, {@link Component#getResponse()} and
* {@link Component#getSession()} provide easy access to the contents of this
* container.
*
* <li><b>Listener Invocation </b>- If the request references a listener on an
* existing Component, that listener is called, allowing arbitrary user code to
* handle events such as link clicks or form submits. Although arbitrary
* listeners are supported in Wicket, the need to implement a new class of
* listener is unlikely for a web application and even the need to implement a
* listener interface directly is highly discouraged. Instead, calls to
* listeners are routed through logic specific to the event, resulting in calls
* to user code through other overridable methods. For example, the
* {@link wicket.markup.html.form.IFormSubmitListener#onFormSubmitted()} method
* implemented by the Form class is really a private implementation detail of
* the Form class that is not designed to be overridden (although unfortunately,
* it must be public since all interface methods in Java must be public).
* Instead, Form subclasses should override user-oriented methods such as
* onValidate(), onSubmit() and onError() (although only the latter two are
* likely to be overridden in practice).
*
* <li><b>onBeginRequest </b>- The {@link Component#onBeginRequest()} method is
* called.
*
* <li><b>Form Submit </b>- If a Form has been submitted and the Component is a
* FormComponent, the component's model is validated by a call to
* FormComponent.validate().
*
* <li><b>Form Model Update </b>- If a valid Form has been submitted and the
* Component is a FormComponent, the component's model is updated by a call to
* FormComponent.updateModel().
*
* <li><b>Rendering </b>- A markup response is generated by the Component via
* {@link Component#render()}, which calls subclass implementation code
* contained in {@link Component#onRender()}. Once this phase begins, a
* Component becomes immutable. Attempts to alter the Component will result in a
* WicketRuntimeException.
*
* <li><b>onEndRequest </b>() - The {@link Component#onEndRequest()} method is
* called.
* </ul>
*
* <li><b>Component Models </b>- The primary responsibility of a component is
* to use its model (an object that implements IModel), which can be set via
* {@link Component#setModel(IModel model)} and retrieved via
* {@link Component#getModel()}, to render a response in an appropriate markup
* language, such as HTML. In addition, form components know how to update their
* models based on request information. Since the IModel interface is a wrapper
* around an actual model object, a convenience method
* {@link Component#getModelObject()} is provided to retrieve the model Object
* from its IModel wrapper. A further convenience method,
* {@link Component#getModelObjectAsString()}, is provided for the very common
* operation of converting the wrapped model Object to a String.
*
* <li><b>Visibility </b>- Components which have setVisible(false) will return
* false from isVisible() and will not render a response (nor will their
* children).
*
* <li><b>Page </b>- The Page containing any given Component can be retrieved
* by calling {@link Component#getPage()}. If the Component is not attached to
* a Page, an IllegalStateException will be thrown. An equivalent method,
* {@link Component#findPage()} is available for special circumstances where it
* might be desirable to get a null reference back instead.
*
* <li><b>Session </b>- The Page for a Component points back to the Session
* that contains the Page. The Session for a component can be accessed with the
* convenience method getSession(), which simply calls getPage().getSession().
*
* <li><b>Locale </b>- The Locale for a Component is available through the
* convenience method getLocale(), which is equivalent to
* getSession().getLocale().
*
* <li><b>String Resources </b>- Components can have associated String
* resources via the Application's Localizer, which is available through the
* method {@link Component#getLocalizer()}. The convenience methods
* {@link Component#getString(String key)} and
* {@link Component#getString(String key, IModel model)} wrap the identical
* methods on the Application Localizer for easy access in Components.
*
* <li><b>Style </b>- The style ("skin") for a component is available through
* {@link Component#getStyle()}, which is equivalent to
* getSession().getStyle(). Styles are intended to give a particular look to a
* Component or Resource that is independent of its Locale. For example, a style
* might be a set of resources, including images and markup files, which gives
* the design look of "ocean" to the user. If the Session's style is set to
* "ocean" and these resources are given names suffixed with "_ocean", Wicket's
* resource management logic will prefer these resources to other resources,
* such as default resources, which are not as good of a match.
*
* <li><b>Variation </b>- Whereas Styles are Session (user) specific,
* variations are component specific. E.g. if the Style is "ocean" and the
* Variation is "NorthSea", than the resources are given the names suffixed with
* "_ocean_NorthSea".
*
* <li><b>AttributeModifiers </b>- You can add one or more
* {@link AttributeModifier}s to any component if you need to programmatically
* manipulate attributes of the markup tag to which a Component is attached.
*
* <li><b>Application, ApplicationSettings and ApplicationPages </b>- The
* getApplication() method provides convenient access to the Application for a
* Component via getSession().getApplication(). The getApplicationSettings()
* method is equivalent to getApplication().getSettings(). The
* getApplicationPages is equivalent to getApplication().getPages().
*
* <li><b>Feedback Messages </b>- The {@link Component#debug(String)},
* {@link Component#info(String)}, {@link Component#warn(String)},
* {@link Component#error(String)} and {@link Component#fatal(String)} methods
* associate feedback messages with a Component. It is generally not necessary
* to use these methods directly since Wicket validators automatically register
* feedback messages on Components. Any feedback message for a given Component
* can be retrieved with {@link Component#getFeedbackMessage}.
*
* <li><b>Page Factory </b>- It is possible to change the way that Pages are
* constructed by overriding the {@link Component#getPageFactory()} method,
* returning your own implementation of {@link wicket.IPageFactory}.
*
* <li><b>Versioning </b>- Pages are the unit of versioning in Wicket, but
* fine-grained control of which Components should participate in versioning is
* possible via the {@link Component#setVersioned(boolean)} method. The
* versioning participation of a given Component can be retrieved with
* {@link Component#isVersioned()}.
*
* <li><b>AJAX support</b>- Components can be re-rendered after the whole Page
* has been rendered at least once by calling doRender(9.
*
* @author Jonathan Locke
* @author Chris Turner
* @author Eelco Hillenius
* @author Johan Compagner
* @author Juergen Donnerstag
*/
public abstract class Component implements Serializable, IBehaviorListener
{
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED1 = 0x0100;
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED2 = 0x0200;
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED3 = 0x0400;
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED4 = 0x0800;
/** True when a component is being auto-added */
private static final short FLAG_AUTO = 0x0001;
/** True when a component is enabled for model updates and is reachable. */
private static final short FLAG_ENABLED = 0x0080;
/** Flag for escaping HTML in model strings */
private static final short FLAG_ESCAPE_MODEL_STRINGS = 0x0002;
/** Flag for Component holding root compound model */
private static final short FLAG_HAS_ROOT_MODEL = 0x0004;
/** Ignore attribute modifiers */
private static final short FLAG_IGNORE_ATTRIBUTE_MODIFIER = 0x0040;
/** boolean whether this component was rendered once for tracking changes. */
private static final short FLAG_IS_RENDERED_ONCE = 0x1000;
/** Render tag boolean */
private static final short FLAG_RENDER_BODY_ONLY = 0x0020;
/** Versioning boolean */
private static final short FLAG_VERSIONED = 0x0008;
/** Visibility boolean */
private static final short FLAG_VISIBLE = 0x0010;
/** Basic model IModelComparator implementation for normal object models */
private static final IModelComparator defaultModelComparator = new IModelComparator()
{
public boolean compare(Object a, Object b)
{
if (a == null && b == null)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return a.equals(b);
}
};
/** Log. */
private static Log log = LogFactory.getLog(Component.class);
/** List of behaviours to be applied for this Component */
private List behaviours = null;
/** Component flags. See FLAG_* for possible non-exclusive flag values. */
private short flags = FLAG_VISIBLE | FLAG_ESCAPE_MODEL_STRINGS | FLAG_VERSIONED | FLAG_ENABLED;
/** Component id. */
private String id;
/**
* The position within the markup stream, where the markup for the component
* begins. Compared to MarkupContainer's markupStream this is NOT just a
* temporary variable to render a page.
*/
private int markupStreamPosition = -1;
/** The model for this component. */
private IModel model;
/** Any parent container. */
private MarkupContainer parent;
/**
* Internal indicator of whether this component may be rendered given the
* current context's authorization. It overrides the visible flag in case
* this is false. Authorization is done before trying to render any
* component (otherwise we would end up with a half rendered page in the
* buffer), and as an optimization, the result for the current request is
* stored in this variable.
*/
private transient boolean renderAllowed = true;
/** True while rendering is in progress */
private transient boolean rendering;
/**
* Change record of a model.
*/
public class ComponentModelChange extends Change
{
private static final long serialVersionUID = 1L;
/** former model. */
private IModel model;
/**
* Construct.
*
* @param model
*/
public ComponentModelChange(IModel model)
{
super();
this.model = model;
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return "ComponentModelChange[component: " + getPath() + "]";
}
/**
* @see wicket.version.undo.Change#undo()
*/
public void undo()
{
setModel(this.model);
}
}
/**
* Generic component visitor interface for component traversals.
*/
public static interface IVisitor
{
/**
* Value to return to continue a traversal.
*/
public static final Object CONTINUE_TRAVERSAL = null;
/**
* A generic value to return to stop a traversal.
*/
public static final Object STOP_TRAVERSAL = new Object();
/**
* Called at each component in a traversal.
*
* @param component
* The component
* @return CONTINUE_TRAVERSAL (null) if the traversal should continue,
* or a non-null return value for the traversal method if it
* should stop. If no return value is useful, the generic
* non-null value STOP_TRAVERSAL can be used.
*/
public Object component(Component component);
}
/**
* A enabled change operation.
*/
protected final static class EnabledChange extends Change
{
private static final long serialVersionUID = 1L;
/** subject. */
private final Component component;
/** former value. */
private final boolean enabled;
/**
* Construct.
*
* @param component
*/
EnabledChange(final Component component)
{
this.component = component;
this.enabled = component.getFlag(FLAG_ENABLED);
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return "EnabledChange[component: " + component.getPath() + ",enabled: " + enabled + "]";
}
/**
* @see wicket.version.undo.Change#undo()
*/
public void undo()
{
component.setEnabled(enabled);
}
}
/**
* A visibility change operation.
*/
protected final static class VisibilityChange extends Change
{
private static final long serialVersionUID = 1L;
/** subject. */
private final Component component;
/** former value. */
private final boolean visible;
/**
* Construct.
*
* @param component
*/
VisibilityChange(final Component component)
{
this.component = component;
this.visible = component.getFlag(FLAG_VISIBLE);
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return "VisibilityChange[component: " + component.getPath() + ", visible: " + visible
+ "]";
}
/**
* @see wicket.version.undo.Change#undo()
*/
public void undo()
{
component.setVisible(visible);
}
}
/**
* Constructor. All components have names. A component's id cannot be null.
* This is the minimal constructor of component. It does not register a
* model.
*
* @param id
* The non-null id of this component
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id)
{
checkAuthorization();
setId(id);
}
/**
* Constructor. All components have names. A component's id cannot be null.
* This is constructor includes a model.
*
* @param id
* The non-null id of this component
* @param model
* The component's model
*
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id, final IModel model)
{
checkAuthorization();
setId(id);
setModel(model);
}
/**
* Adds an behaviour modifier to the component.
*
* @param behaviour
* The behaviour modifier to be added
* @return this (to allow method call chaining)
*/
public final Component add(final IBehavior behaviour)
{
if (behaviour == null)
{
throw new IllegalArgumentException("Argument may not be null");
}
// Lazy create
if (behaviours == null)
{
behaviours = new ArrayList(1);
}
behaviours.add(behaviour);
// Give handler the opportunity to bind this component
behaviour.bind(this);
return this;
}
/**
* Registers a debug message for this component
*
* @param message
* The message
*/
public final void debug(final String message)
{
getPage().getFeedbackMessages().debug(this, message);
}
/**
* Detaches all models
*/
public void detachModels()
{
// Detach any detachable model from this component
detachModel();
// Also detach models from any contained attribute modifiers
if (behaviours != null)
{
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
IBehavior behaviour = (IBehavior)i.next();
behaviour.detachModel();
}
}
}
/**
* Page.doRender() is used to render a whole page. With AJAX however it must
* be possible to re-render anyone component contained in a page. That is
* what Component.doRender() is for.
*/
public void doRender()
{
// Save the parent's markup stream to re-assign it at the end
MarkupContainer parent = getParent();
MarkupStream originalMarkupStream = parent.getMarkupStream();
// Get the parent's associated markup stream.
MarkupStream markupStream = findParentWithAssociatedMarkup().getAssociatedMarkupStream();
// Make sure the markup stream is position at the correct element
markupStream.setCurrentIndex(this.markupStreamPosition);
try
{
// Make sure that while rendering the markup stream is found
parent.setMarkupStream(markupStream);
// Render the component and all its children
internalBeginRequest();
render();
}
finally
{
// Make sure the original markup stream is back in place
parent.setMarkupStream(originalMarkupStream);
}
}
/**
* Registers an error message for this component
*
* @param message
* The message
*/
public final void error(final String message)
{
getPage().getFeedbackMessages().error(this, message);
}
/**
* Registers an fatal error message for this component
*
* @param message
* The message
*/
public final void fatal(final String message)
{
getPage().getFeedbackMessages().fatal(this, message);
}
/**
* Finds the first container parent of this component of the given class.
*
* @param c
* MarkupContainer class to search for
* @return First container parent that is an instance of the given class, or
* null if none can be found
*/
public final MarkupContainer findParent(final Class c)
{
// Start with immediate parent
MarkupContainer current = parent;
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
return current;
}
// Check parent
current = current.getParent();
}
// Failed to find component
return null;
}
/**
* @return The nearest markup container with associated markup
*/
public final MarkupContainer findParentWithAssociatedMarkup()
{
MarkupContainer container = parent;
while (container != null)
{
if (container.hasAssociatedMarkup())
{
return container;
}
container = container.getParent();
}
// This should never happen since Page always has associated markup
throw new WicketRuntimeException("Unable to find parent with associated markup");
}
/**
* Gets interface to application that this component is a part of.
*
* @return The application associated with the session that this component
* is in.
* @see Application
*/
public final Application getApplication()
{
return Application.get();
}
/**
* Gets the application pages from the application that this component
* belongs to.
*
* @return The application pages
* @see IRequiredPageSettings
*/
public final IRequiredPageSettings getApplicationPages()
{
return getApplication().getRequiredPageSettings();
}
/**
* This method has been deprecated in favor of
* Application.get().getXXXSettings()
*
* Gets the application settings from the application that this component
* belongs to.
*
* @return The application settings from the application that this component
* belongs to
* @see Settings
* @deprecated
*
*/
// TODO remove this method in wicket post 1.2
public final Settings getApplicationSettings()
{
return getApplication().getSettings();
}
/**
* @return A path of the form <page-class-name>. <page-relative-path>
* @see Component#getPageRelativePath()
*/
public final String getClassRelativePath()
{
return getClass().getName() + "." + getPageRelativePath();
}
/**
* Gets the converter that should be used by this component.
*
* @return The converter that should be used by this component
*/
public IConverter getConverter()
{
return getSession().getConverter();
}
/**
* Gets whether model strings should be escaped.
*
* @return Returns whether model strings should be escaped
*/
public final boolean getEscapeModelStrings()
{
return getFlag(FLAG_ESCAPE_MODEL_STRINGS);
}
/**
* @return Any feedback message for this component
*/
public final FeedbackMessage getFeedbackMessage()
{
return getPage().getFeedbackMessages().messageForComponent(this);
}
/**
* Gets the id of this component.
*
* @return The id of this component
*/
public String getId()
{
return id;
}
/**
* Gets the locale for the session holding this component.
*
* @return The locale for the session holding this component
* @see Component#getSession()
*/
public final Locale getLocale()
{
return getSession().getLocale();
}
/**
* Convenience method to provide easy access to the localizer object within
* any component.
*
* @return The localizer object
*/
public final Localizer getLocalizer()
{
return getApplication().getMarkupSettings().getLocalizer();
}
/**
* Gets metadata for this component using the given key.
*
* @param key
* The key for the data
* @return The metadata
* @see MetaDataKey
*/
public final Serializable getMetaData(final MetaDataKey key)
{
return getPage().getMetaData(this, key);
}
/**
* Gets the model. It returns the object that wraps the backing model.
*
* @return The model
*/
public IModel getModel()
{
// If model is null
if (model == null)
{
// give subclass a chance to lazy-init model
this.model = initModel();
}
return model;
}
/**
* Gets the backing model object; this is shorthand for
* getModel().getObject().
*
* @return the backing model object
*/
public final Object getModelObject()
{
final IModel model = getModel();
if (model != null)
{
// If this component has the root model for a compound model
if (getFlag(FLAG_HAS_ROOT_MODEL))
{
// we need to return the root model and not a property of the
// model
return getRootModel(model).getObject(null);
}
// Get model value for this component
return model.getObject(this);
}
else
{
return null;
}
}
/**
* Gets a model object as a string.
*
* @return Model object for this component as a string
*/
public final String getModelObjectAsString()
{
final Object modelObject = getModelObject();
if (modelObject != null)
{
// Get converter
final IConverter converter = getConverter();
// Model string from property
final String modelString = (String)converter.convert(modelObject, String.class);
// If we should escape the markup
if (getFlag(FLAG_ESCAPE_MODEL_STRINGS))
{
// Escape it
return Strings.escapeMarkup(modelString);
}
return modelString;
}
return "";
}
/**
* Gets the page holding this component.
*
* @return The page holding this component
*/
public final Page getPage()
{
// Search for nearest Page
final Page page = findPage();
// If no Page was found
if (page == null)
{
// Give up with a nice exception
throw new IllegalStateException("No Page found for component " + this);
}
return page;
}
/**
* @return The page factory for the session that this component is in
*/
public final IPageFactory getPageFactory()
{
return getSession().getPageFactory();
}
/**
* Gets the path to this component relative to the page it is in.
*
* @return The path to this component relative to the page it is in
*/
public final String getPageRelativePath()
{
return Strings.afterFirstPathComponent(getPath(), ':');
}
/**
* Gets any parent container, or null if there is none.
*
* @return Any parent container, or null if there is none
*/
public final MarkupContainer getParent()
{
return parent;
}
/**
* Gets the components' path.
*
* @return Dotted path to this component in the component hierarchy
*/
public final String getPath()
{
final StringBuffer buffer = new StringBuffer();
for (Component c = this; c != null; c = c.getParent())
{
if (buffer.length() > 0)
{
buffer.insert(0, ':');
}
buffer.insert(0, c.getId());
}
return buffer.toString();
}
/**
* If false the component's tag will be printed as well as its body (which
* is default). If true only the body will be printed, but not the
* component's tag.
*
* @return If true, the component tag will not be printed
*/
public final boolean getRenderBodyOnly()
{
return getFlag(FLAG_RENDER_BODY_ONLY);
}
/**
* @return The request for this component's active request cycle
*/
public final Request getRequest()
{
return getRequestCycle().getRequest();
}
/**
* Gets the active request cycle for this component
*
* @return The request cycle
*/
public final RequestCycle getRequestCycle()
{
return RequestCycle.get();
}
/**
* @return The shared resource for this component
*/
public final Resource getResource()
{
return getApplication().getSharedResources().get(Application.class, getId(), getLocale(),
getStyle(), false);
}
/**
* @return The response for this component's active request cycle
*/
public final Response getResponse()
{
return getRequestCycle().getResponse();
}
/**
* Gets the current session object. Although this method is not final
* (because Page overrides it), it is not intended to be overridden by
* clients and clients of the framework should not do so!
*
* @return The session that this component is in
*/
public final Session getSession()
{
return Session.get();
}
/**
* @param key
* Key of string resource in property file
* @return The String
* @see Localizer
*/
public final String getString(final String key)
{
return getString(key, getModel());
}
/**
* @param key
* The resource key
* @param model
* The model
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel model)
{
return getLocalizer().getString(key, this, model);
}
/**
* @param key
* The resource key
* @param model
* The model
* @param defaultValue
* A default value if the string cannot be found
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel model, final String defaultValue)
{
return getLocalizer().getString(key, this, model, defaultValue);
}
/**
* Gets the style of this component (see {@link wicket.Session}).
*
* @return The style of this component.
*
* @see wicket.Session
* @see wicket.Session#getStyle()
*/
public final String getStyle()
{
String variation = getVariation();
String style = getSession().getStyle();
if (variation != null && !"".equals(variation))
{
if (style != null && !"".equals(style))
{
style = variation + "_" + style;
}
else
{
style = variation;
}
}
return style;
}
/**
* Gets the variation string of this component that will be used to look up
* markup for this component. Subclasses can override this method to define
* by an instance what markup variation should be picked up. By default it
* will return null.
*
* @return The variation of this component.
*
*/
public String getVariation()
{
return null;
}
/**
* @return True if this component has an error message
*/
public final boolean hasErrorMessage()
{
return getPage().getFeedbackMessages().hasErrorMessageFor(this);
}
/**
* @return True if this component has some kind of feedback message
*/
public final boolean hasFeedbackMessage()
{
return getPage().getFeedbackMessages().hasMessageFor(this);
}
/**
* Registers a info message for this component
*
* @param message
* The message
*/
public final void info(final String message)
{
getPage().getFeedbackMessages().info(this, message);
}
/**
* Returns true if this component is an ancestor of the given component
*
* @param component
* The component to check
* @return True if the given component has this component as an ancestor
*/
public final boolean isAncestorOf(final Component component)
{
// Walk up containment hierarchy
for (MarkupContainer current = component.parent; current != null; current = current
.getParent())
{
// Is this an ancestor?
if (current == this)
{
return true;
}
}
// This component is not an ancestor of the given component
return false;
}
/**
* Gets whether this component is enabled. Specific components may decide to
* implement special behaviour that uses this property, like web form
* components that add a disabled='disabled' attribute when enabled is
* false.
*
* @return whether this component is enabled.
*/
public boolean isEnabled()
{
return getFlag(FLAG_ENABLED);
}
/**
* @return Returns the isVersioned.
*/
public boolean isVersioned()
{
// Is the component itself versioned?
if (!getFlag(FLAG_VERSIONED) || (!getFlag(FLAG_IS_RENDERED_ONCE)))
{
return false;
}
else
{
// If there's a parent and this component is versioned
if (parent != null)
{
// Check if the parent is unversioned. If any parent
// (recursively) is unversioned, then this component is too
if (!parent.isVersioned())
{
return false;
}
}
return true;
}
}
/**
* Gets whether this component and any children are visible.
*
* @return True if component and any children are visible
*/
public boolean isVisible()
{
return getFlag(FLAG_VISIBLE);
}
/**
* Checks if the component itself and all its parents are visible.
*
* @return true if the component and all its parents are visible.
*/
public final boolean isVisibleInHierarchy()
{
Component component = this;
while (component != null)
{
if (renderAllowed && component.isVisible())
{
component = component.getParent();
}
else
{
return false;
}
}
return true;
}
/**
* Called to indicate that the model content for this component has been
* changed
*/
public final void modelChanged()
{
// Call user code
internalOnModelChanged();
onModelChanged();
}
/**
* Called to indicate that the model content for this component is about to
* change
*/
public final void modelChanging()
{
// Call user code
onModelChanging();
// Tell the page that our model changed
final Page page = findPage();
if (page != null)
{
page.componentModelChanging(this);
}
}
/**
* Creates a new page using the component's page factory
*
* @param c
* The class of page to create
* @return The new page
*/
public final Page newPage(final Class c)
{
return getPageFactory().newPage(c);
}
/**
* Creates a new page using the component's page factory
*
* @param c
* The class of page to create
* @param parameters
* Any parameters to pass to the constructor
* @return The new page
*/
public final Page newPage(final Class c, final PageParameters parameters)
{
return getPageFactory().newPage(c, parameters);
}
/**
* Component has to implement {@link IBehaviorListener} to be able to pass
* through events to behaviours without ending up with many if/else blocks.
*
* @see wicket.behavior.IBehaviorListener#onRequest()
*/
public void onRequest()
{
String id = getRequest().getParameter("behaviourId");
if (id == null)
{
throw new WicketRuntimeException(
"parameter behaviourId was not provided: unable to locate listener");
}
int idAsInt = Integer.parseInt(id);
IBehaviorListener behaviourListener = (IBehaviorListener)behaviours.get(idAsInt);
if (behaviourListener == null)
{
throw new WicketRuntimeException("no behaviour listener found with behaviourId " + id);
}
behaviourListener.onRequest();
}
/**
* Removes this component from its parent. It's important to remember that a
* component that is removed cannot be referenced from the markup still.
*/
public final void remove()
{
if (parent == null)
{
throw new IllegalStateException("cannot remove " + this + " from null parent!");
}
parent.remove(this);
}
/**
* Performs a render of this component as part of a Page level render
* process.
* <p>
* For component level re-render (e.g. AJAX) please call
* Component.doRender(). Though render() does seem to work, it will fail for
* panel children.
*/
public final void render()
{
setFlag(FLAG_IS_RENDERED_ONCE, true);
rendering = true;
try
{
// Determine if component is visible using it's authorization status
// and the isVisible property.
if (renderAllowed && isVisible())
{
// Rendering is beginning
if (log.isDebugEnabled())
{
log.debug("Begin render " + this);
}
// Call implementation to render component
onRender();
// Component has been rendered
rendered();
if (log.isDebugEnabled())
{
log.debug("End render " + this);
}
}
else
{
findMarkupStream().skipComponent();
}
}
finally
{
rendering = false;
}
}
/**
* THIS IS PART OF WICKETS INTERNAL API. DO NOT RELY ON IT WITHIN YOUR CODE.
* <p>
* Renders the component at the current position in the given markup stream.
* The method onComponentTag() is called to allow the component to mutate
* the start tag. The method onComponentTagBody() is then called to permit
* the component to render its body.
*
* @param markupStream
* The markup stream
*/
public final void renderComponent(final MarkupStream markupStream)
{
// If yet unknown, set the markup stream position with the current
// position of markupStream. Else set the
// markupStream.setCurrentPosition
// based on the position already known to the component.
validateMarkupStream(markupStream);
// Get mutable copy of next tag
final ComponentTag openTag = markupStream.getTag();
final ComponentTag tag = openTag.mutable();
// Call any tag handler
onComponentTag(tag);
// If we're an openclose tag
if (!tag.isOpenClose() && !tag.isOpen())
{
// We were something other than <tag> or <tag/>
markupStream
.throwMarkupException("Method renderComponent called on bad markup element: "
+ tag);
}
if (tag.isOpenClose() && openTag.isOpen())
{
markupStream
.throwMarkupException("You can not modify a open tag to open-close: " + tag);
}
// Render open tag
if (getRenderBodyOnly() == false)
{
renderComponentTag(tag);
}
markupStream.next();
// Render the body only if open-body-close. Do not render if open-close.
if (tag.isOpen())
{
// Render the body
onComponentTagBody(markupStream, tag);
}
// Render close tag
if (tag.isOpen())
{
if (openTag.isOpen())
{
renderClosingComponentTag(markupStream, tag, getRenderBodyOnly());
}
else
{
// If a open-close tag has been to modified to be
// open-body-close than a synthetic close tag must be rendered.
if (getRenderBodyOnly() == false)
{
// Close the manually opened panel tag.
getResponse().write(openTag.syntheticCloseTagString());
}
}
}
}
/**
* Called to indicate that a component has been rendered. This method should
* only very rarely be called at all. One usage is in ImageMap, which
* renders its link children its own special way (without calling render()
* on them). If ImageMap did not call rendered() to indicate that its child
* components were actually rendered, the framework would think they had
* never been rendered, and in development mode this would result in a
* runtime exception.
*/
public final void rendered()
{
// Tell the page that the component rendered
getPage().componentRendered(this);
if (behaviours != null)
{
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
IBehavior behaviour = (IBehavior)i.next();
behaviour.rendered(this);
}
}
}
/**
* @param component
* The component to compare with
* @return True if the given component's model is the same as this
* component's model.
*/
public final boolean sameRootModel(final Component component)
{
return sameRootModel(component.getModel());
}
/**
* @param model
* The model to compare with
* @return True if the given component's model is the same as this
* component's model.
*/
public final boolean sameRootModel(final IModel model)
{
// Get the two models
IModel thisModel = getModel();
IModel thatModel = model;
// If both models are non-null they could be the same
if (thisModel != null && thatModel != null)
{
return getRootModel(thisModel) == getRootModel(thatModel);
}
return false;
}
/**
* Sets whether this component is enabled. Specific components may decide to
* implement special behaviour that uses this property, like web form
* components that add a disabled='disabled' attribute when enabled is
* false. If it is not enabled, it will not be allowed to call any listener
* method on it (e.g. Link.onClick) and the model object will be protected
* (for the common use cases, not for programmer's misuse)
*
* @param enabled
* whether this component is enabled
* @return This
*/
public final Component setEnabled(final boolean enabled)
{
// Is new enabled state a change?
if (enabled != getFlag(FLAG_ENABLED))
{
// TODO we can't record any state change as Link.onComponentTag
// potentially sets this property we probably don't need to support
// this, but I'll keep this commented so that we can think about it
// I (johan) changed the way Link.onComponentTag works. It will
// disable versioning for a the setEnabled call.
// Tell the page that this component's enabled was changed
if (isVersioned())
{
final Page page = findPage();
if (page != null)
{
addStateChange(new EnabledChange(this));
}
}
// Change visibility
setFlag(FLAG_ENABLED, enabled);
}
return this;
}
/**
* Sets whether model strings should be escaped.
*
* @param escapeMarkup
* True is model strings should be escaped
* @return This
*/
public final Component setEscapeModelStrings(final boolean escapeMarkup)
{
setFlag(FLAG_ESCAPE_MODEL_STRINGS, escapeMarkup);
return this;
}
/**
* Sets the metadata for this component using the given key. If the metadata
* object is not of the correct type for the metadata key, an
* IllegalArgumentException will be thrown. For information on creating
* MetaDataKeys, see {@link MetaDataKey}.
*
* @param key
* The singleton key for the metadata
* @param object
* The metadata object
* @throws IllegalArgumentException
* @see MetaDataKey
*/
public final void setMetaData(final MetaDataKey key, final Serializable object)
{
getPage().setMetaData(this, key, object);
}
/**
* Sets the given model.
* <p>
* WARNING: DO NOT OVERRIDE THIS METHOD UNLESS YOU HAVE A VERY GOOD REASON
* FOR IT. OVERRIDING THIS MIGHT OPEN UP SECURITY LEAKS AND BROKEN
* BACK-BUTTON SUPPORT.
* </p>
*
* @param model
* the model
* @return This
*/
public Component setModel(final IModel model)
{
// Detach current model
if (this.model != null)
{
this.model.detach();
}
// Change model
if (this.model != model)
{
addStateChange(new ComponentModelChange(this.model));
this.model = model;
}
// If a compound model is explicitly set on this component
if (model instanceof ICompoundModel)
{
// we need to remember this for getModelObject()
setFlag(FLAG_HAS_ROOT_MODEL, true);
}
modelChanged();
return this;
}
/**
* Sets the backing model object; shorthand for
* getModel().setObject(object).
*
* @param object
* The object to set
* @return This
*/
public final Component setModelObject(final Object object)
{
final IModel model = getModel();
// Check whether anything can be set at all
if (model == null)
{
throw new IllegalStateException(
"Attempt to set model object on null model of component: "
+ getPageRelativePath());
}
// Check authorization
if (!getApplication().getSecuritySettings().getAuthorizationStrategy().allowEnabledState(
this))
{
throw new UnauthorizedEnabledStateException(
"operation not allowed in the current authorization context");
}
// Check whether this will result in an actual change
final Object current = model.getObject(this);
if (!getModelComparator().compare(current, object))
{
modelChanging();
if (getFlag(FLAG_HAS_ROOT_MODEL))
{
getRootModel(model).setObject(null, object);
}
else
{
model.setObject(this, object);
}
modelChanged();
}
return this;
}
/**
* @param redirect
* True if the response should be redirected to
* @see RequestCycle#setRedirect(boolean)
*/
public final void setRedirect(final boolean redirect)
{
getRequestCycle().setRedirect(redirect);
}
/**
* If false the component's tag will be printed as well as its body (which
* is default). If true only the body will be printed, but not the
* component's tag.
*
* @param renderTag
* If true, the component tag will not be printed
* @return This
*/
public final Component setRenderBodyOnly(final boolean renderTag)
{
this.setFlag(FLAG_RENDER_BODY_ONLY, renderTag);
return this;
}
/**
* THIS IS PART OF WICKETS INTERNAL API. DO NOT RELY ON IT WITHIN YOUR CODE.
* <p>
*
* @param b
* Boolean to set the rendering
* @return the previous value of the rendering.
*/
public final boolean setRendering(boolean b)
{
boolean tmp = rendering;
rendering = b;
return tmp;
}
/**
* Sets the page that will respond to this request
*
* @param cls
* The response page class
* @see RequestCycle#setResponsePage(Class)
*/
public final void setResponsePage(final Class cls)
{
getRequestCycle().setResponsePage(cls);
}
/**
* Sets the page class and its parameters that will respond to this request
*
* @param cls
* The response page class
* @param parameters
* The parameters for thsi bookmarkable page.
* @see RequestCycle#setResponsePage(Class, PageParameters)
*/
public final void setResponsePage(final Class cls, PageParameters parameters)
{
getRequestCycle().setResponsePage(cls, parameters);
}
/**
* Sets the page that will respond to this request
*
* @param page
* The response page
* @see RequestCycle#setResponsePage(Page)
*/
public final void setResponsePage(final Page page)
{
getRequestCycle().setResponsePage(page);
}
/**
* @param versioned
* True to turn on versioning for this component, false to turn
* it off for this component and any children.
* @return This
*/
public Component setVersioned(boolean versioned)
{
setFlag(FLAG_VERSIONED, versioned);
return this;
}
/**
* Sets whether this component and any children are visible.
*
* @param visible
* True if this component and any children should be visible
* @return This
*/
public final Component setVisible(final boolean visible)
{
// Is new visibility state a change?
if (visible != getFlag(FLAG_VISIBLE))
{
// Tell the page that this component's visibility was changed
final Page page = findPage();
if (page != null)
{
addStateChange(new VisibilityChange(this));
}
// Change visibility
setFlag(FLAG_VISIBLE, visible);
}
return this;
}
/**
* Gets the string representation of this component.
*
* @return The path to this component
*/
public String toString()
{
return toString(true);
}
/**
* @param detailed
* True if a detailed string is desired
* @return The string
*/
public String toString(final boolean detailed)
{
if (detailed)
{
final Page page = findPage();
if (page == null)
{
return new StringBuffer("[Component id = ").append(getId()).append(
", page = <No Page>, path = ").append(getPath()).append(".").append(
Classes.name(getClass())).append("]").toString();
}
else
{
return new StringBuffer("[Component id = ").append(getId()).append(", page = ")
.append(getPage().getClass().getName()).append(", path = ").append(
getPath()).append(".").append(Classes.name(getClass())).append(
", isVisible = ").append((renderAllowed && isVisible())).append(
", isVersioned = ").append(isVersioned()).append("]").toString();
}
}
else
{
return "[Component id = " + getId() + "]";
}
}
/**
* Gets the url for the listener interface (e.g. ILinkListener).
*
* @param listenerInterface
* The listener interface that the URL should call
* @return The URL
* @see Page#urlFor(Component, Class)
*/
public final String urlFor(final Class listenerInterface)
{
return getPage().urlFor(this, listenerInterface);
}
/**
* Gets the url for the provided behaviour listener.
*
* @param behaviourListener
* the behaviour listener to get the url for
* @return The URL
* @see Page#urlFor(Component, Class)
*/
public final String urlFor(final IBehaviorListener behaviourListener)
{
if (behaviourListener == null)
{
throw new IllegalArgumentException("Argument behaviourListener must be not null");
}
if (behaviours == null)
{
throw new IllegalArgumentException("behaviourListener " + behaviourListener
+ " was not registered with this component");
}
int index = behaviours.indexOf(behaviourListener);
if (index == -1)
{
throw new IllegalArgumentException("behaviourListener " + behaviourListener
+ " was not registered with this component");
}
return urlFor(IBehaviorListener.class) + "&behaviourId=" + index;
}
/**
* Registers a warning message for this component.
*
* @param message
* The message
*/
public final void warn(final String message)
{
getPage().getFeedbackMessages().warn(this, message);
}
/**
* Adds state change to page.
*
* @param change
* The change
*/
protected final void addStateChange(Change change)
{
Page page = findPage();
if (page != null)
{
page.componentStateChanging(this, change);
}
}
/**
* Checks whether the given type has the expected name.
*
* @param tag
* The tag to check
* @param name
* The expected tag name
* @throws MarkupException
* Thrown if the tag is not of the right name
*/
protected final void checkComponentTag(final ComponentTag tag, final String name)
{
if (!tag.getName().equalsIgnoreCase(name))
{
findMarkupStream().throwMarkupException(
"Component " + getId() + " must be applied to a tag of type '" + name
+ "', not " + tag.toUserDebugString());
}
}
/**
* Checks that a given tag has a required attribute value.
*
* @param tag
* The tag
* @param key
* The attribute key
* @param value
* The required value for the attribute key
* @throws MarkupException
* Thrown if the tag does not have the required attribute value
*/
protected final void checkComponentTagAttribute(final ComponentTag tag, final String key,
final String value)
{
if (key != null)
{
final String tagAttributeValue = tag.getAttributes().getString(key);
if (tagAttributeValue == null || !value.equalsIgnoreCase(tagAttributeValue))
{
findMarkupStream().throwMarkupException(
"Component " + getId() + " must be applied to a tag with '" + key
+ "' attribute matching '" + value + "', not '" + tagAttributeValue
+ "'");
}
}
}
/**
* Detaches the model for this component if it is detachable.
*/
protected void detachModel()
{
// If the model is compound and it's not the root model, then it can
// be reconstituted via initModel() after replication
if (model instanceof CompoundPropertyModel && !getFlag(FLAG_HAS_ROOT_MODEL))
{
// Get rid of model which can be lazy-initialized again
this.model = null;
}
else
{
if (model != null)
{
model.detach();
}
}
}
/**
* Prefixes an exception message with useful information about this.
* component.
*
* @param message
* The message
* @return The modified message
*/
protected final String exceptionMessage(final String message)
{
return message + ":\n" + toString();
}
/**
* Finds the markup stream for this component.
*
* @return The markup stream for this component. Since a Component cannot
* have a markup stream, we ask this component's parent to search
* for it.
*/
protected MarkupStream findMarkupStream()
{
if (parent == null)
{
throw new IllegalStateException("cannot find markupstream for " + this
+ " as there is no parent");
}
return parent.findMarkupStream();
}
/**
* If this Component is a Page, returns self. Otherwise, searches for the
* nearest Page parent in the component hierarchy. If no Page parent can be
* found, null is returned.
*
* @return The Page or null if none can be found
*/
protected final Page findPage()
{
// Search for page
return (Page)(this instanceof Page ? this : findParent(Page.class));
}
/**
* Gets the currently coupled {@link IBehavior}s as a unmodifiable list.
* Returns an empty list rather than null if there are no behaviours coupled
* to this component.
*
* @return the currently coupled behaviours as a unmodifiable list
*/
protected final List/* <IBehavior> */getBehaviours()
{
if (behaviours == null)
{
return Collections.EMPTY_LIST;
}
return Collections.unmodifiableList(behaviours);
}
/**
* Gets the subset of the currently coupled {@link IBehavior}s that are of
* the provided type as a unmodifiable list or null if there are no
* behaviours attached. Returns an empty list rather than null if there are
* no behaviours coupled to this component.
*
* @param type
* the type
*
* @return the subset of the currently coupled behaviours that are of the
* provided type as a unmodifiable list or null
*/
protected final List/* <IBehavior> */getBehaviours(Class type)
{
if (behaviours == null)
{
return Collections.EMPTY_LIST;
}
List subset = new ArrayList(behaviours.size()); // avoid growing
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
Object behaviour = i.next();
if (type.isAssignableFrom(behaviour.getClass()))
{
subset.add(behaviour);
}
}
return Collections.unmodifiableList(subset);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to test
* @return True if the flag is set
*/
protected final boolean getFlag(final short flag)
{
return (this.flags & flag) != 0;
}
/**
* Gets the value defaultModelComparator. Implementations of this interface
* can be used in the Component.getComparator() for testing the current
* value of the components model data with the new value that is given.
*
* @return the value defaultModelComparator
*/
protected IModelComparator getModelComparator()
{
return defaultModelComparator;
}
/**
* Called when a null model is about to be retrieved in order to allow a
* subclass to provide an initial model. This gives FormComponent, for
* example, an opportunity to instantiate a model on the fly using the
* containing Form's model.
*
* @return The model
*/
protected IModel initModel()
{
// Search parents for CompoundPropertyModel
for (Component current = getParent(); current != null; current = current.getParent())
{
// Get model
final IModel model = current.getModel();
if (model instanceof ICompoundModel)
{
// we turn off versioning as we share the model with another
// component that is the owner of the model (that component
// has to decide whether to version or not
setVersioned(false);
// return the shared compound model
return model;
}
}
// No model for this component!
return null;
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request begins.
*/
protected void internalBeginRequest()
{
onBeginRequest();
internalOnBeginRequest();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request ends.
*/
protected void internalEndRequest()
{
internalOnEndRequest();
onEndRequest();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request begins.
*/
protected void internalOnBeginRequest()
{
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request ends.
*/
protected void internalOnEndRequest()
{
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called anytime a model is changed via setModel or setModelObject.
*/
protected void internalOnModelChanged()
{
}
/**
* Components are allowed to reject behaviour modifiers.
*
* @param behaviour
* @return false, if the component should not apply this behaviour
*/
protected boolean isBehaviourAccepted(final IBehavior behaviour)
{
// Ignore AttributeModifiers when FLAG_IGNORE_ATTRIBUTE_MODIFIER is set
if ((behaviour instanceof AttributeModifier)
&& (getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER) != false))
{
return false;
}
return true;
}
/**
* If true, all attribute modifiers will be ignored
*
* @return True, if attribute modifiers are to be ignored
*/
protected final boolean isIgnoreAttributeModifier()
{
return this.getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER);
}
/**
* Invalidates the markupstream position, called when the markup did change
*/
protected final void markStreamPositionInvalid()
{
markupStreamPosition = -1;
}
/**
* Called when a request begins.
*/
protected void onBeginRequest()
{
}
/**
* Processes the component tag.
*
* @param tag
* Tag to modify
*/
protected void onComponentTag(final ComponentTag tag)
{
}
/**
* Processes the body.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
}
/**
* Called when a request ends.
*/
protected void onEndRequest()
{
}
/**
* Called anytime a model is changed after the change has occurred
*/
protected void onModelChanged()
{
}
/**
* Called anytime a model is changed, but before the change actually occurs
*/
protected void onModelChanging()
{
}
/**
* Implementation that renders this component.
*/
protected abstract void onRender();
/**
* Writes a simple tag out to the response stream. Any components that might
* be referenced by the tag are ignored. Also undertakes any tag attribute
* modifications if they have been added to the component.
*
* @param tag
* The tag to write
*/
protected final void renderComponentTag(ComponentTag tag)
{
final boolean stripWicketTags = Application.get().getMarkupSettings().getStripWicketTags();
if (!(tag instanceof WicketTag) || !stripWicketTags)
{
// Apply behaviour modifiers
if ((behaviours != null) && !behaviours.isEmpty() && !tag.isClose()
&& (isIgnoreAttributeModifier() == false))
{
tag = tag.mutable();
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
IBehavior behaviour = (IBehavior)i.next();
// components may reject some behaviour components
if (isBehaviourAccepted(behaviour))
{
behaviour.onComponentTag(this, tag);
}
}
}
// Write the tag
tag.writeOutput(getResponse(), stripWicketTags, this.findMarkupStream()
.getWicketNamespace());
}
}
/**
* Replaces the body with the given one.
*
* @param markupStream
* The markup stream to replace the tag body in
* @param tag
* The tag
* @param body
* The new markup
*/
protected final void replaceComponentTagBody(final MarkupStream markupStream,
final ComponentTag tag, final String body)
{
// If tag has body
if (tag.isOpen())
{
// skip any raw markup in the body
markupStream.skipRawMarkup();
}
// Write the new body
getResponse().write(body);
// If we had an open tag (and not an openclose tag) and we found a
// close tag, we're good
if (tag.isOpen())
{
// Open tag must have close tag
if (!markupStream.atCloseTag())
{
// There must be a component in this discarded body
markupStream
.throwMarkupException("Expected close tag. Possible attempt to embed component(s) "
+ "in the body of a component which discards its body");
}
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to set
* @param set
* True to turn the flag on, false to turn it off
*/
protected final void setFlag(final short flag, final boolean set)
{
if (set)
{
this.flags |= flag;
}
else
{
this.flags &= ~flag;
}
}
/**
* If true, all attribute modifiers will be ignored
*
* @param ignore
* If true, all attribute modifiers will be ignored
* @return This
*/
protected final Component setIgnoreAttributeModifier(final boolean ignore)
{
this.setFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER, ignore);
return this;
}
/**
* If yet unknown, set the markup stream position with the current position
* of markupStream. Else set the markupStream.setCurrentPosition based the
* position already known to the component.
* <p>
* Note: Parameter markupStream.getCurrentPosition() will be updated, if
* re-render is allowed.
*
* @param markupStream
*/
protected final void validateMarkupStream(final MarkupStream markupStream)
{
// Allow the component to be re-rendered without a page. Partial
// re-rendering is a requirement of AJAX.
final Component parent = getParent();
if (this.isAuto() || (parent != null && parent.isRendering()))
{
// Remember the position while rendering the component the first
// time
this.markupStreamPosition = markupStream.getCurrentIndex();
}
else if (this.markupStreamPosition < 0)
{
throw new WicketRuntimeException(
"The markup stream of the component should be known by now, but isn't: "
+ this.toString());
}
else
{
// Re-set the markups index to the beginning of the component tag
markupStream.setCurrentIndex(this.markupStreamPosition);
}
}
/**
* Visits the parents of this component.
*
* @param c
* Class
* @param visitor
* The visitor to call at each parent of the given type
* @return First non-null value returned by visitor callback
*/
protected final Object visitParents(final Class c, final IVisitor visitor)
{
// Start here
Component current = this;
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
final Object object = visitor.component(current);
if (object != IVisitor.CONTINUE_TRAVERSAL)
{
return object;
}
}
// Check parent
current = current.getParent();
}
return null;
}
/**
* Gets the component at the given path.
*
* @param path
* Path to component
* @return The component at the path
*/
Component get(final String path)
{
// Path to this component is an empty path
if (path.equals(""))
{
return this;
}
throw new IllegalArgumentException(
exceptionMessage("Component is not a container and so does not contain the path "
+ path));
}
/**
* @return True if this component or any of its parents is in auto-add mode
*/
final boolean isAuto()
{
// Search up hierarchy for FLAG_AUTO
for (Component current = this; current != null; current = current.getParent())
{
if (current.getFlag(FLAG_AUTO))
{
return true;
}
}
return false;
}
/**
* Renders the close tag at the current position in the markup stream.
*
* @param markupStream
* the markup stream
* @param openTag
* the tag to render
* @param renderTagOnly
* if true, the tag will not be written to the output
*/
final void renderClosingComponentTag(final MarkupStream markupStream,
final ComponentTag openTag, final boolean renderTagOnly)
{
// Tag should be open tag and not openclose tag
if (openTag.isOpen())
{
// If we found a close tag and it closes the open tag, we're good
if (markupStream.atCloseTag() && markupStream.getTag().closes(openTag))
{
// Get the close tag from the stream
ComponentTag closeTag = markupStream.getTag();
// If the open tag had its id changed
if (openTag.getNameChanged())
{
// change the id of the close tag
closeTag = closeTag.mutable();
closeTag.setName(openTag.getName());
}
// Render the close tag
if (renderTagOnly == false)
{
renderComponentTag(closeTag);
}
markupStream.next();
}
else
{
if (openTag.requiresCloseTag())
{
// Missing close tag
markupStream.throwMarkupException("Expected close tag for " + openTag);
}
}
}
}
/**
* @param auto
* True to put component into auto-add mode
*/
final void setAuto(final boolean auto)
{
setFlag(FLAG_AUTO, auto);
}
/**
* Sets the id of this component. This method is private because the only
* time a component's id can be set is in its constructor.
*
* @param id
* The non-null id of this component
*/
final void setId(final String id)
{
if (id == null && !(this instanceof Page))
{
throw new WicketRuntimeException("Null component id is not allowed.");
}
this.id = id;
}
/**
* Sets the parent of a component.
*
* @param parent
* The parent container
*/
final void setParent(final MarkupContainer parent)
{
if (this.parent != null && log.isDebugEnabled())
{
log.debug("replacing parent " + this.parent + " with " + parent);
}
this.parent = parent;
}
/**
* Sets the render allowed flag.
*
* @param renderAllowed
*/
final void setRenderAllowed(boolean renderAllowed)
{
this.renderAllowed = renderAllowed;
}
/**
* Check whether this component may be created at all. Throws a
* {@link AuthorizationException} when it may not be created
*
*/
private final void checkAuthorization()
{
if (!getApplication().getSecuritySettings().getAuthorizationStrategy().allowInstantiation(
getClass()))
{
throw new UnauthorizedInstantiationException(
"insufficiently authorized to create component " + getClass());
}
}
/**
* Finds the root object for an IModel
*
* @param model
* The model
* @return The root object
*/
private final IModel getRootModel(final IModel model)
{
IModel nestedModelObject = model;
while (true)
{
final IModel next = ((IModel)nestedModelObject).getNestedModel();
if (next == null)
{
break;
}
if (nestedModelObject == next)
{
throw new WicketRuntimeException("Model for " + nestedModelObject
+ " is self-referential");
}
nestedModelObject = next;
}
return nestedModelObject;
}
/**
* @return boolean if this component is currently rendering itself
*/
private boolean isRendering()
{
return rendering;
}
}
| wicket/src/java/wicket/Component.java | /*
* $Id$ $Revision:
* 1.235 $ $Date$
*
* ==============================================================================
* 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 wicket;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.authorization.AuthorizationException;
import wicket.authorization.UnauthorizedEnabledStateException;
import wicket.authorization.UnauthorizedInstantiationException;
import wicket.behavior.IBehavior;
import wicket.behavior.IBehaviorListener;
import wicket.feedback.FeedbackMessage;
import wicket.markup.ComponentTag;
import wicket.markup.MarkupException;
import wicket.markup.MarkupStream;
import wicket.markup.WicketTag;
import wicket.model.CompoundPropertyModel;
import wicket.model.ICompoundModel;
import wicket.model.IModel;
import wicket.model.IModelComparator;
import wicket.settings.IMarkupSettings;
import wicket.settings.IRequiredPageSettings;
import wicket.settings.Settings;
import wicket.util.convert.IConverter;
import wicket.util.lang.Classes;
import wicket.util.string.Strings;
import wicket.version.undo.Change;
/**
* Component serves as the highest level abstract base class for all components.
*
* <ul>
* <li><b>Identity </b>- All Components must have a non-null id which is
* retrieved by calling getId(). The id must be unique within the
* MarkupContainer that holds the Component, but does not have to be globally
* unique or unique within a Page's component hierarchy.
*
* <li><b>Hierarchy </b>- A component has a parent which can be retrieved with
* getParent(). If a component is an instance of MarkupContainer, it may have
* children. In this way it has a place in the hierarchy of components contained
* on a given page. The {@link Component#isAncestorOf(Component)} method returns
* true if this Component is an ancestor of the given Component.
*
* <li><b>Component Paths </b>- The path from the Page at the root of the
* component hierarchy to a given Component is simply the concatenation with dot
* separators of each id along the way. For example, the path "a.b.c" would
* refer to the component named "c" inside the MarkupContainer named "b" inside
* the container named "a". The path to a component can be retrieved by calling
* getPath(). This path is an absolute path beginning with the id of the Page at
* the root. Pages bear a PageMap/Session-relative identifier as their id, so
* each absolute path will begin with a number, such as "0.a.b.c". To get a
* Component path relative to the page that contains it, you can call
* getPageRelativePath().
*
* <li><b>LifeCycle </b>- Components participate in the following lifecycle
* phases:
* <ul>
* <li><b>Construction </b>- A Component is constructed with the Java language
* new operator. Children may be added during construction if the Component is a
* MarkupContainer.
*
* <li><b>Request Handling </b>- An incoming request is processed by a protocol
* request handler such as WicketServlet. An associated Application object
* creates Session, Request and Response objects for use by a given Component in
* updating its model and rendering a response. These objects are stored inside
* a container called {@link RequestCycle} which is accessible via
* {@link Component#getRequestCycle()}. The convenience methods
* {@link Component#getRequest()}, {@link Component#getResponse()} and
* {@link Component#getSession()} provide easy access to the contents of this
* container.
*
* <li><b>Listener Invocation </b>- If the request references a listener on an
* existing Component, that listener is called, allowing arbitrary user code to
* handle events such as link clicks or form submits. Although arbitrary
* listeners are supported in Wicket, the need to implement a new class of
* listener is unlikely for a web application and even the need to implement a
* listener interface directly is highly discouraged. Instead, calls to
* listeners are routed through logic specific to the event, resulting in calls
* to user code through other overridable methods. For example, the
* {@link wicket.markup.html.form.IFormSubmitListener#onFormSubmitted()} method
* implemented by the Form class is really a private implementation detail of
* the Form class that is not designed to be overridden (although unfortunately,
* it must be public since all interface methods in Java must be public).
* Instead, Form subclasses should override user-oriented methods such as
* onValidate(), onSubmit() and onError() (although only the latter two are
* likely to be overridden in practice).
*
* <li><b>onBeginRequest </b>- The {@link Component#onBeginRequest()} method is
* called.
*
* <li><b>Form Submit </b>- If a Form has been submitted and the Component is a
* FormComponent, the component's model is validated by a call to
* FormComponent.validate().
*
* <li><b>Form Model Update </b>- If a valid Form has been submitted and the
* Component is a FormComponent, the component's model is updated by a call to
* FormComponent.updateModel().
*
* <li><b>Rendering </b>- A markup response is generated by the Component via
* {@link Component#render()}, which calls subclass implementation code
* contained in {@link Component#onRender()}. Once this phase begins, a
* Component becomes immutable. Attempts to alter the Component will result in a
* WicketRuntimeException.
*
* <li><b>onEndRequest </b>() - The {@link Component#onEndRequest()} method is
* called.
* </ul>
*
* <li><b>Component Models </b>- The primary responsibility of a component is
* to use its model (an object that implements IModel), which can be set via
* {@link Component#setModel(IModel model)} and retrieved via
* {@link Component#getModel()}, to render a response in an appropriate markup
* language, such as HTML. In addition, form components know how to update their
* models based on request information. Since the IModel interface is a wrapper
* around an actual model object, a convenience method
* {@link Component#getModelObject()} is provided to retrieve the model Object
* from its IModel wrapper. A further convenience method,
* {@link Component#getModelObjectAsString()}, is provided for the very common
* operation of converting the wrapped model Object to a String.
*
* <li><b>Visibility </b>- Components which have setVisible(false) will return
* false from isVisible() and will not render a response (nor will their
* children).
*
* <li><b>Page </b>- The Page containing any given Component can be retrieved
* by calling {@link Component#getPage()}. If the Component is not attached to
* a Page, an IllegalStateException will be thrown. An equivalent method,
* {@link Component#findPage()} is available for special circumstances where it
* might be desirable to get a null reference back instead.
*
* <li><b>Session </b>- The Page for a Component points back to the Session
* that contains the Page. The Session for a component can be accessed with the
* convenience method getSession(), which simply calls getPage().getSession().
*
* <li><b>Locale </b>- The Locale for a Component is available through the
* convenience method getLocale(), which is equivalent to
* getSession().getLocale().
*
* <li><b>String Resources </b>- Components can have associated String
* resources via the Application's Localizer, which is available through the
* method {@link Component#getLocalizer()}. The convenience methods
* {@link Component#getString(String key)} and
* {@link Component#getString(String key, IModel model)} wrap the identical
* methods on the Application Localizer for easy access in Components.
*
* <li><b>Style </b>- The style ("skin") for a component is available through
* {@link Component#getStyle()}, which is equivalent to
* getSession().getStyle(). Styles are intended to give a particular look to a
* Component or Resource that is independent of its Locale. For example, a style
* might be a set of resources, including images and markup files, which gives
* the design look of "ocean" to the user. If the Session's style is set to
* "ocean" and these resources are given names suffixed with "_ocean", Wicket's
* resource management logic will prefer these resources to other resources,
* such as default resources, which are not as good of a match.
*
* <li><b>Variation </b>- Whereas Styles are Session (user) specific,
* variations are component specific. E.g. if the Style is "ocean" and the
* Variation is "NorthSea", than the resources are given the names suffixed with
* "_ocean_NorthSea".
*
* <li><b>AttributeModifiers </b>- You can add one or more
* {@link AttributeModifier}s to any component if you need to programmatically
* manipulate attributes of the markup tag to which a Component is attached.
*
* <li><b>Application, ApplicationSettings and ApplicationPages </b>- The
* getApplication() method provides convenient access to the Application for a
* Component via getSession().getApplication(). The getApplicationSettings()
* method is equivalent to getApplication().getSettings(). The
* getApplicationPages is equivalent to getApplication().getPages().
*
* <li><b>Feedback Messages </b>- The {@link Component#debug(String)},
* {@link Component#info(String)}, {@link Component#warn(String)},
* {@link Component#error(String)} and {@link Component#fatal(String)} methods
* associate feedback messages with a Component. It is generally not necessary
* to use these methods directly since Wicket validators automatically register
* feedback messages on Components. Any feedback message for a given Component
* can be retrieved with {@link Component#getFeedbackMessage}.
*
* <li><b>Page Factory </b>- It is possible to change the way that Pages are
* constructed by overriding the {@link Component#getPageFactory()} method,
* returning your own implementation of {@link wicket.IPageFactory}.
*
* <li><b>Versioning </b>- Pages are the unit of versioning in Wicket, but
* fine-grained control of which Components should participate in versioning is
* possible via the {@link Component#setVersioned(boolean)} method. The
* versioning participation of a given Component can be retrieved with
* {@link Component#isVersioned()}.
*
* <li><b>AJAX support</b>- Components can be re-rendered after the whole Page
* has been rendered at least once by calling doRender(9.
*
* @author Jonathan Locke
* @author Chris Turner
* @author Eelco Hillenius
* @author Johan Compagner
* @author Juergen Donnerstag
*/
public abstract class Component implements Serializable, IBehaviorListener
{
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED1 = 0x0100;
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED2 = 0x0200;
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED3 = 0x0400;
/** Reserved subclass-definable flag bit */
protected static final short FLAG_RESERVED4 = 0x0800;
/** True when a component is being auto-added */
private static final short FLAG_AUTO = 0x0001;
/** True when a component is enabled for model updates and is reachable. */
private static final short FLAG_ENABLED = 0x0080;
/** Flag for escaping HTML in model strings */
private static final short FLAG_ESCAPE_MODEL_STRINGS = 0x0002;
/** Flag for Component holding root compound model */
private static final short FLAG_HAS_ROOT_MODEL = 0x0004;
/** Ignore attribute modifiers */
private static final short FLAG_IGNORE_ATTRIBUTE_MODIFIER = 0x0040;
/** boolean whether this component was rendered once for tracking changes. */
private static final short FLAG_IS_RENDERED_ONCE = 0x1000;
/** Render tag boolean */
private static final short FLAG_RENDER_BODY_ONLY = 0x0020;
/** Versioning boolean */
private static final short FLAG_VERSIONED = 0x0008;
/** Visibility boolean */
private static final short FLAG_VISIBLE = 0x0010;
/** Basic model IModelComparator implementation for normal object models */
private static final IModelComparator defaultModelComparator = new IModelComparator()
{
public boolean compare(Object a, Object b)
{
if (a == null && b == null)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return a.equals(b);
}
};
/** Log. */
private static Log log = LogFactory.getLog(Component.class);
/** List of behaviours to be applied for this Component */
private List behaviours = null;
/** Component flags. See FLAG_* for possible non-exclusive flag values. */
private short flags = FLAG_VISIBLE | FLAG_ESCAPE_MODEL_STRINGS | FLAG_VERSIONED | FLAG_ENABLED;
/** Component id. */
private String id;
/**
* The position within the markup stream, where the markup for the component
* begins. Compared to MarkupContainer's markupStream this is NOT just a
* temporary variable to render a page.
*/
private int markupStreamPosition = -1;
/** The model for this component. */
private IModel model;
/** Any parent container. */
private MarkupContainer parent;
/**
* Internal indicator of whether this component may be rendered given the
* current context's authorization. It overrides the visible flag in case
* this is false. Authorization is done before trying to render any
* component (otherwise we would end up with a half rendered page in the
* buffer), and as an optimization, the result for the current request is
* stored in this variable.
*/
private transient boolean renderAllowed = true;
/** True while rendering is in progress */
private transient boolean rendering;
/**
* Change record of a model.
*/
public class ComponentModelChange extends Change
{
private static final long serialVersionUID = 1L;
/** former model. */
private IModel model;
/**
* Construct.
*
* @param model
*/
public ComponentModelChange(IModel model)
{
super();
this.model = model;
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return "ComponentModelChange[component: " + getPath() + "]";
}
/**
* @see wicket.version.undo.Change#undo()
*/
public void undo()
{
setModel(this.model);
}
}
/**
* Generic component visitor interface for component traversals.
*/
public static interface IVisitor
{
/**
* Value to return to continue a traversal.
*/
public static final Object CONTINUE_TRAVERSAL = null;
/**
* A generic value to return to stop a traversal.
*/
public static final Object STOP_TRAVERSAL = new Object();
/**
* Called at each component in a traversal.
*
* @param component
* The component
* @return CONTINUE_TRAVERSAL (null) if the traversal should continue,
* or a non-null return value for the traversal method if it
* should stop. If no return value is useful, the generic
* non-null value STOP_TRAVERSAL can be used.
*/
public Object component(Component component);
}
/**
* A enabled change operation.
*/
protected final static class EnabledChange extends Change
{
private static final long serialVersionUID = 1L;
/** subject. */
private final Component component;
/** former value. */
private final boolean enabled;
/**
* Construct.
*
* @param component
*/
EnabledChange(final Component component)
{
this.component = component;
this.enabled = component.getFlag(FLAG_ENABLED);
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return "EnabledChange[component: " + component.getPath() + ",enabled: " + enabled + "]";
}
/**
* @see wicket.version.undo.Change#undo()
*/
public void undo()
{
component.setEnabled(enabled);
}
}
/**
* A visibility change operation.
*/
protected final static class VisibilityChange extends Change
{
private static final long serialVersionUID = 1L;
/** subject. */
private final Component component;
/** former value. */
private final boolean visible;
/**
* Construct.
*
* @param component
*/
VisibilityChange(final Component component)
{
this.component = component;
this.visible = component.getFlag(FLAG_VISIBLE);
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return "VisibilityChange[component: " + component.getPath() + ", visible: " + visible
+ "]";
}
/**
* @see wicket.version.undo.Change#undo()
*/
public void undo()
{
component.setVisible(visible);
}
}
/**
* Constructor. All components have names. A component's id cannot be null.
* This is the minimal constructor of component. It does not register a
* model.
*
* @param id
* The non-null id of this component
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id)
{
checkAuthorization();
setId(id);
}
/**
* Constructor. All components have names. A component's id cannot be null.
* This is constructor includes a model.
*
* @param id
* The non-null id of this component
* @param model
* The component's model
*
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id, final IModel model)
{
checkAuthorization();
setId(id);
setModel(model);
}
/**
* Adds an behaviour modifier to the component.
*
* @param behaviour
* The behaviour modifier to be added
* @return this (to allow method call chaining)
*/
public final Component add(final IBehavior behaviour)
{
if (behaviour == null)
{
throw new IllegalArgumentException("Argument may not be null");
}
// Lazy create
if (behaviours == null)
{
behaviours = new ArrayList(1);
}
behaviours.add(behaviour);
// Give handler the opportunity to bind this component
behaviour.bind(this);
return this;
}
/**
* Registers a debug message for this component
*
* @param message
* The message
*/
public final void debug(final String message)
{
getPage().getFeedbackMessages().debug(this, message);
}
/**
* Detaches all models
*/
public void detachModels()
{
// Detach any detachable model from this component
detachModel();
// Also detach models from any contained attribute modifiers
if (behaviours != null)
{
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
IBehavior behaviour = (IBehavior)i.next();
behaviour.detachModel();
}
}
}
/**
* Page.doRender() is used to render a whole page. With AJAX however it must
* be possible to re-render anyone component contained in a page. That is
* what Component.doRender() is for.
*/
public void doRender()
{
// Save the parent's markup stream to re-assign it at the end
MarkupContainer parent = getParent();
MarkupStream originalMarkupStream = parent.getMarkupStream();
// Get the parent's associated markup stream.
MarkupStream markupStream = findParentWithAssociatedMarkup().getAssociatedMarkupStream();
// Make sure the markup stream is position at the correct element
markupStream.setCurrentIndex(this.markupStreamPosition);
try
{
// Make sure that while rendering the markup stream is found
parent.setMarkupStream(markupStream);
// Render the component and all its children
internalBeginRequest();
render();
}
finally
{
// Make sure the original markup stream is back in place
parent.setMarkupStream(originalMarkupStream);
}
}
/**
* Registers an error message for this component
*
* @param message
* The message
*/
public final void error(final String message)
{
getPage().getFeedbackMessages().error(this, message);
}
/**
* Registers an fatal error message for this component
*
* @param message
* The message
*/
public final void fatal(final String message)
{
getPage().getFeedbackMessages().fatal(this, message);
}
/**
* Finds the first container parent of this component of the given class.
*
* @param c
* MarkupContainer class to search for
* @return First container parent that is an instance of the given class, or
* null if none can be found
*/
public final MarkupContainer findParent(final Class c)
{
// Start with immediate parent
MarkupContainer current = parent;
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
return current;
}
// Check parent
current = current.getParent();
}
// Failed to find component
return null;
}
/**
* @return The nearest markup container with associated markup
*/
public final MarkupContainer findParentWithAssociatedMarkup()
{
MarkupContainer container = parent;
while (container != null)
{
if (container.hasAssociatedMarkup())
{
return container;
}
container = container.getParent();
}
// This should never happen since Page always has associated markup
throw new WicketRuntimeException("Unable to find parent with associated markup");
}
/**
* Gets interface to application that this component is a part of.
*
* @return The application associated with the session that this component
* is in.
* @see Application
*/
public final Application getApplication()
{
return Application.get();
}
/**
* Gets the application pages from the application that this component
* belongs to.
*
* @return The application pages
* @see IRequiredPageSettings
*/
public final IRequiredPageSettings getApplicationPages()
{
return getApplication().getRequiredPageSettings();
}
/**
* This method has been deprecated in favor of
* Application.get().getXXXSettings()
*
* Gets the application settings from the application that this component
* belongs to.
*
* @return The application settings from the application that this component
* belongs to
* @see Settings
* @deprecated
*
*/
// TODO remove this method in wicket post 1.2
public final Settings getApplicationSettings()
{
return getApplication().getSettings();
}
/**
* @return A path of the form <page-class-name>. <page-relative-path>
* @see Component#getPageRelativePath()
*/
public final String getClassRelativePath()
{
return getClass().getName() + "." + getPageRelativePath();
}
/**
* Gets the converter that should be used by this component.
*
* @return The converter that should be used by this component
*/
public IConverter getConverter()
{
return getSession().getConverter();
}
/**
* Gets whether model strings should be escaped.
*
* @return Returns whether model strings should be escaped
*/
public final boolean getEscapeModelStrings()
{
return getFlag(FLAG_ESCAPE_MODEL_STRINGS);
}
/**
* @return Any feedback message for this component
*/
public final FeedbackMessage getFeedbackMessage()
{
return getPage().getFeedbackMessages().messageForComponent(this);
}
/**
* Gets the id of this component.
*
* @return The id of this component
*/
public String getId()
{
return id;
}
/**
* Gets the locale for the session holding this component.
*
* @return The locale for the session holding this component
* @see Component#getSession()
*/
public final Locale getLocale()
{
return getSession().getLocale();
}
/**
* Convenience method to provide easy access to the localizer object within
* any component.
*
* @return The localizer object
*/
public final Localizer getLocalizer()
{
return getApplication().getMarkupSettings().getLocalizer();
}
/**
* Gets metadata for this component using the given key.
*
* @param key
* The key for the data
* @return The metadata
* @see MetaDataKey
*/
public final Serializable getMetaData(final MetaDataKey key)
{
return getPage().getMetaData(this, key);
}
/**
* Gets the model. It returns the object that wraps the backing model.
*
* @return The model
*/
public IModel getModel()
{
// If model is null
if (model == null)
{
// give subclass a chance to lazy-init model
this.model = initModel();
}
return model;
}
/**
* Gets the backing model object; this is shorthand for
* getModel().getObject().
*
* @return the backing model object
*/
public final Object getModelObject()
{
final IModel model = getModel();
if (model != null)
{
// If this component has the root model for a compound model
if (getFlag(FLAG_HAS_ROOT_MODEL))
{
// we need to return the root model and not a property of the
// model
return getRootModel(model).getObject(null);
}
// Get model value for this component
return model.getObject(this);
}
else
{
return null;
}
}
/**
* Gets a model object as a string.
*
* @return Model object for this component as a string
*/
public final String getModelObjectAsString()
{
final Object modelObject = getModelObject();
if (modelObject != null)
{
// Get converter
final IConverter converter = getConverter();
// Model string from property
final String modelString = (String)converter.convert(modelObject, String.class);
// If we should escape the markup
if (getFlag(FLAG_ESCAPE_MODEL_STRINGS))
{
// Escape it
return Strings.escapeMarkup(modelString);
}
return modelString;
}
return "";
}
/**
* Gets the page holding this component.
*
* @return The page holding this component
*/
public final Page getPage()
{
// Search for nearest Page
final Page page = findPage();
// If no Page was found
if (page == null)
{
// Give up with a nice exception
throw new IllegalStateException("No Page found for component " + this);
}
return page;
}
/**
* @return The page factory for the session that this component is in
*/
public final IPageFactory getPageFactory()
{
return getSession().getPageFactory();
}
/**
* Gets the path to this component relative to the page it is in.
*
* @return The path to this component relative to the page it is in
*/
public final String getPageRelativePath()
{
return Strings.afterFirstPathComponent(getPath(), ':');
}
/**
* Gets any parent container, or null if there is none.
*
* @return Any parent container, or null if there is none
*/
public final MarkupContainer getParent()
{
return parent;
}
/**
* Gets the components' path.
*
* @return Dotted path to this component in the component hierarchy
*/
public final String getPath()
{
final StringBuffer buffer = new StringBuffer();
for (Component c = this; c != null; c = c.getParent())
{
if (buffer.length() > 0)
{
buffer.insert(0, ':');
}
buffer.insert(0, c.getId());
}
return buffer.toString();
}
/**
* If false the component's tag will be printed as well as its body (which
* is default). If true only the body will be printed, but not the
* component's tag.
*
* @return If true, the component tag will not be printed
*/
public final boolean getRenderBodyOnly()
{
return getFlag(FLAG_RENDER_BODY_ONLY);
}
/**
* @return The request for this component's active request cycle
*/
public final Request getRequest()
{
return getRequestCycle().getRequest();
}
/**
* Gets the active request cycle for this component
*
* @return The request cycle
*/
public final RequestCycle getRequestCycle()
{
return RequestCycle.get();
}
/**
* @return The shared resource for this component
*/
public final Resource getResource()
{
return getApplication().getSharedResources().get(Application.class, getId(), getLocale(),
getStyle(), false);
}
/**
* @return The response for this component's active request cycle
*/
public final Response getResponse()
{
return getRequestCycle().getResponse();
}
/**
* Gets the current session object. Although this method is not final
* (because Page overrides it), it is not intended to be overridden by
* clients and clients of the framework should not do so!
*
* @return The session that this component is in
*/
public final Session getSession()
{
return Session.get();
}
/**
* @param key
* Key of string resource in property file
* @return The String
* @see Localizer
*/
public final String getString(final String key)
{
return getString(key, getModel());
}
/**
* @param key
* The resource key
* @param model
* The model
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel model)
{
return getLocalizer().getString(key, this, model);
}
/**
* @param key
* The resource key
* @param model
* The model
* @param defaultValue
* A default value if the string cannot be found
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel model, final String defaultValue)
{
return getLocalizer().getString(key, this, model, defaultValue);
}
/**
* Gets the style of this component (see {@link wicket.Session}).
*
* @return The style of this component.
*
* @see wicket.Session
* @see wicket.Session#getStyle()
*/
public final String getStyle()
{
String variation = getVariation();
String style = getSession().getStyle();
if (variation != null && !"".equals(variation))
{
if (style != null && !"".equals(style))
{
style = variation + "_" + style;
}
else
{
style = variation;
}
}
return style;
}
/**
* Gets the variation string of this component that will be used to look up
* markup for this component. Subclasses can override this method to define
* by an instance what markup variation should be picked up. By default it
* will return null.
*
* @return The variation of this component.
*
*/
public String getVariation()
{
return null;
}
/**
* @return True if this component has an error message
*/
public final boolean hasErrorMessage()
{
return getPage().getFeedbackMessages().hasErrorMessageFor(this);
}
/**
* @return True if this component has some kind of feedback message
*/
public final boolean hasFeedbackMessage()
{
return getPage().getFeedbackMessages().hasMessageFor(this);
}
/**
* Registers a info message for this component
*
* @param message
* The message
*/
public final void info(final String message)
{
getPage().getFeedbackMessages().info(this, message);
}
/**
* Returns true if this component is an ancestor of the given component
*
* @param component
* The component to check
* @return True if the given component has this component as an ancestor
*/
public final boolean isAncestorOf(final Component component)
{
// Walk up containment hierarchy
for (MarkupContainer current = component.parent; current != null; current = current
.getParent())
{
// Is this an ancestor?
if (current == this)
{
return true;
}
}
// This component is not an ancestor of the given component
return false;
}
/**
* Gets whether this component is enabled. Specific components may decide to
* implement special behaviour that uses this property, like web form
* components that add a disabled='disabled' attribute when enabled is
* false.
*
* @return whether this component is enabled.
*/
public boolean isEnabled()
{
return getFlag(FLAG_ENABLED);
}
/**
* @return Returns the isVersioned.
*/
public boolean isVersioned()
{
// Is the component itself versioned?
if (!getFlag(FLAG_VERSIONED) || (!getFlag(FLAG_IS_RENDERED_ONCE)))
{
return false;
}
else
{
// If there's a parent and this component is versioned
if (parent != null)
{
// Check if the parent is unversioned. If any parent
// (recursively) is unversioned, then this component is too
if (!parent.isVersioned())
{
return false;
}
}
return true;
}
}
/**
* Gets whether this component and any children are visible.
*
* @return True if component and any children are visible
*/
public boolean isVisible()
{
return getFlag(FLAG_VISIBLE);
}
/**
* Checks if the component itself and all its parents are visible.
*
* @return true if the component and all its parents are visible.
*/
public final boolean isVisibleInHierarchy()
{
Component component = this;
while (component != null)
{
if (renderAllowed && component.isVisible())
{
component = component.getParent();
}
else
{
return false;
}
}
return true;
}
/**
* Called to indicate that the model content for this component has been
* changed
*/
public final void modelChanged()
{
// Call user code
internalOnModelChanged();
onModelChanged();
}
/**
* Called to indicate that the model content for this component is about to
* change
*/
public final void modelChanging()
{
// Call user code
onModelChanging();
// Tell the page that our model changed
final Page page = findPage();
if (page != null)
{
page.componentModelChanging(this);
}
}
/**
* Creates a new page using the component's page factory
*
* @param c
* The class of page to create
* @return The new page
*/
public final Page newPage(final Class c)
{
return getPageFactory().newPage(c);
}
/**
* Creates a new page using the component's page factory
*
* @param c
* The class of page to create
* @param parameters
* Any parameters to pass to the constructor
* @return The new page
*/
public final Page newPage(final Class c, final PageParameters parameters)
{
return getPageFactory().newPage(c, parameters);
}
/**
* Component has to implement {@link IBehaviorListener} to be able to pass
* through events to behaviours without ending up with many if/else blocks.
*
* @see wicket.behavior.IBehaviorListener#onRequest()
*/
public void onRequest()
{
String id = getRequest().getParameter("behaviourId");
if (id == null)
{
throw new WicketRuntimeException(
"parameter behaviourId was not provided: unable to locate listener");
}
int idAsInt = Integer.parseInt(id);
IBehaviorListener behaviourListener = (IBehaviorListener)behaviours.get(idAsInt);
if (behaviourListener == null)
{
throw new WicketRuntimeException("no behaviour listener found with behaviourId " + id);
}
behaviourListener.onRequest();
}
/**
* Removes this component from its parent. It's important to remember that a
* component that is removed cannot be referenced from the markup still.
*/
public final void remove()
{
if (parent == null)
{
throw new IllegalStateException("cannot remove " + this + " from null parent!");
}
parent.remove(this);
}
/**
* Performs a render of this component as part of a Page level render
* process.
* <p>
* For component level re-render (e.g. AJAX) please call
* Component.doRender(). Though render() does seem to work, it will fail for
* panel children.
*/
public final void render()
{
setFlag(FLAG_IS_RENDERED_ONCE, true);
rendering = true;
try
{
// Determine if component is visible using it's authorization status
// and the isVisible property.
if (renderAllowed && isVisible())
{
// Rendering is beginning
if (log.isDebugEnabled())
{
log.debug("Begin render " + this);
}
// Call implementation to render component
onRender();
// Component has been rendered
rendered();
if (log.isDebugEnabled())
{
log.debug("End render " + this);
}
}
else
{
findMarkupStream().skipComponent();
}
}
finally
{
rendering = false;
}
}
/**
* THIS IS PART OF WICKETS INTERNAL API. DO NOT RELY ON IT WITHIN YOUR CODE.
* <p>
* Renders the component at the current position in the given markup stream.
* The method onComponentTag() is called to allow the component to mutate
* the start tag. The method onComponentTagBody() is then called to permit
* the component to render its body.
*
* @param markupStream
* The markup stream
*/
public final void renderComponent(final MarkupStream markupStream)
{
// If yet unknown, set the markup stream position with the current
// position of markupStream. Else set the
// markupStream.setCurrentPosition
// based on the position already known to the component.
validateMarkupStream(markupStream);
// Get mutable copy of next tag
final ComponentTag openTag = markupStream.getTag();
final ComponentTag tag = openTag.mutable();
// Call any tag handler
onComponentTag(tag);
// If we're an openclose tag
if (!tag.isOpenClose() && !tag.isOpen())
{
// We were something other than <tag> or <tag/>
markupStream
.throwMarkupException("Method renderComponent called on bad markup element: "
+ tag);
}
if (tag.isOpenClose() && openTag.isOpen())
{
markupStream
.throwMarkupException("You can not modify a open tag to open-close: " + tag);
}
// Render open tag
if (getRenderBodyOnly() == false)
{
renderComponentTag(tag);
}
markupStream.next();
// Render the body only if open-body-close. Do not render if open-close.
if (tag.isOpen())
{
// Render the body
onComponentTagBody(markupStream, tag);
}
// Render close tag
if (tag.isOpen())
{
if (openTag.isOpen())
{
renderClosingComponentTag(markupStream, tag, getRenderBodyOnly());
}
else
{
// If a open-close tag has been to modified to be
// open-body-close than a synthetic close tag must be rendered.
if (getRenderBodyOnly() == false)
{
// Close the manually opened panel tag.
getResponse().write(openTag.syntheticCloseTagString());
}
}
}
}
/**
* Called to indicate that a component has been rendered. This method should
* only very rarely be called at all. One usage is in ImageMap, which
* renders its link children its own special way (without calling render()
* on them). If ImageMap did not call rendered() to indicate that its child
* components were actually rendered, the framework would think they had
* never been rendered, and in development mode this would result in a
* runtime exception.
*/
public final void rendered()
{
// Tell the page that the component rendered
getPage().componentRendered(this);
if (behaviours != null)
{
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
IBehavior behaviour = (IBehavior)i.next();
behaviour.rendered(this);
}
}
}
/**
* @param component
* The component to compare with
* @return True if the given component's model is the same as this
* component's model.
*/
public final boolean sameRootModel(final Component component)
{
return sameRootModel(component.getModel());
}
/**
* @param model
* The model to compare with
* @return True if the given component's model is the same as this
* component's model.
*/
public final boolean sameRootModel(final IModel model)
{
// Get the two models
IModel thisModel = getModel();
IModel thatModel = model;
// If both models are non-null they could be the same
if (thisModel != null && thatModel != null)
{
return getRootModel(thisModel) == getRootModel(thatModel);
}
return false;
}
/**
* Sets whether this component is enabled. Specific components may decide to
* implement special behaviour that uses this property, like web form
* components that add a disabled='disabled' attribute when enabled is
* false. If it is not enabled, it will not be allowed to call any listener
* method on it (e.g. Link.onClick) and the model object will be protected
* (for the common use cases, not for programmer's misuse)
*
* @param enabled
* whether this component is enabled
* @return This
*/
public final Component setEnabled(final boolean enabled)
{
// Is new enabled state a change?
if (enabled != getFlag(FLAG_ENABLED))
{
// TODO we can't record any state change as Link.onComponentTag
// potentially sets this property we probably don't need to support
// this, but I'll keep this commented so that we can think about it
// I (johan) changed the way Link.onComponentTag works. It will
// disable versioning for a the setEnabled call.
// Tell the page that this component's enabled was changed
if (isVersioned())
{
final Page page = findPage();
if (page != null)
{
addStateChange(new EnabledChange(this));
}
}
// Change visibility
setFlag(FLAG_ENABLED, enabled);
}
return this;
}
/**
* Sets whether model strings should be escaped.
*
* @param escapeMarkup
* True is model strings should be escaped
* @return This
*/
public final Component setEscapeModelStrings(final boolean escapeMarkup)
{
setFlag(FLAG_ESCAPE_MODEL_STRINGS, escapeMarkup);
return this;
}
/**
* Sets the metadata for this component using the given key. If the metadata
* object is not of the correct type for the metadata key, an
* IllegalArgumentException will be thrown. For information on creating
* MetaDataKeys, see {@link MetaDataKey}.
*
* @param key
* The singleton key for the metadata
* @param object
* The metadata object
* @throws IllegalArgumentException
* @see MetaDataKey
*/
public final void setMetaData(final MetaDataKey key, final Serializable object)
{
getPage().setMetaData(this, key, object);
}
/**
* Sets the given model.
* <p>
* WARNING: DO NOT OVERRIDE THIS METHOD UNLESS YOU HAVE A VERY GOOD REASON
* FOR IT. OVERRIDING THIS MIGHT OPEN UP SECURITY LEAKS AND BROKEN
* BACK-BUTTON SUPPORT.
* </p>
*
* @param model
* the model
* @return This
*/
public Component setModel(final IModel model)
{
// Detach current model
if (this.model != null)
{
this.model.detach();
}
// Change model
if (this.model != model)
{
addStateChange(new ComponentModelChange(this.model));
this.model = model;
}
// If a compound model is explicitly set on this component
if (model instanceof ICompoundModel)
{
// we need to remember this for getModelObject()
setFlag(FLAG_HAS_ROOT_MODEL, true);
}
modelChanged();
return this;
}
/**
* Sets the backing model object; shorthand for
* getModel().setObject(object).
*
* @param object
* The object to set
* @return This
*/
public final Component setModelObject(final Object object)
{
final IModel model = getModel();
// Check whether anything can be set at all
if (model == null)
{
throw new IllegalStateException(
"Attempt to set model object on null model of component: "
+ getPageRelativePath());
}
// Check authorization
if (!getApplication().getSecuritySettings().getAuthorizationStrategy().allowEnabledState(
this))
{
throw new UnauthorizedEnabledStateException(
"operation not allowed in the current authorization context");
}
// Check whether this will result in an actual change
final Object current = model.getObject(this);
if (!getModelComparator().compare(current, object))
{
modelChanging();
if (getFlag(FLAG_HAS_ROOT_MODEL))
{
getRootModel(model).setObject(null, object);
}
else
{
model.setObject(this, object);
}
modelChanged();
}
return this;
}
/**
* @param redirect
* True if the response should be redirected to
* @see RequestCycle#setRedirect(boolean)
*/
public final void setRedirect(final boolean redirect)
{
getRequestCycle().setRedirect(redirect);
}
/**
* If false the component's tag will be printed as well as its body (which
* is default). If true only the body will be printed, but not the
* component's tag.
*
* @param renderTag
* If true, the component tag will not be printed
* @return This
*/
public final Component setRenderBodyOnly(final boolean renderTag)
{
this.setFlag(FLAG_RENDER_BODY_ONLY, renderTag);
return this;
}
/**
* THIS IS PART OF WICKETS INTERNAL API. DO NOT RELY ON IT WITHIN YOUR CODE.
* <p>
*
* @param b
* Boolean to set the rendering
* @return the previous value of the rendering.
*/
public final boolean setRendering(boolean b)
{
boolean tmp = rendering;
rendering = b;
return tmp;
}
/**
* Sets the page that will respond to this request
*
* @param cls
* The response page class
* @see RequestCycle#setResponsePage(Class)
*/
public final void setResponsePage(final Class cls)
{
getRequestCycle().setResponsePage(cls);
}
/**
* Sets the page class and its parameters that will respond to this request
*
* @param cls
* The response page class
* @param parameters
* The parameters for thsi bookmarkable page.
* @see RequestCycle#setResponsePage(Class, PageParameters)
*/
public final void setResponsePage(final Class cls, PageParameters parameters)
{
getRequestCycle().setResponsePage(cls, parameters);
}
/**
* Sets the page that will respond to this request
*
* @param page
* The response page
* @see RequestCycle#setResponsePage(Page)
*/
public final void setResponsePage(final Page page)
{
getRequestCycle().setResponsePage(page);
}
/**
* @param versioned
* True to turn on versioning for this component, false to turn
* it off for this component and any children.
* @return This
*/
public Component setVersioned(boolean versioned)
{
setFlag(FLAG_VERSIONED, versioned);
return this;
}
/**
* Sets whether this component and any children are visible.
*
* @param visible
* True if this component and any children should be visible
* @return This
*/
public final Component setVisible(final boolean visible)
{
// Is new visibility state a change?
if (visible != getFlag(FLAG_VISIBLE))
{
// Tell the page that this component's visibility was changed
final Page page = findPage();
if (page != null)
{
addStateChange(new VisibilityChange(this));
}
// Change visibility
setFlag(FLAG_VISIBLE, visible);
}
return this;
}
/**
* Gets the string representation of this component.
*
* @return The path to this component
*/
public String toString()
{
return toString(true);
}
/**
* @param detailed
* True if a detailed string is desired
* @return The string
*/
public String toString(final boolean detailed)
{
if (detailed)
{
final Page page = findPage();
if (page == null)
{
return new StringBuffer("[Component id = ").append(getId()).append(
", page = <No Page>, path = ").append(getPath()).append(".").append(
Classes.name(getClass())).append("]").toString();
}
else
{
return new StringBuffer("[Component id = ").append(getId()).append(", page = ")
.append(getPage().getClass().getName()).append(", path = ").append(
getPath()).append(".").append(Classes.name(getClass())).append(
", isVisible = ").append((renderAllowed && isVisible())).append(
", isVersioned = ").append(isVersioned()).append("]").toString();
}
}
else
{
return "[Component id = " + getId() + "]";
}
}
/**
* Gets the url for the listener interface (e.g. ILinkListener).
*
* @param listenerInterface
* The listener interface that the URL should call
* @return The URL
* @see Page#urlFor(Component, Class)
*/
public final String urlFor(final Class listenerInterface)
{
return getPage().urlFor(this, listenerInterface);
}
/**
* Gets the url for the provided behaviour listener.
*
* @param behaviourListener
* the behaviour listener to get the url for
* @return The URL
* @see Page#urlFor(Component, Class)
*/
public final String urlFor(final IBehaviorListener behaviourListener)
{
if (behaviourListener == null)
{
throw new IllegalArgumentException("Argument behaviourListener must be not null");
}
if (behaviours == null)
{
throw new IllegalArgumentException("behaviourListener " + behaviourListener
+ " was not registered with this component");
}
int index = behaviours.indexOf(behaviourListener);
if (index == -1)
{
throw new IllegalArgumentException("behaviourListener " + behaviourListener
+ " was not registered with this component");
}
return urlFor(IBehaviorListener.class) + "&behaviourId=" + index;
}
/**
* Registers a warning message for this component.
*
* @param message
* The message
*/
public final void warn(final String message)
{
getPage().getFeedbackMessages().warn(this, message);
}
/**
* Adds state change to page.
*
* @param change
* The change
*/
protected final void addStateChange(Change change)
{
Page page = findPage();
if (page != null)
{
page.componentStateChanging(this, change);
}
}
/**
* Checks whether the given type has the expected name.
*
* @param tag
* The tag to check
* @param name
* The expected tag name
* @throws MarkupException
* Thrown if the tag is not of the right name
*/
protected final void checkComponentTag(final ComponentTag tag, final String name)
{
if (!tag.getName().equalsIgnoreCase(name))
{
findMarkupStream().throwMarkupException(
"Component " + getId() + " must be applied to a tag of type '" + name
+ "', not " + tag.toUserDebugString());
}
}
/**
* Checks that a given tag has a required attribute value.
*
* @param tag
* The tag
* @param key
* The attribute key
* @param value
* The required value for the attribute key
* @throws MarkupException
* Thrown if the tag does not have the required attribute value
*/
protected final void checkComponentTagAttribute(final ComponentTag tag, final String key,
final String value)
{
if (key != null)
{
final String tagAttributeValue = tag.getAttributes().getString(key);
if (tagAttributeValue == null || !value.equalsIgnoreCase(tagAttributeValue))
{
findMarkupStream().throwMarkupException(
"Component " + getId() + " must be applied to a tag with '" + key
+ "' attribute matching '" + value + "', not '" + tagAttributeValue
+ "'");
}
}
}
/**
* Detaches the model for this component if it is detachable.
*/
protected void detachModel()
{
// If the model is compound and it's not the root model, then it can
// be reconstituted via initModel() after replication
if (model instanceof CompoundPropertyModel && !getFlag(FLAG_HAS_ROOT_MODEL))
{
// Get rid of model which can be lazy-initialized again
this.model = null;
}
else
{
if (model != null)
{
model.detach();
}
}
}
/**
* Prefixes an exception message with useful information about this.
* component.
*
* @param message
* The message
* @return The modified message
*/
protected final String exceptionMessage(final String message)
{
return message + ":\n" + toString();
}
/**
* Finds the markup stream for this component.
*
* @return The markup stream for this component. Since a Component cannot
* have a markup stream, we ask this component's parent to search
* for it.
*/
protected MarkupStream findMarkupStream()
{
if (parent == null)
{
throw new IllegalStateException("cannot find markupstream for " + this
+ " as there is no parent");
}
return parent.findMarkupStream();
}
/**
* If this Component is a Page, returns self. Otherwise, searches for the
* nearest Page parent in the component hierarchy. If no Page parent can be
* found, null is returned.
*
* @return The Page or null if none can be found
*/
protected final Page findPage()
{
// Search for page
return (Page)(this instanceof Page ? this : findParent(Page.class));
}
/**
* Gets the currently coupled {@link IBehavior}s as a unmodifiable list.
* Returns an empty list rather than null if there are no behaviours coupled
* to this component.
*
* @return the currently coupled behaviours as a unmodifiable list
*/
protected final List/* <IBehavior> */getBehaviours()
{
if (behaviours == null)
{
return Collections.EMPTY_LIST;
}
return Collections.unmodifiableList(behaviours);
}
/**
* Gets the subset of the currently coupled {@link IBehavior}s that are of
* the provided type as a unmodifiable list or null if there are no
* behaviours attached. Returns an empty list rather than null if there are
* no behaviours coupled to this component.
*
* @param type
* the type
*
* @return the subset of the currently coupled behaviours that are of the
* provided type as a unmodifiable list or null
*/
protected final List/* <IBehavior> */getBehaviours(Class type)
{
if (behaviours == null)
{
return Collections.EMPTY_LIST;
}
List subset = new ArrayList(behaviours.size()); // avoid growing
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
Object behaviour = i.next();
if (type.isAssignableFrom(behaviour.getClass()))
{
subset.add(behaviour);
}
}
return Collections.unmodifiableList(subset);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to test
* @return True if the flag is set
*/
protected final boolean getFlag(final short flag)
{
return (this.flags & flag) != 0;
}
/**
* Gets the value defaultModelComparator. Implementations of this interface
* can be used in the Component.getComparator() for testing the current
* value of the components model data with the new value that is given.
*
* @return the value defaultModelComparator
*/
protected IModelComparator getModelComparator()
{
return defaultModelComparator;
}
/**
* Called when a null model is about to be retrieved in order to allow a
* subclass to provide an initial model. This gives FormComponent, for
* example, an opportunity to instantiate a model on the fly using the
* containing Form's model.
*
* @return The model
*/
protected IModel initModel()
{
// Search parents for CompoundPropertyModel
for (Component current = getParent(); current != null; current = current.getParent())
{
// Get model
final IModel model = current.getModel();
if (model instanceof ICompoundModel)
{
// we turn off versioning as we share the model with another
// component that is the owner of the model (that component
// has to decide whether to version or not
setVersioned(false);
// return the shared compound model
return model;
}
}
// No model for this component!
return null;
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request begins.
*/
protected void internalBeginRequest()
{
onBeginRequest();
internalOnBeginRequest();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request ends.
*/
protected void internalEndRequest()
{
internalOnEndRequest();
onEndRequest();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request begins.
*/
protected void internalOnBeginRequest()
{
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called when a request ends.
*/
protected void internalOnEndRequest()
{
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR
* OVERRIDE.
*
* Called anytime a model is changed via setModel or setModelObject.
*/
protected void internalOnModelChanged()
{
}
/**
* Components are allowed to reject behaviour modifiers.
*
* @param behaviour
* @return false, if the component should not apply this behaviour
*/
protected boolean isBehaviourAccepted(final IBehavior behaviour)
{
// Ignore AttributeModifiers when FLAG_IGNORE_ATTRIBUTE_MODIFIER is set
if ((behaviour instanceof AttributeModifier)
&& (getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER) != false))
{
return false;
}
return true;
}
/**
* If true, all attribute modifiers will be ignored
*
* @return True, if attribute modifiers are to be ignored
*/
protected final boolean isIgnoreAttributeModifier()
{
return this.getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER);
}
/**
* Invalidates the markupstream position, called when the markup did change
*/
protected final void markStreamPositionInvalid()
{
markupStreamPosition = -1;
}
/**
* Called when a request begins.
*/
protected void onBeginRequest()
{
}
/**
* Processes the component tag.
*
* @param tag
* Tag to modify
*/
protected void onComponentTag(final ComponentTag tag)
{
}
/**
* Processes the body.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
}
/**
* Called when a request ends.
*/
protected void onEndRequest()
{
}
/**
* Called anytime a model is changed after the change has occurred
*/
protected void onModelChanged()
{
}
/**
* Called anytime a model is changed, but before the change actually occurs
*/
protected void onModelChanging()
{
}
/**
* Implementation that renders this component.
*/
protected abstract void onRender();
/**
* Writes a simple tag out to the response stream. Any components that might
* be referenced by the tag are ignored. Also undertakes any tag attribute
* modifications if they have been added to the component.
*
* @param tag
* The tag to write
*/
protected final void renderComponentTag(ComponentTag tag)
{
final boolean stripWicketTags = Application.get().getMarkupSettings().getStripWicketTags();
if (!(tag instanceof WicketTag) || !stripWicketTags)
{
// Apply behaviour modifiers
if ((behaviours != null) && !behaviours.isEmpty() && !tag.isClose()
&& (isIgnoreAttributeModifier() == false))
{
tag = tag.mutable();
for (Iterator i = behaviours.iterator(); i.hasNext();)
{
IBehavior behaviour = (IBehavior)i.next();
// components may reject some behaviour components
if (isBehaviourAccepted(behaviour))
{
behaviour.onComponentTag(this, tag);
}
}
}
// Write the tag
tag.writeOutput(getResponse(), stripWicketTags, this.findMarkupStream()
.getWicketNamespace());
}
}
/**
* Replaces the body with the given one.
*
* @param markupStream
* The markup stream to replace the tag body in
* @param tag
* The tag
* @param body
* The new markup
*/
protected final void replaceComponentTagBody(final MarkupStream markupStream,
final ComponentTag tag, final String body)
{
// If tag has body
if (tag.isOpen())
{
// skip any raw markup in the body
markupStream.skipRawMarkup();
}
// Write the new body
getResponse().write(body);
// If we had an open tag (and not an openclose tag) and we found a
// close tag, we're good
if (tag.isOpen())
{
// Open tag must have close tag
if (!markupStream.atCloseTag())
{
// There must be a component in this discarded body
markupStream
.throwMarkupException("Expected close tag. Possible attempt to embed component(s) "
+ "in the body of a component which discards its body");
}
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to set
* @param set
* True to turn the flag on, false to turn it off
*/
protected final void setFlag(final short flag, final boolean set)
{
if (set)
{
this.flags |= flag;
}
else
{
this.flags &= ~flag;
}
}
/**
* If true, all attribute modifiers will be ignored
*
* @param ignore
* If true, all attribute modifiers will be ignored
* @return This
*/
protected final Component setIgnoreAttributeModifier(final boolean ignore)
{
this.setFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER, ignore);
return this;
}
/**
* If yet unknown, set the markup stream position with the current position
* of markupStream. Else set the markupStream.setCurrentPosition based the
* position already known to the component.
* <p>
* Note: Parameter markupStream.getCurrentPosition() will be updated, if
* re-render is allowed.
*
* @param markupStream
*/
protected final void validateMarkupStream(final MarkupStream markupStream)
{
// Allow the component to be re-rendered without a page. Partial
// re-rendering is a requirement of AJAX.
final Component parent = getParent();
if (this.isAuto() || (parent != null && parent.isRendering()))
{
// Remember the position while rendering the component the first
// time
this.markupStreamPosition = markupStream.getCurrentIndex();
}
else if (this.markupStreamPosition < 0)
{
throw new WicketRuntimeException(
"The markup stream of the component should be known by now, but isn't: "
+ this.toString());
}
else
{
// Re-set the markups index to the beginning of the component tag
markupStream.setCurrentIndex(this.markupStreamPosition);
}
}
/**
* Visits the parents of this component.
*
* @param c
* Class
* @param visitor
* The visitor to call at each parent of the given type
* @return First non-null value returned by visitor callback
*/
protected final Object visitParents(final Class c, final IVisitor visitor)
{
// Start here
Component current = this;
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
final Object object = visitor.component(current);
if (object != IVisitor.CONTINUE_TRAVERSAL)
{
return object;
}
}
// Check parent
current = current.getParent();
}
return null;
}
/**
* Gets the component at the given path.
*
* @param path
* Path to component
* @return The component at the path
*/
Component get(final String path)
{
// Path to this component is an empty path
if (path.equals(""))
{
return this;
}
throw new IllegalArgumentException(
exceptionMessage("Component is not a container and so does not contain the path "
+ path));
}
/**
* @return True if this component or any of its parents is in auto-add mode
*/
final boolean isAuto()
{
// Search up hierarchy for FLAG_AUTO
for (Component current = this; current != null; current = current.getParent())
{
if (current.getFlag(FLAG_AUTO))
{
return true;
}
}
return false;
}
/**
* Renders the close tag at the current position in the markup stream.
*
* @param markupStream
* the markup stream
* @param openTag
* the tag to render
* @param renderTagOnly
* if true, the tag will not be written to the output
*/
final void renderClosingComponentTag(final MarkupStream markupStream,
final ComponentTag openTag, final boolean renderTagOnly)
{
// Tag should be open tag and not openclose tag
if (openTag.isOpen())
{
// If we found a close tag and it closes the open tag, we're good
if (markupStream.atCloseTag() && markupStream.getTag().closes(openTag))
{
// Get the close tag from the stream
ComponentTag closeTag = markupStream.getTag();
// If the open tag had its id changed
if (openTag.getNameChanged())
{
// change the id of the close tag
closeTag = closeTag.mutable();
closeTag.setName(openTag.getName());
}
// Render the close tag
if (renderTagOnly == false)
{
renderComponentTag(closeTag);
}
markupStream.next();
}
else
{
if (openTag.requiresCloseTag())
{
// Missing close tag
markupStream.throwMarkupException("Expected close tag for " + openTag);
}
}
}
}
/**
* @param auto
* True to put component into auto-add mode
*/
final void setAuto(final boolean auto)
{
setFlag(FLAG_AUTO, auto);
}
/**
* Sets the id of this component. This method is private because the only
* time a component's id can be set is in its constructor.
*
* @param id
* The non-null id of this component
*/
final void setId(final String id)
{
if (id == null && !(this instanceof Page))
{
throw new WicketRuntimeException("Null component id is not allowed.");
}
this.id = id;
}
/**
* Sets the parent of a component.
*
* @param parent
* The parent container
*/
final void setParent(final MarkupContainer parent)
{
if (this.parent != null && log.isDebugEnabled())
{
log.debug("replacing parent " + this.parent + " with " + parent);
}
this.parent = parent;
}
/**
* Sets the render allowed flag.
*
* @param renderAllowed
*/
final void setRenderAllowed(boolean renderAllowed)
{
this.renderAllowed = renderAllowed;
}
/**
* Check whether this component may be created at all. Throws a
* {@link AuthorizationException} when it may not be created
*
*/
private final void checkAuthorization()
{
if (!getApplication().getSecuritySettings().getAuthorizationStrategy().allowInstantiation(
getClass()))
{
throw new UnauthorizedInstantiationException(
"insufficiently authorized to create component " + getClass());
}
}
/**
* Finds the root object for an IModel
*
* @param model
* The model
* @return The root object
*/
private final IModel getRootModel(final IModel model)
{
IModel nestedModelObject = model;
while (true)
{
final IModel next = ((IModel)nestedModelObject).getNestedModel();
if (next == null)
{
break;
}
if (nestedModelObject == next)
{
throw new WicketRuntimeException("Model for " + nestedModelObject
+ " is self-referential");
}
nestedModelObject = next;
}
return nestedModelObject;
}
/**
* @return boolean if this component is currently rendering itself
*/
private boolean isRendering()
{
return rendering;
}
}
| Unused import
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@458507 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/java/wicket/Component.java | Unused import | <ide><path>icket/src/java/wicket/Component.java
<ide> import wicket.model.ICompoundModel;
<ide> import wicket.model.IModel;
<ide> import wicket.model.IModelComparator;
<del>import wicket.settings.IMarkupSettings;
<ide> import wicket.settings.IRequiredPageSettings;
<ide> import wicket.settings.Settings;
<ide> import wicket.util.convert.IConverter; |
|
Java | apache-2.0 | 7d977ff3ef3b846b7e04452a43c2fd4b6e96d68b | 0 | cs553-cloud-computing/amazon-cloudengine,cs553-cloud-computing/amazon-cloudengine | package client;
public class Client {
public static void main(String[] args){
System.out.print("amazon cloud stack!");
}
} | src/client/Client.java | package client;
public class Client {
public static void main(String[] args){
System.out.print("aaa");
}
} | java test
| src/client/Client.java | java test | <ide><path>rc/client/Client.java
<ide>
<ide> public class Client {
<ide> public static void main(String[] args){
<del> System.out.print("aaa");
<add> System.out.print("amazon cloud stack!");
<ide> }
<ide> } |
|
Java | mit | d1cc4dc100eff4002bf3a39fed249176d23a350e | 0 | AlexandruGhergut/BattleAI | package ServerMainPackage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import Constants.ServerConstants;
public class ServerDispatcher implements Runnable {
private static ServerDispatcher serverDispatcher = new ServerDispatcher();
private List<MatchConnection> activeConnections =
Collections.synchronizedList(new LinkedList<MatchConnection>());
private boolean isRunning = false;
private Thread mainThread;
private ServerDispatcher() {}
public ServerDispatcher getInstance() {
return serverDispatcher;
}
public boolean start() {
if (!isRunning) {
mainThread = new Thread(this);
mainThread.start();
isRunning = true;
return true;
}
return false;
}
public boolean stop() throws InterruptedException {
if (isRunning) {
isRunning = false;
activeConnections.clear();
mainThread.join();
return true;
}
return false;
}
@Override
public void run() {
Timer connectionCleaner = new Timer();
TimerTask removeInactiveConnections = new TimerTask() {
@Override
public void run() {
for (int i = 0; i < activeConnections.size(); i++)
if (!activeConnections.get(i).isActive()) {
activeConnections.remove(i);
i--;
}
}
};
connectionCleaner.scheduleAtFixedRate(removeInactiveConnections, 0,
ServerConstants.PACKET_DELAY * 2);
Object object = null;
while (isRunning) {
try (ServerSocket serverSocket = new ServerSocket(ServerConstants.PORT)) {
Socket clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
ObjectInputStream objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
object = objectInputStream.readObject();
if (object instanceof ClientRequest)
processRequest(clientSocket, (ClientRequest)object);
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
private void processRequest(Socket clientSocket, ClientRequest clientRequest) throws IOException {
if (clientRequest.getType() == RequestType.HostMatch) {
clientSocket.setSoTimeout(0);
MatchConnection clientConnection = new MatchConnection(clientSocket);
activeConnections.add(clientConnection);
} else if (clientRequest.getType() == RequestType.UpdateServerList) {
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(clientSocket.getOutputStream());
objectOutputStream.writeObject(activeConnections);
objectOutputStream.flush();
clientSocket.close();
}
}
}
| BattleAI-Server/src/ServerMainPackage/ServerDispatcher.java | package ServerMainPackage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import Constants.ServerConstants;
public class ServerDispatcher implements Runnable {
private static ServerDispatcher serverDispatcher = new ServerDispatcher();
private List<MatchConnection> activeConnections =
Collections.synchronizedList(new LinkedList<MatchConnection>());
private boolean isRunning = false;
private ServerDispatcher() {}
public ServerDispatcher getInstance() {
return serverDispatcher;
}
public boolean start() {
if (!isRunning) {
new Thread(this).start();
isRunning = true;
return true;
}
return false;
}
public boolean stop() {
if (isRunning) {
isRunning = false;
activeConnections.clear();
return true;
}
return false;
}
@Override
public void run() {
Timer connectionCleaner = new Timer();
TimerTask removeInactiveConnections = new TimerTask() {
@Override
public void run() {
for (int i = 0; i < activeConnections.size(); i++)
if (!activeConnections.get(i).isActive()) {
activeConnections.remove(i);
i--;
}
}
};
connectionCleaner.scheduleAtFixedRate(removeInactiveConnections, 0,
ServerConstants.PACKET_DELAY * 2);
Object object = null;
while (isRunning) {
try (ServerSocket serverSocket = new ServerSocket(ServerConstants.PORT)) {
Socket clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
ObjectInputStream objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
object = objectInputStream.readObject();
if (object instanceof ClientRequest)
processRequest(clientSocket, (ClientRequest)object);
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
private void processRequest(Socket clientSocket, ClientRequest clientRequest) throws IOException {
if (clientRequest.getType() == RequestType.HostMatch) {
clientSocket.setSoTimeout(0);
MatchConnection clientConnection = new MatchConnection(clientSocket);
activeConnections.add(clientConnection);
} else if (clientRequest.getType() == RequestType.UpdateServerList) {
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(clientSocket.getOutputStream());
objectOutputStream.writeObject(activeConnections);
objectOutputStream.flush();
clientSocket.close();
}
}
}
| Wait for current server dispatcher thread to die before completing stop()
| BattleAI-Server/src/ServerMainPackage/ServerDispatcher.java | Wait for current server dispatcher thread to die before completing stop() | <ide><path>attleAI-Server/src/ServerMainPackage/ServerDispatcher.java
<ide> private List<MatchConnection> activeConnections =
<ide> Collections.synchronizedList(new LinkedList<MatchConnection>());
<ide> private boolean isRunning = false;
<add> private Thread mainThread;
<ide>
<ide> private ServerDispatcher() {}
<ide>
<ide>
<ide> public boolean start() {
<ide> if (!isRunning) {
<del> new Thread(this).start();
<add> mainThread = new Thread(this);
<add> mainThread.start();
<ide> isRunning = true;
<ide> return true;
<ide> }
<ide> return false;
<ide> }
<ide>
<del> public boolean stop() {
<add> public boolean stop() throws InterruptedException {
<ide> if (isRunning) {
<ide> isRunning = false;
<ide> activeConnections.clear();
<add> mainThread.join();
<ide> return true;
<ide> }
<ide> |
|
Java | lgpl-2.1 | d678e031b1f33c9e550ab5ccc5cfd683918a38ed | 0 | xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/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.wikistream.xar.internal.output;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang3.ObjectUtils;
import org.xwiki.model.internal.reference.LocalizedStringEntityReferenceSerializer;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.wikistream.WikiStreamException;
import org.xwiki.wikistream.output.FileOutputTarget;
import org.xwiki.wikistream.output.OutputStreamOutputTarget;
import org.xwiki.wikistream.output.OutputTarget;
import org.xwiki.wikistream.xar.internal.XARModel;
import org.xwiki.wikistream.xml.internal.output.WikiStreamXMLStreamWriter;
/**
* @version $Id$
* @since 5.2M2
*/
public class XARWikiWriter
{
private static final LocalizedStringEntityReferenceSerializer TOSTRING_SERIALIZER =
new LocalizedStringEntityReferenceSerializer();
private static class Entry
{
public LocalDocumentReference reference;
public Locale locale = Locale.ROOT;
public int defaultAction = XARModel.ACTION_OVERWRITE;
public Entry(LocalDocumentReference reference, Locale locale)
{
this.reference = reference;
this.locale = locale;
}
}
private final String name;
private final Map<String, Object> wikiProperties;
private final XAROutputProperties xarProperties;
private final ZipArchiveOutputStream zipStream;
private final List<Entry> entries = new LinkedList<Entry>();
public XARWikiWriter(String name, Map<String, Object> wikiParameters, XAROutputProperties xarProperties)
throws WikiStreamException
{
this.name = name;
this.wikiProperties = wikiParameters;
this.xarProperties = xarProperties;
OutputTarget target = this.xarProperties.getTarget();
try {
if (target instanceof FileOutputTarget && ((FileOutputTarget) target).getFile().isDirectory()) {
this.zipStream =
new ZipArchiveOutputStream(new File(((FileOutputTarget) target).getFile(), name + ".xar"));
} else if (target instanceof OutputStreamOutputTarget) {
this.zipStream = new ZipArchiveOutputStream(((OutputStreamOutputTarget) target).getOutputStream());
} else {
throw new WikiStreamException(String.format("Unsupported output target [%s]. Only [%s] is suppoted",
target, OutputStreamOutputTarget.class));
}
} catch (IOException e) {
throw new WikiStreamException("Files to create zip output stream", e);
}
this.zipStream.setEncoding("UTF8");
// By including the unicode extra fields, it is possible to extract XAR-files containing documents with
// non-ascii characters in the document name using InfoZIP, and the filenames will be correctly
// converted to the character set of the local file system.
this.zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
}
public String getName()
{
return this.name;
}
public Map<String, Object> getMetadata()
{
return this.wikiProperties;
}
public OutputStream newEntry(LocalDocumentReference reference, Locale locale) throws WikiStreamException
{
StringBuilder path = new StringBuilder();
// Add space name
path.append(reference.getParent().getName()).append('/');
// Add document name
path.append(reference.getName());
// Add language
if (locale != null && !locale.equals(Locale.ROOT)) {
path.append('.');
path.append(locale);
}
// Add extension
path.append(".xml");
ZipArchiveEntry zipentry = new ZipArchiveEntry(path.toString());
try {
this.zipStream.putArchiveEntry(zipentry);
} catch (IOException e) {
throw new WikiStreamException("Failed to add a new zip entry for [" + path + "]", e);
}
this.entries.add(new Entry(reference, locale));
return this.zipStream;
}
private void writePackage() throws WikiStreamException, IOException
{
ZipArchiveEntry zipentry = new ZipArchiveEntry(XARModel.PATH_PACKAGE);
this.zipStream.putArchiveEntry(zipentry);
WikiStreamXMLStreamWriter writer =
new WikiStreamXMLStreamWriter(this.zipStream, this.xarProperties.getEncoding());
try {
writer.writeStartDocument();
writer.writeStartElement(XARModel.ELEMENT_PACKAGE);
writer.writeStartElement(XARModel.ELEMENT_INFOS);
writer.writeElement(XARModel.ELEMENT_INFOS_NAME, this.xarProperties.getName());
writer.writeElement(XARModel.ELEMENT_INFOS_DESCRIPTION, this.xarProperties.getDescription());
writer.writeElement(XARModel.ELEMENT_INFOS_LICENSE, this.xarProperties.getLicense());
writer.writeElement(XARModel.ELEMENT_INFOS_AUTHOR, this.xarProperties.getAuthor());
writer.writeElement(XARModel.ELEMENT_INFOS_VERSION, this.xarProperties.getVersion());
writer.writeElement(XARModel.ELEMENT_INFOS_ISBACKUPPACK, this.xarProperties.isBackupPack() ? "1" : "0");
writer.writeElement(XARModel.ELEMENT_INFOS_ISPRESERVEVERSION, this.xarProperties.isPreserveVersion() ? "1"
: "0");
writer.writeEndElement();
writer.writeStartElement(XARModel.ELEMENT_FILES);
for (Entry entry : this.entries) {
writer.writeStartElement(XARModel.ELEMENT_FILES_FILES);
writer.writeAttribute(XARModel.ATTRIBUTE_DEFAULTACTION, String.valueOf(entry.defaultAction));
writer.writeAttribute(XARModel.ATTRIBUTE_LOCALE, ObjectUtils.toString(entry.locale, ""));
writer.writeCharacters(TOSTRING_SERIALIZER.serialize(entry.reference));
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
} finally {
writer.close();
}
}
public void close() throws WikiStreamException
{
// Add package.xml descriptor
try {
writePackage();
} catch (IOException e) {
throw new WikiStreamException("Failed to write package.xml entry", e);
}
// Close zip stream
try {
this.zipStream.close();
} catch (IOException e) {
throw new WikiStreamException("Failed to close zip output stream", e);
}
}
}
| xwiki-platform-core/xwiki-platform-wikistream/xwiki-platform-wikistream-streams/xwiki-platform-wikistream-stream-xar/src/main/java/org/xwiki/wikistream/xar/internal/output/XARWikiWriter.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.wikistream.xar.internal.output;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang3.ObjectUtils;
import org.xwiki.model.internal.reference.LocalizedStringEntityReferenceSerializer;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.wikistream.WikiStreamException;
import org.xwiki.wikistream.output.OutputStreamOutputTarget;
import org.xwiki.wikistream.output.OutputTarget;
import org.xwiki.wikistream.xar.internal.XARModel;
import org.xwiki.wikistream.xml.internal.output.WikiStreamXMLStreamWriter;
/**
*
* @version $Id$
* @since 5.2M2
*/
public class XARWikiWriter
{
private static final LocalizedStringEntityReferenceSerializer TOSTRING_SERIALIZER =
new LocalizedStringEntityReferenceSerializer();
private static class Entry
{
public LocalDocumentReference reference;
public Locale locale = Locale.ROOT;
public int defaultAction = XARModel.ACTION_OVERWRITE;
public Entry(LocalDocumentReference reference, Locale locale)
{
this.reference = reference;
this.locale = locale;
}
}
private final String name;
private final Map<String, Object> wikiProperties;
private final XAROutputProperties xarProperties;
private final ZipArchiveOutputStream zipStream;
private final List<Entry> entries = new LinkedList<Entry>();
public XARWikiWriter(String name, Map<String, Object> wikiParameters, XAROutputProperties xarProperties)
throws WikiStreamException
{
this.name = name;
this.wikiProperties = wikiParameters;
this.xarProperties = xarProperties;
OutputTarget target = this.xarProperties.getTarget();
if (target instanceof OutputStreamOutputTarget) {
try {
this.zipStream = new ZipArchiveOutputStream(((OutputStreamOutputTarget) target).getOutputStream());
this.zipStream.setEncoding("UTF8");
// By including the unicode extra fields, it is possible to extract XAR-files containing documents with
// non-ascii characters in the document name using InfoZIP, and the filenames will be correctly
// converted to the character set of the local file system.
this.zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
} catch (IOException e) {
throw new WikiStreamException("Files to create zip output stream", e);
}
} else {
throw new WikiStreamException("Unsupported output target [" + target + "]. Only ["
+ OutputStreamOutputTarget.class.getName() + "] is suppoted");
}
}
public String getName()
{
return this.name;
}
public Map<String, Object> getMetadata()
{
return this.wikiProperties;
}
public OutputStream newEntry(LocalDocumentReference reference, Locale locale) throws WikiStreamException
{
StringBuilder path = new StringBuilder();
// Add space name
path.append(reference.getParent().getName()).append('/');
// Add document name
path.append(reference.getName());
// Add language
if (locale != null && !locale.equals(Locale.ROOT)) {
path.append('.');
path.append(locale);
}
// Add extension
path.append(".xml");
ZipArchiveEntry zipentry = new ZipArchiveEntry(path.toString());
try {
this.zipStream.putArchiveEntry(zipentry);
} catch (IOException e) {
throw new WikiStreamException("Failed to add a new zip entry for [" + path + "]", e);
}
this.entries.add(new Entry(reference, locale));
return this.zipStream;
}
private void writePackage() throws WikiStreamException, IOException
{
ZipArchiveEntry zipentry = new ZipArchiveEntry(XARModel.PATH_PACKAGE);
this.zipStream.putArchiveEntry(zipentry);
WikiStreamXMLStreamWriter writer =
new WikiStreamXMLStreamWriter(this.zipStream, this.xarProperties.getEncoding());
try {
writer.writeStartDocument();
writer.writeStartElement(XARModel.ELEMENT_PACKAGE);
writer.writeStartElement(XARModel.ELEMENT_INFOS);
writer.writeElement(XARModel.ELEMENT_INFOS_NAME, this.xarProperties.getName());
writer.writeElement(XARModel.ELEMENT_INFOS_DESCRIPTION, this.xarProperties.getDescription());
writer.writeElement(XARModel.ELEMENT_INFOS_LICENSE, this.xarProperties.getLicense());
writer.writeElement(XARModel.ELEMENT_INFOS_AUTHOR, this.xarProperties.getAuthor());
writer.writeElement(XARModel.ELEMENT_INFOS_VERSION, this.xarProperties.getVersion());
writer.writeElement(XARModel.ELEMENT_INFOS_ISBACKUPPACK, this.xarProperties.isBackupPack() ? "1" : "0");
writer.writeElement(XARModel.ELEMENT_INFOS_ISPRESERVEVERSION, this.xarProperties.isPreserveVersion() ? "1"
: "0");
writer.writeEndElement();
writer.writeStartElement(XARModel.ELEMENT_FILES);
for (Entry entry : this.entries) {
writer.writeStartElement(XARModel.ELEMENT_FILES_FILES);
writer.writeAttribute(XARModel.ATTRIBUTE_DEFAULTACTION, String.valueOf(entry.defaultAction));
writer.writeAttribute(XARModel.ATTRIBUTE_LOCALE, ObjectUtils.toString(entry.locale, ""));
writer.writeCharacters(TOSTRING_SERIALIZER.serialize(entry.reference));
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
} finally {
writer.close();
}
}
public void close() throws WikiStreamException
{
// Add package.xml descriptor
try {
writePackage();
} catch (IOException e) {
throw new WikiStreamException("Failed to write package.xml entry", e);
}
// Close zip stream
try {
this.zipStream.close();
} catch (IOException e) {
throw new WikiStreamException("Failed to close zip output stream", e);
}
}
}
| XWIKI-9351: Introduce output XAR component for WikiStream
* add support for folder as output target (where each wiki is exported in a separate XAR file)
| xwiki-platform-core/xwiki-platform-wikistream/xwiki-platform-wikistream-streams/xwiki-platform-wikistream-stream-xar/src/main/java/org/xwiki/wikistream/xar/internal/output/XARWikiWriter.java | XWIKI-9351: Introduce output XAR component for WikiStream * add support for folder as output target (where each wiki is exported in a separate XAR file) | <ide><path>wiki-platform-core/xwiki-platform-wikistream/xwiki-platform-wikistream-streams/xwiki-platform-wikistream-stream-xar/src/main/java/org/xwiki/wikistream/xar/internal/output/XARWikiWriter.java
<ide> */
<ide> package org.xwiki.wikistream.xar.internal.output;
<ide>
<add>import java.io.File;
<ide> import java.io.IOException;
<ide> import java.io.OutputStream;
<ide> import java.util.LinkedList;
<ide> import org.xwiki.model.internal.reference.LocalizedStringEntityReferenceSerializer;
<ide> import org.xwiki.model.reference.LocalDocumentReference;
<ide> import org.xwiki.wikistream.WikiStreamException;
<add>import org.xwiki.wikistream.output.FileOutputTarget;
<ide> import org.xwiki.wikistream.output.OutputStreamOutputTarget;
<ide> import org.xwiki.wikistream.output.OutputTarget;
<ide> import org.xwiki.wikistream.xar.internal.XARModel;
<ide> import org.xwiki.wikistream.xml.internal.output.WikiStreamXMLStreamWriter;
<ide>
<ide> /**
<del> *
<ide> * @version $Id$
<ide> * @since 5.2M2
<ide> */
<ide> this.xarProperties = xarProperties;
<ide>
<ide> OutputTarget target = this.xarProperties.getTarget();
<del> if (target instanceof OutputStreamOutputTarget) {
<del> try {
<add>
<add> try {
<add> if (target instanceof FileOutputTarget && ((FileOutputTarget) target).getFile().isDirectory()) {
<add> this.zipStream =
<add> new ZipArchiveOutputStream(new File(((FileOutputTarget) target).getFile(), name + ".xar"));
<add> } else if (target instanceof OutputStreamOutputTarget) {
<ide> this.zipStream = new ZipArchiveOutputStream(((OutputStreamOutputTarget) target).getOutputStream());
<del> this.zipStream.setEncoding("UTF8");
<del>
<del> // By including the unicode extra fields, it is possible to extract XAR-files containing documents with
<del> // non-ascii characters in the document name using InfoZIP, and the filenames will be correctly
<del> // converted to the character set of the local file system.
<del> this.zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
<del> } catch (IOException e) {
<del> throw new WikiStreamException("Files to create zip output stream", e);
<add> } else {
<add> throw new WikiStreamException(String.format("Unsupported output target [%s]. Only [%s] is suppoted",
<add> target, OutputStreamOutputTarget.class));
<ide> }
<del> } else {
<del> throw new WikiStreamException("Unsupported output target [" + target + "]. Only ["
<del> + OutputStreamOutputTarget.class.getName() + "] is suppoted");
<del> }
<add> } catch (IOException e) {
<add> throw new WikiStreamException("Files to create zip output stream", e);
<add> }
<add>
<add> this.zipStream.setEncoding("UTF8");
<add>
<add> // By including the unicode extra fields, it is possible to extract XAR-files containing documents with
<add> // non-ascii characters in the document name using InfoZIP, and the filenames will be correctly
<add> // converted to the character set of the local file system.
<add> this.zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
<ide> }
<ide>
<ide> public String getName() |
|
Java | mpl-2.0 | error: pathspec 'wizards/com/sun/star/wizards/common/XMLProvider.java' did not match any file(s) known to git
| 22e0aee5e1d947f086bd237825077565de641204 | 1 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*
* XMLSupplier.java
*
* Created on 19. September 2003, 11:52
*/
package com.sun.star.wizards.common;
import org.w3c.dom.Node;
/**
*
* @author rpiterman
*/
public interface XMLProvider {
public Node createDOM(Node parent);
}
| wizards/com/sun/star/wizards/common/XMLProvider.java | INTEGRATION: CWS qwizards1 (1.1.2); FILE ADDED
2004/03/12 16:16:50 rpiterman 1.1.2.3: documentation and small implementation-fixes
2004/02/02 11:27:53 tv 1.1.2.2: formatted with autoformatter (indents now use TAB)
2003/11/04 16:30:46 rpiterman 1.1.2.1: XMLProvider ist an interface which enables an object to "add itself" to a DOM representation.
XMLHelper has convenience methods for adding elements to a document.
| wizards/com/sun/star/wizards/common/XMLProvider.java | INTEGRATION: CWS qwizards1 (1.1.2); FILE ADDED 2004/03/12 16:16:50 rpiterman 1.1.2.3: documentation and small implementation-fixes 2004/02/02 11:27:53 tv 1.1.2.2: formatted with autoformatter (indents now use TAB) 2003/11/04 16:30:46 rpiterman 1.1.2.1: XMLProvider ist an interface which enables an object to "add itself" to a DOM representation. XMLHelper has convenience methods for adding elements to a document. | <ide><path>izards/com/sun/star/wizards/common/XMLProvider.java
<add>/*
<add> * XMLSupplier.java
<add> *
<add> * Created on 19. September 2003, 11:52
<add> */
<add>
<add>package com.sun.star.wizards.common;
<add>
<add>import org.w3c.dom.Node;
<add>/**
<add> *
<add> * @author rpiterman
<add> */
<add>public interface XMLProvider {
<add> public Node createDOM(Node parent);
<add>} |
|
Java | mit | 4e8450d0b2b1eabef26002875b0c301d5c4b82b2 | 0 | IPPETAD/adventure.datetime | /*
* Copyright (c) 2013 Andrew Fontaine, James Finlay, Jesse Tucker, Jacob Viau, and
* Evan DeGraff
*
* 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 ca.cmput301f13t03.adventure_datetime.view;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import ca.cmput301f13t03.adventure_datetime.R;
import ca.cmput301f13t03.adventure_datetime.model.Choice;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ICurrentFragmentListener;
import ca.cmput301f13t03.adventure_datetime.model.StoryFragment;
import ca.cmput301f13t03.adventure_datetime.serviceLocator.Locator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* View Accessed via MainView > Continue > ~Select Item~ or via MainView > BrowseView > StoryDescription > ~Play /
* Continue item ~
* <p/>
* Holds Horizontal filmstrip containing illustrations at top of page, story fragment text in the view, and an actions
* buttons at the bottom of the page.
*
* @author James Finlay
*/
public class FragmentView extends Activity implements ICurrentFragmentListener {
private static final String TAG = "FragmentView";
public static final String FOR_SERVER = "emagherd.server";
private HorizontalScrollView _filmstrip;
private TextView _content;
private LinearLayout _filmLayout;
private Button _choices;
private boolean forServerEh;
private StoryFragment _fragment;
@Override
public void OnCurrentFragmentChange(StoryFragment newFragment) {
_fragment = newFragment;
setUpView();
}
@Override
public void onResume() {
Locator.getPresenter().Subscribe(this);
super.onResume();
}
@Override
public void onPause() {
Locator.getPresenter().Unsubscribe(this);
super.onPause();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_view);
forServerEh = getIntent().getBooleanExtra(FOR_SERVER, false);
setUpView();
}
public void setUpView() {
if (_fragment == null) return;
/** Layout items **/
_filmLayout = (LinearLayout) findViewById(R.id.filmstrip);
_filmstrip = (HorizontalScrollView) findViewById(R.id.filmstrip_wrapper);
_choices = (Button) findViewById(R.id.choices);
_content = (TextView) findViewById(R.id.content);
if (_fragment.getStoryMedia() == null)
_fragment.setStoryMedia(new ArrayList<Uri>());
/** Programmatically set filmstrip height **/
if (_fragment.getStoryMedia().size() > 0)
_filmstrip.getLayoutParams().height = 300;
_content.setText(_fragment.getStoryText());
// 1) Create new ImageView and add to the LinearLayout
// 2) Set appropriate Layout Params to ImageView
// 3) Give onClickListener for going to fullscreen
LinearLayout.LayoutParams lp;
for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {
ImageView li = new ImageView(this);
li.setScaleType(ScaleType.CENTER_INSIDE);
li.setImage
_filmLayout.addView(li);
lp = (LinearLayout.LayoutParams) li.getLayoutParams();
lp.setMargins(10, 10, 10, 10);
lp.width = LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER_VERTICAL;
li.setLayoutParams(lp);
li.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FragmentView.this, FullScreen_Image.class);
intent.putExtra(FullScreen_Image.TAG_AUTHOR, false);
startActivity(intent);
}
});
}
if (_fragment.getChoices().size() > 0) {
/** Choices **/
final List<String> choices = new ArrayList<String>();
for (Choice choice : _fragment.getChoices())
choices.add(choice.getText());
choices.add("I'm feeling lucky.");
_choices.setText("Actions");
_choices.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("Actions")
.setCancelable(true)
.setItems(choices.toArray(new String[choices.size()]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/** You feeling lucky, punk? **/
if (which == _fragment.getChoices().size())
which = (int) (Math.random() * _fragment.getChoices().size());
Choice choice = _fragment.getChoices().get(which);
Toast.makeText(getApplicationContext(),
choice.getText(), Toast.LENGTH_LONG).show();
Locator.getUserController().MakeChoice(choice);
}
})
.create().show();
}
});
} else {
/** End of story **/
Locator.getUserController().deleteBookmark();
_choices.setText("The End");
_choices.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("La Fin")
.setCancelable(true)
.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Locator.getUserController().StartStory(_fragment.getStoryID());
}
})
.setNegativeButton("Change Adventures", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create().show();
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if (forServerEh)
getMenuInflater().inflate(R.menu.fragment_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_comment:
/* Open comments activity */
Intent intent = new Intent(this, CommentsView.class);
intent.putExtra(CommentsView.COMMENT_TYPE, false);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
| adventure.datetime/src/ca/cmput301f13t03/adventure_datetime/view/FragmentView.java | /*
* Copyright (c) 2013 Andrew Fontaine, James Finlay, Jesse Tucker, Jacob Viau, and
* Evan DeGraff
*
* 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 ca.cmput301f13t03.adventure_datetime.view;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import ca.cmput301f13t03.adventure_datetime.R;
import ca.cmput301f13t03.adventure_datetime.model.Choice;
import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ICurrentFragmentListener;
import ca.cmput301f13t03.adventure_datetime.model.StoryFragment;
import ca.cmput301f13t03.adventure_datetime.serviceLocator.Locator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* View Accessed via MainView > Continue > ~Select Item~ or via MainView > BrowseView > StoryDescription > ~Play /
* Continue item ~
* <p/>
* Holds Horizontal filmstrip containing illustrations at top of page, story fragment text in the view, and an actions
* buttons at the bottom of the page.
*
* @author James Finlay
*/
public class FragmentView extends Activity implements ICurrentFragmentListener {
private static final String TAG = "FragmentView";
public static final String FOR_SERVER = "emagherd.server";
private HorizontalScrollView _filmstrip;
private TextView _content;
private LinearLayout _filmLayout;
private Button _choices;
private boolean forServerEh;
private StoryFragment _fragment;
@Override
public void OnCurrentFragmentChange(StoryFragment newFragment) {
_fragment = newFragment;
setUpView();
}
@Override
public void onResume() {
Locator.getPresenter().Subscribe(this);
super.onResume();
}
@Override
public void onPause() {
Locator.getPresenter().Unsubscribe(this);
super.onPause();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_view);
forServerEh = getIntent().getBooleanExtra(FOR_SERVER, false);
setUpView();
}
public void setUpView() {
if (_fragment == null) return;
/** Layout items **/
_filmLayout = (LinearLayout) findViewById(R.id.filmstrip);
_filmstrip = (HorizontalScrollView) findViewById(R.id.filmstrip_wrapper);
_choices = (Button) findViewById(R.id.choices);
_content = (TextView) findViewById(R.id.content);
if (_fragment.getStoryMedia() == null)
_fragment.setStoryMedia(new ArrayList<Uri>());
/** Programmatically set filmstrip height **/
// TODO::JF Unshitify this, aka not static value
//if (_fragment.getStoryMedia().size() > 0)
_filmstrip.getLayoutParams().height = 300;
_content.setText(_fragment.getStoryText());
// 1) Create new ImageView and add to the LinearLayout
// 2) Set appropriate Layout Params to ImageView
// 3) Give onClickListener for going to fullscreen
LinearLayout.LayoutParams lp;
//for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {
for (int i = 0; i < 5; i++) {
// TODO::JF Get images from fragment
ImageView li = new ImageView(this);
li.setScaleType(ScaleType.CENTER_INSIDE);
li.setImageResource(R.drawable.grumpy_cat2);
_filmLayout.addView(li);
lp = (LinearLayout.LayoutParams) li.getLayoutParams();
lp.setMargins(10, 10, 10, 10);
lp.width = LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER_VERTICAL;
li.setLayoutParams(lp);
li.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FragmentView.this, FullScreen_Image.class);
intent.putExtra(FullScreen_Image.TAG_AUTHOR, false);
startActivity(intent);
}
});
}
if (_fragment.getChoices().size() > 0) {
/** Choices **/
final List<String> choices = new ArrayList<String>();
for (Choice choice : _fragment.getChoices())
choices.add(choice.getText());
choices.add("I'm feeling lucky.");
_choices.setText("Actions");
_choices.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("Actions")
.setCancelable(true)
.setItems(choices.toArray(new String[choices.size()]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/** You feeling lucky, punk? **/
if (which == _fragment.getChoices().size())
which = (int) (Math.random() * _fragment.getChoices().size());
Choice choice = _fragment.getChoices().get(which);
Toast.makeText(getApplicationContext(),
choice.getText(), Toast.LENGTH_LONG).show();
Locator.getUserController().MakeChoice(choice);
}
})
.create().show();
}
});
} else {
/** End of story **/
Locator.getUserController().deleteBookmark();
_choices.setText("The End");
_choices.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("La Fin")
.setCancelable(true)
.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Locator.getUserController().StartStory(_fragment.getStoryID());
}
})
.setNegativeButton("Change Adventures", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create().show();
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if (forServerEh)
getMenuInflater().inflate(R.menu.fragment_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_comment:
/* Open comments activity */
Intent intent = new Intent(this, CommentsView.class);
intent.putExtra(CommentsView.COMMENT_TYPE, false);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
| started image stuff
| adventure.datetime/src/ca/cmput301f13t03/adventure_datetime/view/FragmentView.java | started image stuff | <ide><path>dventure.datetime/src/ca/cmput301f13t03/adventure_datetime/view/FragmentView.java
<ide> _fragment.setStoryMedia(new ArrayList<Uri>());
<ide>
<ide> /** Programmatically set filmstrip height **/
<del> // TODO::JF Unshitify this, aka not static value
<del> //if (_fragment.getStoryMedia().size() > 0)
<del> _filmstrip.getLayoutParams().height = 300;
<add> if (_fragment.getStoryMedia().size() > 0)
<add> _filmstrip.getLayoutParams().height = 300;
<ide>
<ide>
<ide> _content.setText(_fragment.getStoryText());
<ide> // 2) Set appropriate Layout Params to ImageView
<ide> // 3) Give onClickListener for going to fullscreen
<ide> LinearLayout.LayoutParams lp;
<del> //for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {
<del> for (int i = 0; i < 5; i++) {
<del> // TODO::JF Get images from fragment
<add> for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {
<ide> ImageView li = new ImageView(this);
<ide> li.setScaleType(ScaleType.CENTER_INSIDE);
<del> li.setImageResource(R.drawable.grumpy_cat2);
<add> li.setImage
<ide> _filmLayout.addView(li);
<ide>
<ide> lp = (LinearLayout.LayoutParams) li.getLayoutParams(); |
|
Java | apache-2.0 | 83b8c1689b7c6b945e8bdbb4c4ed2e2511ae244f | 0 | hellojavaer/ddal,hellojavaer/ddr | /*
* Copyright 2016-2016 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.hellojavaer.ddr.core.datasource.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.sql.Date;
import java.util.*;
/**
*
* @author <a href="mailto:[email protected]">zoukaiming[邹凯明]</a>,created on 20/11/2016.
*/
public abstract class PreparedStatementWrapper implements PreparedStatement {
private Connection connectionWrapper;
private Connection connection;
private PreparedStatement preparedStatement;
private String sql;
private Object[] createStatementMethodParams;
private Class[] createStatementMethodParamTypes;
private Map<Integer, Object> jdbcParamterForFirstAddBatch = new HashMap<Integer, Object>();
private Map<Integer, Object> jdbcParameter = new HashMap<Integer, Object>();
public PreparedStatementWrapper(Connection connectionWrapper, Connection connection, String sql,
Object[] createStatementMethodParams, Class[] createStatementMethodParamTypes) {
this.connectionWrapper = connectionWrapper;
this.connection = connection;
this.sql = sql;
this.createStatementMethodParams = createStatementMethodParams;
this.createStatementMethodParamTypes = createStatementMethodParamTypes;
this.pushNewExecutionContext();
}
private List<ExecutionContext> executionContexts = new LinkedList<ExecutionContext>();
private ExecutionContext getCurParamContext() {
return executionContexts.get(executionContexts.size() - 1);
}
private void pushNewExecutionContext() {
ExecutionContext newContext = new ExecutionContext();
executionContexts.add(newContext);
}
private void pushNewExecutionContext(String sql) {
ExecutionContext newContext = new ExecutionContext();
newContext.setStatementBatchSql(sql);
executionContexts.add(newContext);
}
private class ExecutionContext {
private List<InvokeRecord> invokeRecords;
private String statementBatchSql;
public List<InvokeRecord> getInvokeRecords() {
return invokeRecords;
}
public void setInvokeRecords(List<InvokeRecord> invokeRecords) {
this.invokeRecords = invokeRecords;
}
public String getStatementBatchSql() {
return statementBatchSql;
}
public void setStatementBatchSql(String statementBatchSql) {
this.statementBatchSql = statementBatchSql;
}
}
private class InvokeRecord {
private String methodName;
private Object[] params;
private Class[] paramTypes;
public InvokeRecord(String methodName, Object[] params, Class[] paramTypes) {
this.methodName = methodName;
this.params = params;
this.paramTypes = paramTypes;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
public Class[] getParamTypes() {
return paramTypes;
}
public void setParamTypes(Class[] paramTypes) {
this.paramTypes = paramTypes;
}
}
public abstract String replaceSql(String sql, Map<Integer, Object> jdbcParams);
@Override
public ResultSet executeQuery() throws SQLException {
playbackInvocation(this.sql);
return this.preparedStatement.executeQuery();
}
@Override
public int executeUpdate() throws SQLException {
playbackInvocation(this.sql);
return this.preparedStatement.executeUpdate();
}
@Override
public void clearParameters() throws SQLException {
this.jdbcParamterForFirstAddBatch.clear();
this.jdbcParameter.clear();
Iterator<ExecutionContext> it = executionContexts.iterator();
while (it.hasNext()) {
ExecutionContext context = it.next();
if (context.getStatementBatchSql() == null) {
it.remove();
}
}
}
@Override
public boolean execute() throws SQLException {
this.playbackInvocation(this.sql);
return this.preparedStatement.execute();
}
@Override
public void addBatch() throws SQLException {
this.pushNewExecutionContext();
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
throw new UnsupportedOperationException("getMetaData");
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
throw new UnsupportedOperationException("getParameterMetaData");
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeQuery(sql);
}
@Override
public int executeUpdate(String sql) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeUpdate(sql);
}
@Override
public void close() throws SQLException {
this.preparedStatement.close();
}
private StatementProperty statementProperty = new StatementProperty();
private class StatementProperty {
private int maxFieldSize;
private int maxRows;
private int fetchDirection;
private int fetchSize;
public int getMaxFieldSize() {
return maxFieldSize;
}
public void setMaxFieldSize(int maxFieldSize) {
this.maxFieldSize = maxFieldSize;
}
public int getMaxRows() {
return maxRows;
}
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
public int getFetchDirection() {
return fetchDirection;
}
public void setFetchDirection(int fetchDirection) {
this.fetchDirection = fetchDirection;
}
public int getFetchSize() {
return fetchSize;
}
public void setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
}
}
@Override
public int getMaxFieldSize() throws SQLException {
if (preparedStatement == null) {
return statementProperty.getMaxFieldSize();
} else {
return this.preparedStatement.getMaxFieldSize();
}
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
if (preparedStatement == null) {
statementProperty.setMaxFieldSize(max);
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setMaxFieldSize", new Object[] { max },
new Class[] { int.class }));
} else {
this.preparedStatement.setMaxFieldSize(max);
}
}
@Override
public int getMaxRows() throws SQLException {
if (preparedStatement == null) {
return statementProperty.getMaxRows();
} else {
return this.preparedStatement.getMaxRows();
}
}
@Override
public void setMaxRows(int max) throws SQLException {
if (preparedStatement == null) {
statementProperty.setMaxRows(max);
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setMaxRows", new Object[] { max },
new Class[] { int.class }));
} else {
this.preparedStatement.setMaxRows(max);
}
}
@Override
public void setFetchDirection(int direction) throws SQLException {
if (preparedStatement == null) {
statementProperty.setFetchDirection(direction);
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setFetchDirection",
new Object[] { direction },
new Class[] { int.class }));
} else {
this.preparedStatement.setFetchDirection(direction);
}
}
@Override
public int getFetchDirection() throws SQLException {
if (preparedStatement == null) {
return statementProperty.getFetchDirection();
} else {
return this.preparedStatement.getFetchDirection();
}
}
@Override
public void setFetchSize(int rows) throws SQLException {
if (preparedStatement == null) {
statementProperty.setFetchSize(rows);
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setFetchSize", new Object[] { rows },
new Class[] { int.class }));
} else {
this.preparedStatement.setFetchSize(rows);
}
}
@Override
public int getFetchSize() throws SQLException {
if (preparedStatement == null) {
return statementProperty.getFetchSize();
} else {
return this.preparedStatement.getFetchSize();
}
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setEscapeProcessing",
new Object[] { enable },
new Class[] { boolean.class }));
} else {
this.preparedStatement.setEscapeProcessing(enable);
}
}
@Override
public int getQueryTimeout() throws SQLException {
return this.preparedStatement.getQueryTimeout();
}
@Override
public void cancel() throws SQLException {
this.preparedStatement.cancel();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return this.preparedStatement.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
this.preparedStatement.clearWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
this.preparedStatement.setCursorName(name);
}
@Override
public boolean execute(String sql) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql);
}
@Override
public ResultSet getResultSet() throws SQLException {
return this.preparedStatement.getResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return this.preparedStatement.getUpdateCount();
}
@Override
public boolean getMoreResults() throws SQLException {
return this.preparedStatement.getMoreResults();
}
@Override
public int getResultSetConcurrency() throws SQLException {
return this.preparedStatement.getResultSetConcurrency();
}
@Override
public int getResultSetType() throws SQLException {
return this.preparedStatement.getResultSetType();
}
@Override
public void addBatch(String sql) throws SQLException {
this.pushNewExecutionContext(sql);
}
@Override
public void clearBatch() throws SQLException {
this.executionContexts.clear();
this.pushNewExecutionContext();
}
@Override
public int[] executeBatch() throws SQLException {
this.playbackInvocation(this.sql);
return this.preparedStatement.executeBatch();
}
@Override
public Connection getConnection() throws SQLException {
return this.connectionWrapper;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return this.preparedStatement.getMoreResults();
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return this.preparedStatement.getGeneratedKeys();
}
private String playbackInvocation(String sql) throws SQLException {
try {
// 1. 替换 sql
String targetSql = replaceSql(sql, this.jdbcParamterForFirstAddBatch);
if (preparedStatement == null) {
// 2. 创建 preparedStatement
createStatementMethodParams[0] = targetSql;
PreparedStatement preparedStatement = (PreparedStatement) connection.getClass().getMethod("prepareStatement",
createStatementMethodParamTypes).invoke(connection,
createStatementMethodParams);
this.preparedStatement = preparedStatement;
}
// 2.1 回放set 方法调用
for (ExecutionContext context : executionContexts) {
if (context.getStatementBatchSql() != null) {
// TODO:校验是否同datasource
this.preparedStatement.addBatch(context.getStatementBatchSql());
} else {
// TODO:校验是否同datasource
for (InvokeRecord invokeRecord : context.getInvokeRecords()) {
this.preparedStatement.getClass().getMethod(invokeRecord.getMethodName(),
invokeRecord.getParamTypes()).invoke(preparedStatement,
invokeRecord.getParams());
}
this.preparedStatement.addBatch();
}
}
executionContexts.clear();
return targetSql;
} catch (Exception e) {
throw new SQLException(e);
}
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
sql = this.playbackInvocation(sql);
return preparedStatement.executeUpdate(sql, autoGeneratedKeys);
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeUpdate(sql, columnIndexes);
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeUpdate(sql, columnNames);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql, autoGeneratedKeys);
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql, columnIndexes);
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql, columnNames);
}
@Override
public int getResultSetHoldability() throws SQLException {
return this.preparedStatement.getResultSetHoldability();
}
@Override
public boolean isClosed() throws SQLException {
return this.preparedStatement.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
this.preparedStatement.setPoolable(poolable);
}
@Override
public boolean isPoolable() throws SQLException {
return this.preparedStatement.isPoolable();
}
@Override
public void closeOnCompletion() throws SQLException {
this.preparedStatement.closeOnCompletion();
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return this.preparedStatement.isCloseOnCompletion();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return this.preparedStatement.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.preparedStatement.isWrapperFor(iface);
}
// /////////////////
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setObject", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Object.class, int.class }));
} else {
preparedStatement.setObject(parameterIndex, x, targetSqlType);
}
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setObject", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Object.class }));
} else {
preparedStatement.setObject(parameterIndex, x);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setCharacterStream", new Object[] {
parameterIndex, reader, length }, new Class[] {
int.class, Reader.class, int.class }));
} else {
preparedStatement.setCharacterStream(parameterIndex, reader, length);
}
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setRef", new Object[] { parameterIndex,
x }, new Class[] { int.class, Ref.class }));
} else {
preparedStatement.setRef(parameterIndex, x);
}
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBlob", new Object[] { parameterIndex,
x }, new Class[] { int.class, Blob.class }));
} else {
preparedStatement.setBlob(parameterIndex, x);
}
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setClob", new Object[] { parameterIndex,
x }, new Class[] { int.class, Clob.class }));
} else {
preparedStatement.setClob(parameterIndex, x);
}
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setArray", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Array.class }));
} else {
preparedStatement.setArray(parameterIndex, x);
}
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setDate", new Object[] { parameterIndex,
x }, new Class[] { int.class, Date.class,
Calendar.class }));
} else {
preparedStatement.setDate(parameterIndex, x, cal);
}
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTime", new Object[] { parameterIndex,
x }, new Class[] { int.class, Time.class,
Calendar.class }));
} else {
preparedStatement.setTime(parameterIndex, x, cal);
}
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTimestamp", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Timestamp.class, Calendar.class }));
} else {
preparedStatement.setTimestamp(parameterIndex, x, cal);
}
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
setJdbcParameter(parameterIndex, null);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNull", new Object[] { parameterIndex,
sqlType, typeName }, new Class[] { int.class,
int.class, String.class }));
} else {
preparedStatement.setNull(parameterIndex, sqlType, typeName);
}
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setURL", new Object[] { parameterIndex,
x }, new Class[] { int.class, URL.class }));
} else {
preparedStatement.setURL(parameterIndex, x);
}
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setRowId", new Object[] {
parameterIndex, x }, new Class[] { int.class,
RowId.class }));
} else {
preparedStatement.setRowId(parameterIndex, x);
}
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
setJdbcParameter(parameterIndex, value);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNString", new Object[] {
parameterIndex, value }, new Class[] { int.class,
String.class }));
} else {
preparedStatement.setNString(parameterIndex, value);
}
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNCharacterStream", new Object[] {
parameterIndex, value, length }, new Class[] {
int.class, Reader.class }));
} else {
preparedStatement.setNCharacterStream(parameterIndex, value, length);
}
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
setJdbcParameter(parameterIndex, value);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNClob", new Object[] {
parameterIndex, value }, new Class[] { int.class,
NClob.class }));
} else {
preparedStatement.setNClob(parameterIndex, value);
}
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
setJdbcParameter(parameterIndex, length);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setClob", new Object[] { parameterIndex,
reader, length }, new Class[] { int.class,
Reader.class, long.class }));
} else {
preparedStatement.setClob(parameterIndex, reader, length);
}
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBlob", new Object[] { parameterIndex,
inputStream, length }, new Class[] { int.class,
InputStream.class, long.class }));
} else {
preparedStatement.setBlob(parameterIndex, inputStream, length);
}
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNClob", new Object[] {
parameterIndex, reader, length }, new Class[] {
int.class, Reader.class, long.class }));
} else {
preparedStatement.setNClob(parameterIndex, reader, length);
}
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setSQLXML", new Object[] {
parameterIndex, xmlObject }, new Class[] {
int.class, SQLXML.class }));
} else {
preparedStatement.setSQLXML(parameterIndex, xmlObject);
}
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setObject", new Object[] {
parameterIndex, x, targetSqlType, scaleOrLength },
new Class[] { int.class, Object.class,
int.class, int.class }));
} else {
preparedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setAsciiStream", new Object[] {
parameterIndex, x, length }, new Class[] {
int.class, InputStream.class, long.class }));
} else {
preparedStatement.setAsciiStream(parameterIndex, x, length);
}
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBinaryStream", new Object[] {
parameterIndex, x, length }, new Class[] {
int.class, InputStream.class, long.class }));
} else {
preparedStatement.setBinaryStream(parameterIndex, x, length);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setCharacterStream", new Object[] {
parameterIndex, reader, length }, new Class[] {
int.class, Reader.class, long.class }));
} else {
preparedStatement.setCharacterStream(parameterIndex, reader, length);
}
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setAsciiStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class }));
} else {
preparedStatement.setAsciiStream(parameterIndex, x);
}
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBinaryStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class }));
} else {
preparedStatement.setBinaryStream(parameterIndex, x);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setCharacterStream", new Object[] {
parameterIndex, reader }, new Class[] { int.class,
Reader.class }));
} else {
preparedStatement.setCharacterStream(parameterIndex, reader);
}
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNCharacterStream", new Object[] {
parameterIndex, value }, new Class[] { int.class,
Reader.class }));
} else {
preparedStatement.setNCharacterStream(parameterIndex, value);
}
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setClob", new Object[] { parameterIndex,
reader }, new Class[] { int.class, Reader.class }));
} else {
preparedStatement.setClob(parameterIndex, reader);
}
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBlob", new Object[] { parameterIndex,
inputStream }, new Class[] { int.class,
InputStream.class }));
} else {
preparedStatement.setBlob(parameterIndex, inputStream);
}
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNClob", new Object[] {
parameterIndex, reader }, new Class[] { int.class,
Reader.class }));
} else {
preparedStatement.setNClob(parameterIndex, reader);
}
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setQueryTimeout",
new Object[] { seconds },
new Class[] { int.class }));
} else {
preparedStatement.setQueryTimeout(seconds);
}
}
private void setJdbcParameter(int index, Object val) {
if (preparedStatement == null) {
this.jdbcParamterForFirstAddBatch.put(index, val);
}
this.jdbcParameter.put(index, val);
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
setJdbcParameter(parameterIndex, sqlType);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNull", new Object[] { parameterIndex,
sqlType }, new Class[] { int.class, int.class }));
} else {
preparedStatement.setNull(parameterIndex, sqlType);
}
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBoolean", new Object[] {
parameterIndex, x }, new Class[] { int.class,
boolean.class }));
} else {
preparedStatement.setBoolean(parameterIndex, x);
}
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setByte", new Object[] { parameterIndex,
x }, new Class[] { int.class, byte.class }));
} else {
preparedStatement.setByte(parameterIndex, x);
}
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setShort", new Object[] {
parameterIndex, x }, new Class[] { int.class,
short.class }));
} else {
preparedStatement.setShort(parameterIndex, x);
}
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setInt", new Object[] { parameterIndex,
x }, new Class[] { int.class, int.class }));
} else {
preparedStatement.setInt(parameterIndex, x);
}
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setLong", new Object[] { parameterIndex,
x }, new Class[] { int.class, long.class }));
} else {
preparedStatement.setLong(parameterIndex, x);
}
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setFloat", new Object[] {
parameterIndex, x }, new Class[] { int.class,
float.class }));
} else {
preparedStatement.setFloat(parameterIndex, x);
}
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setDouble", new Object[] {
parameterIndex, x }, new Class[] { int.class,
double.class }));
} else {
preparedStatement.setDouble(parameterIndex, x);
}
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBigDecimal", new Object[] {
parameterIndex, x }, new Class[] { int.class,
BigDecimal.class }));
} else {
preparedStatement.setBigDecimal(parameterIndex, x);
}
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setString", new Object[] {
parameterIndex, x }, new Class[] { int.class,
String.class }));
} else {
preparedStatement.setString(parameterIndex, x);
}
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBytes", new Object[] {
parameterIndex, x }, new Class[] { int.class,
byte[].class }));
} else {
preparedStatement.setBytes(parameterIndex, x);
}
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setDate", new Object[] { parameterIndex,
x }, new Class[] { int.class, Date.class }));
} else {
preparedStatement.setDate(parameterIndex, x);
}
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTime", new Object[] { parameterIndex,
x }, new Class[] { int.class, Time.class }));
} else {
preparedStatement.setTime(parameterIndex, x);
}
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTimestamp", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Timestamp.class }));
} else {
preparedStatement.setTimestamp(parameterIndex, x);
}
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setAsciiStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class, int.class }));
} else {
preparedStatement.setAsciiStream(parameterIndex, x, length);
}
}
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setUnicodeStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class, int.class }));
} else {
preparedStatement.setUnicodeStream(parameterIndex, x, length);
}
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBinaryStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class, int.class }));
} else {
preparedStatement.setBinaryStream(parameterIndex, x, length);
}
}
}
| src/main/java/org/hellojavaer/ddr/core/datasource/jdbc/PreparedStatementWrapper.java | /*
* Copyright 2016-2016 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.hellojavaer.ddr.core.datasource.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.sql.Date;
import java.util.*;
/**
*
* @author <a href="mailto:[email protected]">zoukaiming[邹凯明]</a>,created on 20/11/2016.
*/
public abstract class PreparedStatementWrapper implements PreparedStatement {
private Connection connectionWrapper;
private Connection connection;
private PreparedStatement preparedStatement;
private String sql;
private Object[] createStatementMethodParams;
private Class[] createStatementMethodParamTypes;
private Map<Integer, Object> jdbcParamterForFirstAddBatch = new HashMap<Integer, Object>();
private Map<Integer, Object> jdbcParameter = new HashMap<Integer, Object>();
public PreparedStatementWrapper(Connection connectionWrapper, Connection connection, String sql,
Object[] createStatementMethodParams, Class[] createStatementMethodParamTypes) {
this.connectionWrapper = connectionWrapper;
this.connection = connection;
this.sql = sql;
this.createStatementMethodParams = createStatementMethodParams;
this.createStatementMethodParamTypes = createStatementMethodParamTypes;
this.pushNewExecutionContext();
}
private List<ExecutionContext> executionContexts = new LinkedList<ExecutionContext>();
private ExecutionContext getCurParamContext() {
return executionContexts.get(executionContexts.size() - 1);
}
private void pushNewExecutionContext() {
ExecutionContext newContext = new ExecutionContext();
executionContexts.add(newContext);
}
private void pushNewExecutionContext(String sql) {
ExecutionContext newContext = new ExecutionContext();
newContext.setStatementBatchSql(sql);
executionContexts.add(newContext);
}
private class ExecutionContext {
private List<InvokeRecord> invokeRecords;
private String statementBatchSql;
public List<InvokeRecord> getInvokeRecords() {
return invokeRecords;
}
public void setInvokeRecords(List<InvokeRecord> invokeRecords) {
this.invokeRecords = invokeRecords;
}
public String getStatementBatchSql() {
return statementBatchSql;
}
public void setStatementBatchSql(String statementBatchSql) {
this.statementBatchSql = statementBatchSql;
}
}
private class InvokeRecord {
private String methodName;
private Object[] params;
private Class[] paramTypes;
public InvokeRecord(String methodName, Object[] params, Class[] paramTypes) {
this.methodName = methodName;
this.params = params;
this.paramTypes = paramTypes;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
public Class[] getParamTypes() {
return paramTypes;
}
public void setParamTypes(Class[] paramTypes) {
this.paramTypes = paramTypes;
}
}
public abstract String replaceSql(String sql, Map<Integer, Object> jdbcParams);
@Override
public ResultSet executeQuery() throws SQLException {
playbackInvocation(this.sql);
return this.preparedStatement.executeQuery();
}
@Override
public int executeUpdate() throws SQLException {
playbackInvocation(this.sql);
return this.preparedStatement.executeUpdate();
}
@Override
public void clearParameters() throws SQLException {
this.jdbcParamterForFirstAddBatch.clear();
this.jdbcParameter.clear();
Iterator<ExecutionContext> it = executionContexts.iterator();
while (it.hasNext()) {
ExecutionContext context = it.next();
if (context.getStatementBatchSql() == null) {
it.remove();
}
}
}
@Override
public boolean execute() throws SQLException {
this.playbackInvocation(this.sql);
return this.preparedStatement.execute();
}
@Override
public void addBatch() throws SQLException {
this.pushNewExecutionContext();
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
throw new UnsupportedOperationException("getMetaData");
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
throw new UnsupportedOperationException("getParameterMetaData");
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeQuery(sql);
}
@Override
public int executeUpdate(String sql) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeUpdate(sql);
}
@Override
public void close() throws SQLException {
this.preparedStatement.close();
}
@Override
public int getMaxFieldSize() throws SQLException {
return this.preparedStatement.getMaxFieldSize();
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
this.preparedStatement.setMaxFieldSize(max);
}
@Override
public int getMaxRows() throws SQLException {
return this.preparedStatement.getMaxRows();
}
@Override
public void setMaxRows(int max) throws SQLException {
this.preparedStatement.setMaxRows(max);
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
this.preparedStatement.setEscapeProcessing(enable);
}
@Override
public int getQueryTimeout() throws SQLException {
return this.preparedStatement.getQueryTimeout();
}
@Override
public void cancel() throws SQLException {
this.preparedStatement.cancel();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return this.preparedStatement.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
this.preparedStatement.clearWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
this.preparedStatement.setCursorName(name);
}
@Override
public boolean execute(String sql) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql);
}
@Override
public ResultSet getResultSet() throws SQLException {
return this.preparedStatement.getResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return this.preparedStatement.getUpdateCount();
}
@Override
public boolean getMoreResults() throws SQLException {
return this.preparedStatement.getMoreResults();
}
@Override
public void setFetchDirection(int direction) throws SQLException {
this.preparedStatement.setFetchDirection(direction);
}
@Override
public int getFetchDirection() throws SQLException {
return this.preparedStatement.getFetchDirection();
}
@Override
public void setFetchSize(int rows) throws SQLException {
this.preparedStatement.setFetchSize(rows);
}
@Override
public int getFetchSize() throws SQLException {
return this.preparedStatement.getFetchSize();
}
@Override
public int getResultSetConcurrency() throws SQLException {
return this.preparedStatement.getResultSetConcurrency();
}
@Override
public int getResultSetType() throws SQLException {
return this.preparedStatement.getResultSetType();
}
@Override
public void addBatch(String sql) throws SQLException {
this.pushNewExecutionContext(sql);
}
@Override
public void clearBatch() throws SQLException {
this.executionContexts.clear();
this.pushNewExecutionContext();
}
@Override
public int[] executeBatch() throws SQLException {
this.playbackInvocation(this.sql);
return this.preparedStatement.executeBatch();
}
@Override
public Connection getConnection() throws SQLException {
return this.connectionWrapper;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return this.preparedStatement.getMoreResults();
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return this.preparedStatement.getGeneratedKeys();
}
private String playbackInvocation(String sql) throws SQLException {
try {
// 1. 替换 sql
String targetSql = replaceSql(sql, this.jdbcParamterForFirstAddBatch);
if (preparedStatement == null) {
// 2. 创建 preparedStatement
createStatementMethodParams[0] = targetSql;
PreparedStatement preparedStatement = (PreparedStatement) connection.getClass().getMethod("prepareStatement",
createStatementMethodParamTypes).invoke(connection,
createStatementMethodParams);
this.preparedStatement = preparedStatement;
}
// 2.1 回放set 方法调用
for (ExecutionContext context : executionContexts) {
if (context.getStatementBatchSql() != null) {
// TODO:校验是否同datasource
this.preparedStatement.addBatch(context.getStatementBatchSql());
} else {
// TODO:校验是否同datasource
for (InvokeRecord invokeRecord : context.getInvokeRecords()) {
this.preparedStatement.getClass().getMethod(invokeRecord.getMethodName(),
invokeRecord.getParamTypes()).invoke(preparedStatement,
invokeRecord.getParams());
}
this.preparedStatement.addBatch();
}
}
executionContexts.clear();
return targetSql;
} catch (Exception e) {
throw new SQLException(e);
}
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
sql = this.playbackInvocation(sql);
return preparedStatement.executeUpdate(sql, autoGeneratedKeys);
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeUpdate(sql, columnIndexes);
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.executeUpdate(sql, columnNames);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql, autoGeneratedKeys);
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql, columnIndexes);
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
sql = this.playbackInvocation(sql);
return this.preparedStatement.execute(sql, columnNames);
}
@Override
public int getResultSetHoldability() throws SQLException {
return this.preparedStatement.getResultSetHoldability();
}
@Override
public boolean isClosed() throws SQLException {
return this.preparedStatement.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
this.preparedStatement.setPoolable(poolable);
}
@Override
public boolean isPoolable() throws SQLException {
return this.preparedStatement.isPoolable();
}
@Override
public void closeOnCompletion() throws SQLException {
this.preparedStatement.closeOnCompletion();
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return this.preparedStatement.isCloseOnCompletion();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return this.preparedStatement.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.preparedStatement.isWrapperFor(iface);
}
// /////////////////
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setObject", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Object.class, int.class }));
} else {
preparedStatement.setObject(parameterIndex, x, targetSqlType);
}
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setObject", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Object.class }));
} else {
preparedStatement.setObject(parameterIndex, x);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setCharacterStream", new Object[] {
parameterIndex, reader, length }, new Class[] {
int.class, Reader.class, int.class }));
} else {
preparedStatement.setCharacterStream(parameterIndex, reader, length);
}
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setRef", new Object[] { parameterIndex,
x }, new Class[] { int.class, Ref.class }));
} else {
preparedStatement.setRef(parameterIndex, x);
}
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBlob", new Object[] { parameterIndex,
x }, new Class[] { int.class, Blob.class }));
} else {
preparedStatement.setBlob(parameterIndex, x);
}
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setClob", new Object[] { parameterIndex,
x }, new Class[] { int.class, Clob.class }));
} else {
preparedStatement.setClob(parameterIndex, x);
}
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setArray", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Array.class }));
} else {
preparedStatement.setArray(parameterIndex, x);
}
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setDate", new Object[] { parameterIndex,
x }, new Class[] { int.class, Date.class,
Calendar.class }));
} else {
preparedStatement.setDate(parameterIndex, x, cal);
}
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTime", new Object[] { parameterIndex,
x }, new Class[] { int.class, Time.class,
Calendar.class }));
} else {
preparedStatement.setTime(parameterIndex, x, cal);
}
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTimestamp", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Timestamp.class, Calendar.class }));
} else {
preparedStatement.setTimestamp(parameterIndex, x, cal);
}
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
setJdbcParameter(parameterIndex, null);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNull", new Object[] { parameterIndex,
sqlType, typeName }, new Class[] { int.class,
int.class, String.class }));
} else {
preparedStatement.setNull(parameterIndex, sqlType, typeName);
}
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setURL", new Object[] { parameterIndex,
x }, new Class[] { int.class, URL.class }));
} else {
preparedStatement.setURL(parameterIndex, x);
}
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setRowId", new Object[] {
parameterIndex, x }, new Class[] { int.class,
RowId.class }));
} else {
preparedStatement.setRowId(parameterIndex, x);
}
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
setJdbcParameter(parameterIndex, value);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNString", new Object[] {
parameterIndex, value }, new Class[] { int.class,
String.class }));
} else {
preparedStatement.setNString(parameterIndex, value);
}
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNCharacterStream", new Object[] {
parameterIndex, value, length }, new Class[] {
int.class, Reader.class }));
} else {
preparedStatement.setNCharacterStream(parameterIndex, value, length);
}
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
setJdbcParameter(parameterIndex, value);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNClob", new Object[] {
parameterIndex, value }, new Class[] { int.class,
NClob.class }));
} else {
preparedStatement.setNClob(parameterIndex, value);
}
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
setJdbcParameter(parameterIndex, length);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setClob", new Object[] { parameterIndex,
reader, length }, new Class[] { int.class,
Reader.class, long.class }));
} else {
preparedStatement.setClob(parameterIndex, reader, length);
}
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBlob", new Object[] { parameterIndex,
inputStream, length }, new Class[] { int.class,
InputStream.class, long.class }));
} else {
preparedStatement.setBlob(parameterIndex, inputStream, length);
}
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNClob", new Object[] {
parameterIndex, reader, length }, new Class[] {
int.class, Reader.class, long.class }));
} else {
preparedStatement.setNClob(parameterIndex, reader, length);
}
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setSQLXML", new Object[] {
parameterIndex, xmlObject }, new Class[] {
int.class, SQLXML.class }));
} else {
preparedStatement.setSQLXML(parameterIndex, xmlObject);
}
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setObject", new Object[] {
parameterIndex, x, targetSqlType, scaleOrLength },
new Class[] { int.class, Object.class,
int.class, int.class }));
} else {
preparedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setAsciiStream", new Object[] {
parameterIndex, x, length }, new Class[] {
int.class, InputStream.class, long.class }));
} else {
preparedStatement.setAsciiStream(parameterIndex, x, length);
}
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBinaryStream", new Object[] {
parameterIndex, x, length }, new Class[] {
int.class, InputStream.class, long.class }));
} else {
preparedStatement.setBinaryStream(parameterIndex, x, length);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setCharacterStream", new Object[] {
parameterIndex, reader, length }, new Class[] {
int.class, Reader.class, long.class }));
} else {
preparedStatement.setCharacterStream(parameterIndex, reader, length);
}
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setAsciiStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class }));
} else {
preparedStatement.setAsciiStream(parameterIndex, x);
}
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBinaryStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class }));
} else {
preparedStatement.setBinaryStream(parameterIndex, x);
}
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setCharacterStream", new Object[] {
parameterIndex, reader }, new Class[] { int.class,
Reader.class }));
} else {
preparedStatement.setCharacterStream(parameterIndex, reader);
}
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNCharacterStream", new Object[] {
parameterIndex, value }, new Class[] { int.class,
Reader.class }));
} else {
preparedStatement.setNCharacterStream(parameterIndex, value);
}
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setClob", new Object[] { parameterIndex,
reader }, new Class[] { int.class, Reader.class }));
} else {
preparedStatement.setClob(parameterIndex, reader);
}
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBlob", new Object[] { parameterIndex,
inputStream }, new Class[] { int.class,
InputStream.class }));
} else {
preparedStatement.setBlob(parameterIndex, inputStream);
}
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNClob", new Object[] {
parameterIndex, reader }, new Class[] { int.class,
Reader.class }));
} else {
preparedStatement.setNClob(parameterIndex, reader);
}
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setQueryTimeout",
new Object[] { seconds },
new Class[] { int.class }));
} else {
preparedStatement.setQueryTimeout(seconds);
}
}
private void setJdbcParameter(int index, Object val) {
if (preparedStatement == null) {
this.jdbcParamterForFirstAddBatch.put(index, val);
}
this.jdbcParameter.put(index, val);
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
setJdbcParameter(parameterIndex, sqlType);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setNull", new Object[] { parameterIndex,
sqlType }, new Class[] { int.class, int.class }));
} else {
preparedStatement.setNull(parameterIndex, sqlType);
}
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBoolean", new Object[] {
parameterIndex, x }, new Class[] { int.class,
boolean.class }));
} else {
preparedStatement.setBoolean(parameterIndex, x);
}
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setByte", new Object[] { parameterIndex,
x }, new Class[] { int.class, byte.class }));
} else {
preparedStatement.setByte(parameterIndex, x);
}
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setShort", new Object[] {
parameterIndex, x }, new Class[] { int.class,
short.class }));
} else {
preparedStatement.setShort(parameterIndex, x);
}
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setInt", new Object[] { parameterIndex,
x }, new Class[] { int.class, int.class }));
} else {
preparedStatement.setInt(parameterIndex, x);
}
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setLong", new Object[] { parameterIndex,
x }, new Class[] { int.class, long.class }));
} else {
preparedStatement.setLong(parameterIndex, x);
}
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setFloat", new Object[] {
parameterIndex, x }, new Class[] { int.class,
float.class }));
} else {
preparedStatement.setFloat(parameterIndex, x);
}
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setDouble", new Object[] {
parameterIndex, x }, new Class[] { int.class,
double.class }));
} else {
preparedStatement.setDouble(parameterIndex, x);
}
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBigDecimal", new Object[] {
parameterIndex, x }, new Class[] { int.class,
BigDecimal.class }));
} else {
preparedStatement.setBigDecimal(parameterIndex, x);
}
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setString", new Object[] {
parameterIndex, x }, new Class[] { int.class,
String.class }));
} else {
preparedStatement.setString(parameterIndex, x);
}
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBytes", new Object[] {
parameterIndex, x }, new Class[] { int.class,
byte[].class }));
} else {
preparedStatement.setBytes(parameterIndex, x);
}
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setDate", new Object[] { parameterIndex,
x }, new Class[] { int.class, Date.class }));
} else {
preparedStatement.setDate(parameterIndex, x);
}
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTime", new Object[] { parameterIndex,
x }, new Class[] { int.class, Time.class }));
} else {
preparedStatement.setTime(parameterIndex, x);
}
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
setJdbcParameter(parameterIndex, x);
setJdbcParameter(parameterIndex, x);
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setTimestamp", new Object[] {
parameterIndex, x }, new Class[] { int.class,
Timestamp.class }));
} else {
preparedStatement.setTimestamp(parameterIndex, x);
}
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setAsciiStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class, int.class }));
} else {
preparedStatement.setAsciiStream(parameterIndex, x, length);
}
}
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setUnicodeStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class, int.class }));
} else {
preparedStatement.setUnicodeStream(parameterIndex, x, length);
}
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
if (preparedStatement == null) {
this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setBinaryStream", new Object[] {
parameterIndex, x }, new Class[] { int.class,
InputStream.class, int.class }));
} else {
preparedStatement.setBinaryStream(parameterIndex, x, length);
}
}
}
| update
| src/main/java/org/hellojavaer/ddr/core/datasource/jdbc/PreparedStatementWrapper.java | update | <ide><path>rc/main/java/org/hellojavaer/ddr/core/datasource/jdbc/PreparedStatementWrapper.java
<ide> this.preparedStatement.close();
<ide> }
<ide>
<add> private StatementProperty statementProperty = new StatementProperty();
<add>
<add> private class StatementProperty {
<add>
<add> private int maxFieldSize;
<add> private int maxRows;
<add> private int fetchDirection;
<add> private int fetchSize;
<add>
<add> public int getMaxFieldSize() {
<add> return maxFieldSize;
<add> }
<add>
<add> public void setMaxFieldSize(int maxFieldSize) {
<add> this.maxFieldSize = maxFieldSize;
<add> }
<add>
<add> public int getMaxRows() {
<add> return maxRows;
<add> }
<add>
<add> public void setMaxRows(int maxRows) {
<add> this.maxRows = maxRows;
<add> }
<add>
<add> public int getFetchDirection() {
<add> return fetchDirection;
<add> }
<add>
<add> public void setFetchDirection(int fetchDirection) {
<add> this.fetchDirection = fetchDirection;
<add> }
<add>
<add> public int getFetchSize() {
<add> return fetchSize;
<add> }
<add>
<add> public void setFetchSize(int fetchSize) {
<add> this.fetchSize = fetchSize;
<add> }
<add> }
<add>
<ide> @Override
<ide> public int getMaxFieldSize() throws SQLException {
<del> return this.preparedStatement.getMaxFieldSize();
<add> if (preparedStatement == null) {
<add> return statementProperty.getMaxFieldSize();
<add> } else {
<add> return this.preparedStatement.getMaxFieldSize();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void setMaxFieldSize(int max) throws SQLException {
<del> this.preparedStatement.setMaxFieldSize(max);
<add> if (preparedStatement == null) {
<add> statementProperty.setMaxFieldSize(max);
<add> this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setMaxFieldSize", new Object[] { max },
<add> new Class[] { int.class }));
<add> } else {
<add> this.preparedStatement.setMaxFieldSize(max);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public int getMaxRows() throws SQLException {
<del> return this.preparedStatement.getMaxRows();
<add> if (preparedStatement == null) {
<add> return statementProperty.getMaxRows();
<add> } else {
<add> return this.preparedStatement.getMaxRows();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void setMaxRows(int max) throws SQLException {
<del> this.preparedStatement.setMaxRows(max);
<add> if (preparedStatement == null) {
<add> statementProperty.setMaxRows(max);
<add> this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setMaxRows", new Object[] { max },
<add> new Class[] { int.class }));
<add> } else {
<add> this.preparedStatement.setMaxRows(max);
<add> }
<add> }
<add>
<add> @Override
<add> public void setFetchDirection(int direction) throws SQLException {
<add> if (preparedStatement == null) {
<add> statementProperty.setFetchDirection(direction);
<add> this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setFetchDirection",
<add> new Object[] { direction },
<add> new Class[] { int.class }));
<add> } else {
<add> this.preparedStatement.setFetchDirection(direction);
<add> }
<add> }
<add>
<add> @Override
<add> public int getFetchDirection() throws SQLException {
<add> if (preparedStatement == null) {
<add> return statementProperty.getFetchDirection();
<add> } else {
<add> return this.preparedStatement.getFetchDirection();
<add> }
<add> }
<add>
<add> @Override
<add> public void setFetchSize(int rows) throws SQLException {
<add> if (preparedStatement == null) {
<add> statementProperty.setFetchSize(rows);
<add> this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setFetchSize", new Object[] { rows },
<add> new Class[] { int.class }));
<add> } else {
<add> this.preparedStatement.setFetchSize(rows);
<add> }
<add> }
<add>
<add> @Override
<add> public int getFetchSize() throws SQLException {
<add> if (preparedStatement == null) {
<add> return statementProperty.getFetchSize();
<add> } else {
<add> return this.preparedStatement.getFetchSize();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void setEscapeProcessing(boolean enable) throws SQLException {
<del> this.preparedStatement.setEscapeProcessing(enable);
<add> if (preparedStatement == null) {
<add> this.getCurParamContext().getInvokeRecords().add(new InvokeRecord("setEscapeProcessing",
<add> new Object[] { enable },
<add> new Class[] { boolean.class }));
<add> } else {
<add> this.preparedStatement.setEscapeProcessing(enable);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> @Override
<ide> public boolean getMoreResults() throws SQLException {
<ide> return this.preparedStatement.getMoreResults();
<del> }
<del>
<del> @Override
<del> public void setFetchDirection(int direction) throws SQLException {
<del> this.preparedStatement.setFetchDirection(direction);
<del> }
<del>
<del> @Override
<del> public int getFetchDirection() throws SQLException {
<del> return this.preparedStatement.getFetchDirection();
<del> }
<del>
<del> @Override
<del> public void setFetchSize(int rows) throws SQLException {
<del> this.preparedStatement.setFetchSize(rows);
<del> }
<del>
<del> @Override
<del> public int getFetchSize() throws SQLException {
<del> return this.preparedStatement.getFetchSize();
<ide> }
<ide>
<ide> @Override |
|
JavaScript | bsd-2-clause | a0bf5327740ce4c90a656931f270a49fb594636a | 0 | tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal | /**
* Copyright (c) 2011-2014 by Camptocamp SA
*
* CGXP 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.
*
* CGXP 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 CGXP. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.define('App.controller.Main', {
extend: 'Ext.app.Controller',
config: {
overlay: null,
refs: {
mainView: 'mainview',
layersView: 'layersview',
settingsView: {
selector: 'settingsview',
xtype: 'settingsview',
autoCreate: true
},
loginFormView: {
selector: 'loginformview',
xtype: 'loginformview',
autoCreate: true
},
themesView: {
selector: 'themesview',
xtype: 'themesview',
autoCreate: true
}
},
control: {
'button[action=home]': {
tap: function() {
this.redirectTo('home');
}
},
'button[action=layers]': {
tap: function() {
this.redirectTo('layers');
}
},
'button[action=settings]': {
tap: function() {
this.redirectTo('settings');
}
},
'button[action=loginform]': {
tap: function() {
this.redirectTo('loginform');
}
},
'button[action=login]': {
tap: function() {
this.login();
}
},
'button[action=logout]': {
tap: function() {
this.logout();
}
},
mainView: {
'query': function(view, bounds, map) {
this.queryMap(view, bounds, map);
}
},
'#baselayer_switcher': {
'change': function(select, newValue) {
App.map.setBaseLayer(App.map.getLayer(newValue));
this.redirectTo('');
}
},
'#theme_switcher': {
tap: function() {
this.redirectTo('themes');
}
},
themesView: {
itemtap: 'onThemeChange'
}
},
routes: {
'': 'showHome',
'home': 'showHome',
'layers': 'showLayers',
'settings': 'showSettings',
'themes': 'showThemes',
'loginform': 'showLoginForm'
}
},
//called when the Application is launched, remove if not needed
launch: function(app) {
// To deal with params, the following methods are available:
// * `getParams`: returns all params
// * `setParams`: used to update the values of some params
//
// Three OpenLayers Map events are also available:
// * `changeparams`: launched with the changed params values
// * `changeparamsready`: launched when the application is ready to
// receive `dochangeparams` events
// * `dochangeparams`: used to call for `setParams` without knowing
// the current object.
//
// Events are passed through the map in order to be able to create an
// OpenLayers Controller that uses the params without any dependencies
// on Sencha Touch, required by a project component.
this.params = {};
this.map = this.getMainView().getMap();
this.map.events.register('addlayer', this, function(event){
this.setLayerParams(this.params)(event.layer);
});
this.map.events.register('dochangeparams', this, function(event){
this.setParams(event.params);
});
this.map.events.triggerEvent('changeparamsready');
this.layers = {};
for (var i = 0, il = App.themes.length; i < il; i++ ) {
var theme = App.themes[i];
for (var j = 0, jl = theme.allLayers.length; j < jl; j++ ) {
var layer = theme.allLayers[j];
var childLayers = layer.childLayers || [];
this.layers[layer.name] = layer;
for (var k = 0, kl = childLayers.length; k < kl; k++ ) {
this.layers[childLayers[k].name] = childLayers[k];
}
}
}
},
showHome: function() {
var animation = {type: 'reveal', direction: 'down'};
if (Ext.Viewport.getActiveItem() == this.getLoginFormView()) {
animation = {type: 'fade'};
}
Ext.Viewport.animateActiveItem(0, animation);
var view = this.getLayersView();
var mainView = this.getMainView();
view.getStore().setData(mainView.getMap().layers);
},
showLayers: function() {
var view = this.getLayersView();
if (!view) {
view = Ext.create('App.view.Layers');
view.getStore().setData(this.getMainView().getMap().layers);
}
var animation;
if (Ext.Viewport.getActiveItem() == this.getMainView()) {
animation = {type: 'cover', direction: 'up'};
} else if (Ext.Viewport.getActiveItem() == this.getThemesView()) {
animation = {type: 'slide', direction: 'right'};
}
Ext.Viewport.animateActiveItem(view, animation);
},
showLoginForm: function() {
var view = this.getLoginFormView();
var animation = {type: 'fade'};
Ext.Viewport.animateActiveItem(view, animation);
},
showSettings: function() {
var view = this.getSettingsView();
var animation = {type: 'cover', direction: 'up'};
Ext.Viewport.animateActiveItem(view, animation);
},
showThemes: function() {
var view = this.getThemesView();
var animation = {type: 'slide', direction: 'left'};
Ext.Viewport.animateActiveItem(view, animation);
},
login: function() {
this.getLoginFormView().submit({});
},
logout: function() {
Ext.Ajax.request({
url: App.logoutUrl,
success: function(response) {
var sep = App.cameFrom.indexOf('?') > 0 ? '&' : '?';
window.location = App.cameFrom + sep + 'v=' + Math.round(Math.random() * 1000000);
},
failure: function(response, opts) {
Ext.Msg.alert(response.statusText);
}
});
},
recenterMap: function(f) {
this.getMainView().recenterOnFeature(f);
this.redirectTo('home');
},
getParams: function() {
return this.params;
},
setParams: function(params) {
Ext.apply(this.params, params);
this.map.layers.map(this.setLayerParams(params));
this.map.events.triggerEvent("changeparams", {
params: params
});
},
setLayerParams: function(params) {
return function(layer) {
if (layer.setParams) {
layer.setParams(params);
}
else if (layer.mergeNewParams) { // WMS or WMTS
layer.mergeNewParams(params);
}
};
},
toArray: function(value) {
return Ext.isArray(value) ? value : value.split(',');
},
// get the list of queryable layers given a list of displayed WMS layers
getChildLayers: function(ollayer, params) {
var results = [];
Ext.each(params, function(p) {
var layer = this.layers[p]
if (layer.childLayers) {
Ext.each(layer.childLayers, function(item) {
results.push(item.name);
});
} else {
results.push(layer.name);
}
}, this);
return results;
},
filterScale: function(layers) {
var res = App.map.getResolution();
function inRange(l) {
return (!l.minResolutionHint || res >= l.minResolutionHint) &&
(!l.maxResolutionHint || res <= l.maxResolutionHint);
}
var results = [];
Ext.each(layers, function(layer) {
if (inRange(this.layers[layer])) {
results.push(layer)
}
}, this);
return results;
},
filterWFS: function(layers) {
var results = [];
for (var j = 0; j < layers.length; j++) {
if (App.WFSTypes.indexOf(layers[j]) != -1) {
results.push(layers[j]);
}
}
return results;
},
queryMap: function(view, bounds, map) {
// overlay
var overlay = this.getOverlay();
var layers = this.toArray(overlay.params.LAYERS);
// Ensure that we query the child layers in case of groups
layers = this.getChildLayers(overlay, layers);
layers = this.filterScale(layers);
layers = this.filterWFS(layers);
// currently displayed baseLayer
if (map.baseLayer.WFSTypes) {
layers = layers.concat(this.toArray(map.baseLayer.WFSTypes));
}
// launch query only if there are layers or raster to query
if (layers.length || App.raster) {
var layers = encodeURIComponent(layers.join('-'));
var bounds = encodeURIComponent(bounds.toArray().join('-'));
this.redirectTo(['query', bounds, layers].join('/'));
}
},
onThemeChange: function(list, index, target, record) {
var map = this.getMainView().getMap(),
theme = record.get('name'),
overlay = this.getOverlay();
if (overlay) {
map.removeLayer(overlay);
}
this.loadTheme(theme);
this.getLayersView().getStore().setData(map.layers);
this.redirectTo('layers');
},
loadTheme: function(theme) {
if (!theme) {
if (App.themes && App.themes.length > 0) {
App.theme = theme = App.themes[0].name;
}
else if (console) {
console.log("No themes are displayed in mobile for the curent role");
}
}
Ext.each(App.themes, function(t) {
if (t.name == theme) {
if (App.map.getLayerIndex(this.getOverlay()) != -1) {
App.map.removeLayer(this.getOverlay());
}
var overlay = new OpenLayers.Layer.WMS(
'overlay',
App.wmsUrl,
{
// layers to display at startup
layers: t.layers,
transparent: true
},{
singleTile: true
}
);
App.map.addLayer(overlay);
this.setOverlay(overlay);
App.theme = theme;
App.map.events.triggerEvent('themechange');
return false;
}
}, this);
}
});
| c2cgeoportal/scaffolds/update/+package+/static/mobile/app/controller/Main.js | /**
* Copyright (c) 2011-2014 by Camptocamp SA
*
* CGXP 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.
*
* CGXP 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 CGXP. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.define('App.controller.Main', {
extend: 'Ext.app.Controller',
config: {
overlay: null,
refs: {
mainView: 'mainview',
layersView: 'layersview',
settingsView: {
selector: 'settingsview',
xtype: 'settingsview',
autoCreate: true
},
loginFormView: {
selector: 'loginformview',
xtype: 'loginformview',
autoCreate: true
},
themesView: {
selector: 'themesview',
xtype: 'themesview',
autoCreate: true
}
},
control: {
'button[action=home]': {
tap: function() {
this.redirectTo('home');
}
},
'button[action=layers]': {
tap: function() {
this.redirectTo('layers');
}
},
'button[action=settings]': {
tap: function() {
this.redirectTo('settings');
}
},
'button[action=loginform]': {
tap: function() {
this.redirectTo('loginform');
}
},
'button[action=login]': {
tap: function() {
this.login();
}
},
'button[action=logout]': {
tap: function() {
this.logout();
}
},
mainView: {
'query': function(view, bounds, map) {
this.queryMap(view, bounds, map);
}
},
'#baselayer_switcher': {
'change': function(select, newValue) {
App.map.setBaseLayer(App.map.getLayer(newValue));
this.redirectTo('');
}
},
'#theme_switcher': {
tap: function() {
this.redirectTo('themes');
}
},
themesView: {
itemtap: 'onThemeChange'
}
},
routes: {
'': 'showHome',
'home': 'showHome',
'layers': 'showLayers',
'settings': 'showSettings',
'themes': 'showThemes',
'loginform': 'showLoginForm'
}
},
//called when the Application is launched, remove if not needed
launch: function(app) {
// To deal with params, the following methods are available:
// * `getParams`: returns all params
// * `setParams`: used to update the values of some params
//
// Three OpenLayers Map events are also available:
// * `changeparams`: launched with the changed params values
// * `changeparamsready`: launched when the application is ready to
// receive `dochangeparams` events
// * `dochangeparams`: used to call for `setParams` without knowing
// the current object.
//
// Events are passed through the map in order to be able to create an
// OpenLayers Controller that uses the params without any dependencies
// on Sencha Touch, required by a project component.
this.params = {};
this.map = this.getMainView().getMap();
this.map.events.register('addlayer', this, function(event){
this.setLayerParams(this.params)(event.layer);
});
this.map.events.register('dochangeparams', this, function(event){
this.setParams(event.params);
});
this.map.events.triggerEvent('changeparamsready');
this.layers = {};
for (var i = 0, il = App.themes.length; i < il; i++ ) {
var theme = App.themes[i];
for (var j = 0, jl = theme.allLayers.length; j < jl; j++ ) {
var layer = theme.allLayers[j];
var childLayers = layer.childLayers || [];
this.layers[layer.name] = layer;
for (var k = 0, kl = childLayers.length; k < kl; k++ ) {
this.layers[childLayers[k].name] = childLayers[k];
}
}
}
},
showHome: function() {
var animation = {type: 'reveal', direction: 'down'};
if (Ext.Viewport.getActiveItem() == this.getLoginFormView()) {
animation = {type: 'fade'};
}
Ext.Viewport.animateActiveItem(0, animation);
var view = this.getLayersView();
var mainView = this.getMainView();
view.getStore().setData(mainView.getMap().layers);
},
showLayers: function() {
var view = this.getLayersView();
if (!view) {
view = Ext.create('App.view.Layers');
view.getStore().setData(this.getMainView().getMap().layers);
}
var animation;
if (Ext.Viewport.getActiveItem() == this.getMainView()) {
animation = {type: 'cover', direction: 'up'};
} else if (Ext.Viewport.getActiveItem() == this.getThemesView()) {
animation = {type: 'slide', direction: 'right'};
}
Ext.Viewport.animateActiveItem(view, animation);
},
showLoginForm: function() {
var view = this.getLoginFormView();
var animation = {type: 'fade'};
Ext.Viewport.animateActiveItem(view, animation);
},
showSettings: function() {
var view = this.getSettingsView();
var animation = {type: 'cover', direction: 'up'};
Ext.Viewport.animateActiveItem(view, animation);
},
showThemes: function() {
var view = this.getThemesView();
var animation = {type: 'slide', direction: 'left'};
Ext.Viewport.animateActiveItem(view, animation);
},
login: function() {
this.getLoginFormView().submit({});
},
logout: function() {
Ext.Ajax.request({
url: App.logoutUrl,
success: function(response) {
var sep = App.cameFrom.indexOf('?') > 0 ? '&' : '?';
window.location = App.cameFrom + sep + 'v=' + Math.round(Math.random() * 1000000);
},
failure: function(response, opts) {
Ext.Msg.alert(response.statusText);
}
});
},
recenterMap: function(f) {
this.getMainView().recenterOnFeature(f);
this.redirectTo('home');
},
getParams: function() {
return this.params;
},
setParams: function(params) {
Ext.apply(this.params, params);
this.map.layers.map(this.setLayerParams(params));
this.map.events.triggerEvent("changeparams", {
params: params
});
},
setLayerParams: function(params) {
return function(layer) {
if (layer.setParams) {
layer.setParams(params);
}
else if (layer.mergeNewParams) { // WMS or WMTS
layer.mergeNewParams(params);
}
};
},
toArray: function(value) {
return Ext.isArray(value) ? value : value.split(',');
},
// get the list of queryable layers given a list of displayed WMS layers
getChildLayers: function(ollayer, params) {
var results = [];
Ext.each(params, function(p) {
var layer = this.layers[p]
if (layer.childLayers) {
Ext.each(layer.childLayers, function(item) {
results.push(item.name);
});
} else {
results.push(layer.name);
}
}, this);
return results;
},
filterScale: function(layers) {
var res = App.map.getResolution();
function inRange(l) {
return (!l.minResolutionHint || res >= l.minResolutionHint) &&
(!l.maxResolutionHint || res <= l.maxResolutionHint);
}
var results = [];
Ext.each(layers, function(layer) {
if (inRange(this.layers[layer])) {
results.push(layer)
}
}, this);
return results;
},
filterWFS: function(layers) {
var results = [];
for (var j = 0; j < layers.length; j++) {
if (App.WFSTypes.indexOf(layers[j]) != -1) {
results.push(layers[j]);
}
}
return results;
},
queryMap: function(view, bounds, map) {
// overlay
var overlay = this.getOverlay();
var layers = this.toArray(overlay.params.LAYERS);
// Ensure that we query the child layers in case of groups
layers = this.getChildLayers(overlay, layers);
layers = this.filterScale(layers);
layers = this.filterWFS(layers);
// currently displayed baseLayer
if (map.baseLayer.WFSTypes) {
layers = layers.concat(this.toArray(map.baseLayer.WFSTypes));
}
// launch query only if there are layers or raster to query
if (layers.length || App.raster) {
var layers = encodeURIComponent(layers.join('-'));
var bounds = encodeURIComponent(bounds.toArray().join('-'));
this.redirectTo(['query', bounds, layers].join('/'));
}
},
onThemeChange: function(list, index, target, record) {
var map = this.getMainView().getMap(),
theme = record.get('name'),
overlay = this.getOverlay();
if (overlay) {
map.removeLayer(overlay);
}
this.loadTheme(theme);
this.getLayersView().getStore().setData(map.layers);
this.redirectTo('layers');
},
loadTheme: function(theme) {
if (!theme) {
if (App.themes && App.themes.length > 0) {
App.theme = theme = App.themes[0].name;
}
else if (console) {
console.log("No themes are displayed in mobile for the curent role");
}
}
Ext.each(App.themes, function(t) {
if (t.name == theme) {
if (App.map.getLayerIndex(this.getOverlay()) != -1) {
App.map.removeLayer(this.getOverlay());
}
var overlay = new OpenLayers.Layer.WMS(
'overlay',
App.wmsUrl,
{
// layers to display at startup
layers: t.layers,
transparent: true
},{
singleTile: true,
}
);
App.map.addLayer(overlay);
this.setOverlay(overlay);
App.theme = theme;
App.map.events.triggerEvent('themechange');
return false;
}
}, this);
}
});
| Remove comma
| c2cgeoportal/scaffolds/update/+package+/static/mobile/app/controller/Main.js | Remove comma | <ide><path>2cgeoportal/scaffolds/update/+package+/static/mobile/app/controller/Main.js
<ide> layers: t.layers,
<ide> transparent: true
<ide> },{
<del> singleTile: true,
<add> singleTile: true
<ide> }
<ide> );
<ide> App.map.addLayer(overlay); |
|
Java | mit | 2ed922687135e33c55f14ba97001bb684b14f324 | 0 | FredMaris/touist,touist/touist,olzd/touist,touist/touist,olzd/touist,FredMaris/touist,FredMaris/touist,olzd/touist,touist/touist,touist/touist | /*
* 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 gui.editionView;
import gui.MainFrame;
import gui.State;
import gui.TranslatorLatex.TranslationLatex;
import gui.editionView.editor.Editor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
/**
*
* @author Skander
*/
public class InsertionButton extends JButton {
private final Editor editorTextArea;
private final String codeToInsert;
private ArrayList<Integer> snipets;
public InsertionButton(Editor editorTextArea, final String codeToInsert, ArrayList<Integer> snipets) {
this.editorTextArea = editorTextArea;
this.codeToInsert = codeToInsert;
this.snipets = snipets;
//this.setText(codeToInsert);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
((MainFrame)(getRootPane().getParent())).state = State.EDITION;
insertAtCaret(codeToInsert);
break;
case EDITION_ERROR :
((MainFrame)(getRootPane().getParent())).state = State.EDITION_ERROR;
insertAtCaret(codeToInsert);
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + ((MainFrame)(getRootPane().getParent())).state);
}
}
});
try {
TranslationLatex toLatex = new TranslationLatex(codeToInsert);
TeXFormula formula = new TeXFormula(toLatex.getFormula());
TeXIcon ti = formula.createTeXIcon(TeXConstants.ALIGN_TOP, 15);
this.setIcon(ti);
} catch (Exception ex) {
System.err.println("Erreur lors de la traduction dun bouton "+codeToInsert);
}
this.setFocusable(false);
this.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
this.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
}
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets, String aide) {
this(editorTextArea, codeToInsert, snipets);
setToolTipText(aide);
}
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets, String aide, String latexFormula) {
this(editorTextArea, codeToInsert, snipets,aide);
TeXFormula formula = new TeXFormula(latexFormula);
TeXIcon ti = formula.createTeXIcon(TeXConstants.ALIGN_TOP, 15);
this.setIcon(ti);
}
/**
* Insert text at the caret position in the textArea.
* @param text
*/
private void insertAtCaret(String text) {
if (editorTextArea.hasFocus()) {
Integer caretPosition = editorTextArea.getCaretPosition();
// insert is better than setText: setText entirely remove previous text then make an insert operation
editorTextArea.insert(text, caretPosition);
for(int snippetBegin = 0; snippetBegin < snipets.size(); snippetBegin+=2) {
int snippetEnd = snippetBegin + 1;
editorTextArea.addSnipet(caretPosition+snipets.get(snippetBegin),caretPosition+snipets.get(snippetEnd));
}
}
//TODO update latex schematic area
}
}
| touist-gui/src/gui/editionView/InsertionButton.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 gui.editionView;
import gui.MainFrame;
import gui.State;
import gui.TranslatorLatex.TranslationLatex;
import gui.editionView.editor.Editor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
/**
*
* @author Skander
*/
public class InsertionButton extends JButton {
private final Editor editorTextArea;
private final String codeToInsert;
private ArrayList<Integer> snipets;
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets) {
this.editorTextArea = editorTextArea;
this.codeToInsert = codeToInsert;
this.snipets = snipets;
//this.setText(codeToInsert);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
((MainFrame)(getRootPane().getParent())).state = State.EDITION;
insertAtCaret(codeToInsert);
break;
case EDITION_ERROR :
((MainFrame)(getRootPane().getParent())).state = State.EDITION_ERROR;
insertAtCaret(codeToInsert);
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + ((MainFrame)(getRootPane().getParent())).state);
}
}
});
try {
TranslationLatex toLatex = new TranslationLatex(codeToInsert);
TeXFormula formula = new TeXFormula(toLatex.getFormula());
TeXIcon ti = formula.createTeXIcon(TeXConstants.ALIGN_TOP, 15);
this.setIcon(ti);
} catch (Exception ex) {
System.err.println("Erreur lors de la traduction dun bouton "+codeToInsert);
}
this.setFocusable(false);
this.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
this.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
}
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets, String aide) {
this(editorTextArea, codeToInsert, snipets);
setToolTipText(aide);
}
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets, String aide, String latexFormula) {
this(editorTextArea, codeToInsert, snipets,aide);
TeXFormula formula = new TeXFormula(latexFormula);
TeXIcon ti = formula.createTeXIcon(TeXConstants.ALIGN_TOP, 15);
this.setIcon(ti);
}
/**
* Insert text at the caret position in the textArea.
* @param text
*/
private void insertAtCaret(String text) {
if (editorTextArea.hasFocus()) {
Integer caretPosition = editorTextArea.getCaretPosition();
// insert is better than setText: setText entirely remove previous text then make an insert operation
editorTextArea.insert(text, caretPosition);
for(int snippetBegin = 0; snippetBegin < snipets.size(); snippetBegin+=2) {
int snippetEnd = snippetBegin + 1;
editorTextArea.addSnipet(caretPosition+snipets.get(snippetBegin),caretPosition+snipets.get(snippetEnd));
}
}
//TODO update latex schematic area
}
}
| final on codeToInsert needed when calling insertAtCaret(codeToInsert) #65
| touist-gui/src/gui/editionView/InsertionButton.java | final on codeToInsert needed when calling insertAtCaret(codeToInsert) #65 | <ide><path>ouist-gui/src/gui/editionView/InsertionButton.java
<ide> import gui.State;
<ide> import gui.TranslatorLatex.TranslationLatex;
<ide> import gui.editionView.editor.Editor;
<add>
<ide> import java.awt.event.ActionEvent;
<ide> import java.awt.event.ActionListener;
<ide> import java.util.ArrayList;
<add>
<ide> import javax.swing.JButton;
<add>
<ide> import org.scilab.forge.jlatexmath.TeXConstants;
<ide> import org.scilab.forge.jlatexmath.TeXFormula;
<ide> import org.scilab.forge.jlatexmath.TeXIcon;
<ide> private final String codeToInsert;
<ide> private ArrayList<Integer> snipets;
<ide>
<del> public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets) {
<add> public InsertionButton(Editor editorTextArea, final String codeToInsert, ArrayList<Integer> snipets) {
<ide> this.editorTextArea = editorTextArea;
<ide> this.codeToInsert = codeToInsert;
<ide> this.snipets = snipets; |
|
Java | apache-2.0 | 083285e789eb04cbdc3cb25a96749afebc696a1f | 0 | da1z/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,signed/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,kool79/intellij-community,semonte/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,amith01994/intellij-community,izonder/intellij-community,kdwink/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,caot/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,kool79/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,robovm/robovm-studio,diorcety/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,signed/intellij-community,suncycheng/intellij-community,samthor/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,supersven/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,kool79/intellij-community,holmes/intellij-community,diorcety/intellij-community,da1z/intellij-community,vladmm/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,izonder/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ibinti/intellij-community,dslomov/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,apixandru/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,clumsy/intellij-community,samthor/intellij-community,da1z/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,dslomov/intellij-community,holmes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,samthor/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,signed/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,allotria/intellij-community,diorcety/intellij-community,retomerz/intellij-community,caot/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,signed/intellij-community,slisson/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,petteyg/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,hurricup/intellij-community,apixandru/intellij-community,da1z/intellij-community,orekyuu/intellij-community,samthor/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,supersven/intellij-community,FHannes/intellij-community,fitermay/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,dslomov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,kdwink/intellij-community,blademainer/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,holmes/intellij-community,holmes/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,blademainer/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,holmes/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,holmes/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,supersven/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,xfournet/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,kool79/intellij-community,amith01994/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,caot/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,samthor/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,kool79/intellij-community,fitermay/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ahb0327/intellij-community,kool79/intellij-community,clumsy/intellij-community,signed/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,supersven/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,adedayo/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,asedunov/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,vladmm/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,caot/intellij-community,robovm/robovm-studio,FHannes/intellij-community,kdwink/intellij-community,izonder/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,semonte/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,izonder/intellij-community,signed/intellij-community,xfournet/intellij-community,supersven/intellij-community,robovm/robovm-studio,kool79/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,vladmm/intellij-community,hurricup/intellij-community,izonder/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,allotria/intellij-community,kdwink/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,hurricup/intellij-community,slisson/intellij-community,holmes/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ryano144/intellij-community,xfournet/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,dslomov/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,supersven/intellij-community,FHannes/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,robovm/robovm-studio,kool79/intellij-community,izonder/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,slisson/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,ibinti/intellij-community,ryano144/intellij-community,da1z/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,caot/intellij-community,samthor/intellij-community,fitermay/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,semonte/intellij-community,semonte/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,signed/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,allotria/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,clumsy/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,Distrotech/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,samthor/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,signed/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,apixandru/intellij-community,fnouama/intellij-community,signed/intellij-community,signed/intellij-community,petteyg/intellij-community,slisson/intellij-community,semonte/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,slisson/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,asedunov/intellij-community,kdwink/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,kool79/intellij-community,allotria/intellij-community,clumsy/intellij-community,slisson/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,fnouama/intellij-community,jagguli/intellij-community,allotria/intellij-community,da1z/intellij-community,petteyg/intellij-community,slisson/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ryano144/intellij-community,robovm/robovm-studio,fnouama/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,hurricup/intellij-community,adedayo/intellij-community,samthor/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,allotria/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/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.packaging.impl.run;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper;
import com.intellij.execution.impl.ExecutionManagerImpl;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.packaging.artifacts.*;
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author nik
*/
public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<BuildArtifactsBeforeRunTask> {
@NonNls public static final String BUILD_ARTIFACTS_ID = "BuildArtifacts";
public static final Key<BuildArtifactsBeforeRunTask> ID = Key.create(BUILD_ARTIFACTS_ID);
private final Project myProject;
public BuildArtifactsBeforeRunTaskProvider(Project project) {
myProject = project;
project.getMessageBus().connect().subscribe(ArtifactManager.TOPIC, new ArtifactAdapter() {
@Override
public void artifactRemoved(@NotNull Artifact artifact) {
final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject);
for (RunConfiguration configuration : runManager.getAllConfigurationsList()) {
final List<BuildArtifactsBeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration, ID);
for (BuildArtifactsBeforeRunTask task : tasks) {
final String artifactName = artifact.getName();
final List<ArtifactPointer> pointersList = task.getArtifactPointers();
final ArtifactPointer[] pointers = pointersList.toArray(new ArtifactPointer[pointersList.size()]);
for (ArtifactPointer pointer : pointers) {
if (pointer.getArtifactName().equals(artifactName) && ArtifactManager.getInstance(myProject).findArtifact(artifactName) == null) {
task.removeArtifact(pointer);
}
}
}
}
}
});
}
public Key<BuildArtifactsBeforeRunTask> getId() {
return ID;
}
@Override
public Icon getIcon() {
return AllIcons.Nodes.Artifact;
}
@Override
public String getName() {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
@Override
public Icon getTaskIcon(BuildArtifactsBeforeRunTask task) {
List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers == null || pointers.isEmpty())
return getIcon();
Artifact artifact = pointers.get(0).getArtifact();
if (artifact == null)
return getIcon();
return artifact.getArtifactType().getIcon();
}
@Override
public String getDescription(BuildArtifactsBeforeRunTask task) {
final List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers.isEmpty()) {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
if (pointers.size() == 1) {
return CompilerBundle.message("build.artifacts.before.run.description.single", pointers.get(0).getArtifactName());
}
return CompilerBundle.message("build.artifacts.before.run.description.multiple", pointers.size());
}
public boolean isConfigurable() {
return true;
}
public BuildArtifactsBeforeRunTask createTask(RunConfiguration runConfiguration) {
if (myProject.isDefault()) return null;
return new BuildArtifactsBeforeRunTask(myProject);
}
public boolean configureTask(RunConfiguration runConfiguration, BuildArtifactsBeforeRunTask task) {
final Artifact[] artifacts = ArtifactManager.getInstance(myProject).getArtifacts();
Set<ArtifactPointer> pointers = new THashSet<ArtifactPointer>();
for (Artifact artifact : artifacts) {
pointers.add(ArtifactPointerManager.getInstance(myProject).createPointer(artifact));
}
pointers.addAll(task.getArtifactPointers());
ArtifactChooser chooser = new ArtifactChooser(new ArrayList<ArtifactPointer>(pointers));
chooser.markElements(task.getArtifactPointers());
chooser.setPreferredSize(new Dimension(400, 300));
DialogBuilder builder = new DialogBuilder(myProject);
builder.setTitle(CompilerBundle.message("build.artifacts.before.run.selector.title"));
builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser");
builder.addOkAction();
builder.addCancelAction();
builder.setCenterPanel(chooser);
builder.setPreferredFocusComponent(chooser);
if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
task.setArtifactPointers(chooser.getMarkedElements());
return true;
}
return false;
}
@Override
public boolean canExecuteTask(RunConfiguration configuration, BuildArtifactsBeforeRunTask task) {
for (ArtifactPointer pointer: task.getArtifactPointers()) {
if (pointer.getArtifact() != null)
return true;
}
return false;
}
public boolean executeTask(DataContext context,
RunConfiguration configuration,
final ExecutionEnvironment env,
final BuildArtifactsBeforeRunTask task) {
final Ref<Boolean> result = Ref.create(false);
final Semaphore finished = new Semaphore();
final List<Artifact> artifacts = new ArrayList<Artifact>();
new ReadAction() {
protected void run(final Result result) {
for (ArtifactPointer pointer : task.getArtifactPointers()) {
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
}
}
}.execute();
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
result.set(!aborted && errors == 0);
finished.up();
}
};
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
final CompilerManager manager = CompilerManager.getInstance(myProject);
finished.down();
final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, artifacts);
ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env));
manager.make(scope, CompilerFilter.ALL, callback);
}
}, ModalityState.NON_MODAL);
finished.waitFor();
return result.get();
}
public static void setBuildArtifactBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent,
Project project,
@NotNull Artifact artifact,
final boolean enable) {
final DataContext dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent);
final ConfigurationSettingsEditorWrapper editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext);
if (editor != null) {
List<BeforeRunTask> tasks = editor.getStepsBeforeLaunch();
List<BuildArtifactsBeforeRunTask> myTasks = new ArrayList<BuildArtifactsBeforeRunTask>();
for (BeforeRunTask task : tasks) {
if (task instanceof BuildArtifactsBeforeRunTask) {
myTasks.add((BuildArtifactsBeforeRunTask)task);
}
}
if (enable && myTasks.isEmpty()) {
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
task.addArtifact(artifact);
task.setEnabled(true);
editor.addBeforeLaunchStep(task);
}
else {
for (BuildArtifactsBeforeRunTask task : myTasks) {
if (enable) {
task.addArtifact(artifact);
task.setEnabled(true);
}
else {
task.removeArtifact(artifact);
if (task.getArtifactPointers().isEmpty()) {
task.setEnabled(false);
}
}
}
}
}
}
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
buildArtifactsTasks.add(task);
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
tasks.add(task);
runManager.setBeforeRunTasks(configuration, tasks, false);
}
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
task.setEnabled(true);
task.addArtifact(artifact);
}
}
}
| java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.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.packaging.impl.run;
import com.intellij.compiler.impl.CompileScopeUtil;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper;
import com.intellij.execution.impl.ExecutionManagerImpl;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.packaging.artifacts.*;
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.CmdlineRemoteProto;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* @author nik
*/
public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<BuildArtifactsBeforeRunTask> {
@NonNls public static final String BUILD_ARTIFACTS_ID = "BuildArtifacts";
public static final Key<BuildArtifactsBeforeRunTask> ID = Key.create(BUILD_ARTIFACTS_ID);
private final Project myProject;
public BuildArtifactsBeforeRunTaskProvider(Project project) {
myProject = project;
project.getMessageBus().connect().subscribe(ArtifactManager.TOPIC, new ArtifactAdapter() {
@Override
public void artifactRemoved(@NotNull Artifact artifact) {
final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject);
for (RunConfiguration configuration : runManager.getAllConfigurationsList()) {
final List<BuildArtifactsBeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration, ID);
for (BuildArtifactsBeforeRunTask task : tasks) {
final String artifactName = artifact.getName();
final List<ArtifactPointer> pointersList = task.getArtifactPointers();
final ArtifactPointer[] pointers = pointersList.toArray(new ArtifactPointer[pointersList.size()]);
for (ArtifactPointer pointer : pointers) {
if (pointer.getArtifactName().equals(artifactName) && ArtifactManager.getInstance(myProject).findArtifact(artifactName) == null) {
task.removeArtifact(pointer);
}
}
}
}
}
});
}
public Key<BuildArtifactsBeforeRunTask> getId() {
return ID;
}
@Override
public Icon getIcon() {
return AllIcons.Nodes.Artifact;
}
@Override
public String getName() {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
@Override
public Icon getTaskIcon(BuildArtifactsBeforeRunTask task) {
List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers == null || pointers.isEmpty())
return getIcon();
Artifact artifact = pointers.get(0).getArtifact();
if (artifact == null)
return getIcon();
return artifact.getArtifactType().getIcon();
}
@Override
public String getDescription(BuildArtifactsBeforeRunTask task) {
final List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers.isEmpty()) {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
if (pointers.size() == 1) {
return CompilerBundle.message("build.artifacts.before.run.description.single", pointers.get(0).getArtifactName());
}
return CompilerBundle.message("build.artifacts.before.run.description.multiple", pointers.size());
}
public boolean isConfigurable() {
return true;
}
public BuildArtifactsBeforeRunTask createTask(RunConfiguration runConfiguration) {
if (myProject.isDefault()) return null;
return new BuildArtifactsBeforeRunTask(myProject);
}
public boolean configureTask(RunConfiguration runConfiguration, BuildArtifactsBeforeRunTask task) {
final Artifact[] artifacts = ArtifactManager.getInstance(myProject).getArtifacts();
Set<ArtifactPointer> pointers = new THashSet<ArtifactPointer>();
for (Artifact artifact : artifacts) {
pointers.add(ArtifactPointerManager.getInstance(myProject).createPointer(artifact));
}
pointers.addAll(task.getArtifactPointers());
ArtifactChooser chooser = new ArtifactChooser(new ArrayList<ArtifactPointer>(pointers));
chooser.markElements(task.getArtifactPointers());
chooser.setPreferredSize(new Dimension(400, 300));
DialogBuilder builder = new DialogBuilder(myProject);
builder.setTitle(CompilerBundle.message("build.artifacts.before.run.selector.title"));
builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser");
builder.addOkAction();
builder.addCancelAction();
builder.setCenterPanel(chooser);
builder.setPreferredFocusComponent(chooser);
if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
task.setArtifactPointers(chooser.getMarkedElements());
return true;
}
return false;
}
@Override
public boolean canExecuteTask(RunConfiguration configuration, BuildArtifactsBeforeRunTask task) {
for (ArtifactPointer pointer: task.getArtifactPointers()) {
if (pointer.getArtifact() != null)
return true;
}
return false;
}
public boolean executeTask(DataContext context,
RunConfiguration configuration,
final ExecutionEnvironment env,
final BuildArtifactsBeforeRunTask task) {
final Ref<Boolean> result = Ref.create(false);
final Semaphore finished = new Semaphore();
final List<Artifact> artifacts = new ArrayList<Artifact>();
new ReadAction() {
protected void run(final Result result) {
for (ArtifactPointer pointer : task.getArtifactPointers()) {
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
}
}
}.execute();
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
result.set(!aborted && errors == 0);
finished.up();
}
};
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
final CompilerManager manager = CompilerManager.getInstance(myProject);
finished.down();
final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, artifacts);
CompileScopeUtil.setBaseScopeForExternalBuild(scope, Collections.<CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope>emptyList());
ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env));
manager.make(scope, CompilerFilter.ALL, callback);
}
}, ModalityState.NON_MODAL);
finished.waitFor();
return result.get();
}
public static void setBuildArtifactBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent,
Project project,
@NotNull Artifact artifact,
final boolean enable) {
final DataContext dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent);
final ConfigurationSettingsEditorWrapper editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext);
if (editor != null) {
List<BeforeRunTask> tasks = editor.getStepsBeforeLaunch();
List<BuildArtifactsBeforeRunTask> myTasks = new ArrayList<BuildArtifactsBeforeRunTask>();
for (BeforeRunTask task : tasks) {
if (task instanceof BuildArtifactsBeforeRunTask) {
myTasks.add((BuildArtifactsBeforeRunTask)task);
}
}
if (enable && myTasks.isEmpty()) {
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
task.addArtifact(artifact);
task.setEnabled(true);
editor.addBeforeLaunchStep(task);
}
else {
for (BuildArtifactsBeforeRunTask task : myTasks) {
if (enable) {
task.addArtifact(artifact);
task.setEnabled(true);
}
else {
task.removeArtifact(artifact);
if (task.getArtifactPointers().isEmpty()) {
task.setEnabled(false);
}
}
}
}
}
}
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
buildArtifactsTasks.add(task);
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
tasks.add(task);
runManager.setBeforeRunTasks(configuration, tasks, false);
}
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
task.setEnabled(true);
task.addArtifact(artifact);
}
}
}
| make modules included in artifact when 'build artifact before run' task is performed (IDEA-132397)
| java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java | make modules included in artifact when 'build artifact before run' task is performed (IDEA-132397) | <ide><path>ava/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java
<ide> */
<ide> package com.intellij.packaging.impl.run;
<ide>
<del>import com.intellij.compiler.impl.CompileScopeUtil;
<ide> import com.intellij.execution.BeforeRunTask;
<ide> import com.intellij.execution.BeforeRunTaskProvider;
<ide> import com.intellij.execution.RunManagerEx;
<ide> import gnu.trove.THashSet;
<ide> import org.jetbrains.annotations.NonNls;
<ide> import org.jetbrains.annotations.NotNull;
<del>import org.jetbrains.jps.api.CmdlineRemoteProto;
<ide>
<ide> import javax.swing.*;
<ide> import java.awt.*;
<ide> import java.util.ArrayList;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide>
<ide> final CompilerManager manager = CompilerManager.getInstance(myProject);
<ide> finished.down();
<ide> final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, artifacts);
<del> CompileScopeUtil.setBaseScopeForExternalBuild(scope, Collections.<CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope>emptyList());
<ide> ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env));
<ide> manager.make(scope, CompilerFilter.ALL, callback);
<ide> } |
|
JavaScript | mit | b9846f62ced9620785dc84424f8b4244f5019cfa | 0 | valentingalea/vinyl-shelf-finder,valentingalea/vinyl-shelf-finder,valentingalea/vinyl-shelf-finder | //
// Debug
//
const stringifyObject = require('stringify-object');
function pretty(data) {
return "<pre>" + stringifyObject(data) + "</pre>";
}
//
// Discogs API
//
var Discogs = require('disconnect').Client;
const UserAgent = 'vinyl-shelf-finder/1.0';
const User = 'valentingalea';
const ALL = 0; // id of main folder
var db = new Discogs(UserAgent).database();
var my_col = new Discogs(UserAgent).user().collection();
var json_col = [];
var total_count = 0;
//
// Discogs requests cache
//
console.log("Loading cache...");
var flatCache = require('flat-cache');
const cache_file = 'discogs';
var cache = flatCache.load(cache_file, __dirname + '/cache/');
//
// Search
//
var fuseJs = require("fuse.js");
var searcher = undefined;
function init_search() {
console.log("Indexing...");
var options = {
keys: [ 'basic_information.title', 'basic_information.artists.name' ],
threshold: 0.15
};
searcher = new fuseJs(json_col, options);
}
//
// Express REST server
//
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
//res.send(UserAgent);
res.sendFile('main.html', { root: __dirname + '/public/' });
});
app.get('/random', function (req, res) {
var index = Math.round(Math.random() * total_count);
var msg = json_col[index];
res.send(index + "<br/>" + pretty(msg));
});
app.get('/search', function (req, res) {
console.log("Search request: " + req.query.q);
var found = searcher.search(req.query.q);
var send_release_to_client = function (entry) {
var html = '<li>';
html += '<div class="artist">'
+ entry.basic_information.artists[0].name // TODO: cover all cases
+ '</div>';
html += '<div class="title">'
+ entry.basic_information.title
+ '</div>';
html += '<img class="cover" src="generic.png" width="300" height="300" data-original="'
+ entry.basic_information.cover_image
+ '">';
html += '</li>';
return html;
};
var client_str = '<ul class="grid">';
for (var entry in found) {
client_str += send_release_to_client(found[entry]);
}
client_str += "</ul><script>$('.cover').lazyload();</script>";
res.send(client_str);
});
app.get('/all', function (req, res) {
res.send(pretty(json_col));
});
app.get('/detail/:id(\\d+)', function (req, res) {
db.getRelease(req.params.id, function(err, data){
if (err) return;
res.send(pretty(data));
});
});
//
// Main
//
console.log("Starting...");
var get_folder = my_col.getFolder(User, ALL);
const page_items = 100;
var page_count = 0;
var page_iter = 1;
function get_page(n) {
if (typeof cache.getKey(n) === "undefined") {
process.stdout.write('Downloading page ' + n + '...');
return my_col.getReleases(User, ALL, { page: n, per_page: page_items });
} else {
process.stdout.write('Readback cached page ' + n + '...');
return new Promise(function (resolve, reject) {
return resolve(cache.getKey(n));
});
}
}
function start_server(){
const port = 8080;
app.listen(port, function () {
console.log('Listening on ' + port + '...');
});
}
function async_loop() {
if (page_iter <= page_count) {
return get_page(page_iter).then(function (data) {
console.log("done");
var old_data = cache.getKey(page_iter);
if (typeof old_data === "undefined") {
cache.setKey(page_iter, data);
cache.save({noPrune: true});
console.log("Cached page " + page_iter);
}
json_col = json_col.concat(data.releases);
page_iter++;
async_loop();
}, function (err) {
console.log(err);
});
} else {
init_search();
start_server();
}
};
// build the collection & then start server
get_folder
.then(function (data){
total_count = data.count;
page_count = Math.round(data.count / page_items);
console.log("Found " + total_count + " records, retrieving all in " + page_count + " steps...");
var old_count = cache.getKey('count');
if (old_count != total_count) {
console.log("Cache invalidated!");
flatCache.clearCacheById(cache_file);
cache.setKey('count', total_count);
cache.save({noPrune: true});
}
async_loop();
}, function(err) {
console.log(err);
}); | app/app.js | //
// Debug
//
const stringifyObject = require('stringify-object');
function pretty(data) {
return "<pre>" + stringifyObject(data) + "</pre>";
}
//
// Discogs API
//
var Discogs = require('disconnect').Client;
var UserAgent = 'vinyl-shelf-finder/1.0';
const User = 'valentingalea';
var db = new Discogs(UserAgent).database();
var my_col = new Discogs(UserAgent).user().collection();
var json_col = [];
var total_count = 0;
const ALL = 0;
//
// Discogs requests cache
//
console.log("Loading cache...");
var flatCache = require('flat-cache');
const cache_file = 'discogs';
var cache = flatCache.load(cache_file, __dirname + '/cache/');
//
// Search
//
var fuseJs = require("fuse.js");
var searcher = undefined;
function init_search() {
console.log("Indexing...");
var options = {
keys: [ 'basic_information.title', 'basic_information.artists.name' ],
threshold: 0.15
};
searcher = new fuseJs(json_col, options);
}
//
// Express REST server
//
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
//res.send(UserAgent);
res.sendFile('main.html', { root: __dirname + '/public/' });
});
app.get('/random', function (req, res) {
var index = Math.round(Math.random() * total_count);
var msg = json_col[index];
res.send(index + "<br/>" + pretty(msg));
});
app.get('/search', function (req, res) {
console.log("Search request: " + req.query.q);
var found = searcher.search(req.query.q);
var send_release_to_client = function (entry) {
var html = '<li>';
html += '<div class="artist">'
+ entry.basic_information.artists[0].name // TODO: cover all cases
+ '</div>';
html += '<div class="title">'
+ entry.basic_information.title
+ '</div>';
html += '<img class="cover" src="generic.png" width="300" height="300" data-original="'
+ entry.basic_information.cover_image
+ '">';
html += '</li>';
return html;
};
var client_str = '<ul class="grid">';
for (var entry in found) {
client_str += send_release_to_client(found[entry]);
}
client_str += "</ul><script>$('.cover').lazyload();</script>";
res.send(client_str);
});
app.get('/all', function (req, res) {
res.send(pretty(json_col));
});
app.get('/detail/:id(\\d+)', function (req, res) {
db.getRelease(req.params.id, function(err, data){
if (err) return;
res.send(pretty(data));
});
});
//
// Main
//
console.log("Starting...");
var get_folder = my_col.getFolder(User, ALL);
const page_items = 100;
var page_count = 0;
var page_iter = 1;
function get_page(n) {
if (typeof cache.getKey(n) === "undefined") {
process.stdout.write('Downloading page ' + n + '...');
return my_col.getReleases(User, ALL, { page: n, per_page: page_items });
} else {
process.stdout.write('Readback cached page ' + n + '...');
return new Promise(function (resolve, reject) {
return resolve(cache.getKey(n));
});
}
}
function start_server(){
const port = 8080;
app.listen(port, function () {
console.log('Listening on ' + port + '...');
});
}
function async_loop() {
if (page_iter <= page_count) {
return get_page(page_iter).then(function (data) {
console.log("done");
var old_data = cache.getKey(page_iter);
if (typeof old_data === "undefined") {
cache.setKey(page_iter, data);
cache.save({noPrune: true});
console.log("Cached page " + page_iter);
}
json_col = json_col.concat(data.releases);
page_iter++;
async_loop();
}, function (err) {
console.log(err);
});
} else {
init_search();
start_server();
}
};
// build the collection & then start server
get_folder
.then(function (data){
total_count = data.count;
page_count = Math.round(data.count / page_items);
console.log("Found " + total_count + " records, retrieving all in " + page_count + " steps...");
var old_count = cache.getKey('count');
if (old_count != total_count) {
console.log("Cache invalidated!");
flatCache.clearCacheById(cache_file);
cache.setKey('count', total_count);
cache.save({noPrune: true});
}
async_loop();
}, function(err) {
console.log(err);
}); | small const fixes
| app/app.js | small const fixes | <ide><path>pp/app.js
<ide> // Discogs API
<ide> //
<ide> var Discogs = require('disconnect').Client;
<del>var UserAgent = 'vinyl-shelf-finder/1.0';
<add>const UserAgent = 'vinyl-shelf-finder/1.0';
<ide> const User = 'valentingalea';
<add>const ALL = 0; // id of main folder
<ide> var db = new Discogs(UserAgent).database();
<ide> var my_col = new Discogs(UserAgent).user().collection();
<ide> var json_col = [];
<ide> var total_count = 0;
<del>const ALL = 0;
<ide>
<ide> //
<ide> // Discogs requests cache |
|
Java | agpl-3.0 | error: pathspec 'swows/src/test/java/org/swows/test/ArduinoApp.java' did not match any file(s) known to git
| 9f859282ba35db552400f5e65a459cdf979dad63 | 1 | miguel76/SWOWS,miguel76/SWOWS | package org.swows.test;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.xml.transform.TransformerException;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.util.RunnableQueue;
import org.apache.log4j.PropertyConfigurator;
import org.swows.datatypes.SmartFileManager;
import org.swows.function.Factory;
import org.swows.tuio.TuioApp;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.DatasetFactory;
import com.hp.hpl.jena.sparql.function.FunctionRegistry;
public class ArduinoApp {
static JFrame frame;
static GraphicsDevice device = null;
//static GraphicsConfiguration gc =
//static JFrame frame = new JFrame("SWOWS TUIO test", gc)
static RunnableQueue batikRunnableQueue;
static JSVGCanvas svgCanvas = new JSVGCanvas();
static final String SCREEN = ":0.1";
// static final String SCREEN = ":0.0";
public static void main(final String[] args) throws TransformerException {
//BasicConfigurator.configure();
PropertyConfigurator.configure("/home/miguel/ArduinoDay/log4j.properties");
FunctionRegistry registry = FunctionRegistry.get();
registry.put(Factory.getBaseURI() + "to", Factory.getInstance());
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (int gdIndex = 0; gdIndex < gs.length; gdIndex++ ) {
GraphicsDevice currDevice = gs[gdIndex];
if (currDevice.getIDstring().equals(SCREEN))
device = currDevice;
}
//device = ge.getDefaultScreenDevice(); // TODO: remove this workaround for test without screen
GraphicsConfiguration conf = device.getDefaultConfiguration();
String baseUri = "/home/miguel/ArduinoDay/dataflow/";
// String baseUri = "/home/dario/NetBeansProjects/provaTavolo/test/pampersoriginal/dataflow/";
// String mainGraphUrl = baseUri + "test-circles.n3";
String mainGraphUrl = baseUri + "main.n3";
Dataset wfDataset = DatasetFactory.create(mainGraphUrl, SmartFileManager.get());
final Graph wfGraph = wfDataset.asDatasetGraph().getDefaultGraph();
// System.out.println("*** Workflow graph ***");
// wfDataset.getDefaultModel().write(System.out,"N3");
// System.out.println("***************************************");
// System.out.println("*** Workflow graph in N-TRIPLE ***");
// wfDataset.getDefaultModel().write(System.out,"N-TRIPLE");
// System.out.println("***************************************");
//TuioApp tuioApp =
// new TuioApp("SWOWS TUIO test", conf, wfGraph);
new TuioApp("SWOWS TUIO test", conf, wfGraph, false, 1024, 768);
}
}
| swows/src/test/java/org/swows/test/ArduinoApp.java | Convenient app for tabletop tui | swows/src/test/java/org/swows/test/ArduinoApp.java | Convenient app for tabletop tui | <ide><path>wows/src/test/java/org/swows/test/ArduinoApp.java
<add>package org.swows.test;
<add>
<add>import java.awt.GraphicsConfiguration;
<add>import java.awt.GraphicsDevice;
<add>import java.awt.GraphicsEnvironment;
<add>
<add>import javax.swing.JFrame;
<add>import javax.xml.transform.TransformerException;
<add>
<add>import org.apache.batik.swing.JSVGCanvas;
<add>import org.apache.batik.util.RunnableQueue;
<add>import org.apache.log4j.PropertyConfigurator;
<add>import org.swows.datatypes.SmartFileManager;
<add>import org.swows.function.Factory;
<add>import org.swows.tuio.TuioApp;
<add>
<add>import com.hp.hpl.jena.graph.Graph;
<add>import com.hp.hpl.jena.query.Dataset;
<add>import com.hp.hpl.jena.query.DatasetFactory;
<add>import com.hp.hpl.jena.sparql.function.FunctionRegistry;
<add>
<add>public class ArduinoApp {
<add>
<add> static JFrame frame;
<add> static GraphicsDevice device = null;
<add> //static GraphicsConfiguration gc =
<add> //static JFrame frame = new JFrame("SWOWS TUIO test", gc)
<add> static RunnableQueue batikRunnableQueue;
<add> static JSVGCanvas svgCanvas = new JSVGCanvas();
<add> static final String SCREEN = ":0.1";
<add>// static final String SCREEN = ":0.0";
<add>
<add> public static void main(final String[] args) throws TransformerException {
<add>
<add> //BasicConfigurator.configure();
<add> PropertyConfigurator.configure("/home/miguel/ArduinoDay/log4j.properties");
<add>
<add> FunctionRegistry registry = FunctionRegistry.get();
<add> registry.put(Factory.getBaseURI() + "to", Factory.getInstance());
<add>
<add> GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
<add> GraphicsDevice[] gs = ge.getScreenDevices();
<add> for (int gdIndex = 0; gdIndex < gs.length; gdIndex++ ) {
<add> GraphicsDevice currDevice = gs[gdIndex];
<add> if (currDevice.getIDstring().equals(SCREEN))
<add> device = currDevice;
<add> }
<add> //device = ge.getDefaultScreenDevice(); // TODO: remove this workaround for test without screen
<add> GraphicsConfiguration conf = device.getDefaultConfiguration();
<add>
<add> String baseUri = "/home/miguel/ArduinoDay/dataflow/";
<add>// String baseUri = "/home/dario/NetBeansProjects/provaTavolo/test/pampersoriginal/dataflow/";
<add>
<add>// String mainGraphUrl = baseUri + "test-circles.n3";
<add> String mainGraphUrl = baseUri + "main.n3";
<add>
<add> Dataset wfDataset = DatasetFactory.create(mainGraphUrl, SmartFileManager.get());
<add> final Graph wfGraph = wfDataset.asDatasetGraph().getDefaultGraph();
<add>
<add>// System.out.println("*** Workflow graph ***");
<add>// wfDataset.getDefaultModel().write(System.out,"N3");
<add>// System.out.println("***************************************");
<add>
<add>// System.out.println("*** Workflow graph in N-TRIPLE ***");
<add>// wfDataset.getDefaultModel().write(System.out,"N-TRIPLE");
<add>// System.out.println("***************************************");
<add>
<add> //TuioApp tuioApp =
<add>// new TuioApp("SWOWS TUIO test", conf, wfGraph);
<add> new TuioApp("SWOWS TUIO test", conf, wfGraph, false, 1024, 768);
<add>
<add> }
<add>
<add>} |
|
JavaScript | mit | b93a918af85aea7150d23d79e08b2c1942988d67 | 0 | christopherstott/aws-lib | var http = require("http");
var https = require("https");
var qs = require("querystring")
var crypto = require("crypto")
var events = require("events")
var xml2js = require("xml2js")
// include specific API clients
var ec2 = require("./ec2");
var prodAdv = require("./prodAdv");
var simpledb = require("./simpledb");
var sqs = require("./sqs");
var sns = require("./sns");
var ses = require("./ses");
var emr = require("./emr");
// Returns the hmac digest using the SHA256 algorithm.
function hmacSha256(key, toSign) {
var hash = crypto.createHmac("sha256", key);
return hash.update(toSign).digest("base64");
}
// a generic AWS API Client which handles the general parts
var genericAWSClient = function(obj) {
var creds = crypto.createCredentials({});
if (null == obj.secure)
obj.secure = true;
obj.connection = obj.secure ? https : http;
obj.call = function (action, query, callback) {
if (obj.secretAccessKey == null || obj.accessKeyId == null) {
throw("secretAccessKey and accessKeyId must be set")
}
var now = new Date();
function ISODateString(d) {
function pad(n){
return n<10 ? '0'+n : n
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
if (!obj.signHeader) {
// Add the standard parameters required by all AWS APIs
query["AWSAccessKeyId"] = obj.accessKeyId;
query["SignatureVersion"]="2";
query["SignatureMethod"]="HmacSHA256";
query["Timestamp"]=ISODateString(new Date());
query["Signature"] = obj.sign(query);
}
var body = qs.stringify(query);
var headers = {
"Host": obj.host,
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"Content-Length": body.length
};
if (obj.signHeader) {
headers["Date"] = now.toUTCString();
headers["x-amzn-authorization"] =
"AWS3-HTTPS " +
"AWSAccessKeyId=" + obj.accessKeyId + ", " +
"Algorithm=HmacSHA256, " +
"Signature=" + hmacSha256(obj.secretAccessKey, now.toUTCString());
}
var options = {
host: obj.host,
path: obj.path,
method: 'POST',
headers: headers
};
var doRequest = function(cb) {
var req = obj.connection.request(options, function (res) {
var data = '';
//the listener that handles the response chunks
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
if ( res.statusCode !== 200 ) {
console.error('non-200 status code from aws ' + res.statusCode, data);
return cb(false);
}
var parser = new xml2js.Parser();
parser.addListener('end', function(result) {
cb(true,result);
});
parser.parseString(data);
});
});
req.on('error', function(err) {
console.error('AWS Error',err);
cb(false);
});
req.write(body);
req.end();
};
var success = false;
(function cycle(remainingTries) {
if (remainingTries>0 && !success) {
remainingTries--;
doRequest(function(succeeded,result) {
if (succeeded) {
return callback(result);
}
else {
console.log('Error, retrying');
process.nextTick(function() {
cycle(remainingTries);
});
}
});
}
else {
// ran out of attempts
console.error('AWS Failed too many times : ' + obj.path);
return callback();
}
})(3);
}
/*
Calculate HMAC signature of the query
*/
obj.sign = function (query) {
var keys = []
var sorted = {}
for(var key in query)
keys.push(key)
keys = keys.sort()
for(n in keys) {
var key = keys[n]
sorted[key] = query[key]
}
var stringToSign = ["POST", obj.host, obj.path, qs.stringify(sorted)].join("\n");
// Amazon signature algorithm seems to require this
stringToSign = stringToSign.replace(/!/g,"%21");
stringToSign = stringToSign.replace(/'/g,"%27");
stringToSign = stringToSign.replace(/\*/g,"%2A");
stringToSign = stringToSign.replace(/\(/g,"%28");
stringToSign = stringToSign.replace(/\)/g,"%29");
return hmacSha256(obj.secretAccessKey, stringToSign);
}
return obj;
}
exports.createEC2Client = ec2.init(genericAWSClient);
exports.createProdAdvClient = prodAdv.init(genericAWSClient);
exports.createSimpleDBClient = simpledb.init(genericAWSClient);
exports.createSQSClient = sqs.init(genericAWSClient);
exports.createSNSClient = sns.init(genericAWSClient);
exports.createSESClient = ses.init(genericAWSClient);
exports.createEMRClient = emr.init(genericAWSClient);
| lib/aws.js | var http = require("http");
var https = require("https");
var qs = require("querystring")
var crypto = require("crypto")
var events = require("events")
var xml2js = require("xml2js")
// include specific API clients
var ec2 = require("./ec2");
var prodAdv = require("./prodAdv");
var simpledb = require("./simpledb");
var sqs = require("./sqs");
var sns = require("./sns");
var ses = require("./ses");
var emr = require("./emr");
// Returns the hmac digest using the SHA256 algorithm.
function hmacSha256(key, toSign) {
var hash = crypto.createHmac("sha256", key);
return hash.update(toSign).digest("base64");
}
// a generic AWS API Client which handles the general parts
var genericAWSClient = function(obj) {
var creds = crypto.createCredentials({});
if (null == obj.secure)
obj.secure = true;
obj.connection = obj.secure ? https : http;
obj.call = function (action, query, callback) {
if (obj.secretAccessKey == null || obj.accessKeyId == null) {
throw("secretAccessKey and accessKeyId must be set")
}
var now = new Date();
function ISODateString(d) {
function pad(n){
return n<10 ? '0'+n : n
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
if (!obj.signHeader) {
// Add the standard parameters required by all AWS APIs
query["AWSAccessKeyId"] = obj.accessKeyId;
query["SignatureVersion"]="2";
query["SignatureMethod"]="HmacSHA256";
query["Timestamp"]=ISODateString(new Date());
query["Signature"] = obj.sign(query);
}
var body = qs.stringify(query);
var headers = {
"Host": obj.host,
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"Content-Length": body.length
};
if (obj.signHeader) {
headers["Date"] = now.toUTCString();
headers["x-amzn-authorization"] =
"AWS3-HTTPS " +
"AWSAccessKeyId=" + obj.accessKeyId + ", " +
"Algorithm=HmacSHA256, " +
"Signature=" + hmacSha256(obj.secretAccessKey, now.toUTCString());
}
var options = {
host: obj.host,
path: obj.path,
method: 'POST',
headers: headers
};
var doRequest = function(cb) {
var req = obj.connection.request(options, function (res) {
var data = '';
//the listener that handles the response chunks
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
if ( res.statusCode !== 200 ) {
console.error('non-200 status code from aws ' + res.statusCode, data);
return cb(false);
}
var parser = new xml2js.Parser();
parser.addListener('end', function(result) {
cb(true,result);
});
parser.parseString(data);
});
});
req.on('error', function(err) {
console.error('AWS Error',err);
cb(false);
});
req.write(body);
req.end();
};
var success = false;
(function cycle(remainingTries) {
if (remainingTries>0 && !success) {
remainingTries--;
doRequest(function(succeeded,result) {
if (succeeded) {
return callback(result);
}
else {
console.log('Error, retrying');
process.nextTick(function() {
cycle(remainingTries);
});
}
});
}
else {
// ran out of attempts
console.error('AWS Failed too many times : ' + JSON.stringify(options));
return callback();
}
})(3);
}
/*
Calculate HMAC signature of the query
*/
obj.sign = function (query) {
var keys = []
var sorted = {}
for(var key in query)
keys.push(key)
keys = keys.sort()
for(n in keys) {
var key = keys[n]
sorted[key] = query[key]
}
var stringToSign = ["POST", obj.host, obj.path, qs.stringify(sorted)].join("\n");
// Amazon signature algorithm seems to require this
stringToSign = stringToSign.replace(/!/g,"%21");
stringToSign = stringToSign.replace(/'/g,"%27");
stringToSign = stringToSign.replace(/\*/g,"%2A");
stringToSign = stringToSign.replace(/\(/g,"%28");
stringToSign = stringToSign.replace(/\)/g,"%29");
return hmacSha256(obj.secretAccessKey, stringToSign);
}
return obj;
}
exports.createEC2Client = ec2.init(genericAWSClient);
exports.createProdAdvClient = prodAdv.init(genericAWSClient);
exports.createSimpleDBClient = simpledb.init(genericAWSClient);
exports.createSQSClient = sqs.init(genericAWSClient);
exports.createSNSClient = sns.init(genericAWSClient);
exports.createSESClient = ses.init(genericAWSClient);
exports.createEMRClient = emr.init(genericAWSClient);
| fixed aws crash
| lib/aws.js | fixed aws crash | <ide><path>ib/aws.js
<ide> }
<ide> else {
<ide> // ran out of attempts
<del> console.error('AWS Failed too many times : ' + JSON.stringify(options));
<add> console.error('AWS Failed too many times : ' + obj.path);
<ide> return callback();
<ide> }
<ide> })(3); |
|
Java | apache-2.0 | 8fa5cca78121c8eb12304acbb7458c2a72db9067 | 0 | HewlettPackard/oneview-sdk-java,HewlettPackard/oneview-sdk-java | /*
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* 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.hp.ov.sdk.rest.client;
import com.hp.ov.sdk.rest.client.activity.AlertClient;
import com.hp.ov.sdk.rest.client.facilities.DataCenterClient;
import com.hp.ov.sdk.rest.client.facilities.PowerDeliveryDeviceClient;
import com.hp.ov.sdk.rest.client.facilities.RackClient;
import com.hp.ov.sdk.rest.client.facilities.UnmanagedDeviceClient;
import com.hp.ov.sdk.rest.client.networking.ConnectionTemplateClient;
import com.hp.ov.sdk.rest.client.networking.EthernetNetworkClient;
import com.hp.ov.sdk.rest.client.networking.FabricClient;
import com.hp.ov.sdk.rest.client.networking.FcNetworkClient;
import com.hp.ov.sdk.rest.client.networking.FcoeNetworkClient;
import com.hp.ov.sdk.rest.client.networking.InterconnectClient;
import com.hp.ov.sdk.rest.client.networking.InterconnectLinkTopologyClient;
import com.hp.ov.sdk.rest.client.networking.InterconnectTypeClient;
import com.hp.ov.sdk.rest.client.networking.InternalLinkSetClient;
import com.hp.ov.sdk.rest.client.networking.LogicalDownlinkClient;
import com.hp.ov.sdk.rest.client.networking.LogicalInterconnectClient;
import com.hp.ov.sdk.rest.client.networking.LogicalInterconnectGroupClient;
import com.hp.ov.sdk.rest.client.networking.LogicalSwitchClient;
import com.hp.ov.sdk.rest.client.networking.LogicalSwitchGroupClient;
import com.hp.ov.sdk.rest.client.networking.NetworkSetClient;
import com.hp.ov.sdk.rest.client.networking.SasInterconnectClient;
import com.hp.ov.sdk.rest.client.networking.SasInterconnectTypeClient;
import com.hp.ov.sdk.rest.client.networking.SasLogicalInterconnectClient;
import com.hp.ov.sdk.rest.client.networking.SasLogicalInterconnectGroupClient;
import com.hp.ov.sdk.rest.client.networking.SwitchClient;
import com.hp.ov.sdk.rest.client.networking.SwitchTypeClient;
import com.hp.ov.sdk.rest.client.networking.UplinkSetClient;
import com.hp.ov.sdk.rest.client.security.LoginSessionClient;
import com.hp.ov.sdk.rest.client.security.MessagingCertificateClient;
import com.hp.ov.sdk.rest.client.server.EnclosureClient;
import com.hp.ov.sdk.rest.client.server.EnclosureGroupClient;
import com.hp.ov.sdk.rest.client.server.LogicalEnclosureClient;
import com.hp.ov.sdk.rest.client.server.ServerHardwareClient;
import com.hp.ov.sdk.rest.client.server.ServerHardwareTypeClient;
import com.hp.ov.sdk.rest.client.server.ServerProfileClient;
import com.hp.ov.sdk.rest.client.server.ServerProfileTemplateClient;
import com.hp.ov.sdk.rest.client.settings.FirmwareBundleClient;
import com.hp.ov.sdk.rest.client.settings.FirmwareDriverClient;
import com.hp.ov.sdk.rest.client.settings.LicenseClient;
import com.hp.ov.sdk.rest.client.settings.ScopeClient;
import com.hp.ov.sdk.rest.client.settings.VersionClient;
import com.hp.ov.sdk.rest.client.storage.DriveEnclosureClient;
import com.hp.ov.sdk.rest.client.storage.FcSanDeviceManagerClient;
import com.hp.ov.sdk.rest.client.storage.FcSanManagedSanClient;
import com.hp.ov.sdk.rest.client.storage.FcSanProviderClient;
import com.hp.ov.sdk.rest.client.storage.SasLogicalJbodAttachmentClient;
import com.hp.ov.sdk.rest.client.storage.SasLogicalJbodClient;
import com.hp.ov.sdk.rest.client.storage.StoragePoolClient;
import com.hp.ov.sdk.rest.client.storage.StorageSystemClient;
import com.hp.ov.sdk.rest.client.storage.StorageVolumeAttachmentClient;
import com.hp.ov.sdk.rest.client.storage.StorageVolumeClient;
import com.hp.ov.sdk.rest.client.storage.StorageVolumeTemplateClient;
import com.hp.ov.sdk.rest.client.uncategorized.OsDeploymentPlanClient;
import com.hp.ov.sdk.rest.http.core.client.SDKConfiguration;
import com.hp.ov.sdk.util.OneViewConnector;
import com.hpe.core.AbstractClient;
public class OneViewClient extends AbstractClient {
private final BaseClient baseClient;
private MessagingCertificateClient certificateClient;
public OneViewClient(SDKConfiguration config) {
this.baseClient = new BaseClient(config, config.getOneViewHostname());
OneViewConnector connector = new OneViewConnector(
config, this.versionClient(), this.loginClient());
this.baseClient.setSessionId(connector.connect());
}
public String getSessionId() {
return this.baseClient.getSessionId();
}
@Override
protected BaseClient baseClient() {
return this.baseClient;
}
/**
* Creates or retrieves an existing instance of {@link AlertClient}.
* This client provides an interface for managing alerts.
*
* @return an interface to the alerts REST API.
*/
public synchronized AlertClient alert() {
return getProxy(AlertClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ConnectionTemplateClient}.
* This client provides an interface for managing connection templates.
*
* @return an interface to the connection templates REST API.
*/
public synchronized ConnectionTemplateClient connectionTemplate() {
return getProxy(ConnectionTemplateClient.class);
}
/**
* Creates or retrieves an existing instance of {@link DataCenterClient}.
* This client provides an interface for managing datacenters.
*
* @return an interface to the datacenters REST API.
*/
public synchronized DataCenterClient dataCenter() {
return getProxy(DataCenterClient.class);
}
/**
* Creates or retrieves an existing instance of {@link DriveEnclosureClient}.
* This client provides an interface for managing drive enclosures.
*
* @return an interface to the drive enclosures REST API.
*/
public synchronized DriveEnclosureClient driveEnclosure() {
return getProxy(DriveEnclosureClient.class);
}
/**
* Creates or retrieves an existing instance of {@link EnclosureClient}.
* This client provides an interface for managing enclosures.
*
* @return an interface to the enclosures REST API.
*/
public synchronized EnclosureClient enclosure() {
return getProxy(EnclosureClient.class);
}
/**
* Creates or retrieves an existing instance of {@link EnclosureGroupClient}.
* This client provides an interface for managing enclosure groups.
*
* @return an interface to the enclosure groups REST API.
*/
public synchronized EnclosureGroupClient enclosureGroup() {
return getProxy(EnclosureGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link EthernetNetworkClient}.
* This client provides an interface for managing ethernet networks.
*
* @return an interface to the ethernet networks REST API.
*/
public synchronized EthernetNetworkClient ethernetNetwork() {
return getProxy(EthernetNetworkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FabricClient}.
* This client provides an interface for managing fabrics.
*
* @return an interface to the fabrics REST API.
*/
public synchronized FabricClient fabric() {
return getProxy(FabricClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcNetworkClient}.
* This client provides an interface for managing FC networks.
*
* @return an interface to the FC networks REST API.
*/
public synchronized FcNetworkClient fcNetwork() {
return getProxy(FcNetworkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcoeNetworkClient}.
* This client provides an interface for managing FCoE networks.
*
* @return an interface to the FCoE networks REST API.
*/
public synchronized FcoeNetworkClient fcoeNetwork() {
return getProxy(FcoeNetworkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcSanDeviceManagerClient}.
* This client provides an interface for managing SAN managers.
*
* @return an interface to the SAN managers REST API.
*/
public synchronized FcSanDeviceManagerClient fcSanDeviceManager() {
return getProxy(FcSanDeviceManagerClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcSanManagedSanClient}.
* This client provides an interface for managing managed SANs.
*
* @return an interface to the managed SANs REST API.
*/
public synchronized FcSanManagedSanClient fcSanManagedSan() {
return getProxy(FcSanManagedSanClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcSanProviderClient}.
* This client provides an interface for managing SAN providers.
*
* @return an interface to the SAN providers REST API.
*/
public synchronized FcSanProviderClient fcSanProvider() {
return getProxy(FcSanProviderClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FirmwareBundleClient}.
* This client provides an interface for managing firmware bundles.
*
* @return an interface to the firmware bundles REST API.
*/
public synchronized FirmwareBundleClient firmwareBundle() {
return getProxy(FirmwareBundleClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FirmwareDriverClient}.
* This client provides an interface for managing firmware drivers.
*
* @return an interface to the firmware drivers REST API.
*/
public synchronized FirmwareDriverClient firmwareDriver() {
return getProxy(FirmwareDriverClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InterconnectClient}.
* This client provides an interface for managing interconnects.
*
* @return an interface to the interconnects REST API.
*/
public synchronized InterconnectClient interconnect() {
return getProxy(InterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InterconnectLinkTopologyClient}.
* This client provides an interface for managing interconnect link topologies.
*
* @return an interface to the interconnect link topologies REST API.
*/
public synchronized InterconnectLinkTopologyClient interconnectLinkTopology() {
return getProxy(InterconnectLinkTopologyClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InterconnectTypeClient}.
* This client provides an interface for managing interconnect types.
*
* @return an interface to the interconnect types REST API.
*/
public synchronized InterconnectTypeClient interconnectType() {
return getProxy(InterconnectTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InternalLinkSetClient}.
* This client provides an interface for managing internal link sets.
*
* @return an interface to the internal link sets REST API.
*/
public synchronized InternalLinkSetClient internalLinkSet() {
return getProxy(InternalLinkSetClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LicenseClient}.
* This client provides an interface for managing licenses.
*
* @return an interface to the Licenses REST API.
*/
public synchronized LicenseClient license() {
return getProxy(LicenseClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalDownlinkClient}.
* This client provides an interface for managing logical downlinks.
*
* @return an interface to the logical downlinks REST API.
*/
public synchronized LogicalDownlinkClient logicalDownlink() {
return getProxy(LogicalDownlinkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalEnclosureClient}.
* This client provides an interface for managing logical enclosures.
*
* @return an interface to the logical enclosures REST API.
*/
public synchronized LogicalEnclosureClient logicalEnclosure() {
return getProxy(LogicalEnclosureClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalInterconnectClient}.
* This client provides an interface for managing logical interconnects.
*
* @return an interface to the logical interconnects REST API.
*/
public synchronized LogicalInterconnectClient logicalInterconnect() {
return getProxy(LogicalInterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalInterconnectGroupClient}.
* This client provides an interface for managing logical interconnect groups.
*
* @return an interface to the logical interconnect groups REST API.
*/
public synchronized LogicalInterconnectGroupClient logicalInterconnectGroup() {
return getProxy(LogicalInterconnectGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalSwitchClient}.
* This client provides an interface for managing logical switches.
*
* @return an interface to the logical switches REST API.
*/
public synchronized LogicalSwitchClient logicalSwitch() {
return getProxy(LogicalSwitchClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalSwitchGroupClient}.
* This client provides an interface for managing logical switch groups.
*
* @return an interface to the logical switch groups REST API.
*/
public synchronized LogicalSwitchGroupClient logicalSwitchGroup() {
return getProxy(LogicalSwitchGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LoginSessionClient}.
* This client provides an interface for execute the authentication of an user.
*
* @return an interface to the login session REST API.
*/
private synchronized LoginSessionClient loginClient() {
return getProxy(LoginSessionClient.class);
}
/**
* Creates or retrieves an existing instance of {@link MessagingCertificateClient}.
* This client provides an interface for managing certificates.
*
* @return an interface to the certificates REST API.
*/
public synchronized MessagingCertificateClient messagingCertificate() {
if (this.certificateClient == null) {
this.certificateClient = new MessagingCertificateClient(this.baseClient);
}
return this.certificateClient;
}
/**
* Creates or retrieves an existing instance of {@link NetworkSetClient}.
* This client provides an interface for managing networks sets.
*
* @return an interface to the networks sets REST API.
*/
public synchronized NetworkSetClient networkSet() {
return getProxy(NetworkSetClient.class);
}
/**
* Creates or retrieves an existing instance of {@link OsDeploymentPlanClient}.
* This client provides an interface for managing OS deployment plans.
*
* @return an interface to the OS deployment plans REST API.
*/
public synchronized OsDeploymentPlanClient osDeploymentPlan() {
return getProxy(OsDeploymentPlanClient.class);
}
/**
* Creates or retrieves an existing instance of {@link PowerDeliveryDeviceClient}.
* This client provides an interface for managing power delivery devices.
*
* @return an interface to the power delivery devices REST API.
*/
public synchronized PowerDeliveryDeviceClient powerDeliveryDevice() {
return getProxy(PowerDeliveryDeviceClient.class);
}
/**
* Creates or retrieves an existing instance of {@link RackClient}.
* This client provides an interface for managing racks.
*
* @return an interface to the racks REST API.
*/
public synchronized RackClient rack() {
return getProxy(RackClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasInterconnectClient}.
* This client provides an interface for managing SAS interconnects.
*
* @return an interface to the SAS interconnects REST API.
*/
public synchronized SasInterconnectClient sasInterconnects() {
return getProxy(SasInterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasInterconnectTypeClient}.
* This client provides an interface for managing SAS interconnect types.
*
* @return an interface to the SAS interconnect types REST API.
*/
public synchronized SasInterconnectTypeClient sasInterconnectType() {
return getProxy(SasInterconnectTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalInterconnectClient}.
* This client provides an interface for managing SAS logical interconnects.
*
* @return an interface to the SAS logical interconnects REST API.
*/
public synchronized SasLogicalInterconnectClient sasLogicalInterconnect() {
return getProxy(SasLogicalInterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalInterconnectGroupClient}.
* This client provides an interface for managing SAS logical interconnect groups.
*
* @return an interface to the SAS logical interconnect groups REST API.
*/
public synchronized SasLogicalInterconnectGroupClient sasLogicalInterconnectGroup() {
return getProxy(SasLogicalInterconnectGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalJbodAttachmentClient}.
* This client provides an interface for managing SAS logical JBOD attachments.
*
* @return an interface to the SAS logical JBOD attachments REST API.
*/
public synchronized SasLogicalJbodAttachmentClient sasLogicalJbodAttachment() {
return getProxy(SasLogicalJbodAttachmentClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalJbodClient}.
* This client provides an interface for managing SAS logical JBODs.
*
* @return an interface to the SAS logical JBODs REST API.
*/
public synchronized SasLogicalJbodClient sasLogicalJbod() {
return getProxy(SasLogicalJbodClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ScopeClient}.
* This client provides an interface for managing scopes.
*
* @return an interface to the Scopes REST API.
*/
public synchronized ScopeClient scope() {
return getProxy(ScopeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerHardwareClient}.
* This client provides an interface for managing server hardware.
*
* @return an interface to the server hardware REST API.
*/
public synchronized ServerHardwareClient serverHardware() {
return getProxy(ServerHardwareClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerHardwareTypeClient}.
* This client provides an interface for managing server hardware types.
*
* @return an interface to the server hardware types REST API.
*/
public synchronized ServerHardwareTypeClient serverHardwareType() {
return getProxy(ServerHardwareTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerProfileClient}.
* This client provides an interface for managing server profiles.
*
* @return an interface to the server profiles REST API.
*/
public synchronized ServerProfileClient serverProfile() {
return getProxy(ServerProfileClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerProfileTemplateClient}.
* This client provides an interface for managing server profile templates.
*
* @return an interface to the server profile templates REST API.
*/
public synchronized ServerProfileTemplateClient serverProfileTemplate() {
return getProxy(ServerProfileTemplateClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StoragePoolClient}.
* This client provides an interface for managing storage pools.
*
* @return an interface to the storage pools REST API.
*/
public synchronized StoragePoolClient storagePool() {
return getProxy(StoragePoolClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageSystemClient}.
* This client provides an interface for managing storage systems.
*
* @return an interface to the storage systems REST API.
*/
public synchronized StorageSystemClient storageSystem() {
return getProxy(StorageSystemClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageVolumeClient}.
* This client provides an interface for managing storage volumes.
*
* @return an interface to the storage volumes REST API.
*/
public synchronized StorageVolumeClient storageVolume() {
return getProxy(StorageVolumeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageVolumeAttachmentClient}.
* This client provides an interface for managing storage volume attachments.
*
* @return an interface to the storage volume attachments REST API.
*/
public synchronized StorageVolumeAttachmentClient storageVolumeAttachment() {
return getProxy(StorageVolumeAttachmentClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageVolumeTemplateClient}.
* This client provides an interface for managing storage volume templates.
*
* @return an interface to the storage volume templates REST API.
*/
public synchronized StorageVolumeTemplateClient storageVolumeTemplate() {
return getProxy(StorageVolumeTemplateClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SwitchClient}.
* This client provides an interface for managing switches.
*
* @return an interface to the switches REST API.
*/
public synchronized SwitchClient switches() {
return getProxy(SwitchClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SwitchTypeClient}.
* This client provides an interface for managing switch types.
*
* @return an interface to the switch types REST API.
*/
public synchronized SwitchTypeClient switchType() {
return getProxy(SwitchTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link UnmanagedDeviceClient}.
* This client provides an interface for managing unmanaged devices.
*
* @return an interface to the unmanaged devices REST API.
*/
public synchronized UnmanagedDeviceClient unmanagedDevice() {
return getProxy(UnmanagedDeviceClient.class);
}
/**
* Creates or retrieves an existing instance of {@link UplinkSetClient}.
* This client provides an interface for managing uplink sets.
*
* @return an interface to the uplink sets REST API.
*/
public synchronized UplinkSetClient uplinkSet() {
return getProxy(UplinkSetClient.class);
}
/**
* Creates or retrieves an existing instance of {@link VersionClient}.
* This client provides an interface for retrieving version information.
*
* @return an interface to the version REST API.
*/
private synchronized VersionClient versionClient() {
return getProxy(VersionClient.class);
}
}
| oneview-sdk-java-lib/src/main/java/com/hp/ov/sdk/rest/client/OneViewClient.java | /*
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* 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.hp.ov.sdk.rest.client;
import com.hp.ov.sdk.rest.client.activity.AlertClient;
import com.hp.ov.sdk.rest.client.facilities.DataCenterClient;
import com.hp.ov.sdk.rest.client.facilities.PowerDeliveryDeviceClient;
import com.hp.ov.sdk.rest.client.facilities.RackClient;
import com.hp.ov.sdk.rest.client.facilities.UnmanagedDeviceClient;
import com.hp.ov.sdk.rest.client.networking.ConnectionTemplateClient;
import com.hp.ov.sdk.rest.client.networking.EthernetNetworkClient;
import com.hp.ov.sdk.rest.client.networking.FabricClient;
import com.hp.ov.sdk.rest.client.networking.FcNetworkClient;
import com.hp.ov.sdk.rest.client.networking.FcoeNetworkClient;
import com.hp.ov.sdk.rest.client.networking.InterconnectClient;
import com.hp.ov.sdk.rest.client.networking.InterconnectLinkTopologyClient;
import com.hp.ov.sdk.rest.client.networking.InterconnectTypeClient;
import com.hp.ov.sdk.rest.client.networking.InternalLinkSetClient;
import com.hp.ov.sdk.rest.client.networking.LogicalDownlinkClient;
import com.hp.ov.sdk.rest.client.networking.LogicalInterconnectClient;
import com.hp.ov.sdk.rest.client.networking.LogicalInterconnectGroupClient;
import com.hp.ov.sdk.rest.client.networking.LogicalSwitchClient;
import com.hp.ov.sdk.rest.client.networking.LogicalSwitchGroupClient;
import com.hp.ov.sdk.rest.client.networking.NetworkSetClient;
import com.hp.ov.sdk.rest.client.networking.SasInterconnectClient;
import com.hp.ov.sdk.rest.client.networking.SasInterconnectTypeClient;
import com.hp.ov.sdk.rest.client.networking.SasLogicalInterconnectClient;
import com.hp.ov.sdk.rest.client.networking.SasLogicalInterconnectGroupClient;
import com.hp.ov.sdk.rest.client.networking.SwitchClient;
import com.hp.ov.sdk.rest.client.networking.SwitchTypeClient;
import com.hp.ov.sdk.rest.client.networking.UplinkSetClient;
import com.hp.ov.sdk.rest.client.security.LoginSessionClient;
import com.hp.ov.sdk.rest.client.security.MessagingCertificateClient;
import com.hp.ov.sdk.rest.client.server.EnclosureClient;
import com.hp.ov.sdk.rest.client.server.EnclosureGroupClient;
import com.hp.ov.sdk.rest.client.server.LogicalEnclosureClient;
import com.hp.ov.sdk.rest.client.server.ServerHardwareClient;
import com.hp.ov.sdk.rest.client.server.ServerHardwareTypeClient;
import com.hp.ov.sdk.rest.client.server.ServerProfileClient;
import com.hp.ov.sdk.rest.client.server.ServerProfileTemplateClient;
import com.hp.ov.sdk.rest.client.settings.FirmwareBundleClient;
import com.hp.ov.sdk.rest.client.settings.FirmwareDriverClient;
import com.hp.ov.sdk.rest.client.settings.LicenseClient;
import com.hp.ov.sdk.rest.client.settings.ScopeClient;
import com.hp.ov.sdk.rest.client.settings.VersionClient;
import com.hp.ov.sdk.rest.client.storage.DriveEnclosureClient;
import com.hp.ov.sdk.rest.client.storage.FcSanDeviceManagerClient;
import com.hp.ov.sdk.rest.client.storage.FcSanManagedSanClient;
import com.hp.ov.sdk.rest.client.storage.FcSanProviderClient;
import com.hp.ov.sdk.rest.client.storage.SasLogicalJbodAttachmentClient;
import com.hp.ov.sdk.rest.client.storage.SasLogicalJbodClient;
import com.hp.ov.sdk.rest.client.storage.StoragePoolClient;
import com.hp.ov.sdk.rest.client.storage.StorageSystemClient;
import com.hp.ov.sdk.rest.client.storage.StorageVolumeAttachmentClient;
import com.hp.ov.sdk.rest.client.storage.StorageVolumeClient;
import com.hp.ov.sdk.rest.client.storage.StorageVolumeTemplateClient;
import com.hp.ov.sdk.rest.client.uncategorized.OsDeploymentPlanClient;
import com.hp.ov.sdk.rest.http.core.client.SDKConfiguration;
import com.hp.ov.sdk.util.OneViewConnector;
import com.hpe.core.AbstractClient;
public class OneViewClient extends AbstractClient {
private final BaseClient baseClient;
private MessagingCertificateClient certificateClient;
public OneViewClient(SDKConfiguration config) {
this.baseClient = new BaseClient(config, config.getOneViewHostname());
OneViewConnector connector = new OneViewConnector(
config, this.versionClient(), this.loginClient());
this.baseClient.setSessionId(connector.connect());
}
public String getSessionId() {
return this.baseClient.getSessionId();
}
@Override
protected BaseClient baseClient() {
return this.baseClient;
}
/**
* Creates or retrieves an existing instance of {@link AlertClient}.
* This client provides an interface for managing alerts.
*
* @return an interface to the alerts REST API.
*/
public synchronized AlertClient alert() {
return getProxy(AlertClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ConnectionTemplateClient}.
* This client provides an interface for managing connection templates.
*
* @return an interface to the connection templates REST API.
*/
public synchronized ConnectionTemplateClient connectionTemplate() {
return getProxy(ConnectionTemplateClient.class);
}
/**
* Creates or retrieves an existing instance of {@link DataCenterClient}.
* This client provides an interface for managing datacenters.
*
* @return an interface to the datacenters REST API.
*/
public synchronized DataCenterClient dataCenter() {
return getProxy(DataCenterClient.class);
}
/**
* Creates or retrieves an existing instance of {@link DriveEnclosureClient}.
* This client provides an interface for managing drive enclosures.
*
* @return an interface to the drive enclosures REST API.
*/
public synchronized DriveEnclosureClient driveEnclosure() {
return getProxy(DriveEnclosureClient.class);
}
/**
* Creates or retrieves an existing instance of {@link EnclosureClient}.
* This client provides an interface for managing enclosures.
*
* @return an interface to the enclosures REST API.
*/
public synchronized EnclosureClient enclosure() {
return getProxy(EnclosureClient.class);
}
/**
* Creates or retrieves an existing instance of {@link EnclosureGroupClient}.
* This client provides an interface for managing enclosure groups.
*
* @return an interface to the enclosure groups REST API.
*/
public synchronized EnclosureGroupClient enclosureGroup() {
return getProxy(EnclosureGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link EthernetNetworkClient}.
* This client provides an interface for managing ethernet networks.
*
* @return an interface to the ethernet networks REST API.
*/
public synchronized EthernetNetworkClient ethernetNetwork() {
return getProxy(EthernetNetworkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FabricClient}.
* This client provides an interface for managing fabrics.
*
* @return an interface to the fabrics REST API.
*/
public synchronized FabricClient fabric() {
return getProxy(FabricClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcNetworkClient}.
* This client provides an interface for managing FC networks.
*
* @return an interface to the FC networks REST API.
*/
public synchronized FcNetworkClient fcNetwork() {
return getProxy(FcNetworkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcoeNetworkClient}.
* This client provides an interface for managing FCoE networks.
*
* @return an interface to the FCoE networks REST API.
*/
public synchronized FcoeNetworkClient fcoeNetwork() {
return getProxy(FcoeNetworkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcSanDeviceManagerClient}.
* This client provides an interface for managing SAN managers.
*
* @return an interface to the SAN managers REST API.
*/
public synchronized FcSanDeviceManagerClient fcSanDeviceManager() {
return getProxy(FcSanDeviceManagerClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcSanManagedSanClient}.
* This client provides an interface for managing managed SANs.
*
* @return an interface to the managed SANs REST API.
*/
public synchronized FcSanManagedSanClient fcSanManagedSan() {
return getProxy(FcSanManagedSanClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FcSanProviderClient}.
* This client provides an interface for managing SAN providers.
*
* @return an interface to the SAN providers REST API.
*/
public synchronized FcSanProviderClient fcSanProvider() {
return getProxy(FcSanProviderClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FirmwareBundleClient}.
* This client provides an interface for managing firmware bundles.
*
* @return an interface to the firmware bundles REST API.
*/
public synchronized FirmwareBundleClient firmwareBundle() {
return getProxy(FirmwareBundleClient.class);
}
/**
* Creates or retrieves an existing instance of {@link FirmwareDriverClient}.
* This client provides an interface for managing firmware drivers.
*
* @return an interface to the firmware drivers REST API.
*/
public synchronized FirmwareDriverClient firmwareDriver() {
return getProxy(FirmwareDriverClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InterconnectClient}.
* This client provides an interface for managing interconnects.
*
* @return an interface to the interconnects REST API.
*/
public synchronized InterconnectClient interconnect() {
return getProxy(InterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InterconnectLinkTopologyClient}.
* This client provides an interface for managing interconnect link topologies.
*
* @return an interface to the interconnect link topologies REST API.
*/
public synchronized InterconnectLinkTopologyClient interconnectLinkTopology() {
return getProxy(InterconnectLinkTopologyClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InterconnectTypeClient}.
* This client provides an interface for managing interconnect types.
*
* @return an interface to the interconnect types REST API.
*/
public synchronized InterconnectTypeClient interconnectType() {
return getProxy(InterconnectTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link InternalLinkSetClient}.
* This client provides an interface for managing internal link sets.
*
* @return an interface to the internal link sets REST API.
*/
public synchronized InternalLinkSetClient internalLinkSet() {
return getProxy(InternalLinkSetClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalDownlinkClient}.
* This client provides an interface for managing logical downlinks.
*
* @return an interface to the logical downlinks REST API.
*/
public synchronized LogicalDownlinkClient logicalDownlink() {
return getProxy(LogicalDownlinkClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalEnclosureClient}.
* This client provides an interface for managing logical enclosures.
*
* @return an interface to the logical enclosures REST API.
*/
public synchronized LogicalEnclosureClient logicalEnclosure() {
return getProxy(LogicalEnclosureClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalInterconnectClient}.
* This client provides an interface for managing logical interconnects.
*
* @return an interface to the logical interconnects REST API.
*/
public synchronized LogicalInterconnectClient logicalInterconnect() {
return getProxy(LogicalInterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalInterconnectGroupClient}.
* This client provides an interface for managing logical interconnect groups.
*
* @return an interface to the logical interconnect groups REST API.
*/
public synchronized LogicalInterconnectGroupClient logicalInterconnectGroup() {
return getProxy(LogicalInterconnectGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalSwitchClient}.
* This client provides an interface for managing logical switches.
*
* @return an interface to the logical switches REST API.
*/
public synchronized LogicalSwitchClient logicalSwitch() {
return getProxy(LogicalSwitchClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LogicalSwitchGroupClient}.
* This client provides an interface for managing logical switch groups.
*
* @return an interface to the logical switch groups REST API.
*/
public synchronized LogicalSwitchGroupClient logicalSwitchGroup() {
return getProxy(LogicalSwitchGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LoginSessionClient}.
* This client provides an interface for execute the authentication of an user.
*
* @return an interface to the login session REST API.
*/
private synchronized LoginSessionClient loginClient() {
return getProxy(LoginSessionClient.class);
}
/**
* Creates or retrieves an existing instance of {@link MessagingCertificateClient}.
* This client provides an interface for managing certificates.
*
* @return an interface to the certificates REST API.
*/
public synchronized MessagingCertificateClient messagingCertificate() {
if (this.certificateClient == null) {
this.certificateClient = new MessagingCertificateClient(this.baseClient);
}
return this.certificateClient;
}
/**
* Creates or retrieves an existing instance of {@link NetworkSetClient}.
* This client provides an interface for managing networks sets.
*
* @return an interface to the networks sets REST API.
*/
public synchronized NetworkSetClient networkSet() {
return getProxy(NetworkSetClient.class);
}
/**
* Creates or retrieves an existing instance of {@link PowerDeliveryDeviceClient}.
* This client provides an interface for managing power delivery devices.
*
* @return an interface to the power delivery devices REST API.
*/
public synchronized PowerDeliveryDeviceClient powerDeliveryDevice() {
return getProxy(PowerDeliveryDeviceClient.class);
}
/**
* Creates or retrieves an existing instance of {@link RackClient}.
* This client provides an interface for managing racks.
*
* @return an interface to the racks REST API.
*/
public synchronized RackClient rack() {
return getProxy(RackClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasInterconnectClient}.
* This client provides an interface for managing SAS interconnects.
*
* @return an interface to the SAS interconnects REST API.
*/
public synchronized SasInterconnectClient sasInterconnects() {
return getProxy(SasInterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasInterconnectTypeClient}.
* This client provides an interface for managing SAS interconnect types.
*
* @return an interface to the SAS interconnect types REST API.
*/
public synchronized SasInterconnectTypeClient sasInterconnectType() {
return getProxy(SasInterconnectTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalInterconnectClient}.
* This client provides an interface for managing SAS logical interconnects.
*
* @return an interface to the SAS logical interconnects REST API.
*/
public synchronized SasLogicalInterconnectClient sasLogicalInterconnect() {
return getProxy(SasLogicalInterconnectClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalInterconnectGroupClient}.
* This client provides an interface for managing SAS logical interconnect groups.
*
* @return an interface to the SAS logical interconnect groups REST API.
*/
public synchronized SasLogicalInterconnectGroupClient sasLogicalInterconnectGroup() {
return getProxy(SasLogicalInterconnectGroupClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalJbodAttachmentClient}.
* This client provides an interface for managing SAS logical JBOD attachments.
*
* @return an interface to the SAS logical JBOD attachments REST API.
*/
public synchronized SasLogicalJbodAttachmentClient sasLogicalJbodAttachment() {
return getProxy(SasLogicalJbodAttachmentClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SasLogicalJbodClient}.
* This client provides an interface for managing SAS logical JBODs.
*
* @return an interface to the SAS logical JBODs REST API.
*/
public synchronized SasLogicalJbodClient sasLogicalJbod() {
return getProxy(SasLogicalJbodClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ScopeClient}.
* This client provides an interface for managing scopes.
*
* @return an interface to the Scopes REST API.
*/
public synchronized ScopeClient scope() {
return getProxy(ScopeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerHardwareClient}.
* This client provides an interface for managing server hardware.
*
* @return an interface to the server hardware REST API.
*/
public synchronized ServerHardwareClient serverHardware() {
return getProxy(ServerHardwareClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerHardwareTypeClient}.
* This client provides an interface for managing server hardware types.
*
* @return an interface to the server hardware types REST API.
*/
public synchronized ServerHardwareTypeClient serverHardwareType() {
return getProxy(ServerHardwareTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerProfileClient}.
* This client provides an interface for managing server profiles.
*
* @return an interface to the server profiles REST API.
*/
public synchronized ServerProfileClient serverProfile() {
return getProxy(ServerProfileClient.class);
}
/**
* Creates or retrieves an existing instance of {@link ServerProfileTemplateClient}.
* This client provides an interface for managing server profile templates.
*
* @return an interface to the server profile templates REST API.
*/
public synchronized ServerProfileTemplateClient serverProfileTemplate() {
return getProxy(ServerProfileTemplateClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StoragePoolClient}.
* This client provides an interface for managing storage pools.
*
* @return an interface to the storage pools REST API.
*/
public synchronized StoragePoolClient storagePool() {
return getProxy(StoragePoolClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageSystemClient}.
* This client provides an interface for managing storage systems.
*
* @return an interface to the storage systems REST API.
*/
public synchronized StorageSystemClient storageSystem() {
return getProxy(StorageSystemClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageVolumeClient}.
* This client provides an interface for managing storage volumes.
*
* @return an interface to the storage volumes REST API.
*/
public synchronized StorageVolumeClient storageVolume() {
return getProxy(StorageVolumeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageVolumeAttachmentClient}.
* This client provides an interface for managing storage volume attachments.
*
* @return an interface to the storage volume attachments REST API.
*/
public synchronized StorageVolumeAttachmentClient storageVolumeAttachment() {
return getProxy(StorageVolumeAttachmentClient.class);
}
/**
* Creates or retrieves an existing instance of {@link StorageVolumeTemplateClient}.
* This client provides an interface for managing storage volume templates.
*
* @return an interface to the storage volume templates REST API.
*/
public synchronized StorageVolumeTemplateClient storageVolumeTemplate() {
return getProxy(StorageVolumeTemplateClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SwitchClient}.
* This client provides an interface for managing switches.
*
* @return an interface to the switches REST API.
*/
public synchronized SwitchClient switches() {
return getProxy(SwitchClient.class);
}
/**
* Creates or retrieves an existing instance of {@link SwitchTypeClient}.
* This client provides an interface for managing switch types.
*
* @return an interface to the switch types REST API.
*/
public synchronized SwitchTypeClient switchType() {
return getProxy(SwitchTypeClient.class);
}
/**
* Creates or retrieves an existing instance of {@link UnmanagedDeviceClient}.
* This client provides an interface for managing unmanaged devices.
*
* @return an interface to the unmanaged devices REST API.
*/
public synchronized UnmanagedDeviceClient unmanagedDevice() {
return getProxy(UnmanagedDeviceClient.class);
}
/**
* Creates or retrieves an existing instance of {@link UplinkSetClient}.
* This client provides an interface for managing uplink sets.
*
* @return an interface to the uplink sets REST API.
*/
public synchronized UplinkSetClient uplinkSet() {
return getProxy(UplinkSetClient.class);
}
/**
* Creates or retrieves an existing instance of {@link OsDeploymentPlanClient}.
* This client provides an interface for managing OS deployment plans.
*
* @return an interface to the OS deployment plans REST API.
*/
public synchronized OsDeploymentPlanClient osDeploymentPlan() {
return getProxy(OsDeploymentPlanClient.class);
}
/**
* Creates or retrieves an existing instance of {@link LicenseClient}.
* This client provides an interface for managing licenses.
*
* @return an interface to the Licenses REST API.
*/
public synchronized LicenseClient license() {
return getProxy(LicenseClient.class);
}
/**
* Creates or retrieves an existing instance of {@link VersionClient}.
* This client provides an interface for retrieving version information.
*
* @return an interface to the version REST API.
*/
private synchronized VersionClient versionClient() {
return getProxy(VersionClient.class);
}
}
| Keeping methods alphabetically ordered
| oneview-sdk-java-lib/src/main/java/com/hp/ov/sdk/rest/client/OneViewClient.java | Keeping methods alphabetically ordered | <ide><path>neview-sdk-java-lib/src/main/java/com/hp/ov/sdk/rest/client/OneViewClient.java
<ide> }
<ide>
<ide> /**
<add> * Creates or retrieves an existing instance of {@link LicenseClient}.
<add> * This client provides an interface for managing licenses.
<add> *
<add> * @return an interface to the Licenses REST API.
<add> */
<add> public synchronized LicenseClient license() {
<add> return getProxy(LicenseClient.class);
<add> }
<add>
<add> /**
<ide> * Creates or retrieves an existing instance of {@link LogicalDownlinkClient}.
<ide> * This client provides an interface for managing logical downlinks.
<ide> *
<ide> }
<ide>
<ide> /**
<add> * Creates or retrieves an existing instance of {@link OsDeploymentPlanClient}.
<add> * This client provides an interface for managing OS deployment plans.
<add> *
<add> * @return an interface to the OS deployment plans REST API.
<add> */
<add> public synchronized OsDeploymentPlanClient osDeploymentPlan() {
<add> return getProxy(OsDeploymentPlanClient.class);
<add> }
<add>
<add> /**
<ide> * Creates or retrieves an existing instance of {@link PowerDeliveryDeviceClient}.
<ide> * This client provides an interface for managing power delivery devices.
<ide> *
<ide> }
<ide>
<ide> /**
<del> * Creates or retrieves an existing instance of {@link OsDeploymentPlanClient}.
<del> * This client provides an interface for managing OS deployment plans.
<del> *
<del> * @return an interface to the OS deployment plans REST API.
<del> */
<del> public synchronized OsDeploymentPlanClient osDeploymentPlan() {
<del> return getProxy(OsDeploymentPlanClient.class);
<del> }
<del>
<del> /**
<del> * Creates or retrieves an existing instance of {@link LicenseClient}.
<del> * This client provides an interface for managing licenses.
<del> *
<del> * @return an interface to the Licenses REST API.
<del> */
<del> public synchronized LicenseClient license() {
<del> return getProxy(LicenseClient.class);
<del> }
<del>
<del> /**
<ide> * Creates or retrieves an existing instance of {@link VersionClient}.
<ide> * This client provides an interface for retrieving version information.
<ide> * |
|
Java | apache-2.0 | 4eb83d17eb06293001c4c44c364e4255750bbb77 | 0 | afilimonov/jackrabbit,bartosz-grabski/jackrabbit,afilimonov/jackrabbit,tripodsan/jackrabbit,kigsmtua/jackrabbit,SylvesterAbreu/jackrabbit,tripodsan/jackrabbit,sdmcraft/jackrabbit,kigsmtua/jackrabbit,afilimonov/jackrabbit,Overseas-Student-Living/jackrabbit,tripodsan/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,Overseas-Student-Living/jackrabbit,SylvesterAbreu/jackrabbit,Kast0rTr0y/jackrabbit,kigsmtua/jackrabbit,bartosz-grabski/jackrabbit,Kast0rTr0y/jackrabbit,sdmcraft/jackrabbit,bartosz-grabski/jackrabbit,Kast0rTr0y/jackrabbit,SylvesterAbreu/jackrabbit | /*
* 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.jackrabbit.core.config;
import org.apache.jackrabbit.core.data.DataStore;
import org.apache.jackrabbit.core.data.DataStoreFactory;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.core.fs.FileSystemException;
import org.apache.jackrabbit.core.fs.FileSystemFactory;
import org.apache.jackrabbit.core.state.DefaultISMLocking;
import org.apache.jackrabbit.core.state.ISMLocking;
import org.apache.jackrabbit.core.state.ISMLockingFactory;
import org.apache.jackrabbit.core.util.RepositoryLock;
import org.apache.jackrabbit.core.util.RepositoryLockMechanism;
import org.apache.jackrabbit.core.util.RepositoryLockMechanismFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.File;
import java.util.Properties;
import javax.jcr.RepositoryException;
/**
* Configuration parser. This class is used to parse the repository and
* workspace configuration files.
* <p>
* The following code sample outlines the usage of this class:
* <pre>
* Properties variables = ...; // parser variables
* RepositoryConfigurationParser parser =
* new RepositoryConfigurationParser(variables);
* RepositoryConfig rc = parser.parseRepositoryConfig(...);
* WorkspaceConfig wc = parser.parseWorkspaceConfig(...);
* </pre>
* <p>
* Note that the configuration objects returned by this parser are not
* initialized. The caller needs to initialize the configuration objects
* before using them.
*/
public class RepositoryConfigurationParser extends ConfigurationParser {
/** Name of the repository home directory parser variable. */
public static final String REPOSITORY_HOME_VARIABLE = "rep.home";
/** Name of the workspace home directory parser variable. */
public static final String WORKSPACE_HOME_VARIABLE = "wsp.home";
/** Name of the repository name parser variable. */
public static final String WORKSPACE_NAME_VARIABLE = "wsp.name";
/** Name of the security configuration element. */
public static final String SECURITY_ELEMENT = "Security";
/** Name of the security manager configuration element. */
public static final String SECURITY_MANAGER_ELEMENT = "SecurityManager";
/** Name of the access manager configuration element. */
public static final String ACCESS_MANAGER_ELEMENT = "AccessManager";
/** Name of the login module configuration element. */
public static final String LOGIN_MODULE_ELEMENT = "LoginModule";
/**
* Name of the optional WorkspaceAccessManager element defining which
* implementation of WorkspaceAccessManager to be used.
*/
private static final String WORKSPACE_ACCESS_ELEMENT = "WorkspaceAccessManager";
/** Name of the general workspace configuration element. */
public static final String WORKSPACES_ELEMENT = "Workspaces";
/** Name of the workspace configuration element. */
public static final String WORKSPACE_ELEMENT = "Workspace";
/** Name of the versioning configuration element. */
public static final String VERSIONING_ELEMENT = "Versioning";
/** Name of the file system configuration element. */
public static final String FILE_SYSTEM_ELEMENT = "FileSystem";
/** Name of the cluster configuration element. */
public static final String CLUSTER_ELEMENT = "Cluster";
/** Name of the journal configuration element. */
public static final String JOURNAL_ELEMENT = "Journal";
/** Name of the data store configuration element. */
public static final String DATA_STORE_ELEMENT = "DataStore";
/** Name of the repository lock mechanism configuration element. */
public static final String REPOSITORY_LOCK_MECHANISM_ELEMENT =
"RepositoryLockMechanism";
/** Name of the persistence manager configuration element. */
public static final String PERSISTENCE_MANAGER_ELEMENT =
"PersistenceManager";
/** Name of the search index configuration element. */
public static final String SEARCH_INDEX_ELEMENT = "SearchIndex";
/** Name of the ism locking configuration element. */
public static final String ISM_LOCKING_ELEMENT = "ISMLocking";
/** Name of the application name configuration attribute. */
public static final String APP_NAME_ATTRIBUTE = "appName";
/** Name of the workspace conaining security data. */
public static final String WSP_NAME_ATTRIBUTE = "workspaceName";
/** Name of the root path configuration attribute. */
public static final String ROOT_PATH_ATTRIBUTE = "rootPath";
/** Name of the config root path configuration attribute. */
public static final String CONFIG_ROOT_PATH_ATTRIBUTE = "configRootPath";
/** Name of the maximum idle time configuration attribute. */
public static final String MAX_IDLE_TIME_ATTRIBUTE = "maxIdleTime";
/** Name of the default workspace configuration attribute. */
public static final String DEFAULT_WORKSPACE_ATTRIBUTE =
"defaultWorkspace";
/** Name of the id configuration attribute. */
public static final String ID_ATTRIBUTE = "id";
/** Name of the syncDelay configuration attribute. */
public static final String SYNC_DELAY_ATTRIBUTE = "syncDelay";
/** Name of the default search index implementation class. */
public static final String DEFAULT_QUERY_HANDLER =
"org.apache.jackrabbit.core.query.lucene.SearchIndex";
/** Name of the clustered configuration attribute. */
public static final String CLUSTERED_ATTRIBUTE = "clustered";
/** Default synchronization delay, in milliseconds. */
public static final String DEFAULT_SYNC_DELAY = "5000";
/** Name of the workspace specific security configuration element */
private static final String WSP_SECURITY_ELEMENT = "WorkspaceSecurity";
/**
* Name of the optional AccessControlProvider element defining which
* implementation of AccessControlProvider should be used.
*/
private static final String AC_PROVIDER_ELEMENT = "AccessControlProvider";
/**
* Creates a new configuration parser with the given parser variables.
*
* @param variables parser variables
*/
public RepositoryConfigurationParser(Properties variables) {
super(variables);
}
/**
* Parses repository configuration. Repository configuration uses the
* following format:
* <pre>
* <Repository>
* <FileSystem ...>
* <Security appName="...">
* <SecurityManager ...>
* <AccessManager ...>
* <LoginModule ... (optional)>
* </Security>
* <Workspaces rootPath="..." defaultWorkspace="..."/>
* <Workspace ...>
* <Versioning ...>
* </Repository>
* </pre>
* <p>
* The <code>FileSystem</code> element is a
* {@link #parseBeanConfig(Element,String) bean configuration} element,
* that specifies the file system implementation for storing global
* repository information. The <code>Security</code> element contains
* an <code>AccessManager</code> bean configuration element and the
* JAAS name of the repository application. The <code>Workspaces</code>
* element contains general workspace parameters, and the
* <code>Workspace</code> element is a template for the individual
* workspace configuration files. The <code>Versioning</code> element
* contains
* {@link #parseVersioningConfig(Element) versioning configuration} for
* the repository.
* <p>
* In addition to the configured information, the returned repository
* configuration object also contains the repository home directory path
* that is given as the ${rep.home} parser variable. Note that the
* variable <em>must</em> be available for the configuration document to
* be correctly parsed.
* <p>
* {@link #replaceVariables(String) Variable replacement} is performed
* on the security application name attribute, the general workspace
* configuration attributes, and on the file system, access manager,
* and versioning configuration information.
* <p>
* Note that the returned repository configuration object has not been
* initialized.
*
* @param xml repository configuration document
* @return repository configuration
* @throws ConfigurationException if the configuration is broken
* @see #parseBeanConfig(Element, String)
* @see #parseVersioningConfig(Element)
*/
public RepositoryConfig parseRepositoryConfig(InputSource xml)
throws ConfigurationException {
Element root = parseXML(xml, true);
// Repository home directory
String home = getVariables().getProperty(REPOSITORY_HOME_VARIABLE);
// File system implementation
FileSystemFactory fsf = getFileSystemFactory(root, FILE_SYSTEM_ELEMENT);
// Security configuration and access manager implementation
Element security = getElement(root, SECURITY_ELEMENT);
SecurityConfig securityConfig = parseSecurityConfig(security);
// General workspace configuration
Element workspaces = getElement(root, WORKSPACES_ELEMENT);
String workspaceDirectory = replaceVariables(
getAttribute(workspaces, ROOT_PATH_ATTRIBUTE));
String workspaceConfigDirectory =
getAttribute(workspaces, CONFIG_ROOT_PATH_ATTRIBUTE, null);
String defaultWorkspace = replaceVariables(
getAttribute(workspaces, DEFAULT_WORKSPACE_ATTRIBUTE));
int maxIdleTime = Integer.parseInt(
getAttribute(workspaces, MAX_IDLE_TIME_ATTRIBUTE, "0"));
// Workspace configuration template
Element template = getElement(root, WORKSPACE_ELEMENT);
// Versioning configuration
VersioningConfig vc = parseVersioningConfig(root);
// Optional search configuration
SearchConfig sc = parseSearchConfig(root);
// Optional journal configuration
ClusterConfig cc = parseClusterConfig(root);
// Optional data store factory
DataStoreFactory dsf = getDataStoreFactory(root, home);
RepositoryLockMechanismFactory rlf = getRepositoryLockMechanismFactory(root);
return new RepositoryConfig(home, securityConfig, fsf,
workspaceDirectory, workspaceConfigDirectory, defaultWorkspace,
maxIdleTime, template, vc, sc, cc, dsf, rlf, this);
}
/**
* Parses security configuration. Security configuration
* uses the following format:
* <pre>
* <Security appName="...">
* <SecurityManager ...>
* <AccessManager ...>
* <LoginModule ... (optional)>
* </Security>
* </pre>
* <p/>
* The <code>SecurityManager</code>, the <code>AccessManager</code>
* and <code>LoginModule</code> are all
* {@link #parseBeanConfig(Element,String) bean configuration}
* elements.
* <p/>
* The login module is an optional feature of repository configuration.
*
* @param security the <security> element.
* @return the security configuration.
* @throws ConfigurationException if the configuration is broken
*/
public SecurityConfig parseSecurityConfig(Element security)
throws ConfigurationException {
String appName = getAttribute(security, APP_NAME_ATTRIBUTE);
SecurityManagerConfig smc = parseSecurityManagerConfig(security);
AccessManagerConfig amc = parseAccessManagerConfig(security);
LoginModuleConfig lmc = parseLoginModuleConfig(security);
return new SecurityConfig(appName, smc, amc, lmc);
}
/**
* Parses the security manager configuration.
*
* @param security the <security> element.
* @return the security manager configuration or <code>null</code>.
* @throws ConfigurationException if the configuration is broken
*/
public SecurityManagerConfig parseSecurityManagerConfig(Element security)
throws ConfigurationException {
// Optional security manager config entry
Element smElement = getElement(security, SECURITY_MANAGER_ELEMENT, false);
if (smElement != null) {
BeanConfig bc = parseBeanConfig(smElement);
String wspAttr = getAttribute(smElement, WSP_NAME_ATTRIBUTE, null);
BeanConfig wac = null;
Element element = getElement(smElement, WORKSPACE_ACCESS_ELEMENT, false);
if (element != null) {
wac = parseBeanConfig(smElement, WORKSPACE_ACCESS_ELEMENT);
}
return new SecurityManagerConfig(bc, wspAttr, wac);
} else {
return null;
}
}
/**
* Parses the access manager configuration.
*
* @param security the <security> element.
* @return the access manager configuration or <code>null</code>.
* @throws ConfigurationException if the configuration is broken
*/
public AccessManagerConfig parseAccessManagerConfig(Element security)
throws ConfigurationException {
// Optional access manager config entry
Element accessMgr = getElement(security, ACCESS_MANAGER_ELEMENT, false);
if (accessMgr != null) {
return new AccessManagerConfig(parseBeanConfig(accessMgr));
} else {
return null;
}
}
/**
* Parses the login module configuration.
*
* @param security the <security> element.
* @return the login module configuration or <code>null</code>.
* @throws ConfigurationException if the configuration is broken
*/
public LoginModuleConfig parseLoginModuleConfig(Element security)
throws ConfigurationException {
// Optional login module
Element loginModule = getElement(security, LOGIN_MODULE_ELEMENT, false);
if (loginModule != null) {
return new LoginModuleConfig(parseBeanConfig(security, LOGIN_MODULE_ELEMENT));
} else {
return null;
}
}
/**
* Parses workspace configuration. Workspace configuration uses the
* following format:
* <pre>
* <Workspace name="...">
* <FileSystem ...>
* <PersistenceManager ...>
* <SearchIndex ...>
* <ISMLocking ...>
* <WorkspaceSecurity ...>
* <ISMLocking ...>
* </Workspace>
* </pre>
* <p>
* All the child elements (<code>FileSystem</code>,
* <code>PersistenceManager</code>, and <code>SearchIndex</code>) are
* {@link #parseBeanConfig(Element,String) bean configuration} elements.
* In addition to bean configuration, the
* {@link #parseSearchConfig(Element) search element} also contains
* configuration for the search file system.
* <p>
* In addition to the configured information, the returned workspace
* configuration object also contains the workspace home directory path
* that is given as the ${wsp.home} parser variable. Note that the
* variable <em>must</em> be available for the configuration document to
* be correctly parsed.
* <p>
* Variable replacement is performed on the optional workspace name
* attribute. If the name is not given, then the name of the workspace
* home directory is used as the workspace name. Once the name has been
* determined, it will be added as the ${wsp.name} variable in a temporary
* configuration parser that is used to parse the contained configuration
* elements.
* <p>
* The search index configuration element is optional. If it is not given,
* then the workspace will not have search capabilities.
* <p>
* The ism locking configuration element is optional. If it is not given,
* then a default implementation is used.
* <p>
* Note that the returned workspace configuration object has not been
* initialized.
*
* @param xml workspace configuration document
* @return workspace configuration
* @throws ConfigurationException if the configuration is broken
* @see #parseBeanConfig(Element, String)
* @see #parseSearchConfig(Element)
* @see #parseWorkspaceSecurityConfig(Element)
*/
public WorkspaceConfig parseWorkspaceConfig(InputSource xml)
throws ConfigurationException {
Element root = parseXML(xml);
return parseWorkspaceConfig(root);
}
/**
* Parse workspace config.
*
* @param root root element of the workspace configuration
*
* @see #parseWorkspaceConfig(InputSource)
*/
protected WorkspaceConfig parseWorkspaceConfig(Element root)
throws ConfigurationException {
// Workspace home directory
String home = getVariables().getProperty(WORKSPACE_HOME_VARIABLE);
// Workspace name
String name =
getAttribute(root, NAME_ATTRIBUTE, new File(home).getName());
// Clustered attribute
boolean clustered = Boolean.valueOf(
getAttribute(root, CLUSTERED_ATTRIBUTE, "true")).booleanValue();
// Create a temporary parser that contains the ${wsp.name} variable
Properties tmpVariables = (Properties) getVariables().clone();
tmpVariables.put(WORKSPACE_NAME_VARIABLE, name);
RepositoryConfigurationParser tmpParser = createSubParser(tmpVariables);
// File system implementation
FileSystemFactory fsf =
tmpParser.getFileSystemFactory(root, FILE_SYSTEM_ELEMENT);
// Persistence manager implementation
PersistenceManagerConfig pmc = tmpParser.parsePersistenceManagerConfig(root);
// Search implementation (optional)
SearchConfig sc = tmpParser.parseSearchConfig(root);
// Item state manager locking configuration (optional)
ISMLockingFactory ismLockingFactory =
tmpParser.getISMLockingFactory(root);
// workspace specific security configuration
WorkspaceSecurityConfig workspaceSecurityConfig = tmpParser.parseWorkspaceSecurityConfig(root);
return new WorkspaceConfig(
home, name, clustered, fsf, pmc, sc,
ismLockingFactory, workspaceSecurityConfig);
}
/**
* Parses search index configuration. Search index configuration
* uses the following format:
* <pre>
* <SearchIndex class="...">
* <param name="..." value="...">
* ...
* <FileSystem ...>
* </Search>
* </pre>
* <p/>
* Both the <code>SearchIndex</code> and <code>FileSystem</code>
* elements are {@link #parseBeanConfig(Element,String) bean configuration}
* elements. If the search implementation class is not given, then
* a default implementation is used.
* <p/>
* The search index is an optional feature of workspace configuration.
* If the search configuration element is not found, then this method
* returns <code>null</code>.
* <p/>
* The FileSystem element in a search index configuration is optional.
* However some implementations may require a FileSystem.
*
* @param parent parent of the <code>SearchIndex</code> element
* @return search configuration, or <code>null</code>
* @throws ConfigurationException if the configuration is broken
*/
protected SearchConfig parseSearchConfig(Element parent)
throws ConfigurationException {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& SEARCH_INDEX_ELEMENT.equals(child.getNodeName())) {
Element element = (Element) child;
// Search implementation class
String className = getAttribute(
element, CLASS_ATTRIBUTE, DEFAULT_QUERY_HANDLER);
// Search parameters
Properties parameters = parseParameters(element);
// Optional file system implementation
FileSystemFactory fsf = null;
if (getElement(element, FILE_SYSTEM_ELEMENT, false) != null) {
fsf = getFileSystemFactory(element, FILE_SYSTEM_ELEMENT);
}
return new SearchConfig(className, parameters, fsf);
}
}
return null;
}
/**
* Read the WorkspaceSecurity Element of Workspace's configuration. It uses
* the following format:
* <pre>
* <WorkspaceSecurity>
* <AccessControlProvider class="..." (optional)>
* </WorkspaceSecurity>
* </pre>
*
* @param parent Workspace-Root-Element
* @return a new <code>WorkspaceSecurityConfig</code>
* @throws ConfigurationException
*/
public WorkspaceSecurityConfig parseWorkspaceSecurityConfig(Element parent)
throws ConfigurationException {
BeanConfig acProviderConfig = null;
Element element = getElement(parent, WSP_SECURITY_ELEMENT, false);
if (element != null) {
Element provFact = getElement(element, AC_PROVIDER_ELEMENT, false);
if (provFact != null) {
acProviderConfig = parseBeanConfig(element, AC_PROVIDER_ELEMENT);
acProviderConfig.setValidate(false); // JCR-1920
}
}
return new WorkspaceSecurityConfig(acProviderConfig);
}
/**
* Returns an ISM locking factory that creates {@link ISMLocking} instances
* based on the given configuration. ISM locking configuration uses the
* following format:
* <pre>
* <ISMLocking class="...">
* <param name="..." value="...">
* ...
* </ISMLocking>
* </pre>
* <p>
* The <code>ISMLocking</code> is a
* {@link #parseBeanConfig(Element,String) bean configuration} element.
* <p>
* ISM locking is an optional part of the workspace configuration. If
* the ISM locking element is not found, then the returned factory will
* create instances of the {@link DefaultISMLocking} class.
*
* @param parent parent of the <code>ISMLocking</code> element
* @return ISM locking factory
*/
protected ISMLockingFactory getISMLockingFactory(final Element parent) {
return new ISMLockingFactory() {
public ISMLocking getISMLocking() throws RepositoryException {
Element element = getElement(parent, ISM_LOCKING_ELEMENT, false);
if (element != null) {
BeanConfig config = parseBeanConfig(element);
try {
return (ISMLocking) config.newInstance();
} catch (ClassCastException e) {
throw new RepositoryException(
"Invalid ISMLocking class: "
+ config.getClassName(), e);
}
} else {
return new DefaultISMLocking();
}
}
};
}
/**
* Parses versioning configuration. Versioning configuration uses the
* following format:
* <pre>
* <Versioning rootPath="...">
* <FileSystem ...>
* <PersistenceManager ...>
* </Versioning>
* </pre>
* <p>
* Both the <code>FileSystem</code> and <code>PersistenceManager</code>
* elements are {@link #parseBeanConfig(Element,String) bean configuration}
* elements. In addition to the bean parameter values,
* {@link #replaceVariables(String) variable replacement} is performed
* also on the versioning root path attribute.
*
* @param parent parent of the <code>Versioning</code> element
* @return versioning configuration
* @throws ConfigurationException if the configuration is broken
*/
protected VersioningConfig parseVersioningConfig(Element parent)
throws ConfigurationException {
Element element = getElement(parent, VERSIONING_ELEMENT);
// Versioning home directory
String home =
replaceVariables(getAttribute(element, ROOT_PATH_ATTRIBUTE));
// File system implementation
FileSystemFactory fsf =
getFileSystemFactory(element, FILE_SYSTEM_ELEMENT);
// Persistence manager implementation
PersistenceManagerConfig pmc = parsePersistenceManagerConfig(element);
// Item state manager locking configuration (optional)
ISMLockingFactory ismLockingFactory =
getISMLockingFactory(element);
return new VersioningConfig(home, fsf, pmc, ismLockingFactory);
}
/**
* Parses cluster configuration. Cluster configuration uses the following format:
* <pre>
* <Cluster>
* <Journal ...>
* </Journal>
* </pre>
* <p/>
* <code>Cluster</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
* element.
* <p/>
* Clustering is an optional feature. If the cluster element is not found, then this
* method returns <code>null</code>.
*
* @param parent parent of the <code>Journal</code> element
* @return journal configuration, or <code>null</code>
* @throws ConfigurationException if the configuration is broken
*/
protected ClusterConfig parseClusterConfig(Element parent)
throws ConfigurationException {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& CLUSTER_ELEMENT.equals(child.getNodeName())) {
Element element = (Element) child;
String id = null;
String value = getAttribute(element, ID_ATTRIBUTE, null);
if (value != null) {
id = replaceVariables(value);
}
value = getAttribute(element, SYNC_DELAY_ATTRIBUTE, DEFAULT_SYNC_DELAY);
long syncDelay = Long.parseLong(replaceVariables(value));
JournalConfig jc = parseJournalConfig(element);
return new ClusterConfig(id, syncDelay, jc);
}
}
return null;
}
/**
* Parses journal configuration. Journal configuration uses the following format:
* <pre>
* <Journal class="...">
* <param name="..." value="...">
* ...
* </Journal>
* </pre>
* <p/>
* <code>Journal</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
* element.
*
* @param cluster parent cluster element
* @return journal configuration, or <code>null</code>
* @throws ConfigurationException if the configuration is broken
*/
protected JournalConfig parseJournalConfig(Element cluster)
throws ConfigurationException {
return new JournalConfig(
parseBeanConfig(cluster, JOURNAL_ELEMENT));
}
/**
* Parses data store configuration. Data store configuration uses the following format:
* <pre>
* <DataStore class="...">
* <param name="..." value="...">
* ...
* </DataStore>
* </pre>
* <p/>
* <code>DataStore</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
* element.
*
* @param parent configuration element
* @param directory the repository directory
* @return data store factory
* @throws ConfigurationException if the configuration is broken
*/
protected DataStoreFactory getDataStoreFactory(
final Element parent, final String directory)
throws ConfigurationException {
return new DataStoreFactory() {
public DataStore getDataStore() throws RepositoryException {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& DATA_STORE_ELEMENT.equals(child.getNodeName())) {
BeanConfig bc =
parseBeanConfig(parent, DATA_STORE_ELEMENT);
DataStore store = (DataStore) bc.newInstance();
store.init(directory);
return store;
}
}
return null;
}
};
}
/**
* Parses repository lock mechanism configuration. Repository lock mechanism
* configuration uses the following format:
* <pre>
* <RepositoryLockMechanism class="..." >
* <param name="..." value="...">
* ...
* </RepositoryLockMechanism>
* </pre>
* <p/>
* <code>RepositoryLockMechanism</code> is a
* {@link #parseBeanConfig(Element,String) bean configuration} element.
*
* @param root the root configuration element
* @return repository lock mechanism factory
* @throws ConfigurationException if the configuration is broken
*/
protected RepositoryLockMechanismFactory getRepositoryLockMechanismFactory(final Element root) {
return new RepositoryLockMechanismFactory() {
public RepositoryLockMechanism getRepositoryLockMechanism() throws RepositoryException {
RepositoryLockMechanism lock = null;
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& REPOSITORY_LOCK_MECHANISM_ELEMENT.equals(child.getNodeName())) {
BeanConfig bc =
parseBeanConfig(root, REPOSITORY_LOCK_MECHANISM_ELEMENT);
lock = (RepositoryLockMechanism) bc.newInstance();
break;
}
}
if (lock == null) {
lock = new RepositoryLock();
}
return lock;
}
};
}
/**
* Parses the PersistenceManager config.
*
* @param parent parent of the <code>PersistenceManager</code> element
* @return persistence manager configuration
* @throws ConfigurationException if the configuration is broken
*/
protected PersistenceManagerConfig parsePersistenceManagerConfig(
Element parent) throws ConfigurationException {
return new PersistenceManagerConfig(
parseBeanConfig(parent, PERSISTENCE_MANAGER_ELEMENT));
}
/**
* Creates a new instance of a configuration parser but with overlayed
* variables.
*
* @param variables the variables overlay
* @return a new configuration parser instance
*/
protected RepositoryConfigurationParser createSubParser(Properties variables) {
// overlay the properties
Properties props = new Properties(getVariables());
props.putAll(variables);
return new RepositoryConfigurationParser(props);
}
/**
* Creates and returns a factory object that creates {@link FileSystem}
* instances based on the bean configuration at the named element.
*
* @param parent parent element
* @param name name of the bean configuration element
* @return file system factory
* @throws ConfigurationException if the bean configuration is invalid
*/
protected FileSystemFactory getFileSystemFactory(Element parent, String name)
throws ConfigurationException {
final BeanConfig config = parseBeanConfig(parent, name);
return new FileSystemFactory() {
public FileSystem getFileSystem() throws RepositoryException {
try {
FileSystem fs = (FileSystem) config.newInstance();
fs.init();
return fs;
} catch (ClassCastException e) {
throw new RepositoryException(
"Invalid file system implementation class: "
+ config.getClassName(), e);
} catch (FileSystemException e) {
throw new RepositoryException(
"File system initialization failure.", e);
}
}
};
}
}
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/config/RepositoryConfigurationParser.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.jackrabbit.core.config;
import org.apache.jackrabbit.core.data.DataStore;
import org.apache.jackrabbit.core.data.DataStoreFactory;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.core.fs.FileSystemException;
import org.apache.jackrabbit.core.fs.FileSystemFactory;
import org.apache.jackrabbit.core.state.DefaultISMLocking;
import org.apache.jackrabbit.core.state.ISMLocking;
import org.apache.jackrabbit.core.state.ISMLockingFactory;
import org.apache.jackrabbit.core.util.RepositoryLock;
import org.apache.jackrabbit.core.util.RepositoryLockMechanism;
import org.apache.jackrabbit.core.util.RepositoryLockMechanismFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.File;
import java.util.Properties;
import javax.jcr.RepositoryException;
/**
* Configuration parser. This class is used to parse the repository and
* workspace configuration files.
* <p>
* The following code sample outlines the usage of this class:
* <pre>
* Properties variables = ...; // parser variables
* RepositoryConfigurationParser parser =
* new RepositoryConfigurationParser(variables);
* RepositoryConfig rc = parser.parseRepositoryConfig(...);
* WorkspaceConfig wc = parser.parseWorkspaceConfig(...);
* </pre>
* <p>
* Note that the configuration objects returned by this parser are not
* initialized. The caller needs to initialize the configuration objects
* before using them.
*/
public class RepositoryConfigurationParser extends ConfigurationParser {
/** Name of the repository home directory parser variable. */
public static final String REPOSITORY_HOME_VARIABLE = "rep.home";
/** Name of the workspace home directory parser variable. */
public static final String WORKSPACE_HOME_VARIABLE = "wsp.home";
/** Name of the repository name parser variable. */
public static final String WORKSPACE_NAME_VARIABLE = "wsp.name";
/** Name of the security configuration element. */
public static final String SECURITY_ELEMENT = "Security";
/** Name of the security manager configuration element. */
public static final String SECURITY_MANAGER_ELEMENT = "SecurityManager";
/** Name of the access manager configuration element. */
public static final String ACCESS_MANAGER_ELEMENT = "AccessManager";
/** Name of the login module configuration element. */
public static final String LOGIN_MODULE_ELEMENT = "LoginModule";
/**
* Name of the optional WorkspaceAccessManager element defining which
* implementation of WorkspaceAccessManager to be used.
*/
private static final String WORKSPACE_ACCESS_ELEMENT = "WorkspaceAccessManager";
/** Name of the general workspace configuration element. */
public static final String WORKSPACES_ELEMENT = "Workspaces";
/** Name of the workspace configuration element. */
public static final String WORKSPACE_ELEMENT = "Workspace";
/** Name of the versioning configuration element. */
public static final String VERSIONING_ELEMENT = "Versioning";
/** Name of the file system configuration element. */
public static final String FILE_SYSTEM_ELEMENT = "FileSystem";
/** Name of the cluster configuration element. */
public static final String CLUSTER_ELEMENT = "Cluster";
/** Name of the journal configuration element. */
public static final String JOURNAL_ELEMENT = "Journal";
/** Name of the data store configuration element. */
public static final String DATA_STORE_ELEMENT = "DataStore";
/** Name of the repository lock mechanism configuration element. */
public static final String REPOSITORY_LOCK_MECHANISM_ELEMENT =
"RepositoryLockMechanism";
/** Name of the persistence manager configuration element. */
public static final String PERSISTENCE_MANAGER_ELEMENT =
"PersistenceManager";
/** Name of the search index configuration element. */
public static final String SEARCH_INDEX_ELEMENT = "SearchIndex";
/** Name of the ism locking configuration element. */
public static final String ISM_LOCKING_ELEMENT = "ISMLocking";
/** Name of the application name configuration attribute. */
public static final String APP_NAME_ATTRIBUTE = "appName";
/** Name of the workspace conaining security data. */
public static final String WSP_NAME_ATTRIBUTE = "workspaceName";
/** Name of the root path configuration attribute. */
public static final String ROOT_PATH_ATTRIBUTE = "rootPath";
/** Name of the config root path configuration attribute. */
public static final String CONFIG_ROOT_PATH_ATTRIBUTE = "configRootPath";
/** Name of the maximum idle time configuration attribute. */
public static final String MAX_IDLE_TIME_ATTRIBUTE = "maxIdleTime";
/** Name of the default workspace configuration attribute. */
public static final String DEFAULT_WORKSPACE_ATTRIBUTE =
"defaultWorkspace";
/** Name of the id configuration attribute. */
public static final String ID_ATTRIBUTE = "id";
/** Name of the syncDelay configuration attribute. */
public static final String SYNC_DELAY_ATTRIBUTE = "syncDelay";
/** Name of the default search index implementation class. */
public static final String DEFAULT_QUERY_HANDLER =
"org.apache.jackrabbit.core.query.lucene.SearchIndex";
/** Name of the clustered configuration attribute. */
public static final String CLUSTERED_ATTRIBUTE = "clustered";
/** Default synchronization delay, in milliseconds. */
public static final String DEFAULT_SYNC_DELAY = "5000";
/** Name of the workspace specific security configuration element */
private static final String WSP_SECURITY_ELEMENT = "WorkspaceSecurity";
/**
* Name of the optional AccessControlProvider element defining which
* implementation of AccessControlProvider should be used.
*/
private static final String AC_PROVIDER_ELEMENT = "AccessControlProvider";
/**
* Creates a new configuration parser with the given parser variables.
*
* @param variables parser variables
*/
public RepositoryConfigurationParser(Properties variables) {
super(variables);
}
/**
* Parses repository configuration. Repository configuration uses the
* following format:
* <pre>
* <Repository>
* <FileSystem ...>
* <Security appName="...">
* <SecurityManager ...>
* <AccessManager ...>
* <LoginModule ... (optional)>
* </Security>
* <Workspaces rootPath="..." defaultWorkspace="..."/>
* <Workspace ...>
* <Versioning ...>
* </Repository>
* </pre>
* <p>
* The <code>FileSystem</code> element is a
* {@link #parseBeanConfig(Element,String) bean configuration} element,
* that specifies the file system implementation for storing global
* repository information. The <code>Security</code> element contains
* an <code>AccessManager</code> bean configuration element and the
* JAAS name of the repository application. The <code>Workspaces</code>
* element contains general workspace parameters, and the
* <code>Workspace</code> element is a template for the individual
* workspace configuration files. The <code>Versioning</code> element
* contains
* {@link #parseVersioningConfig(Element) versioning configuration} for
* the repository.
* <p>
* In addition to the configured information, the returned repository
* configuration object also contains the repository home directory path
* that is given as the ${rep.home} parser variable. Note that the
* variable <em>must</em> be available for the configuration document to
* be correctly parsed.
* <p>
* {@link #replaceVariables(String) Variable replacement} is performed
* on the security application name attribute, the general workspace
* configuration attributes, and on the file system, access manager,
* and versioning configuration information.
* <p>
* Note that the returned repository configuration object has not been
* initialized.
*
* @param xml repository configuration document
* @return repository configuration
* @throws ConfigurationException if the configuration is broken
* @see #parseBeanConfig(Element, String)
* @see #parseVersioningConfig(Element)
*/
public RepositoryConfig parseRepositoryConfig(InputSource xml)
throws ConfigurationException {
Element root = parseXML(xml, true);
// Repository home directory
String home = getVariables().getProperty(REPOSITORY_HOME_VARIABLE);
// File system implementation
FileSystemFactory fsf = getFileSystemFactory(root, FILE_SYSTEM_ELEMENT);
// Security configuration and access manager implementation
Element security = getElement(root, SECURITY_ELEMENT);
SecurityConfig securityConfig = parseSecurityConfig(security);
// General workspace configuration
Element workspaces = getElement(root, WORKSPACES_ELEMENT);
String workspaceDirectory = replaceVariables(
getAttribute(workspaces, ROOT_PATH_ATTRIBUTE));
String workspaceConfigDirectory =
getAttribute(workspaces, CONFIG_ROOT_PATH_ATTRIBUTE, null);
String defaultWorkspace = replaceVariables(
getAttribute(workspaces, DEFAULT_WORKSPACE_ATTRIBUTE));
int maxIdleTime = Integer.parseInt(
getAttribute(workspaces, MAX_IDLE_TIME_ATTRIBUTE, "0"));
// Workspace configuration template
Element template = getElement(root, WORKSPACE_ELEMENT);
// Versioning configuration
VersioningConfig vc = parseVersioningConfig(root);
// Optional search configuration
SearchConfig sc = parseSearchConfig(root);
// Optional journal configuration
ClusterConfig cc = parseClusterConfig(root);
// Optional data store factory
DataStoreFactory dsf = getDataStoreFactory(root, home);
RepositoryLockMechanismFactory rlf = getRepositoryLockMechanismFactory(root);
return new RepositoryConfig(home, securityConfig, fsf,
workspaceDirectory, workspaceConfigDirectory, defaultWorkspace,
maxIdleTime, template, vc, sc, cc, dsf, rlf, this);
}
/**
* Parses security configuration. Security configuration
* uses the following format:
* <pre>
* <Security appName="...">
* <SecurityManager ...>
* <AccessManager ...>
* <LoginModule ... (optional)>
* </Security>
* </pre>
* <p/>
* The <code>SecurityManager</code>, the <code>AccessManager</code>
* and <code>LoginModule</code> are all
* {@link #parseBeanConfig(Element,String) bean configuration}
* elements.
* <p/>
* The login module is an optional feature of repository configuration.
*
* @param security the <security> element.
* @return the security configuration.
* @throws ConfigurationException if the configuration is broken
*/
public SecurityConfig parseSecurityConfig(Element security)
throws ConfigurationException {
String appName = getAttribute(security, APP_NAME_ATTRIBUTE);
SecurityManagerConfig smc = parseSecurityManagerConfig(security);
AccessManagerConfig amc = parseAccessManagerConfig(security);
LoginModuleConfig lmc = parseLoginModuleConfig(security);
return new SecurityConfig(appName, smc, amc, lmc);
}
/**
* Parses the security manager configuration.
*
* @param security the <security> element.
* @return the security manager configuration or <code>null</code>.
* @throws ConfigurationException if the configuration is broken
*/
public SecurityManagerConfig parseSecurityManagerConfig(Element security)
throws ConfigurationException {
// Optional security manager config entry
Element smElement = getElement(security, SECURITY_MANAGER_ELEMENT, false);
if (smElement != null) {
BeanConfig bc = parseBeanConfig(smElement);
String wspAttr = getAttribute(smElement, WSP_NAME_ATTRIBUTE, null);
BeanConfig wac = null;
Element element = getElement(smElement, WORKSPACE_ACCESS_ELEMENT, false);
if (element != null) {
wac = parseBeanConfig(smElement, WORKSPACE_ACCESS_ELEMENT);
}
return new SecurityManagerConfig(bc, wspAttr, wac);
} else {
return null;
}
}
/**
* Parses the access manager configuration.
*
* @param security the <security> element.
* @return the access manager configuration or <code>null</code>.
* @throws ConfigurationException if the configuration is broken
*/
public AccessManagerConfig parseAccessManagerConfig(Element security)
throws ConfigurationException {
// Optional access manager config entry
Element accessMgr = getElement(security, ACCESS_MANAGER_ELEMENT, false);
if (accessMgr != null) {
return new AccessManagerConfig(parseBeanConfig(accessMgr));
} else {
return null;
}
}
/**
* Parses the login module configuration.
*
* @param security the <security> element.
* @return the login module configuration or <code>null</code>.
* @throws ConfigurationException if the configuration is broken
*/
public LoginModuleConfig parseLoginModuleConfig(Element security)
throws ConfigurationException {
// Optional login module
Element loginModule = getElement(security, LOGIN_MODULE_ELEMENT, false);
if (loginModule != null) {
return new LoginModuleConfig(parseBeanConfig(security, LOGIN_MODULE_ELEMENT));
} else {
return null;
}
}
/**
* Parses workspace configuration. Workspace configuration uses the
* following format:
* <pre>
* <Workspace name="...">
* <FileSystem ...>
* <PersistenceManager ...>
* <SearchIndex ...>
* <ISMLocking ...>
* <WorkspaceSecurity ...>
* <ISMLocking ...>
* </Workspace>
* </pre>
* <p>
* All the child elements (<code>FileSystem</code>,
* <code>PersistenceManager</code>, and <code>SearchIndex</code>) are
* {@link #parseBeanConfig(Element,String) bean configuration} elements.
* In addition to bean configuration, the
* {@link #parseSearchConfig(Element) search element} also contains
* configuration for the search file system.
* <p>
* In addition to the configured information, the returned workspace
* configuration object also contains the workspace home directory path
* that is given as the ${wsp.home} parser variable. Note that the
* variable <em>must</em> be available for the configuration document to
* be correctly parsed.
* <p>
* Variable replacement is performed on the optional workspace name
* attribute. If the name is not given, then the name of the workspace
* home directory is used as the workspace name. Once the name has been
* determined, it will be added as the ${wsp.name} variable in a temporary
* configuration parser that is used to parse the contained configuration
* elements.
* <p>
* The search index configuration element is optional. If it is not given,
* then the workspace will not have search capabilities.
* <p>
* The ism locking configuration element is optional. If it is not given,
* then a default implementation is used.
* <p>
* Note that the returned workspace configuration object has not been
* initialized.
*
* @param xml workspace configuration document
* @return workspace configuration
* @throws ConfigurationException if the configuration is broken
* @see #parseBeanConfig(Element, String)
* @see #parseSearchConfig(Element)
* @see #parseWorkspaceSecurityConfig(Element)
*/
public WorkspaceConfig parseWorkspaceConfig(InputSource xml)
throws ConfigurationException {
Element root = parseXML(xml);
// Workspace home directory
String home = getVariables().getProperty(WORKSPACE_HOME_VARIABLE);
// Workspace name
String name =
getAttribute(root, NAME_ATTRIBUTE, new File(home).getName());
// Clustered attribute
boolean clustered = Boolean.valueOf(
getAttribute(root, CLUSTERED_ATTRIBUTE, "true")).booleanValue();
// Create a temporary parser that contains the ${wsp.name} variable
Properties tmpVariables = (Properties) getVariables().clone();
tmpVariables.put(WORKSPACE_NAME_VARIABLE, name);
RepositoryConfigurationParser tmpParser = createSubParser(tmpVariables);
// File system implementation
FileSystemFactory fsf =
tmpParser.getFileSystemFactory(root, FILE_SYSTEM_ELEMENT);
// Persistence manager implementation
PersistenceManagerConfig pmc = tmpParser.parsePersistenceManagerConfig(root);
// Search implementation (optional)
SearchConfig sc = tmpParser.parseSearchConfig(root);
// Item state manager locking configuration (optional)
ISMLockingFactory ismLockingFactory =
tmpParser.getISMLockingFactory(root);
// workspace specific security configuration
WorkspaceSecurityConfig workspaceSecurityConfig = tmpParser.parseWorkspaceSecurityConfig(root);
return new WorkspaceConfig(
home, name, clustered, fsf, pmc, sc,
ismLockingFactory, workspaceSecurityConfig);
}
/**
* Parses search index configuration. Search index configuration
* uses the following format:
* <pre>
* <SearchIndex class="...">
* <param name="..." value="...">
* ...
* <FileSystem ...>
* </Search>
* </pre>
* <p/>
* Both the <code>SearchIndex</code> and <code>FileSystem</code>
* elements are {@link #parseBeanConfig(Element,String) bean configuration}
* elements. If the search implementation class is not given, then
* a default implementation is used.
* <p/>
* The search index is an optional feature of workspace configuration.
* If the search configuration element is not found, then this method
* returns <code>null</code>.
* <p/>
* The FileSystem element in a search index configuration is optional.
* However some implementations may require a FileSystem.
*
* @param parent parent of the <code>SearchIndex</code> element
* @return search configuration, or <code>null</code>
* @throws ConfigurationException if the configuration is broken
*/
protected SearchConfig parseSearchConfig(Element parent)
throws ConfigurationException {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& SEARCH_INDEX_ELEMENT.equals(child.getNodeName())) {
Element element = (Element) child;
// Search implementation class
String className = getAttribute(
element, CLASS_ATTRIBUTE, DEFAULT_QUERY_HANDLER);
// Search parameters
Properties parameters = parseParameters(element);
// Optional file system implementation
FileSystemFactory fsf = null;
if (getElement(element, FILE_SYSTEM_ELEMENT, false) != null) {
fsf = getFileSystemFactory(element, FILE_SYSTEM_ELEMENT);
}
return new SearchConfig(className, parameters, fsf);
}
}
return null;
}
/**
* Read the WorkspaceSecurity Element of Workspace's configuration. It uses
* the following format:
* <pre>
* <WorkspaceSecurity>
* <AccessControlProvider class="..." (optional)>
* </WorkspaceSecurity>
* </pre>
*
* @param parent Workspace-Root-Element
* @return a new <code>WorkspaceSecurityConfig</code>
* @throws ConfigurationException
*/
public WorkspaceSecurityConfig parseWorkspaceSecurityConfig(Element parent)
throws ConfigurationException {
BeanConfig acProviderConfig = null;
Element element = getElement(parent, WSP_SECURITY_ELEMENT, false);
if (element != null) {
Element provFact = getElement(element, AC_PROVIDER_ELEMENT, false);
if (provFact != null) {
acProviderConfig = parseBeanConfig(element, AC_PROVIDER_ELEMENT);
acProviderConfig.setValidate(false); // JCR-1920
}
}
return new WorkspaceSecurityConfig(acProviderConfig);
}
/**
* Returns an ISM locking factory that creates {@link ISMLocking} instances
* based on the given configuration. ISM locking configuration uses the
* following format:
* <pre>
* <ISMLocking class="...">
* <param name="..." value="...">
* ...
* </ISMLocking>
* </pre>
* <p>
* The <code>ISMLocking</code> is a
* {@link #parseBeanConfig(Element,String) bean configuration} element.
* <p>
* ISM locking is an optional part of the workspace configuration. If
* the ISM locking element is not found, then the returned factory will
* create instances of the {@link DefaultISMLocking} class.
*
* @param parent parent of the <code>ISMLocking</code> element
* @return ISM locking factory
*/
protected ISMLockingFactory getISMLockingFactory(final Element parent) {
return new ISMLockingFactory() {
public ISMLocking getISMLocking() throws RepositoryException {
Element element = getElement(parent, ISM_LOCKING_ELEMENT, false);
if (element != null) {
BeanConfig config = parseBeanConfig(element);
try {
return (ISMLocking) config.newInstance();
} catch (ClassCastException e) {
throw new RepositoryException(
"Invalid ISMLocking class: "
+ config.getClassName(), e);
}
} else {
return new DefaultISMLocking();
}
}
};
}
/**
* Parses versioning configuration. Versioning configuration uses the
* following format:
* <pre>
* <Versioning rootPath="...">
* <FileSystem ...>
* <PersistenceManager ...>
* </Versioning>
* </pre>
* <p>
* Both the <code>FileSystem</code> and <code>PersistenceManager</code>
* elements are {@link #parseBeanConfig(Element,String) bean configuration}
* elements. In addition to the bean parameter values,
* {@link #replaceVariables(String) variable replacement} is performed
* also on the versioning root path attribute.
*
* @param parent parent of the <code>Versioning</code> element
* @return versioning configuration
* @throws ConfigurationException if the configuration is broken
*/
protected VersioningConfig parseVersioningConfig(Element parent)
throws ConfigurationException {
Element element = getElement(parent, VERSIONING_ELEMENT);
// Versioning home directory
String home =
replaceVariables(getAttribute(element, ROOT_PATH_ATTRIBUTE));
// File system implementation
FileSystemFactory fsf =
getFileSystemFactory(element, FILE_SYSTEM_ELEMENT);
// Persistence manager implementation
PersistenceManagerConfig pmc = parsePersistenceManagerConfig(element);
// Item state manager locking configuration (optional)
ISMLockingFactory ismLockingFactory =
getISMLockingFactory(element);
return new VersioningConfig(home, fsf, pmc, ismLockingFactory);
}
/**
* Parses cluster configuration. Cluster configuration uses the following format:
* <pre>
* <Cluster>
* <Journal ...>
* </Journal>
* </pre>
* <p/>
* <code>Cluster</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
* element.
* <p/>
* Clustering is an optional feature. If the cluster element is not found, then this
* method returns <code>null</code>.
*
* @param parent parent of the <code>Journal</code> element
* @return journal configuration, or <code>null</code>
* @throws ConfigurationException if the configuration is broken
*/
protected ClusterConfig parseClusterConfig(Element parent)
throws ConfigurationException {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& CLUSTER_ELEMENT.equals(child.getNodeName())) {
Element element = (Element) child;
String id = null;
String value = getAttribute(element, ID_ATTRIBUTE, null);
if (value != null) {
id = replaceVariables(value);
}
value = getAttribute(element, SYNC_DELAY_ATTRIBUTE, DEFAULT_SYNC_DELAY);
long syncDelay = Long.parseLong(replaceVariables(value));
JournalConfig jc = parseJournalConfig(element);
return new ClusterConfig(id, syncDelay, jc);
}
}
return null;
}
/**
* Parses journal configuration. Journal configuration uses the following format:
* <pre>
* <Journal class="...">
* <param name="..." value="...">
* ...
* </Journal>
* </pre>
* <p/>
* <code>Journal</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
* element.
*
* @param cluster parent cluster element
* @return journal configuration, or <code>null</code>
* @throws ConfigurationException if the configuration is broken
*/
protected JournalConfig parseJournalConfig(Element cluster)
throws ConfigurationException {
return new JournalConfig(
parseBeanConfig(cluster, JOURNAL_ELEMENT));
}
/**
* Parses data store configuration. Data store configuration uses the following format:
* <pre>
* <DataStore class="...">
* <param name="..." value="...">
* ...
* </DataStore>
* </pre>
* <p/>
* <code>DataStore</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
* element.
*
* @param parent configuration element
* @param directory the repository directory
* @return data store factory
* @throws ConfigurationException if the configuration is broken
*/
protected DataStoreFactory getDataStoreFactory(
final Element parent, final String directory)
throws ConfigurationException {
return new DataStoreFactory() {
public DataStore getDataStore() throws RepositoryException {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& DATA_STORE_ELEMENT.equals(child.getNodeName())) {
BeanConfig bc =
parseBeanConfig(parent, DATA_STORE_ELEMENT);
DataStore store = (DataStore) bc.newInstance();
store.init(directory);
return store;
}
}
return null;
}
};
}
/**
* Parses repository lock mechanism configuration. Repository lock mechanism
* configuration uses the following format:
* <pre>
* <RepositoryLockMechanism class="..." >
* <param name="..." value="...">
* ...
* </RepositoryLockMechanism>
* </pre>
* <p/>
* <code>RepositoryLockMechanism</code> is a
* {@link #parseBeanConfig(Element,String) bean configuration} element.
*
* @param root the root configuration element
* @return repository lock mechanism factory
* @throws ConfigurationException if the configuration is broken
*/
protected RepositoryLockMechanismFactory getRepositoryLockMechanismFactory(final Element root) {
return new RepositoryLockMechanismFactory() {
public RepositoryLockMechanism getRepositoryLockMechanism() throws RepositoryException {
RepositoryLockMechanism lock = null;
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& REPOSITORY_LOCK_MECHANISM_ELEMENT.equals(child.getNodeName())) {
BeanConfig bc =
parseBeanConfig(root, REPOSITORY_LOCK_MECHANISM_ELEMENT);
lock = (RepositoryLockMechanism) bc.newInstance();
break;
}
}
if (lock == null) {
lock = new RepositoryLock();
}
return lock;
}
};
}
/**
* Parses the PersistenceManager config.
*
* @param parent parent of the <code>PersistenceManager</code> element
* @return persistence manager configuration
* @throws ConfigurationException if the configuration is broken
*/
protected PersistenceManagerConfig parsePersistenceManagerConfig(
Element parent) throws ConfigurationException {
return new PersistenceManagerConfig(
parseBeanConfig(parent, PERSISTENCE_MANAGER_ELEMENT));
}
/**
* Creates a new instance of a configuration parser but with overlayed
* variables.
*
* @param variables the variables overlay
* @return a new configuration parser instance
*/
protected RepositoryConfigurationParser createSubParser(Properties variables) {
// overlay the properties
Properties props = new Properties(getVariables());
props.putAll(variables);
return new RepositoryConfigurationParser(props);
}
/**
* Creates and returns a factory object that creates {@link FileSystem}
* instances based on the bean configuration at the named element.
*
* @param parent parent element
* @param name name of the bean configuration element
* @return file system factory
* @throws ConfigurationException if the bean configuration is invalid
*/
protected FileSystemFactory getFileSystemFactory(Element parent, String name)
throws ConfigurationException {
final BeanConfig config = parseBeanConfig(parent, name);
return new FileSystemFactory() {
public FileSystem getFileSystem() throws RepositoryException {
try {
FileSystem fs = (FileSystem) config.newInstance();
fs.init();
return fs;
} catch (ClassCastException e) {
throw new RepositoryException(
"Invalid file system implementation class: "
+ config.getClassName(), e);
} catch (FileSystemException e) {
throw new RepositoryException(
"File system initialization failure.", e);
}
}
};
}
}
| JCR-2184 - Allow parsing custom elements in workspace config
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@790930 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/config/RepositoryConfigurationParser.java | JCR-2184 - Allow parsing custom elements in workspace config | <ide><path>ackrabbit-core/src/main/java/org/apache/jackrabbit/core/config/RepositoryConfigurationParser.java
<ide> */
<ide> public WorkspaceConfig parseWorkspaceConfig(InputSource xml)
<ide> throws ConfigurationException {
<add>
<ide> Element root = parseXML(xml);
<del>
<add> return parseWorkspaceConfig(root);
<add> }
<add>
<add> /**
<add> * Parse workspace config.
<add> *
<add> * @param root root element of the workspace configuration
<add> *
<add> * @see #parseWorkspaceConfig(InputSource)
<add> */
<add> protected WorkspaceConfig parseWorkspaceConfig(Element root)
<add> throws ConfigurationException {
<add>
<ide> // Workspace home directory
<ide> String home = getVariables().getProperty(WORKSPACE_HOME_VARIABLE);
<ide> |
|
Java | apache-2.0 | 16943314a383cae148f037060246a064711762a8 | 0 | robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.impldeps;
import com.google.common.base.Charsets;
import com.google.common.collect.Iterables;
import org.gradle.api.GradleException;
import org.gradle.internal.ErroringAction;
import org.gradle.internal.IoActions;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.progress.PercentageProgressFormatter;
import org.gradle.logging.ProgressLogger;
import org.gradle.logging.ProgressLoggerFactory;
import org.gradle.util.GFileUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.commons.RemappingClassAdapter;
import java.io.*;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class GradleImplDepsRelocatedJarCreator implements RelocatedJarCreator {
private static final int BUFFER_SIZE = 8192;
private static final GradleImplDepsRelocator REMAPPER = new GradleImplDepsRelocator();
private final ProgressLoggerFactory progressLoggerFactory;
public GradleImplDepsRelocatedJarCreator(ProgressLoggerFactory progressLoggerFactory) {
this.progressLoggerFactory = progressLoggerFactory;
}
public void create(final File outputJar, final Iterable<? extends File> files) {
ProgressLogger progressLogger = progressLoggerFactory.newOperation(GradleImplDepsRelocatedJarCreator.class);
progressLogger.setDescription("Gradle JARs generation");
progressLogger.setLoggingHeader(String.format("Generating JAR file '%s'", outputJar.getName()));
progressLogger.started();
try {
createFatJar(outputJar, files, progressLogger);
} finally {
progressLogger.completed();
}
}
private void createFatJar(final File outputJar, final Iterable<? extends File> files, final ProgressLogger progressLogger) {
final File tmpFile;
try {
tmpFile = File.createTempFile(outputJar.getName(), ".tmp");
tmpFile.deleteOnExit();
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
IoActions.withResource(openJarOutputStream(tmpFile), new ErroringAction<ZipOutputStream>() {
@Override
protected void doExecute(ZipOutputStream jarOutputStream) throws Exception {
processFiles(jarOutputStream, files, new byte[BUFFER_SIZE], new HashSet<String>(), progressLogger);
jarOutputStream.finish();
}
});
GFileUtils.moveFile(tmpFile, outputJar);
}
private ZipOutputStream openJarOutputStream(File outputJar) {
try {
ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputJar), BUFFER_SIZE));
outputStream.setLevel(0);
return outputStream;
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
private void processFiles(ZipOutputStream outputStream, Iterable<? extends File> files, byte[] buffer, HashSet<String> seenPaths, ProgressLogger progressLogger) throws Exception {
PercentageProgressFormatter progressFormatter = new PercentageProgressFormatter("Generating", Iterables.size(files));
for (File file : files) {
progressLogger.progress(progressFormatter.getProgress());
if (file.getName().endsWith(".jar")) {
processJarFile(outputStream, file, buffer, seenPaths);
} else {
throw new RuntimeException("non JAR on classpath: " + file.getAbsolutePath());
}
progressFormatter.incrementAndGetProgress();
}
}
private void processJarFile(final ZipOutputStream outputStream, File file, final byte[] buffer, final HashSet<String> seenPaths) throws IOException {
IoActions.withResource(openJarFile(file), new ErroringAction<ZipInputStream>() {
@Override
protected void doExecute(ZipInputStream inputStream) throws Exception {
ZipEntry zipEntry = inputStream.getNextEntry();
while (zipEntry != null) {
if (seenPaths.add(zipEntry.getName())) {
processEntry(outputStream, inputStream, zipEntry, buffer);
}
zipEntry = inputStream.getNextEntry();
}
}
});
}
private void processEntry(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
if (zipEntry.isDirectory() || zipEntry.getName().equals("META-INF/MANIFEST.MF")) {
return;
}
String name = zipEntry.getName();
if (name.endsWith(".class")) {
processClassFile(outputStream, inputStream, zipEntry, buffer);
} else if (name.startsWith("META-INF/services/")) {
processServiceDescriptor(outputStream, inputStream, zipEntry, buffer);
} else {
copyEntry(outputStream, inputStream, zipEntry, buffer);
}
}
private void processServiceDescriptor(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
String descriptorName = zipEntry.getName().substring("META-INF/services/".length());
String descriptorApiClass = periodsToSlashes(descriptorName);
String relocatedApiClassName = REMAPPER.relocateClass(descriptorApiClass);
if (relocatedApiClassName == null) {
relocatedApiClassName = descriptorApiClass;
}
byte[] bytes = readEntry(inputStream, zipEntry, buffer);
String descriptorImplClass = periodsToSlashes(new String(bytes, Charsets.UTF_8));
String relocatedImplClassName = REMAPPER.relocateClass(descriptorImplClass);
if (relocatedImplClassName == null) {
relocatedImplClassName = descriptorImplClass;
}
writeEntry(outputStream, "META-INF/services/" + slashesToPeriods(relocatedApiClassName), slashesToPeriods(relocatedImplClassName).getBytes(Charsets.UTF_8));
}
private String slashesToPeriods(String slashClassName) {
return slashClassName.replace('/', '.');
}
private String periodsToSlashes(String periodClassName) {
return periodClassName.replace('.', '/');
}
private void copyEntry(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
outputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
pipe(inputStream, outputStream, buffer);
outputStream.closeEntry();
}
private void writeEntry(ZipOutputStream outputStream, String name, byte[] content) throws IOException {
ZipEntry zipEntry = new ZipEntry(name);
outputStream.putNextEntry(zipEntry);
outputStream.write(content);
outputStream.closeEntry();
}
private void processClassFile(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
String className = zipEntry.getName().substring(0, zipEntry.getName().length() - ".class".length());
byte[] bytes = readEntry(inputStream, zipEntry, buffer);
ClassReader classReader = new ClassReader(bytes);
ClassWriter classWriter = new ClassWriter(0);
ClassVisitor remappingVisitor = new RemappingClassAdapter(classWriter, REMAPPER);
try {
classReader.accept(remappingVisitor, ClassReader.EXPAND_FRAMES);
} catch (Exception e) {
throw new GradleException("Error in ASM processing class: " + className, e);
}
byte[] remappedClass = classWriter.toByteArray();
String remappedClassName = REMAPPER.relocateClass(className);
String newFileName = (remappedClassName == null ? className : remappedClassName).concat(".class");
writeEntry(outputStream, newFileName, remappedClass);
}
private byte[] readEntry(InputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
int size = (int) zipEntry.getSize();
if (size == -1) {
ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.length);
int read = inputStream.read(buffer);
while (read != -1) {
out.write(buffer, 0, read);
read = inputStream.read(buffer);
}
return out.toByteArray();
} else {
byte[] bytes = new byte[size];
int read = inputStream.read(bytes);
while (read < size) {
read += inputStream.read(bytes, read, size - read);
}
return bytes;
}
}
private void pipe(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException {
int read = inputStream.read(buffer);
while (read != -1) {
outputStream.write(buffer, 0, read);
read = inputStream.read(buffer);
}
}
private ZipInputStream openJarFile(File file) throws IOException {
return new ZipInputStream(new FileInputStream(file));
}
} | subprojects/dependency-management/src/main/java/org/gradle/api/internal/impldeps/GradleImplDepsRelocatedJarCreator.java | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.impldeps;
import com.google.common.base.Charsets;
import com.google.common.collect.Iterables;
import org.gradle.api.GradleException;
import org.gradle.internal.ErroringAction;
import org.gradle.internal.IoActions;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.progress.PercentageProgressFormatter;
import org.gradle.logging.ProgressLogger;
import org.gradle.logging.ProgressLoggerFactory;
import org.gradle.util.GFileUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.commons.RemappingClassAdapter;
import java.io.*;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class GradleImplDepsRelocatedJarCreator implements RelocatedJarCreator {
private static final int BUFFER_SIZE = 8192;
private static final GradleImplDepsRelocator REMAPPER = new GradleImplDepsRelocator();
private final ProgressLoggerFactory progressLoggerFactory;
public GradleImplDepsRelocatedJarCreator(ProgressLoggerFactory progressLoggerFactory) {
this.progressLoggerFactory = progressLoggerFactory;
}
public void create(final File outputJar, final Iterable<? extends File> files) {
ProgressLogger progressLogger = progressLoggerFactory.newOperation(GradleImplDepsRelocatedJarCreator.class);
progressLogger.setDescription("Gradle JARs generation");
progressLogger.setLoggingHeader(String.format("Generating JAR file '%s'", outputJar.getName()));
progressLogger.started();
try {
createFatJar(outputJar, files, progressLogger);
} finally {
progressLogger.completed();
}
}
private void createFatJar(final File outputJar, final Iterable<? extends File> files, final ProgressLogger progressLogger) {
final File tmpFile;
try {
tmpFile = File.createTempFile(outputJar.getName(), ".tmp");
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
IoActions.withResource(openJarOutputStream(tmpFile), new ErroringAction<ZipOutputStream>() {
@Override
protected void doExecute(ZipOutputStream jarOutputStream) throws Exception {
processFiles(jarOutputStream, files, new byte[BUFFER_SIZE], new HashSet<String>(), progressLogger);
jarOutputStream.finish();
}
});
GFileUtils.moveFile(tmpFile, outputJar);
}
private ZipOutputStream openJarOutputStream(File outputJar) {
try {
ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputJar), BUFFER_SIZE));
outputStream.setLevel(0);
return outputStream;
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
private void processFiles(ZipOutputStream outputStream, Iterable<? extends File> files, byte[] buffer, HashSet<String> seenPaths, ProgressLogger progressLogger) throws Exception {
PercentageProgressFormatter progressFormatter = new PercentageProgressFormatter("Generating", Iterables.size(files));
for (File file : files) {
progressLogger.progress(progressFormatter.getProgress());
if (file.getName().endsWith(".jar")) {
processJarFile(outputStream, file, buffer, seenPaths);
} else {
throw new RuntimeException("non JAR on classpath: " + file.getAbsolutePath());
}
progressFormatter.incrementAndGetProgress();
}
}
private void processJarFile(final ZipOutputStream outputStream, File file, final byte[] buffer, final HashSet<String> seenPaths) throws IOException {
IoActions.withResource(openJarFile(file), new ErroringAction<ZipInputStream>() {
@Override
protected void doExecute(ZipInputStream inputStream) throws Exception {
ZipEntry zipEntry = inputStream.getNextEntry();
while (zipEntry != null) {
if (seenPaths.add(zipEntry.getName())) {
processEntry(outputStream, inputStream, zipEntry, buffer);
}
zipEntry = inputStream.getNextEntry();
}
}
});
}
private void processEntry(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
if (zipEntry.isDirectory() || zipEntry.getName().equals("META-INF/MANIFEST.MF")) {
return;
}
String name = zipEntry.getName();
if (name.endsWith(".class")) {
processClassFile(outputStream, inputStream, zipEntry, buffer);
} else if (name.startsWith("META-INF/services/")) {
processServiceDescriptor(outputStream, inputStream, zipEntry, buffer);
} else {
copyEntry(outputStream, inputStream, zipEntry, buffer);
}
}
private void processServiceDescriptor(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
String descriptorName = zipEntry.getName().substring("META-INF/services/".length());
String descriptorApiClass = periodsToSlashes(descriptorName);
String relocatedApiClassName = REMAPPER.relocateClass(descriptorApiClass);
if (relocatedApiClassName == null) {
relocatedApiClassName = descriptorApiClass;
}
byte[] bytes = readEntry(inputStream, zipEntry, buffer);
String descriptorImplClass = periodsToSlashes(new String(bytes, Charsets.UTF_8));
String relocatedImplClassName = REMAPPER.relocateClass(descriptorImplClass);
if (relocatedImplClassName == null) {
relocatedImplClassName = descriptorImplClass;
}
writeEntry(outputStream, "META-INF/services/" + slashesToPeriods(relocatedApiClassName), slashesToPeriods(relocatedImplClassName).getBytes(Charsets.UTF_8));
}
private String slashesToPeriods(String slashClassName) {
return slashClassName.replace('/', '.');
}
private String periodsToSlashes(String periodClassName) {
return periodClassName.replace('.', '/');
}
private void copyEntry(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
outputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
pipe(inputStream, outputStream, buffer);
outputStream.closeEntry();
}
private void writeEntry(ZipOutputStream outputStream, String name, byte[] content) throws IOException {
ZipEntry zipEntry = new ZipEntry(name);
outputStream.putNextEntry(zipEntry);
outputStream.write(content);
outputStream.closeEntry();
}
private void processClassFile(ZipOutputStream outputStream, ZipInputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
String className = zipEntry.getName().substring(0, zipEntry.getName().length() - ".class".length());
byte[] bytes = readEntry(inputStream, zipEntry, buffer);
ClassReader classReader = new ClassReader(bytes);
ClassWriter classWriter = new ClassWriter(0);
ClassVisitor remappingVisitor = new RemappingClassAdapter(classWriter, REMAPPER);
try {
classReader.accept(remappingVisitor, ClassReader.EXPAND_FRAMES);
} catch (Exception e) {
throw new GradleException("Error in ASM processing class: " + className, e);
}
byte[] remappedClass = classWriter.toByteArray();
String remappedClassName = REMAPPER.relocateClass(className);
String newFileName = (remappedClassName == null ? className : remappedClassName).concat(".class");
writeEntry(outputStream, newFileName, remappedClass);
}
private byte[] readEntry(InputStream inputStream, ZipEntry zipEntry, byte[] buffer) throws IOException {
int size = (int) zipEntry.getSize();
if (size == -1) {
ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.length);
int read = inputStream.read(buffer);
while (read != -1) {
out.write(buffer, 0, read);
read = inputStream.read(buffer);
}
return out.toByteArray();
} else {
byte[] bytes = new byte[size];
int read = inputStream.read(bytes);
while (read < size) {
read += inputStream.read(bytes, read, size - read);
}
return bytes;
}
}
private void pipe(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException {
int read = inputStream.read(buffer);
while (read != -1) {
outputStream.write(buffer, 0, read);
read = inputStream.read(buffer);
}
}
private ZipInputStream openJarFile(File file) throws IOException {
return new ZipInputStream(new FileInputStream(file));
}
} | Delete tmp file when JVM terminates
+review REVIEW-5867
| subprojects/dependency-management/src/main/java/org/gradle/api/internal/impldeps/GradleImplDepsRelocatedJarCreator.java | Delete tmp file when JVM terminates | <ide><path>ubprojects/dependency-management/src/main/java/org/gradle/api/internal/impldeps/GradleImplDepsRelocatedJarCreator.java
<ide>
<ide> try {
<ide> tmpFile = File.createTempFile(outputJar.getName(), ".tmp");
<add> tmpFile.deleteOnExit();
<ide> } catch (IOException e) {
<ide> throw UncheckedException.throwAsUncheckedException(e);
<ide> } |
|
Java | apache-2.0 | 8a5c66f0fc8eceb95df1c550fa5913feb49a7542 | 0 | justinma246/gateway,stanculescu/gateway,Anisotrop/gateway,justinma246/gateway,krismcqueen/gateway,nemigaservices/gateway,michaelcretzman/gateway,cmebarrow/gateway,krismcqueen/gateway,irina-mitrea-luxoft/gateway,stanculescu/gateway,mgherghe/gateway,irina-mitrea-luxoft/gateway,cmebarrow/gateway,sanjay-saxena/gateway,nemigaservices/gateway,vmaraloiu/gateway,jitsni/gateway,stanculescu/gateway,EArdeleanu/gateway,krismcqueen/gateway,chao-sun-kaazing/gateway,danibusu/gateway,adrian-galbenus/gateway,mjolie/gateway,a-zuckut/gateway,adrian-galbenus/gateway,chao-sun-kaazing/gateway,mgherghe/gateway,kaazing-build/gateway,a-zuckut/gateway,a-zuckut/gateway,nemigaservices/gateway,vmaraloiu/gateway,AdrianCozma/gateway,adrian-galbenus/gateway,mgherghe/gateway,irina-mitrea-luxoft/gateway,veschup/gateway,vmaraloiu/gateway,jitsni/gateway,stanculescu/gateway,AdrianCozma/gateway,sanjay-saxena/gateway,sanjay-saxena/gateway,mjolie/gateway,jfallows/gateway,biddyweb/gateway,DoruM/gateway,krismcqueen/gateway,jitsni/gateway,mgherghe/gateway,veschup/gateway,Anisotrop/gateway,kaazing/gateway,kaazing-build/gateway,jfallows/gateway,AdrianCozma/gateway,kaazing-build/gateway,danibusu/gateway,dpwspoon/gateway,irina-mitrea-luxoft/gateway,kaazing/gateway,EArdeleanu/gateway,AdrianCozma/gateway,sanjay-saxena/gateway,biddyweb/gateway,danibusu/gateway,dpwspoon/gateway,adrian-galbenus/gateway,michaelcretzman/gateway,michaelcretzman/gateway,DoruM/gateway,veschup/gateway,jfallows/gateway,mjolie/gateway,justinma246/gateway,kaazing/gateway,mjolie/gateway,cmebarrow/gateway,jitsni/gateway,DoruM/gateway,EArdeleanu/gateway,cmebarrow/gateway,kaazing/gateway,chao-sun-kaazing/gateway,danibusu/gateway,Anisotrop/gateway,biddyweb/gateway,Anisotrop/gateway,dpwspoon/gateway,a-zuckut/gateway,nemigaservices/gateway,dpwspoon/gateway,EArdeleanu/gateway,vmaraloiu/gateway,biddyweb/gateway,kaazing-build/gateway,chao-sun-kaazing/gateway,DoruM/gateway,veschup/gateway,michaelcretzman/gateway,jfallows/gateway,justinma246/gateway | /**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.transport.wsn;
import static java.nio.ByteBuffer.wrap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.kaazing.gateway.util.Utils.asByteBuffer;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.resource.address.ResourceAddressFactory;
import org.kaazing.gateway.transport.BridgeServiceFactory;
import org.kaazing.gateway.transport.BridgeSession;
import org.kaazing.gateway.transport.IoHandlerAdapter;
import org.kaazing.gateway.transport.TransportFactory;
import org.kaazing.gateway.transport.http.HttpAcceptor;
import org.kaazing.gateway.transport.http.HttpConnector;
import org.kaazing.gateway.transport.nio.NioSocketAcceptor;
import org.kaazing.gateway.transport.nio.NioSocketConnector;
import org.kaazing.gateway.transport.ws.bridge.filter.WsBuffer;
import org.kaazing.gateway.transport.ws.bridge.filter.WsBufferAllocator;
import org.kaazing.gateway.util.Utils;
import org.kaazing.gateway.util.scheduler.SchedulerProvider;
import org.kaazing.mina.core.buffer.IoBufferAllocatorEx;
import org.kaazing.mina.core.buffer.IoBufferEx;
import org.kaazing.mina.core.buffer.SimpleBufferAllocator;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.test.util.MethodExecutionTrace;
public class WsnConnectorTest {
@Rule
public MethodRule testExecutionTrace = new MethodExecutionTrace("src/test/resources/log4j-trace.properties");
private SchedulerProvider schedulerProvider;
private static int NETWORK_OPERATION_WAIT_SECS = 10; // was 3, increasing for loaded environments
private ResourceAddressFactory addressFactory;
private BridgeServiceFactory serviceFactory;
private NioSocketConnector tcpConnector;
private HttpConnector httpConnector;
private WsnConnector wsnConnector;
private NioSocketAcceptor tcpAcceptor;
private HttpAcceptor httpAcceptor;
private WsnAcceptor wsnAcceptor;
private static final boolean DEBUG = false;
@BeforeClass
public static void initLogging()
throws Exception {
if (DEBUG) {
PropertyConfigurator.configure("src/test/resources/log4j-trace.properties");
}
}
@Before
public void init() {
schedulerProvider = new SchedulerProvider();
addressFactory = ResourceAddressFactory.newResourceAddressFactory();
TransportFactory transportFactory = TransportFactory.newTransportFactory(Collections.EMPTY_MAP);
serviceFactory = new BridgeServiceFactory(transportFactory);
tcpAcceptor = (NioSocketAcceptor)transportFactory.getTransport("tcp").getAcceptor();
tcpAcceptor.setResourceAddressFactory(addressFactory);
tcpAcceptor.setBridgeServiceFactory(serviceFactory);
tcpAcceptor.setSchedulerProvider(schedulerProvider);
tcpConnector = (NioSocketConnector)transportFactory.getTransport("tcp").getConnector();
tcpConnector.setResourceAddressFactory(addressFactory);
tcpConnector.setBridgeServiceFactory(serviceFactory);
tcpConnector.setTcpAcceptor(tcpAcceptor);
httpAcceptor = (HttpAcceptor)transportFactory.getTransport("http").getAcceptor();
httpAcceptor.setBridgeServiceFactory(serviceFactory);
httpAcceptor.setResourceAddressFactory(addressFactory);
httpAcceptor.setSchedulerProvider(schedulerProvider);
httpConnector = (HttpConnector)transportFactory.getTransport("http").getConnector();
httpConnector.setBridgeServiceFactory(serviceFactory);
httpConnector.setResourceAddressFactory(addressFactory);
wsnAcceptor = (WsnAcceptor)transportFactory.getTransport("wsn").getAcceptor();
wsnAcceptor.setConfiguration(new Properties());
wsnAcceptor.setBridgeServiceFactory(serviceFactory);
wsnAcceptor.setResourceAddressFactory(addressFactory);
wsnAcceptor.setSchedulerProvider(schedulerProvider);
wsnConnector = (WsnConnector)transportFactory.getTransport("wsn").getConnector();
wsnConnector.setConfiguration(new Properties());
wsnConnector.setBridgeServiceFactory(serviceFactory);
wsnConnector.setSchedulerProvider(schedulerProvider);
wsnConnector.setResourceAddressFactory(addressFactory);
}
@After
public void disposeConnector() {
if (tcpAcceptor != null) {
tcpAcceptor.dispose();
}
if (httpAcceptor != null) {
httpAcceptor.dispose();
}
if (wsnAcceptor != null) {
wsnAcceptor.dispose();
}
if (tcpConnector != null) {
tcpConnector.dispose();
}
if (httpConnector != null) {
httpConnector.dispose();
}
if (wsnConnector != null) {
wsnConnector.dispose();
}
}
@Test (timeout = 10000)
public void shouldCloseWsnSessionWhenTransportClosesCleanlyButUnexpectedly() throws Exception {
URI location = URI.create("wsn://localhost:8000/echo");
Map<String, Object> addressOptions = Collections.<String, Object>emptyMap(); //Collections.<String, Object>singletonMap("http.transport", URI.create("pipe://internal"));
ResourceAddress address = addressFactory.newResourceAddress(location, addressOptions);
final CountDownLatch waitForClientParentSessionCloseListenerEstabished = new CountDownLatch(1);
IoHandler acceptHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
protected void doMessageReceived(IoSessionEx session, Object message)
throws Exception {
// echo message
IoBuffer buf = (IoBuffer)message;
WriteFuture future = session.write(buf.duplicate());
// close session abruptly, without triggering WebSocket close handshake
future.addListener(new IoFutureListener<WriteFuture>() {
@Override
public void operationComplete(WriteFuture future) {
IoSession session = future.getSession();
WsnSession wsnSession = (WsnSession)session;
IoSession parentSession = wsnSession.getParent();
IoFilterChain parentFilterChain = parentSession.getFilterChain();
// remove WebSocket close filter to avoid intercepting filterClose
wsnConnector.removeBridgeFilters(parentFilterChain);
try {
boolean ok = waitForClientParentSessionCloseListenerEstabished.await(2, TimeUnit.SECONDS);
if ( !ok ) {
throw new RuntimeException("Failed to establish close listener on client-side parent session in time");
}
} catch (InterruptedException e) {
throw new RuntimeException("Failed to establish close listener on client-side parent session in time", e);
}
parentSession.close(true);
}
});
}
};
wsnAcceptor.bind(address, acceptHandler, null);
IoHandler connectHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
protected void doSessionOpened(IoSessionEx session) throws Exception {
IoBufferAllocatorEx<?> allocator = session.getBufferAllocator();
session.write(allocator.wrap(wrap("Hello, world".getBytes())));
}
};
ConnectFuture connectFuture = wsnConnector.connect(address, connectHandler, null);
final WsnSession wsnSession = (WsnSession)connectFuture.await().getSession();
IoSession parentSession = wsnSession.getParent();
CloseFuture parentCloseFuture = parentSession.getCloseFuture();
parentCloseFuture.addListener(new IoFutureListener<CloseFuture>() {
@Override
public void operationComplete(CloseFuture future) {
// the parent session close future listener fires before
// delivering close event to parent session filter chain,
// so we can use this opportunity to force a pending write
// when reacting to the parent session closing
assert !wsnSession.isClosing();
IoBufferAllocatorEx<? extends WsBuffer> wsnAllocator = wsnSession.getBufferAllocator();
wsnSession.write(wsnAllocator.wrap(wrap("Goodbye, world".getBytes())));
}
});
waitForClientParentSessionCloseListenerEstabished.countDown();
CloseFuture closeFuture = wsnSession.getCloseFuture();
assertTrue("WsnSession closed", closeFuture.await().isClosed());
}
@Test
public void shouldCorrectlyConstructLocalAndRemoteAddressesForConnectedWsnSessions() throws Exception {
final URI location = URI.create("ws://localhost:8000/echo");
Map<String, Object> addressOptions = Collections.<String, Object>emptyMap();
ResourceAddress address = addressFactory.newResourceAddress(location, addressOptions);
TransportTestIoHandlerAdapter acceptHandler = new TransportTestIoHandlerAdapter(1) {
@Override
public String getCheckpointFailureMessage() {
return "Failed to construct accept session local/remote addresses correctly.";
}
@Override
public void doMessageReceived(final IoSessionEx session, Object message)
throws Exception {
// echo message
IoBufferEx buf = (IoBufferEx)message;
WriteFuture future = session.write(buf.duplicate());
// close session abruptly, without triggering WebSocket close handshake
future.addListener(new IoFutureListener<WriteFuture>() {
@Override
public void operationComplete(WriteFuture future) {
BridgeSession bridgeSession = (BridgeSession) session;
assertEquals("remote address of accept session was not "+location, location, BridgeSession.REMOTE_ADDRESS.get(bridgeSession).getResource());
assertEquals("local address of accept session was not "+location, location, BridgeSession.LOCAL_ADDRESS.get(bridgeSession).getResource());
checkpoint();
}
});
}
};
wsnAcceptor.bind(address, acceptHandler, null);
TransportTestIoHandlerAdapter connectHandler = new TransportTestIoHandlerAdapter(1) {
@Override
public String getCheckpointFailureMessage() {
return "Failed to construct connect session local/remote addresses correctly.";
}
@Override
public void doSessionCreated(final IoSessionEx session) throws Exception {
final IoBufferAllocatorEx<?> allocator = session.getBufferAllocator();
session.write(allocator.wrap(ByteBuffer.wrap("Hello, world".getBytes()))).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
BridgeSession bridgeSession = (BridgeSession) session;
assertEquals("remote address of connect session was not " + location, location, BridgeSession.REMOTE_ADDRESS.get(bridgeSession).getResource());
assertEquals("local address of connect session was not " + location, location, BridgeSession.LOCAL_ADDRESS.get(bridgeSession).getResource());
checkpoint();
}
});
}
};
ConnectFuture connectFuture = wsnConnector.connect(address, connectHandler, null);
connectFuture.await(3000, TimeUnit.MILLISECONDS);
assert connectFuture.isConnected();
acceptHandler.await(3000, TimeUnit.MILLISECONDS);
connectHandler.await(3000, TimeUnit.MILLISECONDS);
}
@Test (timeout = 30000)
public void shouldNotHangOnToHttpConnectSessionsWhenEstablishingAndTearingDownWsnConnectorSessions() throws Exception {
long iterations = 100;
final URI location = URI.create("wsn://localhost:8000/echo");
Map<String, Object> addressOptions = Collections.<String, Object>emptyMap(); //Collections.<String, Object>singletonMap("http.transport", URI.create("pipe://internal"));
ResourceAddress address = addressFactory.newResourceAddress(location, addressOptions);
//
// Accept stuff, do once
//
final CountDownLatch acceptSessionClosed = new CountDownLatch(1);
IoHandler acceptHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
public void doMessageReceived(final IoSessionEx session, Object message)
throws Exception {
// echo message
IoBufferEx buf = (IoBufferEx) message;
IoSessionEx sessionEx = session;
System.out.println("Acceptor: received message: " + Utils.asString(buf.buf()));
IoBufferAllocatorEx<?> allocator = sessionEx.getBufferAllocator();
session.write(allocator.wrap(asByteBuffer("Reply from acceptor"))).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
session.close(true);
}
});
}
@Override
public void doSessionClosed(IoSessionEx session) throws Exception {
acceptSessionClosed.countDown();
}
};
wsnAcceptor.bind(address, acceptHandler, null);
do {
System.out.println("Managed http sessions: "+httpConnector.getManagedSessionCount());
System.out.println("Managed wsn sessions: "+wsnConnector.getManagedSessionCount());
final CountDownLatch echoReceived = new CountDownLatch(1);
IoHandler connectHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
public void doSessionOpened(IoSessionEx session) throws Exception {
//session.write(wrap("Hello, world".getBytes()));
}
@Override
public void doMessageReceived(IoSessionEx session, Object message) throws Exception {
}
@Override
protected void doSessionClosed(IoSessionEx session) throws Exception {
echoReceived.countDown();
}
};
ConnectFuture connectFuture = wsnConnector.connect(address, connectHandler, null);
final WsnSession session = (WsnSession)connectFuture.await().getSession();
session.write(new WsBufferAllocator(SimpleBufferAllocator.BUFFER_ALLOCATOR).wrap(Utils.asByteBuffer("Message from connector")));
waitForLatch(echoReceived, NETWORK_OPERATION_WAIT_SECS, TimeUnit.SECONDS, "echo not received");
} while (--iterations > 0);
System.out.println("Managed http sessions: "+httpConnector.getManagedSessionCount());
System.out.println("Managed wsn sessions: "+wsnConnector.getManagedSessionCount());
Assert.assertEquals(0, wsnConnector.getManagedSessionCount());
Assert.assertEquals(0, httpConnector.getManagedSessionCount());
}
private static void waitForLatch(CountDownLatch l,
final int delay,
final TimeUnit unit,
final String failureMessage)
throws InterruptedException {
l.await(delay, unit);
if ( l.getCount() != 0 ) {
fail(failureMessage);
}
}
}
| transport/wsn/src/test/java/org/kaazing/gateway/transport/wsn/WsnConnectorTest.java | /**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.transport.wsn;
import static java.nio.ByteBuffer.wrap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.kaazing.gateway.util.Utils.asByteBuffer;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.resource.address.ResourceAddressFactory;
import org.kaazing.gateway.transport.BridgeServiceFactory;
import org.kaazing.gateway.transport.BridgeSession;
import org.kaazing.gateway.transport.IoHandlerAdapter;
import org.kaazing.gateway.transport.TransportFactory;
import org.kaazing.gateway.transport.http.HttpAcceptor;
import org.kaazing.gateway.transport.http.HttpConnector;
import org.kaazing.gateway.transport.nio.NioSocketAcceptor;
import org.kaazing.gateway.transport.nio.NioSocketConnector;
import org.kaazing.gateway.transport.ws.bridge.filter.WsBuffer;
import org.kaazing.gateway.transport.ws.bridge.filter.WsBufferAllocator;
import org.kaazing.gateway.util.Utils;
import org.kaazing.gateway.util.scheduler.SchedulerProvider;
import org.kaazing.mina.core.buffer.IoBufferAllocatorEx;
import org.kaazing.mina.core.buffer.IoBufferEx;
import org.kaazing.mina.core.buffer.SimpleBufferAllocator;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.test.util.MethodExecutionTrace;
public class WsnConnectorTest {
@Rule
public MethodRule testExecutionTrace = new MethodExecutionTrace("src/test/resources/log4j-trace.properties");
private SchedulerProvider schedulerProvider;
private static int NETWORK_OPERATION_WAIT_SECS = 10; // was 3, increasing for loaded environments
private ResourceAddressFactory addressFactory;
private BridgeServiceFactory serviceFactory;
private NioSocketConnector tcpConnector;
private HttpConnector httpConnector;
private WsnConnector wsnConnector;
private NioSocketAcceptor tcpAcceptor;
private HttpAcceptor httpAcceptor;
private WsnAcceptor wsnAcceptor;
private static final boolean DEBUG = false;
@BeforeClass
public static void initLogging()
throws Exception {
if (DEBUG) {
PropertyConfigurator.configure("src/test/resources/log4j-trace.properties");
}
}
@Before
public void init() {
schedulerProvider = new SchedulerProvider();
addressFactory = ResourceAddressFactory.newResourceAddressFactory();
TransportFactory transportFactory = TransportFactory.newTransportFactory(Collections.EMPTY_MAP);
serviceFactory = new BridgeServiceFactory(transportFactory);
tcpAcceptor = (NioSocketAcceptor)transportFactory.getTransport("tcp").getAcceptor();
tcpAcceptor.setResourceAddressFactory(addressFactory);
tcpAcceptor.setBridgeServiceFactory(serviceFactory);
tcpAcceptor.setSchedulerProvider(schedulerProvider);
tcpConnector = (NioSocketConnector)transportFactory.getTransport("tcp").getConnector();
tcpConnector.setResourceAddressFactory(addressFactory);
tcpConnector.setBridgeServiceFactory(serviceFactory);
tcpConnector.setTcpAcceptor(tcpAcceptor);
httpAcceptor = (HttpAcceptor)transportFactory.getTransport("http").getAcceptor();
httpAcceptor.setBridgeServiceFactory(serviceFactory);
httpAcceptor.setResourceAddressFactory(addressFactory);
httpAcceptor.setSchedulerProvider(schedulerProvider);
httpConnector = (HttpConnector)transportFactory.getTransport("http").getConnector();
httpConnector.setBridgeServiceFactory(serviceFactory);
httpConnector.setResourceAddressFactory(addressFactory);
wsnAcceptor = (WsnAcceptor)transportFactory.getTransport("wsn").getAcceptor();
wsnAcceptor.setConfiguration(new Properties());
wsnAcceptor.setBridgeServiceFactory(serviceFactory);
wsnAcceptor.setResourceAddressFactory(addressFactory);
wsnAcceptor.setSchedulerProvider(schedulerProvider);
wsnConnector = (WsnConnector)transportFactory.getTransport("wsn").getConnector();
wsnConnector.setConfiguration(new Properties());
wsnConnector.setBridgeServiceFactory(serviceFactory);
wsnConnector.setSchedulerProvider(schedulerProvider);
wsnConnector.setResourceAddressFactory(addressFactory);
}
@After
public void disposeConnector() {
if (tcpAcceptor != null) {
tcpAcceptor.dispose();
}
if (httpAcceptor != null) {
httpAcceptor.dispose();
}
if (wsnAcceptor != null) {
wsnAcceptor.dispose();
}
if (tcpConnector != null) {
tcpConnector.dispose();
}
if (httpConnector != null) {
httpConnector.dispose();
}
if (wsnConnector != null) {
wsnConnector.dispose();
}
}
@Test (timeout = 10000)
public void shouldCloseWsnSessionWhenTransportClosesCleanlyButUnexpectedly() throws Exception {
URI location = URI.create("wsn://localhost:8000/echo");
Map<String, Object> addressOptions = Collections.<String, Object>emptyMap(); //Collections.<String, Object>singletonMap("http.transport", URI.create("pipe://internal"));
ResourceAddress address = addressFactory.newResourceAddress(location, addressOptions);
final CountDownLatch waitForClientParentSessionCloseListenerEstabished = new CountDownLatch(1);
IoHandler acceptHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
protected void doMessageReceived(IoSessionEx session, Object message)
throws Exception {
// echo message
IoBuffer buf = (IoBuffer)message;
WriteFuture future = session.write(buf.duplicate());
// close session abruptly, without triggering WebSocket close handshake
future.addListener(new IoFutureListener<WriteFuture>() {
@Override
public void operationComplete(WriteFuture future) {
IoSession session = future.getSession();
WsnSession wsnSession = (WsnSession)session;
IoSession parentSession = wsnSession.getParent();
IoFilterChain parentFilterChain = parentSession.getFilterChain();
// remove WebSocket close filter to avoid intercepting filterClose
wsnConnector.removeBridgeFilters(parentFilterChain);
try {
boolean ok = waitForClientParentSessionCloseListenerEstabished.await(2, TimeUnit.SECONDS);
if ( !ok ) {
throw new RuntimeException("Failed to establish close listener on client-side parent session in time");
}
} catch (InterruptedException e) {
throw new RuntimeException("Failed to establish close listener on client-side parent session in time", e);
}
parentSession.close(true);
}
});
}
};
wsnAcceptor.bind(address, acceptHandler, null);
IoHandler connectHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
protected void doSessionOpened(IoSessionEx session) throws Exception {
IoBufferAllocatorEx<?> allocator = session.getBufferAllocator();
session.write(allocator.wrap(wrap("Hello, world".getBytes())));
}
};
ConnectFuture connectFuture = wsnConnector.connect(address, connectHandler, null);
final WsnSession wsnSession = (WsnSession)connectFuture.await().getSession();
IoSession parentSession = wsnSession.getParent();
CloseFuture parentCloseFuture = parentSession.getCloseFuture();
parentCloseFuture.addListener(new IoFutureListener<CloseFuture>() {
@Override
public void operationComplete(CloseFuture future) {
// the parent session close future listener fires before
// delivering close event to parent session filter chain,
// so we can use this opportunity to force a pending write
// when reacting to the parent session closing
assert !wsnSession.isClosing();
IoBufferAllocatorEx<? extends WsBuffer> wsnAllocator = wsnSession.getBufferAllocator();
wsnSession.write(wsnAllocator.wrap(wrap("Goodbye, world".getBytes())));
}
});
waitForClientParentSessionCloseListenerEstabished.countDown();
CloseFuture closeFuture = wsnSession.getCloseFuture();
assertTrue("WsnSession closed", closeFuture.await().isClosed());
}
@Test
public void shouldCorrectlyConstructLocalAndRemoteAddressesForConnectedWsnSessions() throws Exception {
final URI location = URI.create("ws://localhost:8000/echo");
Map<String, Object> addressOptions = Collections.<String, Object>emptyMap();
ResourceAddress address = addressFactory.newResourceAddress(location, addressOptions);
TransportTestIoHandlerAdapter acceptHandler = new TransportTestIoHandlerAdapter(1) {
@Override
public String getCheckpointFailureMessage() {
return "Failed to construct accept session local/remote addresses correctly.";
}
@Override
public void doMessageReceived(final IoSessionEx session, Object message)
throws Exception {
// echo message
IoBufferEx buf = (IoBufferEx)message;
WriteFuture future = session.write(buf.duplicate());
// close session abruptly, without triggering WebSocket close handshake
future.addListener(new IoFutureListener<WriteFuture>() {
@Override
public void operationComplete(WriteFuture future) {
BridgeSession bridgeSession = (BridgeSession) session;
assertEquals("remote address of accept session was not "+location, location, BridgeSession.REMOTE_ADDRESS.get(bridgeSession).getResource());
assertEquals("local address of accept session was not "+location, location, BridgeSession.LOCAL_ADDRESS.get(bridgeSession).getResource());
checkpoint();
}
});
}
};
wsnAcceptor.bind(address, acceptHandler, null);
TransportTestIoHandlerAdapter connectHandler = new TransportTestIoHandlerAdapter(1) {
@Override
public String getCheckpointFailureMessage() {
return "Failed to construct connect session local/remote addresses correctly.";
}
@Override
public void doSessionCreated(final IoSessionEx session) throws Exception {
final IoBufferAllocatorEx<?> allocator = session.getBufferAllocator();
session.write(allocator.wrap(ByteBuffer.wrap("Hello, world".getBytes()))).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
BridgeSession bridgeSession = (BridgeSession) session;
assertEquals("remote address of connect session was not " + location, location, BridgeSession.REMOTE_ADDRESS.get(bridgeSession).getResource());
assertEquals("local address of connect session was not " + location, location, BridgeSession.LOCAL_ADDRESS.get(bridgeSession).getResource());
checkpoint();
}
});
}
};
ConnectFuture connectFuture = wsnConnector.connect(address, connectHandler, null);
connectFuture.await(3000, TimeUnit.MILLISECONDS);
assert connectFuture.isConnected();
acceptHandler.await(3000, TimeUnit.MILLISECONDS);
connectHandler.await(3000, TimeUnit.MILLISECONDS);
}
@Test // (timeout = 30000)
public void shouldNotHangOnToHttpConnectSessionsWhenEstablishingAndTearingDownWsnConnectorSessions() throws Exception {
long iterations = 100;
final URI location = URI.create("wsn://localhost:8000/echo");
Map<String, Object> addressOptions = Collections.<String, Object>emptyMap(); //Collections.<String, Object>singletonMap("http.transport", URI.create("pipe://internal"));
ResourceAddress address = addressFactory.newResourceAddress(location, addressOptions);
//
// Accept stuff, do once
//
final CountDownLatch acceptSessionClosed = new CountDownLatch(1);
IoHandler acceptHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
public void doMessageReceived(final IoSessionEx session, Object message)
throws Exception {
// echo message
IoBufferEx buf = (IoBufferEx) message;
IoSessionEx sessionEx = session;
System.out.println("Acceptor: received message: " + Utils.asString(buf.buf()));
IoBufferAllocatorEx<?> allocator = sessionEx.getBufferAllocator();
session.write(allocator.wrap(asByteBuffer("Reply from acceptor"))).addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
session.close(true);
}
});
}
@Override
public void doSessionClosed(IoSessionEx session) throws Exception {
acceptSessionClosed.countDown();
}
};
wsnAcceptor.bind(address, acceptHandler, null);
do {
System.out.println("Managed http sessions: "+httpConnector.getManagedSessionCount());
System.out.println("Managed wsn sessions: "+wsnConnector.getManagedSessionCount());
final CountDownLatch echoReceived = new CountDownLatch(1);
IoHandler connectHandler = new IoHandlerAdapter<IoSessionEx>() {
@Override
public void doSessionOpened(IoSessionEx session) throws Exception {
//session.write(wrap("Hello, world".getBytes()));
}
@Override
public void doMessageReceived(IoSessionEx session, Object message) throws Exception {
}
@Override
protected void doSessionClosed(IoSessionEx session) throws Exception {
echoReceived.countDown();
}
};
ConnectFuture connectFuture = wsnConnector.connect(address, connectHandler, null);
final WsnSession session = (WsnSession)connectFuture.await().getSession();
session.write(new WsBufferAllocator(SimpleBufferAllocator.BUFFER_ALLOCATOR).wrap(Utils.asByteBuffer("Message from connector")));
waitForLatch(echoReceived, NETWORK_OPERATION_WAIT_SECS, TimeUnit.SECONDS, "echo not received");
} while (--iterations > 0);
System.out.println("Managed http sessions: "+httpConnector.getManagedSessionCount());
System.out.println("Managed wsn sessions: "+wsnConnector.getManagedSessionCount());
Assert.assertEquals(0, wsnConnector.getManagedSessionCount());
Assert.assertEquals(0, httpConnector.getManagedSessionCount());
}
private static void waitForLatch(CountDownLatch l,
final int delay,
final TimeUnit unit,
final String failureMessage)
throws InterruptedException {
l.await(delay, unit);
if ( l.getCount() != 0 ) {
fail(failureMessage);
}
}
}
| Added timeout back into WsnConnectorTest
| transport/wsn/src/test/java/org/kaazing/gateway/transport/wsn/WsnConnectorTest.java | Added timeout back into WsnConnectorTest | <ide><path>ransport/wsn/src/test/java/org/kaazing/gateway/transport/wsn/WsnConnectorTest.java
<ide>
<ide> }
<ide>
<del> @Test // (timeout = 30000)
<add> @Test (timeout = 30000)
<ide> public void shouldNotHangOnToHttpConnectSessionsWhenEstablishingAndTearingDownWsnConnectorSessions() throws Exception {
<ide>
<ide> long iterations = 100; |
|
Java | agpl-3.0 | error: pathspec 'solrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/BiblicalStudies.java' did not match any file(s) known to git
| cf4e27d9b61336279166b0e833165fea9fba288e | 1 | ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools | package de.unituebingen.ub.ubtools.solrmarcMixin;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import org.marc4j.marc.DataField;
import org.marc4j.marc.Record;
import org.marc4j.marc.VariableField;
import org.marc4j.marc.*;
import org.solrmarc.index.SolrIndexerMixin;
import org.solrmarc.tools.Utils;
public class BiblicalStudies extends IxTheo {
final static String TRUE = "true";
final static String FALSE = "false";
final static String BIBSTUDIES_IXTHEO_PATTERN="^[H][A-Z].*|.*:[H][A-Z].*";
Pattern bibStudiesIxTheoPattern = Pattern.compile(BIBSTUDIES_IXTHEO_PATTERN);
public String getIsBiblicalStudiesIxTheoNotation(final Record record) {
final List<VariableField> _652Fields = record.getVariableFields("652");
for (final VariableField _652Field : _652Fields) {
final DataField dataField = (DataField) _652Field;
for (final Subfield subfieldA : dataField.getSubfields('a')) {
if (subfieldA == null)
continue;
Matcher matcher = bibStudiesIxTheoPattern.matcher(subfieldA.getData());
if (matcher.matches())
return TRUE;
}
}
return FALSE;
}
public String getIsBiblicalStudies(final Record record) {
return getIsBiblicalStudiesIxTheoNotation(record);
}
}
| solrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/BiblicalStudies.java | Boilerplate for biblical studies selection
| solrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/BiblicalStudies.java | Boilerplate for biblical studies selection | <ide><path>olrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/BiblicalStudies.java
<add>package de.unituebingen.ub.ubtools.solrmarcMixin;
<add>
<add>import java.util.regex.Matcher;
<add>import java.util.regex.Pattern;
<add>import java.util.List;
<add>import org.marc4j.marc.DataField;
<add>import org.marc4j.marc.Record;
<add>import org.marc4j.marc.VariableField;
<add>import org.marc4j.marc.*;
<add>import org.solrmarc.index.SolrIndexerMixin;
<add>import org.solrmarc.tools.Utils;
<add>
<add>public class BiblicalStudies extends IxTheo {
<add>
<add> final static String TRUE = "true";
<add> final static String FALSE = "false";
<add>
<add> final static String BIBSTUDIES_IXTHEO_PATTERN="^[H][A-Z].*|.*:[H][A-Z].*";
<add> Pattern bibStudiesIxTheoPattern = Pattern.compile(BIBSTUDIES_IXTHEO_PATTERN);
<add>
<add> public String getIsBiblicalStudiesIxTheoNotation(final Record record) {
<add> final List<VariableField> _652Fields = record.getVariableFields("652");
<add> for (final VariableField _652Field : _652Fields) {
<add> final DataField dataField = (DataField) _652Field;
<add> for (final Subfield subfieldA : dataField.getSubfields('a')) {
<add> if (subfieldA == null)
<add> continue;
<add> Matcher matcher = bibStudiesIxTheoPattern.matcher(subfieldA.getData());
<add> if (matcher.matches())
<add> return TRUE;
<add> }
<add> }
<add> return FALSE;
<add> }
<add>
<add> public String getIsBiblicalStudies(final Record record) {
<add> return getIsBiblicalStudiesIxTheoNotation(record);
<add> }
<add>} |
|
Java | apache-2.0 | a513aac7700bad33367f14088f76fa82c8a337a9 | 0 | dtanzer/babystepstimer,dtanzer/babystepstimer,dtanzer/babystepstimer,dtanzer/babystepstimer,dtanzer/babystepstimer,dtanzer/babystepstimer,dtanzer/babystepstimer,dtanzer/babystepstimer | /* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.davidtanzer.babysteps;
import net.davidtanzer.babysteps.ui.TimerPresentationModel;
import net.davidtanzer.babysteps.ui.TimerView;
public class BabystepsTimer {
private static final long SECONDS_IN_CYCLE = 120;
public static void main(final String[] args) throws InterruptedException {
TimerPresentationModel presentationModel = new TimerPresentationModel();
presentationModel.setRemainingSeconds(SECONDS_IN_CYCLE);
Timer timer = TimerFactory.get().createTimer(SECONDS_IN_CYCLE, presentationModel);
TimerView timerView = new TimerView(presentationModel, SECONDS_IN_CYCLE, timer);
timer.addTimerEventListener(timerView);
}
}
| src/main/java/net/davidtanzer/babysteps/BabystepsTimer.java | /* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.davidtanzer.babysteps;
import net.davidtanzer.babysteps.ui.TimerPresentationModel;
import net.davidtanzer.babysteps.ui.TimerView;
public class BabystepsTimer {
private static final long SECONDS_IN_CYCLE = 12;
public static void main(final String[] args) throws InterruptedException {
TimerPresentationModel presentationModel = new TimerPresentationModel();
presentationModel.setRemainingSeconds(SECONDS_IN_CYCLE);
Timer timer = TimerFactory.get().createTimer(SECONDS_IN_CYCLE, presentationModel);
TimerView timerView = new TimerView(presentationModel, SECONDS_IN_CYCLE, timer);
timer.addTimerEventListener(timerView);
}
}
| The timer now runs for two minutes.
| src/main/java/net/davidtanzer/babysteps/BabystepsTimer.java | The timer now runs for two minutes. | <ide><path>rc/main/java/net/davidtanzer/babysteps/BabystepsTimer.java
<ide>
<ide>
<ide> public class BabystepsTimer {
<del> private static final long SECONDS_IN_CYCLE = 12;
<add> private static final long SECONDS_IN_CYCLE = 120;
<ide>
<ide> public static void main(final String[] args) throws InterruptedException {
<ide> TimerPresentationModel presentationModel = new TimerPresentationModel(); |
|
Java | epl-1.0 | add6e131f434350a4565436b480a735a7201df4b | 0 | forge/core,oscerd/core,oscerd/core,oscerd/core,ivannov/core,forge/core,D9110/core,jerr/jbossforge-core,agoncal/core,ivannov/core,jerr/jbossforge-core,D9110/core,agoncal/core,oscerd/core,ivannov/core,D9110/core,agoncal/core,agoncal/core,oscerd/core,D9110/core,pplatek/core,oscerd/core,agoncal/core,ivannov/core,D9110/core,oscerd/core,agoncal/core,forge/core,ivannov/core,D9110/core,pplatek/core,ivannov/core,D9110/core,jerr/jbossforge-core,agoncal/core,jerr/jbossforge-core,jerr/jbossforge-core,jerr/jbossforge-core,pplatek/core,agoncal/core,oscerd/core,oscerd/core,ivannov/core,D9110/core,pplatek/core,forge/core,ivannov/core,oscerd/core,forge/core,ivannov/core,pplatek/core,agoncal/core,D9110/core,jerr/jbossforge-core,pplatek/core,pplatek/core,forge/core,jerr/jbossforge-core,agoncal/core,pplatek/core,jerr/jbossforge-core,pplatek/core,ivannov/core,D9110/core,forge/core,forge/core,forge/core,jerr/jbossforge-core,pplatek/core,forge/core | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.ui.impl;
import java.util.Arrays;
import java.util.Iterator;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.convert.Converter;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.facets.HintsFacet;
import org.jboss.forge.addon.ui.hints.InputType;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.UICompleter;
import org.jboss.forge.addon.ui.input.UIInput;
import org.jboss.forge.addon.ui.input.UIInputMany;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.forge.furnace.util.Callables;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class UIInputInjectionTest
{
@Deployment
@Dependencies({ @AddonDependency(name = "org.jboss.forge.addon:ui"),
@AddonDependency(name = "org.jboss.forge.furnace.container:cdi") })
public static ForgeArchive getDeployment()
{
ForgeArchive archive = ShrinkWrap
.create(ForgeArchive.class)
.addBeansXML()
.addClasses(Career.class, Gender.class)
.addAsAddonDependencies(
AddonDependencyEntry.create("org.jboss.forge.addon:ui"),
AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi"));
return archive;
}
@Inject
@WithAttributes(defaultValue = "true", label = "")
UIInput<Boolean> enabled;
@Inject
UIInput<Boolean> disabled;
@Inject
UIInput<String> firstName;
@Inject
UISelectOne<Career> careers;
@Inject
UISelectMany<String> partners;
@Inject
UIInputMany<String> unknown;
@Inject
@WithAttributes(label = "Attributed Input", shortName = 'a', enabled = false, required = false, requiredMessage = "REQUIRED_MESSAGE")
UIInputMany<String> attributedInput;
@Inject
UISelectOne<Gender> gender;
@SuppressWarnings("rawtypes")
@Inject
UIInput noParameter;
@Test
public void testNoParameterInput()
{
Assert.assertNotNull(noParameter);
Assert.assertEquals(String.class, noParameter.getValueType());
}
@Test
public void testEnumValuesAvailability() throws Exception
{
Assert.assertNotNull(gender);
Iterable<Gender> valueChoices = gender.getValueChoices();
Iterator<Gender> it = valueChoices.iterator();
Assert.assertNotNull(it);
Assert.assertTrue(it.hasNext());
Assert.assertEquals(Gender.MALE, it.next());
Assert.assertTrue(it.hasNext());
Assert.assertEquals(Gender.FEMALE, it.next());
Assert.assertFalse(it.hasNext());
}
@Test
public void testInjectionNotNull()
{
Assert.assertNotNull(enabled);
Assert.assertNotNull(disabled);
Assert.assertNotNull(firstName);
Assert.assertNotNull(careers);
Assert.assertNotNull(partners);
Assert.assertNotNull(unknown);
Assert.assertNotNull(gender);
}
@Test
public void testInputValues()
{
Assert.assertEquals("enabled", enabled.getName());
Assert.assertEquals(Boolean.class, enabled.getValueType());
Assert.assertEquals(true, enabled.getValue());
Assert.assertEquals("disabled", disabled.getName());
Assert.assertEquals(Boolean.class, disabled.getValueType());
Assert.assertEquals(false, disabled.getValue());
Assert.assertEquals("firstName", firstName.getName());
Assert.assertEquals(String.class, firstName.getValueType());
Assert.assertEquals("careers", careers.getName());
Assert.assertEquals(Career.class, careers.getValueType());
Assert.assertEquals("partners", partners.getName());
Assert.assertEquals(String.class, partners.getValueType());
Assert.assertEquals("unknown", unknown.getName());
Assert.assertEquals(String.class, unknown.getValueType());
}
@Test
public void testValueConverters()
{
Converter<String, String> stringValueConverter = new Converter<String, String>()
{
@Override
public String convert(String source)
{
return "NAME: " + source;
}
};
Converter<String, Career> careersValueConverter = new Converter<String, Career>()
{
@Override
public Career convert(String source)
{
return Career.valueOf(source);
}
};
Assert.assertNull(firstName.getValueConverter());
firstName.setValueConverter(stringValueConverter);
Assert.assertSame(firstName.getValueConverter(), stringValueConverter);
Assert.assertNull(careers.getValueConverter());
careers.setValueConverter(careersValueConverter);
Assert.assertSame(careers.getValueConverter(), careersValueConverter);
Assert.assertNull(partners.getValueConverter());
partners.setValueConverter(stringValueConverter);
Assert.assertSame(partners.getValueConverter(), stringValueConverter);
Assert.assertNull(unknown.getValueConverter());
unknown.setValueConverter(stringValueConverter);
Assert.assertSame(unknown.getValueConverter(), stringValueConverter);
}
@Test
public void testRequired()
{
firstName.setRequired(true);
Assert.assertTrue(firstName.isRequired());
firstName.setRequired(false);
Assert.assertFalse(firstName.isRequired());
}
@Test
public void testDefaultValue()
{
String inputVal = "A String";
firstName.setDefaultValue(inputVal);
Assert.assertEquals(inputVal, firstName.getValue());
final String inputVal2 = "Another String";
firstName.setDefaultValue(Callables.returning(inputVal2));
Assert.assertEquals(inputVal2, firstName.getValue());
}
@Test
public void testCompleter()
{
UICompleter<String> originalCompleter = firstName.getCompleter();
Assert.assertNull(originalCompleter);
Assert.assertEquals(firstName, firstName.setCompleter(new UICompleter<String>()
{
@Override
public Iterable<String> getCompletionProposals(UIContext context, InputComponent<?, String> input, String value)
{
return Arrays.asList("one", "two", "three");
}
}));
Assert.assertNotEquals(originalCompleter, firstName.getCompleter());
Iterator<String> iterator = firstName.getCompleter().getCompletionProposals(null, null, null).iterator();
Assert.assertEquals("one", iterator.next());
Assert.assertEquals("two", iterator.next());
Assert.assertEquals("three", iterator.next());
Assert.assertFalse(iterator.hasNext());
}
@Test
public void testInputType()
{
HintsFacet hints = firstName.getFacet(HintsFacet.class);
String inputType = hints.getInputType();
Assert.assertEquals(InputType.DEFAULT, inputType);
hints.setInputType(InputType.TEXTAREA);
Assert.assertSame(firstName, firstName);
Assert.assertSame(InputType.TEXTAREA, hints.getInputType());
}
@Test
public void testInputWithAttributes()
{
Assert.assertEquals("Attributed Input", attributedInput.getLabel());
Assert.assertFalse(attributedInput.isEnabled());
Assert.assertFalse(attributedInput.isRequired());
Assert.assertEquals("REQUIRED_MESSAGE", attributedInput.getRequiredMessage());
Assert.assertEquals('a', attributedInput.getShortName());
}
}
| ui/tests/src/test/java/org/jboss/forge/addon/ui/impl/UIInputInjectionTest.java | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.ui.impl;
import java.util.Arrays;
import java.util.Iterator;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.convert.Converter;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.facets.HintsFacet;
import org.jboss.forge.addon.ui.hints.InputType;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.UICompleter;
import org.jboss.forge.addon.ui.input.UIInput;
import org.jboss.forge.addon.ui.input.UIInputMany;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.forge.furnace.util.Callables;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class UIInputInjectionTest
{
@Deployment
@Dependencies({ @AddonDependency(name = "org.jboss.forge.addon:ui"),
@AddonDependency(name = "org.jboss.forge.furnace.container:cdi") })
public static ForgeArchive getDeployment()
{
ForgeArchive archive = ShrinkWrap
.create(ForgeArchive.class)
.addBeansXML()
.addClasses(Career.class, Gender.class)
.addAsAddonDependencies(
AddonDependencyEntry.create("org.jboss.forge.addon:ui"),
AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi"));
return archive;
}
@Inject
@WithAttributes(defaultValue="true", label = "")
UIInput<Boolean> enabled;
@Inject
UIInput<Boolean> disabled;
@Inject
UIInput<String> firstName;
@Inject
UISelectOne<Career> careers;
@Inject
UISelectMany<String> partners;
@Inject
UIInputMany<String> unknown;
@Inject
@WithAttributes(label = "Attributed Input", shortName = 'a', enabled = false, required = false, requiredMessage = "REQUIRED_MESSAGE")
UIInputMany<String> attributedInput;
@Inject
UISelectOne<Gender> gender;
@Test
public void testEnumValuesAvailability() throws Exception
{
Assert.assertNotNull(gender);
Iterable<Gender> valueChoices = gender.getValueChoices();
Iterator<Gender> it = valueChoices.iterator();
Assert.assertNotNull(it);
Assert.assertTrue(it.hasNext());
Assert.assertEquals(Gender.MALE, it.next());
Assert.assertTrue(it.hasNext());
Assert.assertEquals(Gender.FEMALE, it.next());
Assert.assertFalse(it.hasNext());
}
@Test
public void testInjectionNotNull()
{
Assert.assertNotNull(enabled);
Assert.assertNotNull(disabled);
Assert.assertNotNull(firstName);
Assert.assertNotNull(careers);
Assert.assertNotNull(partners);
Assert.assertNotNull(unknown);
Assert.assertNotNull(gender);
}
@Test
public void testInputValues()
{
Assert.assertEquals("enabled", enabled.getName());
Assert.assertEquals(Boolean.class, enabled.getValueType());
Assert.assertEquals(true, enabled.getValue());
Assert.assertEquals("disabled", disabled.getName());
Assert.assertEquals(Boolean.class, disabled.getValueType());
Assert.assertEquals(false, disabled.getValue());
Assert.assertEquals("firstName", firstName.getName());
Assert.assertEquals(String.class, firstName.getValueType());
Assert.assertEquals("careers", careers.getName());
Assert.assertEquals(Career.class, careers.getValueType());
Assert.assertEquals("partners", partners.getName());
Assert.assertEquals(String.class, partners.getValueType());
Assert.assertEquals("unknown", unknown.getName());
Assert.assertEquals(String.class, unknown.getValueType());
}
@Test
public void testValueConverters()
{
Converter<String, String> stringValueConverter = new Converter<String, String>()
{
@Override
public String convert(String source)
{
return "NAME: " + source;
}
};
Converter<String, Career> careersValueConverter = new Converter<String, Career>()
{
@Override
public Career convert(String source)
{
return Career.valueOf(source);
}
};
Assert.assertNull(firstName.getValueConverter());
firstName.setValueConverter(stringValueConverter);
Assert.assertSame(firstName.getValueConverter(), stringValueConverter);
Assert.assertNull(careers.getValueConverter());
careers.setValueConverter(careersValueConverter);
Assert.assertSame(careers.getValueConverter(), careersValueConverter);
Assert.assertNull(partners.getValueConverter());
partners.setValueConverter(stringValueConverter);
Assert.assertSame(partners.getValueConverter(), stringValueConverter);
Assert.assertNull(unknown.getValueConverter());
unknown.setValueConverter(stringValueConverter);
Assert.assertSame(unknown.getValueConverter(), stringValueConverter);
}
@Test
public void testRequired()
{
firstName.setRequired(true);
Assert.assertTrue(firstName.isRequired());
firstName.setRequired(false);
Assert.assertFalse(firstName.isRequired());
}
@Test
public void testDefaultValue()
{
String inputVal = "A String";
firstName.setDefaultValue(inputVal);
Assert.assertEquals(inputVal, firstName.getValue());
final String inputVal2 = "Another String";
firstName.setDefaultValue(Callables.returning(inputVal2));
Assert.assertEquals(inputVal2, firstName.getValue());
}
@Test
public void testCompleter()
{
UICompleter<String> originalCompleter = firstName.getCompleter();
Assert.assertNull(originalCompleter);
Assert.assertEquals(firstName, firstName.setCompleter(new UICompleter<String>()
{
@Override
public Iterable<String> getCompletionProposals(UIContext context, InputComponent<?, String> input, String value)
{
return Arrays.asList("one", "two", "three");
}
}));
Assert.assertNotEquals(originalCompleter, firstName.getCompleter());
Iterator<String> iterator = firstName.getCompleter().getCompletionProposals(null, null, null).iterator();
Assert.assertEquals("one", iterator.next());
Assert.assertEquals("two", iterator.next());
Assert.assertEquals("three", iterator.next());
Assert.assertFalse(iterator.hasNext());
}
@Test
public void testInputType()
{
HintsFacet hints = firstName.getFacet(HintsFacet.class);
String inputType = hints.getInputType();
Assert.assertEquals(InputType.DEFAULT, inputType);
hints.setInputType(InputType.TEXTAREA);
Assert.assertSame(firstName, firstName);
Assert.assertSame(InputType.TEXTAREA, hints.getInputType());
}
@Test
public void testInputWithAttributes()
{
Assert.assertEquals("Attributed Input", attributedInput.getLabel());
Assert.assertFalse(attributedInput.isEnabled());
Assert.assertFalse(attributedInput.isRequired());
Assert.assertEquals("REQUIRED_MESSAGE", attributedInput.getRequiredMessage());
Assert.assertEquals('a', attributedInput.getShortName());
}
}
| FORGE-1781: Added test case to reproduce issue
| ui/tests/src/test/java/org/jboss/forge/addon/ui/impl/UIInputInjectionTest.java | FORGE-1781: Added test case to reproduce issue | <ide><path>i/tests/src/test/java/org/jboss/forge/addon/ui/impl/UIInputInjectionTest.java
<ide> }
<ide>
<ide> @Inject
<del> @WithAttributes(defaultValue="true", label = "")
<add> @WithAttributes(defaultValue = "true", label = "")
<ide> UIInput<Boolean> enabled;
<ide>
<ide> @Inject
<ide>
<ide> @Inject
<ide> UISelectOne<Gender> gender;
<add>
<add> @SuppressWarnings("rawtypes")
<add> @Inject
<add> UIInput noParameter;
<add>
<add> @Test
<add> public void testNoParameterInput()
<add> {
<add> Assert.assertNotNull(noParameter);
<add> Assert.assertEquals(String.class, noParameter.getValueType());
<add> }
<ide>
<ide> @Test
<ide> public void testEnumValuesAvailability() throws Exception |
|
Java | lgpl-2.1 | fb51a424be7cc7e3c0ae89922b770a21e645c61c | 0 | cawka/ndnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,cawka/ndnx,cawka/ndnx | package org.ccnx.ccn.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.ccnx.ccn.CCNInterestListener;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* A class to help write tests without a repo. Pulls things
* through ccnd, under a set of namespaces.
* Cheesy -- uses excludes to not get the same content back.
*
* TODO FIX -- not entirely correct. Gets more duplicates than it needs to.
*
* See CCNVersionedInputStream for related stream-based flossing code.
* The "floss" term refers to "mental floss" -- think a picture of
* someone running dental floss in and out through their ears.
* @author smetters
*
*/
public class Flosser implements CCNInterestListener {
CCNHandle _library;
Map<ContentName, Interest> _interests = new HashMap<ContentName, Interest>();
Map<ContentName, Set<ContentName>> _subInterests = new HashMap<ContentName, Set<ContentName>>();
HashSet<ContentObject> _processedObjects = new HashSet<ContentObject>();
/**
* Constructors that called handleNamespace() now throwing NullPointerException as this doesn't exist yet.
* @throws ConfigurationException
* @throws IOException
*/
public Flosser() throws ConfigurationException, IOException {
_library = CCNHandle.open();
}
public Flosser(ContentName namespace) throws ConfigurationException, IOException {
this();
handleNamespace(namespace);
}
public void handleNamespace(String namespace) throws MalformedContentNameStringException, IOException {
handleNamespace(ContentName.fromNative(namespace));
}
public void stopMonitoringNamespace(String namespace) throws MalformedContentNameStringException {
stopMonitoringNamespace(ContentName.fromNative(namespace));
}
public void stopMonitoringNamespace(ContentName namespace) {
synchronized(_interests) {
if (!_interests.containsKey(namespace)) {
return;
}
Set<ContentName> subInterests = _subInterests.get(namespace);
if (null != subInterests) {
Iterator<ContentName> it = subInterests.iterator();
while (it.hasNext()) {
ContentName subNamespace = it.next();
removeInterest(subNamespace);
it.remove();
}
}
// Remove the top-level interest.
removeInterest(namespace);
_subInterests.remove(namespace);
Log.info("FLOSSER: no longer monitoring namespace: {0}", namespace);
}
}
protected void removeInterest(ContentName namespace) {
synchronized(_interests) {
if (!_interests.containsKey(namespace)) {
return;
}
Interest interest = _interests.get(namespace);
_library.cancelInterest(interest, this);
_interests.remove(namespace);
Log.fine("Cancelled interest in {0}", namespace);
}
}
/**
* Handle a top-level namespace.
* @param namespace
* @throws IOException
*/
public void handleNamespace(ContentName namespace) throws IOException {
synchronized(_interests) {
if (_interests.containsKey(namespace)) {
Log.fine("FLOSSER: Already handling namespace: {0}", namespace);
return;
}
Log.info("FLOSSER: handling namespace: {0}", namespace);
Interest namespaceInterest = new Interest(namespace);
_interests.put(namespace, namespaceInterest);
_library.expressInterest(namespaceInterest, this);
Set<ContentName> subNamespaces = _subInterests.get(namespace);
if (null == subNamespaces) {
subNamespaces = new HashSet<ContentName>();
_subInterests.put(namespace, subNamespaces);
Log.info("FLOSSER: setup parent namespace: {0}", namespace);
}
}
}
public void handleNamespace(ContentName namespace, ContentName parent) throws IOException {
synchronized(_interests) {
if (_interests.containsKey(namespace)) {
Log.fine("Already handling child namespace: {0}", namespace);
return;
}
Log.info("FLOSSER: handling child namespace: {0} expected parent: {1}", namespace, parent);
Interest namespaceInterest = new Interest(namespace);
_interests.put(namespace, namespaceInterest);
_library.expressInterest(namespaceInterest, this);
// Now we need to find a parent in the subInterest map, and reflect this namespace underneath it.
ContentName parentNamespace = parent;
Set<ContentName> subNamespace = _subInterests.get(parentNamespace);
while ((subNamespace == null) && (!parentNamespace.equals(ContentName.ROOT))) {
parentNamespace = parentNamespace.parent();
subNamespace = _subInterests.get(parentNamespace);
Log.info("FLOSSER: initial parent not found in map, looked up {0} found in map? {1}", parentNamespace, ((null == subNamespace) ? "no" : "yes"));
}
if (null != subNamespace) {
Log.info("FLOSSER: Adding subnamespace: {0} to ancestor {1}", namespace, parentNamespace);
subNamespace.add(namespace);
} else {
Log.info("FLOSSER: Cannot find ancestor namespace for {0}", namespace);
for (ContentName n : _subInterests.keySet()) {
Log.info("FLOSSER: available ancestor: {0}", n);
}
}
}
}
public Interest handleContent(ArrayList<ContentObject> results,
Interest interest) {
Log.finest("Interests registered: " + _interests.size() + " content objects returned: "+results.size());
// Parameterized behavior that subclasses can override.
ContentName interestName = null;
for (ContentObject result : results) {
if (_processedObjects.contains(result)) {
Log.fine("FLOSSER: Got repeated content for interest: {0} content: {1}", interest, result.name());
continue;
}
Log.finest("FLOSSER: Got new content for interest {0} content name: {1}", interest, result.name());
processContent(result);
// update the interest. follow process used by ccnslurp.
// exclude the next component of this object, and set up a
// separate interest to explore its children.
// first, remove the interest from our list as we aren't going to
// reexpress it in exactly the same way
synchronized(_interests) {
for (Entry<ContentName, Interest> entry : _interests.entrySet()) {
if (entry.getValue().equals(interest)) {
interestName = entry.getKey();
_interests.remove(interestName);
break;
}
}
}
int prefixCount = interest.name().count();
// DKS TODO should the count above be count()-1 and this just prefixCount?
if (prefixCount == result.name().count()) {
if (null == interest.exclude()) {
ArrayList<Exclude.Element> excludes = new ArrayList<Exclude.Element>();
excludes.add(new ExcludeComponent(result.contentDigest()));
interest.exclude(new Exclude(excludes));
Log.finest("Creating new exclude filter for interest {0}", interest.name());
} else {
if (interest.exclude().match(result.contentDigest())) {
Log.fine("We should have already excluded content digest: " + DataUtils.printBytes(result.contentDigest()));
} else {
// Has to be in order...
Log.finest("Adding child component to exclude.");
interest.exclude().add(new byte [][] { result.contentDigest() });
}
}
Log.finer("Excluding content digest: " + DataUtils.printBytes(result.contentDigest()) + " onto interest {0} total excluded: " + interest.exclude().size(), interest.name());
} else {
if (null == interest.exclude()) {
ArrayList<Exclude.Element> excludes = new ArrayList<Exclude.Element>();
excludes.add(new ExcludeComponent(result.name().component(prefixCount)));
interest.exclude(new Exclude(excludes));
Log.finest("Creating new exclude filter for interest {0}", interest.name());
} else {
if (interest.exclude().match(result.name().component(prefixCount))) {
Log.fine("We should have already excluded child component: {0}", ContentName.componentPrintURI(result.name().component(prefixCount)));
} else {
// Has to be in order...
Log.finest("Adding child component to exclude.");
interest.exclude().add(
new byte [][] { result.name().component(prefixCount) });
}
}
Log.finer("Excluding child " + ContentName.componentPrintURI(result.name().component(prefixCount)) + " total excluded: " + interest.exclude().size());
// DKS TODO might need to split to matchedComponents like ccnslurp
ContentName newNamespace = null;
try {
if (interest.name().count() == result.name().count()) {
newNamespace = new ContentName(interest.name(), result.contentDigest());
Log.info("Not adding content exclusion namespace: {0}", newNamespace);
} else {
newNamespace = new ContentName(interest.name(),
result.name().component(interest.name().count()));
Log.info("Adding new namespace: {0}", newNamespace);
handleNamespace(newNamespace, interest.name());
}
} catch (IOException ioex) {
Log.warning("IOException picking up namespace: {0}", newNamespace);
}
}
}
if (null != interest)
synchronized(_interests) {
_interests.put(interest.name(), interest);
}
return interest;
}
public void stop() {
Log.info("Stop flossing.");
synchronized (_interests) {
for (Interest interest : _interests.values()) {
Log.info("Cancelling pending interest: " + interest);
_library.cancelInterest(interest, this);
}
}
}
public void logNamespaces() {
ContentName [] namespaces = getNamespaces().toArray(new ContentName[getNamespaces().size()]);
for (ContentName name : namespaces) {
Log.info("Flosser: monitoring namespace: " + name);
}
}
public Set<ContentName> getNamespaces() {
synchronized (_interests) {
return _interests.keySet();
}
}
/**
* Override in subclasses that want to do something more interesting than log.
* @param result
*/
protected void processContent(ContentObject result) {
Log.info("Flosser got: " + result.name() + " Digest: " +
DataUtils.printBytes(result.contentDigest()));
}
}
| javasrc/src/org/ccnx/ccn/test/Flosser.java | package org.ccnx.ccn.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.ccnx.ccn.CCNInterestListener;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* A class to help write tests without a repo. Pulls things
* through ccnd, under a set of namespaces.
* Cheesy -- uses excludes to not get the same content back.
*
* TODO FIX -- not entirely correct. Gets more duplicates than it needs to.
*
* See CCNVersionedInputStream for related stream-based flossing code.
* The "floss" term refers to "mental floss" -- think a picture of
* someone running dental floss in and out through their ears.
* @author smetters
*
*/
public class Flosser implements CCNInterestListener {
CCNHandle _library;
Map<ContentName, Interest> _interests = new HashMap<ContentName, Interest>();
Map<ContentName, Set<ContentName>> _subInterests = new HashMap<ContentName, Set<ContentName>>();
HashSet<ContentObject> _processedObjects = new HashSet<ContentObject>();
/**
* Constructors that called handleNamespace() now throwing NullPointerException as this doesn't exist yet.
* @throws ConfigurationException
* @throws IOException
*/
public Flosser() throws ConfigurationException, IOException {
_library = CCNHandle.open();
}
public Flosser(ContentName namespace) throws ConfigurationException, IOException {
this();
handleNamespace(namespace);
}
public void handleNamespace(String namespace) throws MalformedContentNameStringException, IOException {
handleNamespace(ContentName.fromNative(namespace));
}
public void stopMonitoringNamespace(String namespace) throws MalformedContentNameStringException {
stopMonitoringNamespace(ContentName.fromNative(namespace));
}
public void stopMonitoringNamespace(ContentName namespace) {
synchronized(_interests) {
if (!_interests.containsKey(namespace)) {
return;
}
Set<ContentName> subInterests = _subInterests.get(namespace);
if (null != subInterests) {
Iterator<ContentName> it = subInterests.iterator();
while (it.hasNext()) {
ContentName subNamespace = it.next();
removeInterest(subNamespace);
it.remove();
}
}
// Remove the top-level interest.
removeInterest(namespace);
_subInterests.remove(namespace);
Log.info("FLOSSER: no longer monitoring namespace: " + namespace);
}
}
protected void removeInterest(ContentName namespace) {
synchronized(_interests) {
if (!_interests.containsKey(namespace)) {
return;
}
Interest interest = _interests.get(namespace);
_library.cancelInterest(interest, this);
_interests.remove(namespace);
Log.fine("Cancelled interest in " + namespace);
}
}
/**
* Handle a top-level namespace.
* @param namespace
* @throws IOException
*/
public void handleNamespace(ContentName namespace) throws IOException {
synchronized(_interests) {
if (_interests.containsKey(namespace)) {
Log.fine("FLOSSER: Already handling namespace: {0}", namespace);
return;
}
Log.info("FLOSSER: handling namespace: {0}", namespace);
Interest namespaceInterest = new Interest(namespace);
_interests.put(namespace, namespaceInterest);
_library.expressInterest(namespaceInterest, this);
Set<ContentName> subNamespaces = _subInterests.get(namespace);
if (null == subNamespaces) {
subNamespaces = new HashSet<ContentName>();
_subInterests.put(namespace, subNamespaces);
Log.info("FLOSSER: setup parent namespace: {0}", namespace);
}
}
}
public void handleNamespace(ContentName namespace, ContentName parent) throws IOException {
synchronized(_interests) {
if (_interests.containsKey(namespace)) {
Log.fine("Already handling child namespace: {0}", namespace);
return;
}
Log.info("FLOSSER: handling child namespace: {0} expected parent: {1}", namespace, parent);
Interest namespaceInterest = new Interest(namespace);
_interests.put(namespace, namespaceInterest);
_library.expressInterest(namespaceInterest, this);
// Now we need to find a parent in the subInterest map, and reflect this namespace underneath it.
ContentName parentNamespace = parent;
Set<ContentName> subNamespace = _subInterests.get(parentNamespace);
while ((subNamespace == null) && (!parentNamespace.equals(ContentName.ROOT))) {
parentNamespace = parentNamespace.parent();
subNamespace = _subInterests.get(parentNamespace);
Log.info("FLOSSER: initial parent not found in map, looked up {0} found in map? {1}", parentNamespace, ((null == subNamespace) ? "no" : "yes"));
}
if (null != subNamespace) {
Log.info("FLOSSER: Adding subnamespace: {0} to ancestor {1}", namespace, parentNamespace);
subNamespace.add(namespace);
} else {
Log.info("FLOSSER: Cannot find ancestor namespace for {0}", namespace);
for (ContentName n : _subInterests.keySet()) {
Log.info("FLOSSER: available ancestor: {0}", n);
}
}
}
}
public Interest handleContent(ArrayList<ContentObject> results,
Interest interest) {
Log.finest("Interests registered: " + _interests.size() + " content objects returned: "+results.size());
// Parameterized behavior that subclasses can override.
ContentName interestName = null;
for (ContentObject result : results) {
if (_processedObjects.contains(result)) {
Log.fine("FLOSSER: Got repeated content for interest: {0} content: {1}", interest, result.name());
continue;
}
Log.finest("FLOSSER: Got new content for interest {0} content name: {1}", interest, result.name());
processContent(result);
// update the interest. follow process used by ccnslurp.
// exclude the next component of this object, and set up a
// separate interest to explore its children.
// first, remove the interest from our list as we aren't going to
// reexpress it in exactly the same way
synchronized(_interests) {
for (Entry<ContentName, Interest> entry : _interests.entrySet()) {
if (entry.getValue().equals(interest)) {
interestName = entry.getKey();
_interests.remove(interestName);
break;
}
}
}
int prefixCount = interest.name().count();
// DKS TODO should the count above be count()-1 and this just prefixCount?
if (prefixCount == result.name().count()) {
if (null == interest.exclude()) {
ArrayList<Exclude.Element> excludes = new ArrayList<Exclude.Element>();
excludes.add(new ExcludeComponent(result.contentDigest()));
interest.exclude(new Exclude(excludes));
Log.finest("Creating new exclude filter for interest " + interest.name());
} else {
if (interest.exclude().match(result.contentDigest())) {
Log.fine("We should have already excluded content digest: " + DataUtils.printBytes(result.contentDigest()));
} else {
// Has to be in order...
Log.finest("Adding child component to exclude.");
interest.exclude().add(new byte [][] { result.contentDigest() });
}
}
Log.finer("Excluding content digest: " + DataUtils.printBytes(result.contentDigest()) + " onto interest " + interest.name() + " total excluded: " + interest.exclude().size());
} else {
if (null == interest.exclude()) {
ArrayList<Exclude.Element> excludes = new ArrayList<Exclude.Element>();
excludes.add(new ExcludeComponent(result.name().component(prefixCount)));
interest.exclude(new Exclude(excludes));
Log.finest("Creating new exclude filter for interest " + interest.name());
} else {
if (interest.exclude().match(result.name().component(prefixCount))) {
Log.fine("We should have already excluded child component: " + ContentName.componentPrintURI(result.name().component(prefixCount)));
} else {
// Has to be in order...
Log.finest("Adding child component to exclude.");
interest.exclude().add(
new byte [][] { result.name().component(prefixCount) });
}
}
Log.finer("Excluding child " + ContentName.componentPrintURI(result.name().component(prefixCount)) + " total excluded: " + interest.exclude().size());
// DKS TODO might need to split to matchedComponents like ccnslurp
ContentName newNamespace = null;
try {
if (interest.name().count() == result.name().count()) {
newNamespace = new ContentName(interest.name(), result.contentDigest());
} else {
newNamespace = new ContentName(interest.name(),
result.name().component(interest.name().count()));
}
Log.info("Adding new namespace: " + newNamespace);
handleNamespace(newNamespace, interest.name());
} catch (IOException ioex) {
Log.warning("IOException picking up namespace: " + newNamespace);
}
}
}
if (null != interest)
synchronized(_interests) {
_interests.put(interest.name(), interest);
}
return interest;
}
public void stop() {
Log.info("Stop flossing.");
synchronized (_interests) {
for (Interest interest : _interests.values()) {
Log.info("Cancelling pending interest: " + interest);
_library.cancelInterest(interest, this);
}
}
}
public void logNamespaces() {
ContentName [] namespaces = getNamespaces().toArray(new ContentName[getNamespaces().size()]);
for (ContentName name : namespaces) {
Log.info("Flosser: monitoring namespace: " + name);
}
}
public Set<ContentName> getNamespaces() {
synchronized (_interests) {
return _interests.keySet();
}
}
/**
* Override in subclasses that want to do something more interesting than log.
* @param result
*/
protected void processContent(ContentObject result) {
Log.info("Flosser got: " + result.name() + " Digest: " +
DataUtils.printBytes(result.contentDigest()));
}
}
| Tone down flosser interests.
| javasrc/src/org/ccnx/ccn/test/Flosser.java | Tone down flosser interests. | <ide><path>avasrc/src/org/ccnx/ccn/test/Flosser.java
<ide> // Remove the top-level interest.
<ide> removeInterest(namespace);
<ide> _subInterests.remove(namespace);
<del> Log.info("FLOSSER: no longer monitoring namespace: " + namespace);
<add> Log.info("FLOSSER: no longer monitoring namespace: {0}", namespace);
<ide> }
<ide> }
<ide>
<ide> Interest interest = _interests.get(namespace);
<ide> _library.cancelInterest(interest, this);
<ide> _interests.remove(namespace);
<del> Log.fine("Cancelled interest in " + namespace);
<add> Log.fine("Cancelled interest in {0}", namespace);
<ide> }
<ide> }
<ide>
<ide> ArrayList<Exclude.Element> excludes = new ArrayList<Exclude.Element>();
<ide> excludes.add(new ExcludeComponent(result.contentDigest()));
<ide> interest.exclude(new Exclude(excludes));
<del> Log.finest("Creating new exclude filter for interest " + interest.name());
<add> Log.finest("Creating new exclude filter for interest {0}", interest.name());
<ide> } else {
<ide> if (interest.exclude().match(result.contentDigest())) {
<ide> Log.fine("We should have already excluded content digest: " + DataUtils.printBytes(result.contentDigest()));
<ide> interest.exclude().add(new byte [][] { result.contentDigest() });
<ide> }
<ide> }
<del> Log.finer("Excluding content digest: " + DataUtils.printBytes(result.contentDigest()) + " onto interest " + interest.name() + " total excluded: " + interest.exclude().size());
<add> Log.finer("Excluding content digest: " + DataUtils.printBytes(result.contentDigest()) + " onto interest {0} total excluded: " + interest.exclude().size(), interest.name());
<ide> } else {
<ide> if (null == interest.exclude()) {
<ide> ArrayList<Exclude.Element> excludes = new ArrayList<Exclude.Element>();
<ide> excludes.add(new ExcludeComponent(result.name().component(prefixCount)));
<ide> interest.exclude(new Exclude(excludes));
<del> Log.finest("Creating new exclude filter for interest " + interest.name());
<add> Log.finest("Creating new exclude filter for interest {0}", interest.name());
<ide> } else {
<ide> if (interest.exclude().match(result.name().component(prefixCount))) {
<del> Log.fine("We should have already excluded child component: " + ContentName.componentPrintURI(result.name().component(prefixCount)));
<add> Log.fine("We should have already excluded child component: {0}", ContentName.componentPrintURI(result.name().component(prefixCount)));
<ide> } else {
<ide> // Has to be in order...
<ide> Log.finest("Adding child component to exclude.");
<ide> try {
<ide> if (interest.name().count() == result.name().count()) {
<ide> newNamespace = new ContentName(interest.name(), result.contentDigest());
<add> Log.info("Not adding content exclusion namespace: {0}", newNamespace);
<ide> } else {
<ide> newNamespace = new ContentName(interest.name(),
<ide> result.name().component(interest.name().count()));
<del> }
<del> Log.info("Adding new namespace: " + newNamespace);
<del> handleNamespace(newNamespace, interest.name());
<add> Log.info("Adding new namespace: {0}", newNamespace);
<add> handleNamespace(newNamespace, interest.name());
<add> }
<ide> } catch (IOException ioex) {
<del> Log.warning("IOException picking up namespace: " + newNamespace);
<add> Log.warning("IOException picking up namespace: {0}", newNamespace);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 4e1b063ffaee18bfbca9083fc277c16e13d2bdc8 | 0 | b2b2244424/StickyGridHeaders,bigsui/StickyGridHeaders,java02014/StickyGridHeaders,inmite/StickyGridHeaders,kopihao/StickyGridHeaders,guoxiaojun001/StickyGridHeaders,bboyfeiyu/StickyGridHeaders,hgl888/StickyGridHeaders,HiWong/StickyGridHeaders,silentnuke/StickyGridHeaders,rchandnani/StickyGridHeaders,TonicArtos/StickyGridHeaders | /*
Copyright 2013 Tonic Artos
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.tonicartos.stickygridheadersexample;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersSimpleArrayAdapter;
/**
* A list fragment representing a list of Items. This fragment also supports
* tablet devices by allowing list items to be given an 'activated' state upon
* selection. This helps indicate which item is currently being viewed in a
* {@link ItemDetailFragment}.
* <p>
* Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*
* @author Tonic Artos
*/
public class ItemListFragment extends SherlockFragment implements OnItemClickListener {
private static final String KEY_LIST_POSITION = "key_list_position";
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(int id) {
}
};
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private int firstVisible;
private GridView gridView;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemListFragment() {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_grid, container, false);
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onItemClick(AdapterView<?> gridView, View view, int position, long id) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(position);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridView = (GridView) view.findViewById(R.id.asset_grid);
gridView.setOnItemClickListener(this);
gridView.setColumnWidth((int) calculatePixelsFromDips(100));
gridView.setNumColumns(-1);
gridView.setAdapter(new StickyGridHeadersSimpleArrayAdapter<String>(getActivity().getApplicationContext(), getResources().getStringArray(R.array.countries), R.layout.header, R.layout.item));
if (savedInstanceState != null) {
firstVisible = savedInstanceState.getInt(KEY_LIST_POSITION);
}
gridView.setSelection(firstVisible);
// Restore the previously serialized activated item position.
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
private float calculatePixelsFromDips(float dips) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, getResources().getDisplayMetrics());
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
gridView.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE);
}
}
@SuppressLint("NewApi")
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
gridView.setItemChecked(mActivatedPosition, false);
} else {
gridView.setItemChecked(position, true);
}
mActivatedPosition = position;
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(int position);
}
}
| Example/src/com/tonicartos/stickygridheadersexample/ItemListFragment.java | /*
Copyright 2013 Tonic Artos
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.tonicartos.stickygridheadersexample;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersSimpleArrayAdapter;
/**
* A list fragment representing a list of Items. This fragment also supports
* tablet devices by allowing list items to be given an 'activated' state upon
* selection. This helps indicate which item is currently being viewed in a
* {@link ItemDetailFragment}.
* <p>
* Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*
* @author Tonic Artos
*/
public class ItemListFragment extends SherlockFragment implements OnItemClickListener {
private static final String KEY_LIST_POSITION = "key_list_position";
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(int id) {
}
};
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private int firstVisible;
private GridView gridView;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemListFragment() {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_grid, container, false);
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onItemClick(AdapterView<?> gridView, View view, int position, long id) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(position);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridView = (GridView) view.findViewById(R.id.asset_grid);
gridView.setOnItemClickListener(this);
gridView.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
gridView.setNumColumns(-1);
gridView.setAdapter(new StickyGridHeadersSimpleArrayAdapter<String>(getActivity().getApplicationContext(), getResources().getStringArray(R.array.countries), R.layout.header, R.layout.item));
if (savedInstanceState != null) {
firstVisible = savedInstanceState.getInt(KEY_LIST_POSITION);
}
gridView.setSelection(firstVisible);
// Restore the previously serialized activated item position.
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
gridView.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE);
}
}
@SuppressLint("NewApi")
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
gridView.setItemChecked(mActivatedPosition, false);
} else {
gridView.setItemChecked(position, true);
}
mActivatedPosition = position;
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(int position);
}
}
| Tidy example dip calculation.
| Example/src/com/tonicartos/stickygridheadersexample/ItemListFragment.java | Tidy example dip calculation. | <ide><path>xample/src/com/tonicartos/stickygridheadersexample/ItemListFragment.java
<ide>
<ide> gridView = (GridView) view.findViewById(R.id.asset_grid);
<ide> gridView.setOnItemClickListener(this);
<del> gridView.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
<add> gridView.setColumnWidth((int) calculatePixelsFromDips(100));
<ide> gridView.setNumColumns(-1);
<ide> gridView.setAdapter(new StickyGridHeadersSimpleArrayAdapter<String>(getActivity().getApplicationContext(), getResources().getStringArray(R.array.countries), R.layout.header, R.layout.item));
<ide>
<ide> if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
<ide> setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
<ide> }
<add> }
<add>
<add> private float calculatePixelsFromDips(float dips) {
<add> return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, getResources().getDisplayMetrics());
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | e8ec73084c4f37388a9a7d0e62fc21839de5b284 | 0 | zurb/foundation-emails,zurb/foundation-emails,jsit/foundation-emails,zurb/ink,jsit/foundation-emails,zurb/foundation-emails,Stadly/foundation-emails,Stadly/foundation-emails,struankl/foundation-emails,struankl/foundation-emails,struankl/foundation-emails,Stadly/foundation-emails,struankl/foundation-emails,Smartmessages/foundation-emails,jsit/foundation-emails,zurb/foundation-emails,jsit/foundation-emails,Smartmessages/foundation-emails,zurb/ink,Stadly/foundation-emails | // Columns
// TODO: Make private function
var createCol = function(obj) {
var output = '';
$.each(obj, function(v,k) {
var temp = ''
var contents = $(this).html();
var colClass = 'columns ' + $(this).attr('class');
if (v !== obj.length - 1) {
temp = '<td class="wrapper">'
+'<table class="' + colClass + '">'
+'<tr><td>'
+ contents +'</td><td class="expander"></td></tr></table></td>';
} else {
temp = '<td class="wrapper last">'
+'<table class="' + colClass + '">'
+'<tr><td>'
+ contents +'</td><td class="expander"></td></tr></table></td>';
}
output += temp;
});
return output;
};
| js/components/col.js | // Columns
// TODO: Make private function
var createCol = function(obj) {
var output = '';
$.each(obj, function(v,k) {
var temp = ''
var contents = $(this).html();
var colClass = 'columns ' + $(this).attr('class');
if (v !== obj.length - 1) {
temp = '<td class="wrapper">'
+'<table class="' + colClass + '">'
+'<tr><td>'
+ contents +'</tr></td></table></td>';
} else {
temp = '<td class="wrapper last">'
+'<table class="' + colClass + '">'
+'<tr><td>'
+ contents +'</tr></td></table></td>';
}
output += temp;
});
return output;
};
| Added 'expander' class into columns.
| js/components/col.js | Added 'expander' class into columns. | <ide><path>s/components/col.js
<ide> temp = '<td class="wrapper">'
<ide> +'<table class="' + colClass + '">'
<ide> +'<tr><td>'
<del> + contents +'</tr></td></table></td>';
<add> + contents +'</td><td class="expander"></td></tr></table></td>';
<ide> } else {
<ide> temp = '<td class="wrapper last">'
<ide> +'<table class="' + colClass + '">'
<ide> +'<tr><td>'
<del> + contents +'</tr></td></table></td>';
<add> + contents +'</td><td class="expander"></td></tr></table></td>';
<ide> }
<ide>
<ide> output += temp; |
|
JavaScript | mit | 6e2cca781710ad34bc94e2ed05c97dc46bf20715 | 0 | Rafer45/soup |
const ytdl = require('ytdl-core');
const queues = {};
module.exports = {
play: (message, config, _, url) => {
enqueue(message, url)
.then(() => {
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
return false;
}
const vc = message.member.voiceChannel;
if (!vc) {
return message.reply('Join a voice channel before using the command.');
}
return vc.join()
.then(dispatch.bind(
null,
message,
queues[message.guild.id].shift().url,
config,
));
})
.catch(console.error);
},
stop: (message) => {
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
return new Promise((resolve, reject) => {
message.channel.send('Interrupting song...')
.then((_message) => {
const dispatcher = voiceConn.dispatcher;
dispatcher.end();
resolve(_message);
})
.catch(reject);
});
}
return message.channel.send('Stop what?');
},
pleasestop: (message) => {
module.exports.clearqueue(message)
.then(module.exports.stop);
},
clearqueue: message => (
new Promise((resolve, reject) => {
message.channel.send('Queue cleared.').then((_message) => {
queues[message.guild.id] = [];
resolve(_message);
}).catch(reject);
})
),
queue: (message) => {
const q = queues[message.guild.id] || [];
if (q.length === 0) {
message.channel.send('Queue is empty');
} else {
const cb = '```';
const qStr = q.map(elem => (
`${elem.title} - Requested by ${elem.requester}`
)).join('\n');
message.channel.send(`${cb}${qStr}${cb}`);
}
},
volume: (message) => {
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
const dispatcher = voiceConn.dispatcher;
message.channel.send(`Volume is at ${dispatcher.volume}%.`);
} else {
message.channel.send('Volume can only be shown when playing music.');
}
},
volumeshift: (message, config, _, n) => {
n = Number(n);
n = !isNaN(n) ? (n / 50) : 0;
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
const dispatcher = voiceConn.dispatcher;
const oldVol = dispatcher.volume;
const newVol = Math.max(0,
Math.min(2,
clean(dispatcher.volume + n),
),
);
dispatcher.setVolume(newVol);
message.channel.send(`Volume shifted by ${clean(newVol - oldVol) * 50}%. It is now ${clean(dispatcher.volume) * 50}%.`);
} else {
message.channel.send('Volume can only be shifted when playing music.');
}
function clean(_n) {
return Math.round(_n * 10) / 10;
}
},
};
function dispatch(message, url, config, connection) {
const stream = ytdl(url, {
filter: 'audioonly',
});
const dispatcher = connection.playStream(
stream,
{ passes: config.music.passes },
);
dispatcher.setVolume(config.music.volume);
dispatcher.on('end', () => {
if (queues[message.guild.id].length > 0) {
setTimeout(() => {
dispatch(
message,
queues[message.guild.id].shift().url,
config,
connection,
);
}, 500);
} else {
message.channel.send('Queue is now empty.').then(() => {
connection.channel.leave();
});
}
});
message.channel.send(`Playing song at url:\n${url}`);
}
function enqueue(message, url = '') {
queues[message.guild.id] = queues[message.guild.id] || [];
return new Promise((resolve, reject) => {
ytdl.getInfo(url, (e, info) => {
if (e) {
message.channel.send('Invalid YouTube URL.');
reject(e);
} else {
queues[message.guild.id].push({
'url': url,
'title': info.title,
requester: message.author,
});
message.channel.send(`Enqueued **${info.title}**.`);
resolve();
}
});
});
}
| commands/music_commands.js |
const ytdl = require('ytdl-core');
const queues = {};
module.exports = {
play: (message, config, _, url) => {
enqueue(message, url)
.then(() => {
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
return false;
}
const vc = message.member.voiceChannel;
if (!vc) {
return message.reply('Join a voice channel before using the command.');
}
return vc.join()
.then(dispatch.bind(
null,
message,
queues[message.guild.id].shift().url,
config,
));
})
.catch(console.error);
},
stop: (message) => {
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
return new Promise((resolve, reject) => {
message.channel.send('Interrupting song...')
.then((_message) => {
const dispatcher = voiceConn.dispatcher;
dispatcher.end();
resolve(_message);
})
.catch(reject);
});
}
return message.channel.send('Stop what?');
},
pleasestop: (message) => {
module.exports.clearqueue(message)
.then(module.exports.stop);
},
clearqueue: message => (
new Promise((resolve, reject) => {
message.channel.send('Queue cleared.').then((_message) => {
queues[message.guild.id] = [];
resolve(_message);
}).catch(reject);
})
),
queue: (message) => {
const q = queues[message.guild.id] || [];
if (q.length === 0) {
message.channel.send('Queue is empty');
} else {
const cb = '```';
const qStr = q.map(elem => (
`${elem.title} - Requested by ${elem.requester}`
)).join('\n');
message.channel.send(`${cb}${qStr}${cb}`);
}
},
volumeshift: (message, config, _, n) => {
n = Number(n);
n = !isNaN(n) ? (n / 50) : 0;
const voiceConn = message.guild.voiceConnection;
if (voiceConn) {
const dispatcher = voiceConn.dispatcher;
const oldVol = dispatcher.volume;
const newVol = Math.max(0,
Math.min(2,
clean(dispatcher.volume + n),
),
);
dispatcher.setVolume(newVol);
message.channel.send(`Volume shifted by ${clean(newVol - oldVol) * 50}%. It is now ${clean(dispatcher.volume) * 50}%.`);
}
function clean(_n) {
return Math.round(_n * 10) / 10;
}
},
};
function dispatch(message, url, config, connection) {
const stream = ytdl(url, {
filter: 'audioonly',
});
const dispatcher = connection.playStream(
stream,
{ passes: config.music.passes },
);
dispatcher.setVolume(config.music.volume);
dispatcher.on('end', () => {
if (queues[message.guild.id].length > 0) {
setTimeout(() => {
dispatch(
message,
queues[message.guild.id].shift().url,
config,
connection,
);
}, 500);
} else {
message.channel.send('Queue is now empty.').then(() => {
connection.channel.leave();
});
}
});
message.channel.send(`Playing song at url:\n${url}`);
}
function enqueue(message, url) {
queues[message.guild.id] = queues[message.guild.id] || [];
return new Promise((resolve, reject) => {
ytdl.getInfo(url, (e, info) => {
if (e) {
message.channel.send('Invalid YouTube URL.');
reject(e);
} else {
queues[message.guild.id].push({
'url': url,
'title': info.title,
requester: message.author,
});
message.channel.send(`Enqueued **${info.title}**.`);
resolve();
}
});
});
}
| Add volume command and empty url handling for enqueue
| commands/music_commands.js | Add volume command and empty url handling for enqueue | <ide><path>ommands/music_commands.js
<ide> }
<ide> },
<ide>
<add> volume: (message) => {
<add> const voiceConn = message.guild.voiceConnection;
<add> if (voiceConn) {
<add> const dispatcher = voiceConn.dispatcher;
<add> message.channel.send(`Volume is at ${dispatcher.volume}%.`);
<add> } else {
<add> message.channel.send('Volume can only be shown when playing music.');
<add> }
<add> },
<add>
<ide> volumeshift: (message, config, _, n) => {
<ide> n = Number(n);
<ide> n = !isNaN(n) ? (n / 50) : 0;
<ide>
<ide> dispatcher.setVolume(newVol);
<ide> message.channel.send(`Volume shifted by ${clean(newVol - oldVol) * 50}%. It is now ${clean(dispatcher.volume) * 50}%.`);
<add> } else {
<add> message.channel.send('Volume can only be shifted when playing music.');
<ide> }
<ide>
<ide> function clean(_n) {
<ide> message.channel.send(`Playing song at url:\n${url}`);
<ide> }
<ide>
<del>function enqueue(message, url) {
<add>function enqueue(message, url = '') {
<ide> queues[message.guild.id] = queues[message.guild.id] || [];
<ide>
<ide> return new Promise((resolve, reject) => { |
|
Java | mit | 8fdd8618850f381eb6abadacbb60762711e12482 | 0 | jruby/joni | /*
* 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 org.joni;
import java.io.PrintStream;
public interface Config extends org.jcodings.Config {
final boolean VANILLA = false;
final int CHAR_TABLE_SIZE = 256;
final int SCANENV_MEMNODES_SIZE = 8;
final boolean USE_NAMED_GROUP = true;
final boolean USE_SUBEXP_CALL = true;
final boolean USE_PERL_SUBEXP_CALL = true;
final boolean USE_BACKREF_WITH_LEVEL = true; /* \k<name+n>, \k<name-n> */
final boolean USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT = true; /* /(?:()|())*\2/ */
final boolean USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE = true; /* /\n$/ =~ "\n" */
final boolean USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR = false;
final boolean CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS = true;
final boolean USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE = false;
final boolean USE_CAPTURE_HISTORY = false;
final boolean USE_VARIABLE_META_CHARS = true;
final boolean USE_WORD_BEGIN_END = true; /* "\<": word-begin, "\>": word-end */
final boolean USE_POSIX_API_REGION_OPTION = true; /* needed for POSIX API support */
final boolean USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE = true;
final boolean USE_COMBINATION_EXPLOSION_CHECK = false;
final int NREGION = 10;
final int MAX_BACKREF_NUM = 1000;
final int MAX_REPEAT_NUM = 100000;
final int MAX_MULTI_BYTE_RANGES_NUM = 10000;
final boolean USE_WARN = true;
// internal config
final boolean USE_PARSE_TREE_NODE_RECYCLE = true;
final boolean USE_OP_PUSH_OR_JUMP_EXACT = true;
final boolean USE_SHARED_CCLASS_TABLE = false;
final boolean USE_QTFR_PEEK_NEXT = true;
final int INIT_MATCH_STACK_SIZE = 64;
final int DEFAULT_MATCH_STACK_LIMIT_SIZE = 0; /* unlimited */
final int NUMBER_OF_POOLED_STACKS = 4;
final boolean DONT_OPTIMIZE = false;
final boolean USE_STRING_TEMPLATES = true; // use embeded string templates in Regex object as byte arrays instead of compiling them into int bytecode array
final int MAX_CAPTURE_HISTORY_GROUP = 31;
final int CHECK_STRING_THRESHOLD_LEN = 7;
final int CHECK_BUFF_MAX_SIZE = 0x4000;
final boolean NON_UNICODE_SDW = true;
final PrintStream log = System.out;
final PrintStream err = System.err;
final boolean DEBUG_ALL = false;
final boolean DEBUG = DEBUG_ALL;
final boolean DEBUG_PARSE_TREE = DEBUG_ALL;
final boolean DEBUG_PARSE_TREE_RAW = true;
final boolean DEBUG_COMPILE = DEBUG_ALL;
final boolean DEBUG_COMPILE_BYTE_CODE_INFO = DEBUG_ALL;
final boolean DEBUG_SEARCH = DEBUG_ALL;
final boolean DEBUG_MATCH = DEBUG_ALL;
final boolean DEBUG_ASM = true;
final boolean DEBUG_ASM_EXEC = true;
}
| src/org/joni/Config.java | /*
* 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 org.joni;
import java.io.PrintStream;
public interface Config extends org.jcodings.Config {
final int CHAR_TABLE_SIZE = 256;
final int SCANENV_MEMNODES_SIZE = 8;
final boolean USE_NAMED_GROUP = true;
final boolean USE_SUBEXP_CALL = true;
final boolean USE_PERL_SUBEXP_CALL = true;
final boolean USE_BACKREF_WITH_LEVEL = true; /* \k<name+n>, \k<name-n> */
final boolean USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT = true; /* /(?:()|())*\2/ */
final boolean USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE = true; /* /\n$/ =~ "\n" */
final boolean USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR = false;
final boolean CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS = true;
final boolean USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE = false;
final boolean USE_CAPTURE_HISTORY = false;
final boolean USE_VARIABLE_META_CHARS = true;
final boolean USE_WORD_BEGIN_END = true; /* "\<": word-begin, "\>": word-end */
final boolean USE_POSIX_API_REGION_OPTION = true; /* needed for POSIX API support */
final boolean USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE = true;
final boolean USE_COMBINATION_EXPLOSION_CHECK = false;
final int NREGION = 10;
final int MAX_BACKREF_NUM = 1000;
final int MAX_REPEAT_NUM = 100000;
final int MAX_MULTI_BYTE_RANGES_NUM = 10000;
final boolean USE_WARN = true;
// internal config
final boolean USE_PARSE_TREE_NODE_RECYCLE = true;
final boolean USE_OP_PUSH_OR_JUMP_EXACT = true;
final boolean USE_SHARED_CCLASS_TABLE = false;
final boolean USE_QTFR_PEEK_NEXT = true;
final int INIT_MATCH_STACK_SIZE = 64;
final int DEFAULT_MATCH_STACK_LIMIT_SIZE = 0; /* unlimited */
final int NUMBER_OF_POOLED_STACKS = 4;
final boolean DONT_OPTIMIZE = false;
final boolean USE_STRING_TEMPLATES = true; // use embeded string templates in Regex object as byte arrays instead of compiling them into int bytecode array
final int MAX_CAPTURE_HISTORY_GROUP = 31;
final int CHECK_STRING_THRESHOLD_LEN = 7;
final int CHECK_BUFF_MAX_SIZE = 0x4000;
final boolean NON_UNICODE_SDW = true;
final PrintStream log = System.out;
final PrintStream err = System.err;
final boolean DEBUG_ALL = false;
final boolean DEBUG = DEBUG_ALL;
final boolean DEBUG_PARSE_TREE = DEBUG_ALL;
final boolean DEBUG_PARSE_TREE_RAW = true;
final boolean DEBUG_COMPILE = DEBUG_ALL;
final boolean DEBUG_COMPILE_BYTE_CODE_INFO = DEBUG_ALL;
final boolean DEBUG_SEARCH = DEBUG_ALL;
final boolean DEBUG_MATCH = DEBUG_ALL;
final boolean DEBUG_ASM = true;
final boolean DEBUG_ASM_EXEC = true;
}
| hide jcodings VANILLA flag
| src/org/joni/Config.java | hide jcodings VANILLA flag | <ide><path>rc/org/joni/Config.java
<ide> import java.io.PrintStream;
<ide>
<ide> public interface Config extends org.jcodings.Config {
<add> final boolean VANILLA = false;
<ide> final int CHAR_TABLE_SIZE = 256;
<ide> final int SCANENV_MEMNODES_SIZE = 8;
<ide> |
|
Java | epl-1.0 | 6565970adcc274aea6285e8bf1c51f4d4647ccc8 | 0 | edgarmueller/emfstore-rest | /*******************************************************************************
* Copyright (c) 2008-2011 Chair for Applied Software Engineering,
* Technische Universitaet Muenchen.
* 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:
* Maximilian Koegel
******************************************************************************/
package org.eclipse.emf.emfstore.internal.client.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.emfstore.client.ESLocalProject;
import org.eclipse.emf.emfstore.client.ESWorkspaceProvider;
import org.eclipse.emf.emfstore.client.observer.ESCheckoutObserver;
import org.eclipse.emf.emfstore.client.observer.ESCommitObserver;
import org.eclipse.emf.emfstore.client.observer.ESShareObserver;
import org.eclipse.emf.emfstore.client.observer.ESUpdateObserver;
import org.eclipse.emf.emfstore.client.observer.ESWorkspaceInitObserver;
import org.eclipse.emf.emfstore.client.provider.ESEditingDomainProvider;
import org.eclipse.emf.emfstore.client.sessionprovider.ESAbstractSessionProvider;
import org.eclipse.emf.emfstore.client.util.ClientURIUtil;
import org.eclipse.emf.emfstore.client.util.RunESCommand;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionElement;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPoint;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPointException;
import org.eclipse.emf.emfstore.common.extensionpoint.ESPriorityComparator;
import org.eclipse.emf.emfstore.common.extensionpoint.ESResourceSetProvider;
import org.eclipse.emf.emfstore.internal.client.model.changeTracking.commands.EMFStoreBasicCommandStack;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.AdminConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.ConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.SessionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.xmlrpc.XmlRpcAdminConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.xmlrpc.XmlRpcConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.impl.WorkspaceImpl;
import org.eclipse.emf.emfstore.internal.client.model.impl.api.ESWorkspaceImpl;
import org.eclipse.emf.emfstore.internal.client.model.util.EMFStoreCommand;
import org.eclipse.emf.emfstore.internal.client.model.util.WorkspaceUtil;
import org.eclipse.emf.emfstore.internal.common.CommonUtil;
import org.eclipse.emf.emfstore.internal.common.model.Project;
import org.eclipse.emf.emfstore.internal.common.model.util.ModelUtil;
import org.eclipse.emf.emfstore.internal.common.observer.ObserverBus;
import org.eclipse.emf.emfstore.internal.migration.EMFStoreMigrationException;
import org.eclipse.emf.emfstore.internal.migration.EMFStoreMigrator;
import org.eclipse.emf.emfstore.internal.migration.EMFStoreMigratorUtil;
import org.eclipse.emf.emfstore.server.model.ESChangePackage;
import org.eclipse.emf.emfstore.server.model.versionspec.ESPrimaryVersionSpec;
/**
* Controller for workspaces. Workspace Manager is a singleton.
*
* @author Maximilian Koegel
* @generated NOT
*/
public final class ESWorkspaceProviderImpl implements ESWorkspaceProvider, ESCommitObserver, ESUpdateObserver,
ESShareObserver, ESCheckoutObserver {
private static ESWorkspaceProviderImpl instance;
private AdminConnectionManager adminConnectionManager;
private ConnectionManager connectionManager;
private EditingDomain editingDomain;
private ObserverBus observerBus;
private ResourceSet resourceSet;
private SessionManager sessionManager;
private Workspace currentWorkspace;
/**
* Get an instance of the workspace manager. Will create an instance if no
* workspace manager is present.
*
* @return the workspace manager singleton
* @generated NOT
*/
public static synchronized ESWorkspaceProviderImpl getInstance() {
if (instance == null) {
try {
instance = new ESWorkspaceProviderImpl();
instance.initialize();
// BEGIN SUPRESS CATCH EXCEPTION
} catch (RuntimeException e) {
// END SURPRESS CATCH EXCEPTION
ModelUtil.logException("Workspace Initialization failed, shutting down", e);
throw e;
}
// init ecore packages
CommonUtil.getAllModelElementEClasses();
// notify post workspace observers
instance.notifyPostWorkspaceInitiators();
}
return instance;
}
/**
* Initialize the Workspace Manager singleton.
*/
public static synchronized void init() {
getInstance();
}
/**
* Retrieve the editing domain.
*
* @return the workspace editing domain
*/
public EditingDomain getEditingDomain() {
if (editingDomain == null) {
ESWorkspaceProviderImpl.getInstance();
}
return editingDomain;
}
/**
* Sets the EditingDomain.
*
* @param editingDomain
* new domain.
*/
public void setEditingDomain(EditingDomain editingDomain) {
this.editingDomain = editingDomain;
}
/**
* Private constructor.
*
*/
private ESWorkspaceProviderImpl() {
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.common.ESDisposable#dispose()
*/
public void dispose() {
if (currentWorkspace != null) {
RunESCommand.run(new Callable<Void>() {
public Void call() throws Exception {
((WorkspaceImpl) currentWorkspace).dispose();
return null;
}
});
currentWorkspace = null;
}
}
/**
* Whether the current workspace is disposed.
*
* @return {@code true} if the current workspace is disposed, {@code false} otherwise
*/
public boolean isDisposed() {
return currentWorkspace == null;
}
/**
* (Re-)Initializes the workspace. Loads workspace from persistent storage
* if present. There is always one current Workspace.
*/
public void load() {
ESExtensionPoint extensionPoint = new ESExtensionPoint("org.eclipse.emf.emfstore.client.resourceSetProvider",
true);
extensionPoint.setComparator(new ESPriorityComparator("priority", true));
extensionPoint.reload();
ESResourceSetProvider resourceSetProvider = extensionPoint.getElementWithHighestPriority().getClass("class",
ESResourceSetProvider.class);
resourceSet = resourceSetProvider.getResourceSet();
setEditingDomain(createEditingDomain(resourceSet));
URI workspaceURI = ClientURIUtil.createWorkspaceURI();
final Workspace workspace;
final Resource resource;
if (!resourceSet.getURIConverter().exists(workspaceURI, null)) {
workspace = createNewWorkspace(resourceSet, workspaceURI);
} else {
// file exists, load it,
// check if a migration is needed
migrateModelIfNeeded(resourceSet);
resource = resourceSet.createResource(workspaceURI);
try {
resource.load(ModelUtil.getResourceLoadOptions());
} catch (IOException e) {
WorkspaceUtil.logException("Error while loading workspace.", e);
}
EList<EObject> directContents = resource.getContents();
workspace = (Workspace) directContents.get(0);
}
workspace.setResourceSet(resourceSet);
new EMFStoreCommand() {
@Override
protected void doRun() {
workspace.init();
}
}.run(true);
currentWorkspace = workspace;
getObserverBus().register(this);
}
/**
* Flushes the command stack.
*/
public void flushCommandStack() {
getEditingDomain().getCommandStack().flush();
}
/**
* Get the admin connection manager. Return the admin connection manager for
* this workspace.
*
* @return the connectionManager
*/
public AdminConnectionManager getAdminConnectionManager() {
return adminConnectionManager;
}
/**
* Retrieve the project space for a model element.
*
* @param modelElement
* the model element
* @return the project space
*/
public static ProjectSpace getProjectSpace(EObject modelElement) {
if (modelElement == null) {
throw new IllegalArgumentException("The model element is null");
} else if (modelElement instanceof ProjectSpace) {
return (ProjectSpace) modelElement;
}
Project project = ModelUtil.getProject(modelElement);
if (project == null) {
throw new IllegalArgumentException("The model element " + modelElement + " has no project");
}
return getProjectSpace(project);
}
/**
* Retrieve the project space for a project.
*
* @param project
* the project
* @return the project space
*/
public static ProjectSpace getProjectSpace(Project project) {
if (project == null) {
throw new IllegalArgumentException("The project is null");
}
// check if my container is a project space
if (ModelPackage.eINSTANCE.getProjectSpace().isInstance(project.eContainer())) {
return (ProjectSpace) project.eContainer();
} else {
throw new IllegalStateException("Project is not contained by any project space");
}
}
/**
* Returns the {@link ObserverBus}.
*
* @return observer bus
*/
public static ObserverBus getObserverBus() {
return getInstance().observerBus;
}
/**
* Returns the {@link SessionManager}.
*
* @return session manager
*/
public SessionManager getSessionManager() {
return sessionManager;
}
/**
* Get the current workspace. There is always one current workspace.
*
* @return the workspace
*/
public ESWorkspaceImpl getWorkspace() {
return getInternalWorkspace().toAPI();
}
public Workspace getInternalWorkspace() {
if (currentWorkspace == null) {
load();
}
return currentWorkspace;
}
/**
* Get the connection manager. Return the connection manager for this
* workspace.
*
* @return the connectionManager
*/
public ConnectionManager getConnectionManager() {
return connectionManager;
}
/**
* Set the connectionmanager.
*
* @param manager
* connection manager.
*/
public void setConnectionManager(ConnectionManager manager) {
connectionManager = manager;
}
/**
*
* {@inheritDoc}
*
* @see ESWorkspaceProvider#setSessionProvider(ESAbstractSessionProvider)
*/
public void setSessionProvider(ESAbstractSessionProvider sessionProvider) {
getSessionManager().setSessionProvider(sessionProvider);
}
private void initialize() {
this.observerBus = new ObserverBus();
this.connectionManager = initConnectionManager();
this.adminConnectionManager = initAdminConnectionManager();
this.sessionManager = new SessionManager();
load();
}
private void notifyPostWorkspaceInitiators() {
for (ESExtensionElement element : new ESExtensionPoint("org.eclipse.emf.emfstore.client.notify.postinit", true)
.getExtensionElements()) {
try {
element.getClass("class", ESWorkspaceInitObserver.class).workspaceInitComplete(
currentWorkspace
.toAPI());
} catch (ESExtensionPointException e) {
WorkspaceUtil.logException(e.getMessage(), e);
}
}
}
/**
* Initialize the connection manager of the workspace. The connection
* manager connects the workspace with EMFStore.
*
* @return the connection manager
*/
private ConnectionManager initConnectionManager() {
KeyStoreManager.getInstance().setupKeys();
return new XmlRpcConnectionManager();
}
/**
* Initialize the connection manager of the workspace. The connection
* manager connects the workspace with the emf store.
*
* @return the admin connection manager
* @generated NOT
*/
private AdminConnectionManager initAdminConnectionManager() {
// return new RMIAdminConnectionManagerImpl();
return new XmlRpcAdminConnectionManager();
}
private EditingDomain createEditingDomain(ResourceSet resourceSet) {
ESEditingDomainProvider domainProvider = getDomainProvider();
if (domainProvider != null) {
return domainProvider.getEditingDomain(resourceSet);
} else {
AdapterFactory adapterFactory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { adapterFactory,
new ReflectiveItemProviderAdapterFactory() });
AdapterFactoryEditingDomain domain = new AdapterFactoryEditingDomain(adapterFactory,
new EMFStoreBasicCommandStack(), resourceSet);
resourceSet.eAdapters().add(new AdapterFactoryEditingDomain.EditingDomainProvider(domain));
return domain;
}
}
private ESEditingDomainProvider getDomainProvider() {
// TODO EXPT PRIO
return new ESExtensionPoint("org.eclipse.emf.emfstore.client.editingDomainProvider")
.getClass("class",
ESEditingDomainProvider.class);
}
private Workspace createNewWorkspace(ResourceSet resourceSet, URI fileURI) {
final Workspace workspace;
final Resource resource;
// no workspace content found, create a workspace
resource = resourceSet.createResource(fileURI);
workspace = ModelFactory.eINSTANCE.createWorkspace();
workspace.getServerInfos().addAll(Configuration.getClientBehavior().getDefaultServerInfos());
EList<Usersession> usersessions = workspace.getUsersessions();
for (ServerInfo serverInfo : workspace.getServerInfos()) {
Usersession lastUsersession = serverInfo.getLastUsersession();
if (lastUsersession != null) {
usersessions.add(lastUsersession);
}
}
new EMFStoreCommand() {
@Override
protected void doRun() {
resource.getContents().add(workspace);
}
}.run(true);
try {
resource.save(ModelUtil.getResourceSaveOptions());
} catch (IOException e) {
WorkspaceUtil.logException(
"Creating new workspace failed! Delete workspace folder: "
+ Configuration.getFileInfo().getWorkspaceDirectory(), e);
}
return workspace;
}
private void migrateModelIfNeeded(ResourceSet resourceSet) {
EMFStoreMigrator migrator = null;
try {
migrator = EMFStoreMigratorUtil.getEMFStoreMigrator();
} catch (EMFStoreMigrationException e2) {
WorkspaceUtil.logWarning(e2.getMessage(), null);
return;
}
for (List<URI> curModels : getPhysicalURIsForMigration()) {
// TODO logging?
if (!migrator.canHandle(curModels)) {
return;
}
if (!migrator.needsMigration(curModels)) {
return;
}
try {
migrator.migrate(curModels, new NullProgressMonitor());
} catch (EMFStoreMigrationException e) {
WorkspaceUtil.logException("The migration of the project in projectspace at " + curModels.get(0)
+ " failed!", e);
}
}
// ModelVersion workspaceModelVersion = getWorkspaceModelVersion();
// int modelVersionNumber;
// try {
// modelVersionNumber = ModelUtil.getModelVersionNumber();
// stampCurrentVersionNumber(modelVersionNumber);
// } catch (MalformedModelVersionException e1) {
// WorkspaceUtil.logException("Loading model version failed, migration skipped!", e1);
// return;
// }
// if (workspaceModelVersion.getReleaseNumber() == modelVersionNumber) {
// return;
// } else if (workspaceModelVersion.getReleaseNumber() > modelVersionNumber) {
// backupAndRecreateWorkspace(resourceSet);
// WorkspaceUtil.logException("Model conforms to a newer version, update client! New workspace was backuped!",
// new IllegalStateException());
// return;
// }
//
// // we need to migrate
// if (!EMFStoreMigratorUtil.isMigratorAvailable()) {
// WorkspaceUtil.logException("Model requires migration, but no migrators are registered!",
// new IllegalStateException());
// return;
// }
//
// backupWorkspace(false);
//
// // ////////// start migration
// // load workspace in new resourceset
// ESExtensionPoint extensionPoint = new ESExtensionPoint("org.eclipse.emf.emfstore.client.resourceSetProvider",
// true);
// extensionPoint.setComparator(new ESPriorityComparator("priority", true));
// extensionPoint.reload();
//
// ESResourceSetProvider resourceSetProvider = extensionPoint.getElementWithHighestPriority().getClass("class",
// ESResourceSetProvider.class);
//
// ResourceSet migrationResourceSet = resourceSetProvider.getResourceSet();
// Resource resource = migrationResourceSet.createResource(ClientURIUtil.createWorkspaceURI());
//
// try {
// resource.load(ModelUtil.getResourceLoadOptions());
// } catch (IOException e) {
// WorkspaceUtil.logException("Error while loading workspace.", e);
// }
//
// EList<EObject> directContents = resource.getContents();
// Workspace workspace = (Workspace) directContents.get(0);
// for (ProjectSpace ps : workspace.getProjectSpaces()) {
// // TODO test this
// URI projectURI = migrationResourceSet.getURIConverter().normalize(ps.getProject().eResource().getURI());
// URI operationsURI = migrationResourceSet.getURIConverter()
// .normalize(ps.getLocalChangePackage().eResource().getURI());
// try {
// migrate(projectURI, operationsURI, workspaceModelVersion.getReleaseNumber());
// } catch (EMFStoreMigrationException e) {
// WorkspaceUtil.logException("The migration of the project in projectspace at " + ps.eResource().getURI()
// + " failed!", e);
// backupAndRecreateWorkspace(resourceSet);
// }
// }
//
// // TODO delete if new migration works
// // // start migrations
// // File workspaceFile = new File(Configuration.getFileInfo().getWorkspaceDirectory());
// // for (File file : workspaceFile.listFiles()) {
// // if (file.getName().startsWith(Configuration.getFileInfo().getProjectSpaceDirectoryPrefix())) {
// // String projectFilePath = file.getAbsolutePath() + File.separatorChar
// // + Configuration.getFileInfo().ProjectFragmentFileName
// // + Configuration.getFileInfo().ProjectFragmentExtension;
// // URI projectURI = URI.createFileURI(projectFilePath);
// // String operationsFilePath = null;
// // File[] listFiles = file.listFiles();
// // if (listFiles == null) {
// // WorkspaceUtil.logException("The migration of the project in projectspace at " + projectFilePath
// // + " failed!", new IllegalStateException("Broken projectSpace!"));
// // continue;
// // }
// // for (File subDirFile : listFiles) {
// // if (subDirFile.getName().endsWith(Configuration.getFileInfo().LocalChangePackageExtension)) {
// // operationsFilePath = subDirFile.getAbsolutePath();
// // }
// // }
// // if (operationsFilePath == null) {
// // WorkspaceUtil.logException("The migration of the project in projectspace at " + projectFilePath
// // + " failed!", new IllegalStateException("Broken workspace!"));
// // backupAndRecreateWorkspace(resourceSet);
// // }
// // URI operationsURI = URI.createFileURI(operationsFilePath);
// // try {
// // migrate(projectURI, operationsURI, workspaceModelVersion.getReleaseNumber());
// // } catch (EMFStoreMigrationException e) {
// // WorkspaceUtil.logException("The migration of the project in projectspace at " + projectFilePath
// // + " failed!", e);
// // backupAndRecreateWorkspace(resourceSet);
// // }
// // }
// // }
// // // end migration
//
// stampCurrentVersionNumber(modelVersionNumber);
}
private List<List<URI>> getPhysicalURIsForMigration() {
ESExtensionPoint extensionPoint = new ESExtensionPoint("org.eclipse.emf.emfstore.client.resourceSetProvider",
true);
extensionPoint.setComparator(new ESPriorityComparator("priority", true));
extensionPoint.reload();
ESResourceSetProvider resourceSetProvider = extensionPoint.getElementWithHighestPriority().getClass("class",
ESResourceSetProvider.class);
ResourceSet migrationResourceSet = resourceSetProvider.getResourceSet();
Resource resource = migrationResourceSet.createResource(ClientURIUtil.createWorkspaceURI());
try {
resource.load(ModelUtil.getResourceLoadOptions());
} catch (IOException e) {
WorkspaceUtil.logException("Error while loading workspace.", e);
}
List<List<URI>> physicalURIs = new ArrayList<List<URI>>();
EList<EObject> directContents = resource.getContents();
Workspace workspace = (Workspace) directContents.get(0);
for (ProjectSpace ps : workspace.getProjectSpaces()) {
List<URI> uris = new ArrayList<URI>();
URI projectURI = migrationResourceSet.getURIConverter().normalize(ps.getProject().eResource().getURI());
URI operationsURI = migrationResourceSet.getURIConverter()
.normalize(ps.getLocalChangePackage().eResource().getURI());
uris.add(projectURI);
uris.add(operationsURI);
physicalURIs.add(uris);
}
return physicalURIs;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESCheckoutObserver#checkoutDone(org.eclipse.emf.emfstore.client.ESLocalProject)
*/
public void checkoutDone(ESLocalProject project) {
flushCommandStack();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESShareObserver#shareDone(org.eclipse.emf.emfstore.client.ESLocalProject)
*/
public void shareDone(ESLocalProject localProject) {
flushCommandStack();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESUpdateObserver#inspectChanges(org.eclipse.emf.emfstore.client.ESLocalProject,
* java.util.List, org.eclipse.core.runtime.IProgressMonitor)
*/
public boolean inspectChanges(ESLocalProject project, List<ESChangePackage> changePackages, IProgressMonitor monitor) {
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESUpdateObserver#updateCompleted(org.eclipse.emf.emfstore.client.ESLocalProject,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void updateCompleted(ESLocalProject project, IProgressMonitor monitor) {
flushCommandStack();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESCommitObserver#inspectChanges(org.eclipse.emf.emfstore.client.ESLocalProject,
* org.eclipse.emf.emfstore.server.model.ESChangePackage, org.eclipse.core.runtime.IProgressMonitor)
*/
public boolean inspectChanges(ESLocalProject project, ESChangePackage changePackage, IProgressMonitor monitor) {
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESCommitObserver#commitCompleted(org.eclipse.emf.emfstore.client.ESLocalProject,
* org.eclipse.emf.emfstore.server.model.versionspec.ESPrimaryVersionSpec,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void commitCompleted(ESLocalProject project, ESPrimaryVersionSpec newRevision, IProgressMonitor monitor) {
flushCommandStack();
}
} | bundles/org.eclipse.emf.emfstore.client/src/org/eclipse/emf/emfstore/internal/client/model/ESWorkspaceProviderImpl.java | /*******************************************************************************
* Copyright (c) 2008-2011 Chair for Applied Software Engineering,
* Technische Universitaet Muenchen.
* 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:
* Maximilian Koegel
******************************************************************************/
package org.eclipse.emf.emfstore.internal.client.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.emfstore.client.ESLocalProject;
import org.eclipse.emf.emfstore.client.ESWorkspaceProvider;
import org.eclipse.emf.emfstore.client.observer.ESCheckoutObserver;
import org.eclipse.emf.emfstore.client.observer.ESCommitObserver;
import org.eclipse.emf.emfstore.client.observer.ESShareObserver;
import org.eclipse.emf.emfstore.client.observer.ESUpdateObserver;
import org.eclipse.emf.emfstore.client.observer.ESWorkspaceInitObserver;
import org.eclipse.emf.emfstore.client.provider.ESEditingDomainProvider;
import org.eclipse.emf.emfstore.client.sessionprovider.ESAbstractSessionProvider;
import org.eclipse.emf.emfstore.client.util.ClientURIUtil;
import org.eclipse.emf.emfstore.client.util.RunESCommand;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionElement;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPoint;
import org.eclipse.emf.emfstore.common.extensionpoint.ESExtensionPointException;
import org.eclipse.emf.emfstore.common.extensionpoint.ESPriorityComparator;
import org.eclipse.emf.emfstore.common.extensionpoint.ESResourceSetProvider;
import org.eclipse.emf.emfstore.internal.client.model.changeTracking.commands.EMFStoreBasicCommandStack;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.AdminConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.ConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.SessionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.xmlrpc.XmlRpcAdminConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.connectionmanager.xmlrpc.XmlRpcConnectionManager;
import org.eclipse.emf.emfstore.internal.client.model.impl.WorkspaceImpl;
import org.eclipse.emf.emfstore.internal.client.model.impl.api.ESWorkspaceImpl;
import org.eclipse.emf.emfstore.internal.client.model.util.EMFStoreCommand;
import org.eclipse.emf.emfstore.internal.client.model.util.WorkspaceUtil;
import org.eclipse.emf.emfstore.internal.common.CommonUtil;
import org.eclipse.emf.emfstore.internal.common.model.Project;
import org.eclipse.emf.emfstore.internal.common.model.util.ModelUtil;
import org.eclipse.emf.emfstore.internal.common.observer.ObserverBus;
import org.eclipse.emf.emfstore.internal.migration.EMFStoreMigrationException;
import org.eclipse.emf.emfstore.internal.migration.EMFStoreMigrator;
import org.eclipse.emf.emfstore.internal.migration.EMFStoreMigratorUtil;
import org.eclipse.emf.emfstore.server.model.ESChangePackage;
import org.eclipse.emf.emfstore.server.model.versionspec.ESPrimaryVersionSpec;
/**
* Controller for workspaces. Workspace Manager is a singleton.
*
* @author Maximilian Koegel
* @generated NOT
*/
public final class ESWorkspaceProviderImpl implements ESWorkspaceProvider, ESCommitObserver, ESUpdateObserver,
ESShareObserver, ESCheckoutObserver {
private static ESWorkspaceProviderImpl instance;
private AdminConnectionManager adminConnectionManager;
private ConnectionManager connectionManager;
private EditingDomain editingDomain;
private ObserverBus observerBus;
private ResourceSet resourceSet;
private SessionManager sessionManager;
private Workspace currentWorkspace;
/**
* Get an instance of the workspace manager. Will create an instance if no
* workspace manager is present.
*
* @return the workspace manager singleton
* @generated NOT
*/
public static synchronized ESWorkspaceProviderImpl getInstance() {
if (instance == null) {
try {
instance = new ESWorkspaceProviderImpl();
instance.initialize();
// BEGIN SUPRESS CATCH EXCEPTION
} catch (RuntimeException e) {
// END SURPRESS CATCH EXCEPTION
ModelUtil.logException("Workspace Initialization failed, shutting down", e);
throw e;
}
// init ecore packages
CommonUtil.getAllModelElementEClasses();
// notify post workspace observers
instance.notifyPostWorkspaceInitiators();
}
return instance;
}
/**
* Initialize the Workspace Manager singleton.
*/
public static synchronized void init() {
getInstance();
}
/**
* Retrieve the editing domain.
*
* @return the workspace editing domain
*/
public EditingDomain getEditingDomain() {
if (editingDomain == null) {
ESWorkspaceProviderImpl.getInstance();
}
return editingDomain;
}
/**
* Sets the EditingDomain.
*
* @param editingDomain
* new domain.
*/
public void setEditingDomain(EditingDomain editingDomain) {
this.editingDomain = editingDomain;
}
/**
* Private constructor.
*
*/
private ESWorkspaceProviderImpl() {
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.common.ESDisposable#dispose()
*/
public void dispose() {
if (currentWorkspace != null) {
RunESCommand.run(new Callable<Void>() {
public Void call() throws Exception {
((WorkspaceImpl) currentWorkspace).dispose();
return null;
}
});
currentWorkspace = null;
}
}
/**
* Whether the current workspace is disposed.
*
* @return {@code true} if the current workspace is disposed, {@code false} otherwise
*/
public boolean isDisposed() {
return currentWorkspace == null;
}
/**
* (Re-)Initializes the workspace. Loads workspace from persistent storage
* if present. There is always one current Workspace.
*/
public void load() {
ESExtensionPoint extensionPoint = new ESExtensionPoint("org.eclipse.emf.emfstore.client.resourceSetProvider",
true);
extensionPoint.setComparator(new ESPriorityComparator("priority", true));
extensionPoint.reload();
ESResourceSetProvider resourceSetProvider = extensionPoint.getElementWithHighestPriority().getClass("class",
ESResourceSetProvider.class);
resourceSet = resourceSetProvider.getResourceSet();
// TODO register editing domain in resource set provider
// register an editing domain on the resource
setEditingDomain(createEditingDomain(resourceSet));
URI workspaceURI = ClientURIUtil.createWorkspaceURI();
final Workspace workspace;
final Resource resource;
if (!resourceSet.getURIConverter().exists(workspaceURI, null)) {
workspace = createNewWorkspace(resourceSet, workspaceURI);
} else {
// file exists, load it,
// check if a migration is needed
migrateModelIfNeeded(resourceSet);
resource = resourceSet.createResource(workspaceURI);
try {
resource.load(ModelUtil.getResourceLoadOptions());
} catch (IOException e) {
WorkspaceUtil.logException("Error while loading workspace.", e);
}
EList<EObject> directContents = resource.getContents();
workspace = (Workspace) directContents.get(0);
}
workspace.setResourceSet(resourceSet);
new EMFStoreCommand() {
@Override
protected void doRun() {
workspace.init();
}
}.run(true);
currentWorkspace = workspace;
getObserverBus().register(this);
}
/**
* Flushes the command stack.
*/
public void flushCommandStack() {
getEditingDomain().getCommandStack().flush();
}
/**
* Get the admin connection manager. Return the admin connection manager for
* this workspace.
*
* @return the connectionManager
*/
public AdminConnectionManager getAdminConnectionManager() {
return adminConnectionManager;
}
/**
* Retrieve the project space for a model element.
*
* @param modelElement
* the model element
* @return the project space
*/
public static ProjectSpace getProjectSpace(EObject modelElement) {
if (modelElement == null) {
throw new IllegalArgumentException("The model element is null");
} else if (modelElement instanceof ProjectSpace) {
return (ProjectSpace) modelElement;
}
Project project = ModelUtil.getProject(modelElement);
if (project == null) {
throw new IllegalArgumentException("The model element " + modelElement + " has no project");
}
return getProjectSpace(project);
}
/**
* Retrieve the project space for a project.
*
* @param project
* the project
* @return the project space
*/
public static ProjectSpace getProjectSpace(Project project) {
if (project == null) {
throw new IllegalArgumentException("The project is null");
}
// check if my container is a project space
if (ModelPackage.eINSTANCE.getProjectSpace().isInstance(project.eContainer())) {
return (ProjectSpace) project.eContainer();
} else {
throw new IllegalStateException("Project is not contained by any project space");
}
}
/**
* Returns the {@link ObserverBus}.
*
* @return observer bus
*/
public static ObserverBus getObserverBus() {
return getInstance().observerBus;
}
/**
* Returns the {@link SessionManager}.
*
* @return session manager
*/
public SessionManager getSessionManager() {
return sessionManager;
}
/**
* Get the current workspace. There is always one current workspace.
*
* @return the workspace
*/
public ESWorkspaceImpl getWorkspace() {
return getInternalWorkspace().toAPI();
}
public Workspace getInternalWorkspace() {
if (currentWorkspace == null) {
load();
}
return currentWorkspace;
}
/**
* Get the connection manager. Return the connection manager for this
* workspace.
*
* @return the connectionManager
*/
public ConnectionManager getConnectionManager() {
return connectionManager;
}
/**
* Set the connectionmanager.
*
* @param manager
* connection manager.
*/
public void setConnectionManager(ConnectionManager manager) {
connectionManager = manager;
}
/**
*
* {@inheritDoc}
*
* @see ESWorkspaceProvider#setSessionProvider(ESAbstractSessionProvider)
*/
public void setSessionProvider(ESAbstractSessionProvider sessionProvider) {
getSessionManager().setSessionProvider(sessionProvider);
}
private void initialize() {
this.observerBus = new ObserverBus();
this.connectionManager = initConnectionManager();
this.adminConnectionManager = initAdminConnectionManager();
this.sessionManager = new SessionManager();
load();
}
private void notifyPostWorkspaceInitiators() {
for (ESExtensionElement element : new ESExtensionPoint("org.eclipse.emf.emfstore.client.notify.postinit", true)
.getExtensionElements()) {
try {
element.getClass("class", ESWorkspaceInitObserver.class).workspaceInitComplete(
currentWorkspace
.toAPI());
} catch (ESExtensionPointException e) {
WorkspaceUtil.logException(e.getMessage(), e);
}
}
}
/**
* Initialize the connection manager of the workspace. The connection
* manager connects the workspace with EMFStore.
*
* @return the connection manager
*/
private ConnectionManager initConnectionManager() {
KeyStoreManager.getInstance().setupKeys();
return new XmlRpcConnectionManager();
}
/**
* Initialize the connection manager of the workspace. The connection
* manager connects the workspace with the emf store.
*
* @return the admin connection manager
* @generated NOT
*/
private AdminConnectionManager initAdminConnectionManager() {
// return new RMIAdminConnectionManagerImpl();
return new XmlRpcAdminConnectionManager();
}
private EditingDomain createEditingDomain(ResourceSet resourceSet) {
ESEditingDomainProvider domainProvider = getDomainProvider();
if (domainProvider != null) {
return domainProvider.getEditingDomain(resourceSet);
} else {
AdapterFactory adapterFactory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { adapterFactory,
new ReflectiveItemProviderAdapterFactory() });
AdapterFactoryEditingDomain domain = new AdapterFactoryEditingDomain(adapterFactory,
new EMFStoreBasicCommandStack(), resourceSet);
resourceSet.eAdapters().add(new AdapterFactoryEditingDomain.EditingDomainProvider(domain));
return domain;
}
}
private ESEditingDomainProvider getDomainProvider() {
// TODO EXPT PRIO
return new ESExtensionPoint("org.eclipse.emf.emfstore.client.editingDomainProvider")
.getClass("class",
ESEditingDomainProvider.class);
}
private Workspace createNewWorkspace(ResourceSet resourceSet, URI fileURI) {
final Workspace workspace;
final Resource resource;
// no workspace content found, create a workspace
resource = resourceSet.createResource(fileURI);
workspace = ModelFactory.eINSTANCE.createWorkspace();
workspace.getServerInfos().addAll(Configuration.getClientBehavior().getDefaultServerInfos());
EList<Usersession> usersessions = workspace.getUsersessions();
for (ServerInfo serverInfo : workspace.getServerInfos()) {
Usersession lastUsersession = serverInfo.getLastUsersession();
if (lastUsersession != null) {
usersessions.add(lastUsersession);
}
}
new EMFStoreCommand() {
@Override
protected void doRun() {
resource.getContents().add(workspace);
}
}.run(true);
try {
resource.save(ModelUtil.getResourceSaveOptions());
} catch (IOException e) {
WorkspaceUtil.logException(
"Creating new workspace failed! Delete workspace folder: "
+ Configuration.getFileInfo().getWorkspaceDirectory(), e);
}
return workspace;
}
private void migrateModelIfNeeded(ResourceSet resourceSet) {
EMFStoreMigrator migrator = null;
try {
migrator = EMFStoreMigratorUtil.getEMFStoreMigrator();
} catch (EMFStoreMigrationException e2) {
WorkspaceUtil.logWarning(e2.getMessage(), null);
return;
}
for (List<URI> curModels : getPhysicalURIsForMigration()) {
// TODO logging?
if (!migrator.canHandle(curModels)) {
return;
}
if (!migrator.needsMigration(curModels)) {
return;
}
try {
migrator.migrate(curModels, new NullProgressMonitor());
} catch (EMFStoreMigrationException e) {
WorkspaceUtil.logException("The migration of the project in projectspace at " + curModels.get(0)
+ " failed!", e);
}
}
// ModelVersion workspaceModelVersion = getWorkspaceModelVersion();
// int modelVersionNumber;
// try {
// modelVersionNumber = ModelUtil.getModelVersionNumber();
// stampCurrentVersionNumber(modelVersionNumber);
// } catch (MalformedModelVersionException e1) {
// WorkspaceUtil.logException("Loading model version failed, migration skipped!", e1);
// return;
// }
// if (workspaceModelVersion.getReleaseNumber() == modelVersionNumber) {
// return;
// } else if (workspaceModelVersion.getReleaseNumber() > modelVersionNumber) {
// backupAndRecreateWorkspace(resourceSet);
// WorkspaceUtil.logException("Model conforms to a newer version, update client! New workspace was backuped!",
// new IllegalStateException());
// return;
// }
//
// // we need to migrate
// if (!EMFStoreMigratorUtil.isMigratorAvailable()) {
// WorkspaceUtil.logException("Model requires migration, but no migrators are registered!",
// new IllegalStateException());
// return;
// }
//
// backupWorkspace(false);
//
// // ////////// start migration
// // load workspace in new resourceset
// ESExtensionPoint extensionPoint = new ESExtensionPoint("org.eclipse.emf.emfstore.client.resourceSetProvider",
// true);
// extensionPoint.setComparator(new ESPriorityComparator("priority", true));
// extensionPoint.reload();
//
// ESResourceSetProvider resourceSetProvider = extensionPoint.getElementWithHighestPriority().getClass("class",
// ESResourceSetProvider.class);
//
// ResourceSet migrationResourceSet = resourceSetProvider.getResourceSet();
// Resource resource = migrationResourceSet.createResource(ClientURIUtil.createWorkspaceURI());
//
// try {
// resource.load(ModelUtil.getResourceLoadOptions());
// } catch (IOException e) {
// WorkspaceUtil.logException("Error while loading workspace.", e);
// }
//
// EList<EObject> directContents = resource.getContents();
// Workspace workspace = (Workspace) directContents.get(0);
// for (ProjectSpace ps : workspace.getProjectSpaces()) {
// // TODO test this
// URI projectURI = migrationResourceSet.getURIConverter().normalize(ps.getProject().eResource().getURI());
// URI operationsURI = migrationResourceSet.getURIConverter()
// .normalize(ps.getLocalChangePackage().eResource().getURI());
// try {
// migrate(projectURI, operationsURI, workspaceModelVersion.getReleaseNumber());
// } catch (EMFStoreMigrationException e) {
// WorkspaceUtil.logException("The migration of the project in projectspace at " + ps.eResource().getURI()
// + " failed!", e);
// backupAndRecreateWorkspace(resourceSet);
// }
// }
//
// // TODO delete if new migration works
// // // start migrations
// // File workspaceFile = new File(Configuration.getFileInfo().getWorkspaceDirectory());
// // for (File file : workspaceFile.listFiles()) {
// // if (file.getName().startsWith(Configuration.getFileInfo().getProjectSpaceDirectoryPrefix())) {
// // String projectFilePath = file.getAbsolutePath() + File.separatorChar
// // + Configuration.getFileInfo().ProjectFragmentFileName
// // + Configuration.getFileInfo().ProjectFragmentExtension;
// // URI projectURI = URI.createFileURI(projectFilePath);
// // String operationsFilePath = null;
// // File[] listFiles = file.listFiles();
// // if (listFiles == null) {
// // WorkspaceUtil.logException("The migration of the project in projectspace at " + projectFilePath
// // + " failed!", new IllegalStateException("Broken projectSpace!"));
// // continue;
// // }
// // for (File subDirFile : listFiles) {
// // if (subDirFile.getName().endsWith(Configuration.getFileInfo().LocalChangePackageExtension)) {
// // operationsFilePath = subDirFile.getAbsolutePath();
// // }
// // }
// // if (operationsFilePath == null) {
// // WorkspaceUtil.logException("The migration of the project in projectspace at " + projectFilePath
// // + " failed!", new IllegalStateException("Broken workspace!"));
// // backupAndRecreateWorkspace(resourceSet);
// // }
// // URI operationsURI = URI.createFileURI(operationsFilePath);
// // try {
// // migrate(projectURI, operationsURI, workspaceModelVersion.getReleaseNumber());
// // } catch (EMFStoreMigrationException e) {
// // WorkspaceUtil.logException("The migration of the project in projectspace at " + projectFilePath
// // + " failed!", e);
// // backupAndRecreateWorkspace(resourceSet);
// // }
// // }
// // }
// // // end migration
//
// stampCurrentVersionNumber(modelVersionNumber);
}
private List<List<URI>> getPhysicalURIsForMigration() {
ESExtensionPoint extensionPoint = new ESExtensionPoint("org.eclipse.emf.emfstore.client.resourceSetProvider",
true);
extensionPoint.setComparator(new ESPriorityComparator("priority", true));
extensionPoint.reload();
ESResourceSetProvider resourceSetProvider = extensionPoint.getElementWithHighestPriority().getClass("class",
ESResourceSetProvider.class);
ResourceSet migrationResourceSet = resourceSetProvider.getResourceSet();
Resource resource = migrationResourceSet.createResource(ClientURIUtil.createWorkspaceURI());
try {
resource.load(ModelUtil.getResourceLoadOptions());
} catch (IOException e) {
WorkspaceUtil.logException("Error while loading workspace.", e);
}
List<List<URI>> physicalURIs = new ArrayList<List<URI>>();
EList<EObject> directContents = resource.getContents();
Workspace workspace = (Workspace) directContents.get(0);
for (ProjectSpace ps : workspace.getProjectSpaces()) {
List<URI> uris = new ArrayList<URI>();
URI projectURI = migrationResourceSet.getURIConverter().normalize(ps.getProject().eResource().getURI());
URI operationsURI = migrationResourceSet.getURIConverter()
.normalize(ps.getLocalChangePackage().eResource().getURI());
uris.add(projectURI);
uris.add(operationsURI);
physicalURIs.add(uris);
}
return physicalURIs;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESCheckoutObserver#checkoutDone(org.eclipse.emf.emfstore.client.ESLocalProject)
*/
public void checkoutDone(ESLocalProject project) {
flushCommandStack();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESShareObserver#shareDone(org.eclipse.emf.emfstore.client.ESLocalProject)
*/
public void shareDone(ESLocalProject localProject) {
flushCommandStack();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESUpdateObserver#inspectChanges(org.eclipse.emf.emfstore.client.ESLocalProject,
* java.util.List, org.eclipse.core.runtime.IProgressMonitor)
*/
public boolean inspectChanges(ESLocalProject project, List<ESChangePackage> changePackages, IProgressMonitor monitor) {
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESUpdateObserver#updateCompleted(org.eclipse.emf.emfstore.client.ESLocalProject,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void updateCompleted(ESLocalProject project, IProgressMonitor monitor) {
flushCommandStack();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESCommitObserver#inspectChanges(org.eclipse.emf.emfstore.client.ESLocalProject,
* org.eclipse.emf.emfstore.server.model.ESChangePackage, org.eclipse.core.runtime.IProgressMonitor)
*/
public boolean inspectChanges(ESLocalProject project, ESChangePackage changePackage, IProgressMonitor monitor) {
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.observer.ESCommitObserver#commitCompleted(org.eclipse.emf.emfstore.client.ESLocalProject,
* org.eclipse.emf.emfstore.server.model.versionspec.ESPrimaryVersionSpec,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void commitCompleted(ESLocalProject project, ESPrimaryVersionSpec newRevision, IProgressMonitor monitor) {
flushCommandStack();
}
} | removed todo
| bundles/org.eclipse.emf.emfstore.client/src/org/eclipse/emf/emfstore/internal/client/model/ESWorkspaceProviderImpl.java | removed todo | <ide><path>undles/org.eclipse.emf.emfstore.client/src/org/eclipse/emf/emfstore/internal/client/model/ESWorkspaceProviderImpl.java
<ide>
<ide> resourceSet = resourceSetProvider.getResourceSet();
<ide>
<del> // TODO register editing domain in resource set provider
<del> // register an editing domain on the resource
<ide> setEditingDomain(createEditingDomain(resourceSet));
<ide>
<ide> URI workspaceURI = ClientURIUtil.createWorkspaceURI(); |
|
Java | mit | d022af2cab9f24acf34e48149790857c0d969388 | 0 | mantazer/WiFiSentry,mantazer/WiFiSentry | package muntaserahmed.wifisentry;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class DashboardActivity extends Activity {
SharedPreferences preferences;
ActionBar actionBar;
ListView scanListView;
WifiManager wifiManager;
ConnectivityManager connManager;
NetworkInfo netInfo;
ArrayList<CustomScanResult> scanResults;
ArrayAdapter<CustomScanResult> arrayAdapter;
SortLevel sortByLevel = new SortLevel();
final String ipApiUrl = "http://ip-api.com/json/";
final String icanhazipUrl = "http://icanhazip.com/";
String ipAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
preferences = getSharedPreferences(ServerActivity.SERVER_PREFERENCES, MODE_PRIVATE);
final String serverAddress = preferences.getString("serverIp", null);
scanListView = (ListView) findViewById(R.id.scanListView);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
scanListView.setBackgroundColor(getResources().getColor(R.color.greensea));
refresh();
scanListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
view.setSelected(true);
CustomScanResult item = (CustomScanResult) adapterView.getItemAtPosition(i);
int level = item.level;
if (serverAddress != null) {
JSONObject requestObj = constructJSONObject(level);
try {
StringEntity jsonEntity = new StringEntity(requestObj.toString());
jsonEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
RestClient.post(getApplicationContext(), serverAddress, "rpi", jsonEntity, "application/json", new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(getApplicationContext(), "JSONObject", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Toast.makeText(getApplicationContext(), "JSONArray", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
Log.d("EXCEPTION:", "ENCODING");
}
} else {
Toast.makeText(getApplicationContext(), "Add a server first", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard, 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();
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_server) {
Intent intent = new Intent(this, ServerActivity.class);
startActivity(intent);
return true;
}
else if (id == R.id.action_refresh) {
refresh();
}
else if (id == R.id.action_place) {
getLocation();
}
return super.onOptionsItemSelected(item);
}
public ArrayList<CustomScanResult> scan() throws IllegalStateException {
boolean scanSuccess = wifiManager.startScan();
if (scanSuccess) {
ArrayList<ScanResult> scanResults = (ArrayList) wifiManager.getScanResults();
ArrayList<CustomScanResult> sanitizedResults = sanitizeResults(scanResults);
return sanitizedResults;
}
else {
Log.d("EXCEPTION: ", "SCAN FAILED");
throw new IllegalStateException();
}
}
public ArrayList<CustomScanResult> sanitizeResults(ArrayList<ScanResult> scanResults) {
ArrayList<CustomScanResult> customScanResults = new ArrayList<CustomScanResult>();
for (ScanResult sr : scanResults) {
CustomScanResult csr = new CustomScanResult(sr.SSID, sr.level);
if (!csr.SSID.equals("")) {
customScanResults.add(csr);
}
}
HashSet noDupes = new HashSet();
noDupes.addAll(customScanResults);
customScanResults.clear();
customScanResults.addAll(noDupes);
Collections.sort(customScanResults, sortByLevel);
return customScanResults;
}
public void refresh() {
scanResults = scan();
arrayAdapter = new ArrayAdapter<CustomScanResult>(
this,
R.layout.row,
scanResults
);
scanListView.setAdapter(arrayAdapter);
}
public void getLocation() {
connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// if (!netInfo.isConnected()) {
// Toast.makeText(getApplicationContext(), "You are not connected!", Toast.LENGTH_SHORT).show();
// return;
// }
// Toast.makeText(getApplicationContext(), "Connected!", Toast.LENGTH_SHORT).show();
setIp();
String urlWithParam = ipApiUrl + getIp();
RestClient.get(urlWithParam, null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
String status = response.getString("status");
String lat = response.getString("lat");
String lon = response.getString("lon");
Toast.makeText(getApplicationContext(), lat + ", " + lon, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.d("JSONException", "Failed to parse");
}
}
});
}
public void setIp() {
RestClient.get(icanhazipUrl, null, new JsonHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
ipAddress = responseString;
}
});
}
public String getIp() {
return ipAddress;
}
public JSONObject constructJSONObject(int level) {
double normalizedLevel = (double) (level * -1); // Make positive
int percentLevel = (int)(normalizedLevel * 0.32) + 1; // 1% of light is 0.32
JSONObject mainObj = new JSONObject();
JSONArray lightArray = new JSONArray();
JSONObject lightObject = new JSONObject();
JSONObject offLightObject = new JSONObject();
try {
lightObject.put("lightId", 1); // Make beginning light up
lightObject.put("intensity", 1);
lightObject.put("red", 46);
lightObject.put("green", 204);
lightObject.put("blue", 113);
offLightObject.put("lightId", percentLevel); // Turn off the rest where it should stop
offLightObject.put("intensity", 0);
offLightObject.put("red", 46);
offLightObject.put("green", 204);
offLightObject.put("blue", 113);
lightArray.put(lightObject);
lightArray.put(offLightObject);
mainObj.put("lights", lightArray);
mainObj.put("propagate", true);
} catch (JSONException e) {
Log.d("EXCEPTION: ", "JSONException constructJSONObject");
}
return mainObj;
}
}
| app/src/main/java/muntaserahmed/wifisentry/DashboardActivity.java | package muntaserahmed.wifisentry;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class DashboardActivity extends Activity {
SharedPreferences preferences;
ActionBar actionBar;
ListView scanListView;
WifiManager wifiManager;
ConnectivityManager connManager;
NetworkInfo netInfo;
ArrayList<CustomScanResult> scanResults;
ArrayAdapter<CustomScanResult> arrayAdapter;
SortLevel sortByLevel = new SortLevel();
final String ipApiUrl = "http://ip-api.com/json/";
final String icanhazipUrl = "http://icanhazip.com/";
String ipAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
preferences = getSharedPreferences(ServerActivity.SERVER_PREFERENCES, MODE_PRIVATE);
final String serverAddress = preferences.getString("serverIp", null);
scanListView = (ListView) findViewById(R.id.scanListView);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
scanListView.setBackgroundColor(getResources().getColor(R.color.greensea));
refresh();
scanListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
view.setSelected(true);
CustomScanResult item = (CustomScanResult) adapterView.getItemAtPosition(i);
int level = item.level;
if (serverAddress != null) {
JSONObject requestObj = constructJSONObject(level);
try {
StringEntity jsonEntity = new StringEntity(requestObj.toString());
jsonEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
RestClient.post(getApplicationContext(), serverAddress, "rpi", jsonEntity, "application/json", new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(getApplicationContext(), "JSONObject", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Toast.makeText(getApplicationContext(), "JSONArray", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
Log.d("EXCEPTION:", "ENCODING");
}
} else {
Toast.makeText(getApplicationContext(), "Add a server first", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard, 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();
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_server) {
Intent intent = new Intent(this, ServerActivity.class);
startActivity(intent);
return true;
}
else if (id == R.id.action_refresh) {
refresh();
}
else if (id == R.id.action_place) {
getLocation();
}
return super.onOptionsItemSelected(item);
}
public ArrayList<CustomScanResult> scan() throws IllegalStateException {
boolean scanSuccess = wifiManager.startScan();
if (scanSuccess) {
ArrayList<ScanResult> scanResults = (ArrayList) wifiManager.getScanResults();
ArrayList<CustomScanResult> sanitizedResults = sanitizeResults(scanResults);
return sanitizedResults;
}
else {
Log.d("EXCEPTION: ", "SCAN FAILED");
throw new IllegalStateException();
}
}
public ArrayList<CustomScanResult> sanitizeResults(ArrayList<ScanResult> scanResults) {
ArrayList<CustomScanResult> customScanResults = new ArrayList<CustomScanResult>();
for (ScanResult sr : scanResults) {
CustomScanResult csr = new CustomScanResult(sr.SSID, sr.level);
if (!csr.SSID.equals("")) {
customScanResults.add(csr);
}
}
HashSet noDupes = new HashSet();
noDupes.addAll(customScanResults);
customScanResults.clear();
customScanResults.addAll(noDupes);
Collections.sort(customScanResults, sortByLevel);
return customScanResults;
}
public void refresh() {
scanResults = scan();
arrayAdapter = new ArrayAdapter<CustomScanResult>(
this,
R.layout.row,
scanResults
);
scanListView.setAdapter(arrayAdapter);
}
public void getLocation() {
connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// if (!netInfo.isConnected()) {
// Toast.makeText(getApplicationContext(), "You are not connected!", Toast.LENGTH_SHORT).show();
// return;
// }
// Toast.makeText(getApplicationContext(), "Connected!", Toast.LENGTH_SHORT).show();
setIp();
String urlWithParam = ipApiUrl + getIp();
RestClient.get(urlWithParam, null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
String status = response.getString("status");
String lat = response.getString("lat");
String lon = response.getString("lon");
Toast.makeText(getApplicationContext(), lat + ", " + lon, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.d("JSONException", "Failed to parse");
}
}
});
}
public void setIp() {
RestClient.get(icanhazipUrl, null, new JsonHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
ipAddress = responseString;
}
});
}
public String getIp() {
return ipAddress;
}
public JSONObject constructJSONObject(int level) {
JSONObject mainObj = new JSONObject();
JSONArray lightArray = new JSONArray();
JSONObject lightObject = new JSONObject();
try {
lightObject.put("lightId", 1);
lightObject.put("intensity", 1);
lightObject.put("red", 46);
lightObject.put("green", 204);
lightObject.put("blue", 113);
lightArray.put(lightObject);
mainObj.put("lights", lightArray);
mainObj.put("propagate", true);
} catch (JSONException e) {
Log.d("EXCEPTION: ", "JSONException constructJSONObject");
}
return mainObj;
}
}
| Added Dan Truong's changes - manipulating lights according to level
| app/src/main/java/muntaserahmed/wifisentry/DashboardActivity.java | Added Dan Truong's changes - manipulating lights according to level | <ide><path>pp/src/main/java/muntaserahmed/wifisentry/DashboardActivity.java
<ide> }
<ide>
<ide> public JSONObject constructJSONObject(int level) {
<add> double normalizedLevel = (double) (level * -1); // Make positive
<add> int percentLevel = (int)(normalizedLevel * 0.32) + 1; // 1% of light is 0.32
<add>
<ide> JSONObject mainObj = new JSONObject();
<ide> JSONArray lightArray = new JSONArray();
<ide> JSONObject lightObject = new JSONObject();
<add> JSONObject offLightObject = new JSONObject();
<ide>
<ide> try {
<del> lightObject.put("lightId", 1);
<add> lightObject.put("lightId", 1); // Make beginning light up
<ide> lightObject.put("intensity", 1);
<ide> lightObject.put("red", 46);
<ide> lightObject.put("green", 204);
<ide> lightObject.put("blue", 113);
<ide>
<add> offLightObject.put("lightId", percentLevel); // Turn off the rest where it should stop
<add> offLightObject.put("intensity", 0);
<add> offLightObject.put("red", 46);
<add> offLightObject.put("green", 204);
<add> offLightObject.put("blue", 113);
<add>
<ide> lightArray.put(lightObject);
<add> lightArray.put(offLightObject);
<ide> mainObj.put("lights", lightArray);
<ide> mainObj.put("propagate", true);
<ide> } catch (JSONException e) { |
|
Java | apache-2.0 | d97dd68782401b8e37f898fb97d4d1acfa5abcbc | 0 | mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android | package org.mtransit.android.ui.fragment;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.mtransit.android.R;
import org.mtransit.android.commons.BundleUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.StringUtils;
import org.mtransit.android.commons.ThreadSafeDateFormatter;
import org.mtransit.android.commons.TimeUtils;
import org.mtransit.android.commons.data.RouteTripStop;
import org.mtransit.android.commons.data.Schedule;
import org.mtransit.android.commons.provider.POIProviderContract;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.commons.TaskUtils;
import org.mtransit.android.commons.ui.widget.MTBaseAdapter;
import org.mtransit.android.data.DataSourceManager;
import org.mtransit.android.data.DataSourceProvider;
import org.mtransit.android.data.POIManager;
import org.mtransit.android.task.ScheduleTimestampsLoader;
import org.mtransit.android.util.LoaderUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AbsListView;
import android.widget.TextView;
public class ScheduleDayFragment extends MTFragmentV4 implements VisibilityAwareFragment, DataSourceProvider.ModulesUpdateListener,
LoaderManager.LoaderCallbacks<ArrayList<Schedule.Timestamp>> {
private static final String TAG = ScheduleDayFragment.class.getSimpleName();
@Override
public String getLogTag() {
return TAG + "-" + dayStartsAtInMs;
}
private static final String EXTRA_AUTHORITY = "extra_agency_authority";
private static final String EXTRA_POI_UUID = "extra_poi_uuid";
private static final String EXTRA_DAY_START_AT_IN_MS = "extra_day_starts_at_ms";
private static final String EXTRA_FRAGMENT_POSITION = "extra_fragment_position";
private static final String EXTRA_LAST_VISIBLE_FRAGMENT_POSITION = "extra_last_visible_fragment_position";
private static final String EXTRA_SCOLLED_TO_NOW = "extra_scolled_to_now";
public static ScheduleDayFragment newInstance(String uuid, String authority, long dayStartsAtInMs, int fragmentPosition, int lastVisibleFragmentPosition,
RouteTripStop optRts) {
ScheduleDayFragment f = new ScheduleDayFragment();
Bundle args = new Bundle();
args.putString(EXTRA_AUTHORITY, authority);
f.authority = authority;
args.putString(EXTRA_POI_UUID, uuid);
f.uuid = uuid;
f.rts = optRts;
args.putLong(EXTRA_DAY_START_AT_IN_MS, dayStartsAtInMs);
f.dayStartsAtInMs = dayStartsAtInMs;
if (fragmentPosition >= 0) {
args.putInt(EXTRA_FRAGMENT_POSITION, fragmentPosition);
f.fragmentPosition = fragmentPosition;
}
if (lastVisibleFragmentPosition >= 0) {
args.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, lastVisibleFragmentPosition);
f.lastVisibleFragmentPosition = lastVisibleFragmentPosition;
}
f.setArguments(args);
return f;
}
private TimeAdapter adapter;
private int fragmentPosition = -1;
private int lastVisibleFragmentPosition = -1;
private boolean fragmentVisible = false;
private boolean scrolledToNow = false;
private long dayStartsAtInMs = -1l;
private Calendar dayStartsAtCal = null;
private Date dayStartsAtDate;
private void resetDayStarts() {
this.dayStartsAtCal = null;
this.dayStartsAtDate = null;
}
private Calendar getDayStartsAtCal() {
if (this.dayStartsAtCal == null) {
initDayStartsAtCal();
}
return this.dayStartsAtCal;
}
private void initDayStartsAtCal() {
if (this.dayStartsAtInMs > 0l) {
this.dayStartsAtCal = TimeUtils.getNewCalendar(this.dayStartsAtInMs);
}
}
private Date getDayStartsAtDate() {
if (this.dayStartsAtDate == null) {
initDayStartsAtDate();
}
return this.dayStartsAtDate;
}
private void initDayStartsAtDate() {
if (getDayStartsAtCal() != null) {
this.dayStartsAtDate = getDayStartsAtCal().getTime();
}
}
private String authority;
private String uuid;
private RouteTripStop rts;
private boolean hasRts() {
if (this.rts == null) {
initRtsAsync();
return false;
}
return true;
}
private void initRtsAsync() {
if (this.loadRtsTask != null && this.loadRtsTask.getStatus() == MTAsyncTask.Status.RUNNING) {
return;
}
if (TextUtils.isEmpty(this.uuid) || TextUtils.isEmpty(this.authority)) {
return;
}
this.loadRtsTask = new LoadRtsTask();
TaskUtils.execute(this.loadRtsTask);
}
private LoadRtsTask loadRtsTask = null;
private class LoadRtsTask extends MTAsyncTask<Void, Void, Boolean> {
@Override
public String getLogTag() {
return ScheduleDayFragment.this.getLogTag() + ">" + LoadRtsTask.class.getSimpleName();
}
@Override
protected Boolean doInBackgroundMT(Void... params) {
return initRtsSync();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
applyNewRts();
}
}
}
private void resetRts() {
this.rts = null;
}
private RouteTripStop getRtsOrNull() {
if (!hasRts()) {
return null;
}
return this.rts;
}
private boolean initRtsSync() {
if (this.rts != null) {
return false;
}
if (!TextUtils.isEmpty(this.uuid) && !TextUtils.isEmpty(this.authority)) {
POIManager poim = DataSourceManager.findPOI(getActivity(), this.authority, POIProviderContract.Filter.getNewUUIDFilter(this.uuid));
if (poim != null && poim.poi instanceof RouteTripStop) {
this.rts = (RouteTripStop) poim.poi;
}
}
return this.rts != null;
}
private void applyNewRts() {
if (this.rts == null) {
return;
}
if (this.adapter != null) {
this.adapter.setRts(this.rts);
}
if (this.adapter == null || !this.adapter.isInitialized()) {
LoaderUtils.restartLoader(this, SCHEDULE_LOADER, null, this);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
initAdapters(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreInstanceState(savedInstanceState, getArguments());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_schedule_day, container, false);
setupView(view);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (!TextUtils.isEmpty(this.authority)) {
outState.putString(EXTRA_AUTHORITY, this.authority);
}
if (!TextUtils.isEmpty(this.uuid)) {
outState.putString(EXTRA_POI_UUID, this.uuid);
}
if (this.dayStartsAtInMs >= 0l) {
outState.putLong(EXTRA_DAY_START_AT_IN_MS, this.dayStartsAtInMs);
}
if (this.fragmentPosition >= 0) {
outState.putInt(EXTRA_FRAGMENT_POSITION, this.fragmentPosition);
}
if (this.lastVisibleFragmentPosition >= 0) {
outState.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, this.lastVisibleFragmentPosition);
}
outState.putBoolean(EXTRA_SCOLLED_TO_NOW, this.scrolledToNow);
super.onSaveInstanceState(outState);
}
private void restoreInstanceState(Bundle... bundles) {
String newAuthority = BundleUtils.getString(EXTRA_AUTHORITY, bundles);
if (!TextUtils.isEmpty(newAuthority) && !newAuthority.equals(this.authority)) {
this.authority = newAuthority;
resetRts();
}
String newUuid = BundleUtils.getString(EXTRA_POI_UUID, bundles);
if (!TextUtils.isEmpty(newUuid) && !newUuid.equals(this.uuid)) {
this.uuid = newUuid;
resetRts();
}
Long newDayStartsAtInMs = BundleUtils.getLong(EXTRA_DAY_START_AT_IN_MS, bundles);
if (newDayStartsAtInMs != null && !newDayStartsAtInMs.equals(this.dayStartsAtInMs)) {
this.dayStartsAtInMs = newDayStartsAtInMs;
resetDayStarts();
}
Integer newFragmentPosition = BundleUtils.getInt(EXTRA_FRAGMENT_POSITION, bundles);
if (newFragmentPosition != null) {
if (newFragmentPosition >= 0) {
this.fragmentPosition = newFragmentPosition;
} else {
this.fragmentPosition = -1;
}
}
Integer newLastVisibleFragmentPosition = BundleUtils.getInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, bundles);
if (newLastVisibleFragmentPosition != null) {
if (newLastVisibleFragmentPosition >= 0) {
this.lastVisibleFragmentPosition = newLastVisibleFragmentPosition;
} else {
this.lastVisibleFragmentPosition = -1;
}
}
Boolean newScrolledToNow = BundleUtils.getBoolean(EXTRA_SCOLLED_TO_NOW, bundles);
if (newScrolledToNow != null) {
this.scrolledToNow = newScrolledToNow;
}
this.adapter.setDayStartsAt(getDayStartsAtCal());
}
public int getFragmentPosition() {
return fragmentPosition;
}
private void setupView(View view) {
if (view == null) {
return;
}
((TextView) view.findViewById(R.id.dayDate)).setText(getDayDateString());
setupAdapter(view);
}
private static final ThreadSafeDateFormatter DAY_DATE_FORMAT = new ThreadSafeDateFormatter("EEEE, MMM d, yyyy");
private CharSequence getDayDateString() {
CharSequence dateS;
if (TimeUtils.isYesterday(this.dayStartsAtInMs)) {
dateS = getString(R.string.yesterday) + " " + DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
} else if (TimeUtils.isToday(this.dayStartsAtInMs)) {
dateS = getString(R.string.today) + " " + DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
} else if (TimeUtils.isTomorrow(this.dayStartsAtInMs)) {
dateS = getString(R.string.tomorrow) + " " + DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
} else {
dateS = DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
}
return dateS;
}
private void setupAdapter(View view) {
if (view == null) {
return;
}
inflateList(view);
switchView(view);
linkAdapterWithListView(view);
}
private void linkAdapterWithListView(View view) {
if (view == null || this.adapter == null) {
return;
}
View listView = view.findViewById(R.id.list);
if (listView != null) {
((AbsListView) listView).setAdapter(this.adapter);
}
}
@Override
public void onModulesUpdated() {
}
@Override
public void onPause() {
super.onPause();
onFragmentInvisible();
}
@Override
public void onResume() {
super.onResume();
if (this.fragmentPosition >= 0 && this.fragmentPosition == this.lastVisibleFragmentPosition) {
onFragmentVisible();
} // ELSE would be call later
if (this.adapter != null) {
this.adapter.setActivity(getActivity());
}
}
@Override
public void setFragmentPosition(int fragmentPosition) {
this.fragmentPosition = fragmentPosition;
setFragmentVisibleAtPosition(this.lastVisibleFragmentPosition); // force reset visibility
}
@Override
public void setFragmentVisibleAtPosition(int visibleFragmentPosition) {
if (this.lastVisibleFragmentPosition == visibleFragmentPosition //
&& (//
(this.fragmentPosition == visibleFragmentPosition && this.fragmentVisible) //
|| //
(this.fragmentPosition != visibleFragmentPosition && !this.fragmentVisible) //
) //
) {
return;
}
this.lastVisibleFragmentPosition = visibleFragmentPosition;
if (this.fragmentPosition < 0) {
return;
}
if (this.fragmentPosition == visibleFragmentPosition) {
onFragmentVisible();
} else {
onFragmentInvisible();
}
}
private void onFragmentInvisible() {
if (!this.fragmentVisible) {
return; // already invisible
}
this.fragmentVisible = false;
if (this.adapter != null) {
this.adapter.onPause();
}
}
@Override
public boolean isFragmentVisible() {
return this.fragmentVisible;
}
private void onFragmentVisible() {
if (this.fragmentVisible) {
return; // already visible
}
if (!isResumed()) {
return;
}
this.fragmentVisible = true;
switchView(getView());
if (this.adapter == null || !this.adapter.isInitialized()) {
if (hasRts()) {
LoaderUtils.restartLoader(this, SCHEDULE_LOADER, null, this);
}
} else {
this.adapter.onResume(getActivity());
}
}
private static final int SCHEDULE_LOADER = 0;
@Override
public Loader<ArrayList<Schedule.Timestamp>> onCreateLoader(int id, Bundle args) {
switch (id) {
case SCHEDULE_LOADER:
RouteTripStop rts = getRtsOrNull();
if (this.dayStartsAtInMs <= 0l || rts == null) {
return null;
}
return new ScheduleTimestampsLoader(getActivity(), rts, this.dayStartsAtInMs);
default:
MTLog.w(this, "Loader id '%s' unknown!", id);
return null;
}
}
@Override
public void onLoaderReset(Loader<ArrayList<Schedule.Timestamp>> loader) {
if (this.adapter != null) {
this.adapter.clearTimes();
this.adapter.onPause();
}
}
@Override
public void onLoadFinished(Loader<ArrayList<Schedule.Timestamp>> loader, ArrayList<Schedule.Timestamp> data) {
View view = getView();
if (view == null) {
return; // too late
}
switchView(view);
this.adapter.setTimes(data);
if (!this.scrolledToNow) {
int compareToToday = this.adapter.compareToToday();
int selectPosition;
if (compareToToday < 0) { // past
selectPosition = this.adapter.getCount(); // scroll down
} else if (compareToToday > 0) { // future
selectPosition = 0; // scroll up
} else { // today
selectPosition = getTodaySelectPosition();
}
((AbsListView) view.findViewById(R.id.list)).setSelection(selectPosition);
this.scrolledToNow = true;
}
switchView(view);
}
private int getTodaySelectPosition() {
Schedule.Timestamp nextTime = this.adapter.getNextTimeInMs();
if (nextTime != null) {
int nextTimePosition = this.adapter.getPosition(nextTime);
if (nextTimePosition > 0) {
nextTimePosition--; // show 1 more time on top of the list
if (nextTimePosition > 0) {
nextTimePosition--; // show 1 more time on top of the list
}
}
if (nextTimePosition >= 0) {
return nextTimePosition;
}
}
return 0;
}
private void initAdapters(Activity activity) {
this.adapter = new TimeAdapter(activity, null, null);
}
private void switchView(View view) {
if (view == null) {
return;
}
if (this.adapter == null || !this.adapter.isInitialized()) {
showLoading(view);
} else if (this.adapter.getCount() == 0) {
showEmpty(view);
} else {
showList(view);
}
}
private void showList(View view) {
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
inflateList(view);
view.findViewById(R.id.list).setVisibility(View.VISIBLE); // show
}
private void inflateList(View view) {
if (view.findViewById(R.id.list) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.list_stub)).inflate(); // inflate
}
}
private void showLoading(View view) {
if (view.findViewById(R.id.list) != null) { // IF inflated/present DO
view.findViewById(R.id.list).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show
}
private void showEmpty(View view) {
if (view.findViewById(R.id.list) != null) { // IF inflated/present DO
view.findViewById(R.id.list).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate
}
view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show
}
@Override
public void onDestroy() {
super.onDestroy();
TaskUtils.cancelQuietly(this.loadRtsTask, true);
}
private static class TimeAdapter extends MTBaseAdapter implements TimeUtils.TimeChangedReceiver.TimeChangedListener {
private static final String TAG = ScheduleDayFragment.class.getSimpleName() + ">" + TimeAdapter.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
private static final int ITEM_VIEW_TYPE_HOUR_SERATORS = 0;
private static final int ITEM_VIEW_TYPE_TIME = 1;
private static final int HOUR_SEPARATORS_COUNT = 24;
private int timesCount = 0;
private SparseArray<ArrayList<Schedule.Timestamp>> hourToTimes = new SparseArray<ArrayList<Schedule.Timestamp>>();
private boolean initialized = false;
private ArrayList<Date> hours = new ArrayList<Date>();
private LayoutInflater layoutInflater;
private Calendar dayStartsAt;
private WeakReference<Activity> activityWR;
private Schedule.Timestamp nextTimeInMs = null;
private RouteTripStop optRts;
private TimeZone deviceTimeZone = TimeZone.getDefault();
public TimeAdapter(Activity activity, Calendar dayStartsAt, RouteTripStop optRts) {
super();
setActivity(activity);
this.layoutInflater = LayoutInflater.from(activity);
setDayStartsAt(dayStartsAt);
setRts(optRts);
}
public void setDayStartsAt(Calendar dayStartsAt) {
this.dayStartsAt = dayStartsAt;
resetHours();
if (this.dayStartsAt != null) {
initHours();
}
}
public void setRts(RouteTripStop optRts) {
this.optRts = optRts;
}
public void onResume(Activity activity) {
setActivity(activity);
}
public void setActivity(Activity activity) {
this.activityWR = new WeakReference<Activity>(activity);
}
public void onPause() {
disableTimeChangeddReceiver();
}
private void initHours() {
resetHours();
Calendar cal;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
cal = (Calendar) this.dayStartsAt.clone();
cal.set(Calendar.HOUR_OF_DAY, hourOfTheDay);
this.hours.add(cal.getTime());
this.hourToTimes.put(hourOfTheDay, new ArrayList<Schedule.Timestamp>());
}
}
private void resetHours() {
this.hours.clear();
this.hourToTimes.clear();
}
public void clearTimes() {
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
this.hourToTimes.get(hourOfTheDay).clear();
}
this.timesCount = 0;
this.nextTimeInMs = null;
}
public void setTimes(ArrayList<Schedule.Timestamp> times) {
clearTimes();
for (Schedule.Timestamp time : times) {
addTime(time);
if (this.nextTimeInMs == null && time.t >= getNowToTheMinute()) {
this.nextTimeInMs = time;
MTLog.d(this, "setTimes() > this.nextTimeInMs: %s", this.nextTimeInMs);
}
}
this.initialized = true;
}
public boolean isInitialized() {
return this.initialized;
}
@Override
public void notifyDataSetChanged() {
findNextTimeInMs();
super.notifyDataSetChanged();
}
private void findNextTimeInMs() {
this.nextTimeInMs = null;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
for (Schedule.Timestamp time : this.hourToTimes.get(hourOfTheDay)) {
if (this.nextTimeInMs == null && time.t >= getNowToTheMinute()) {
this.nextTimeInMs = time;
return;
}
}
}
}
public Schedule.Timestamp getNextTimeInMs() {
if (this.nextTimeInMs == null) {
findNextTimeInMs();
}
return nextTimeInMs;
}
private long nowToTheMinute = -1l;
private boolean timeChangedReceiverEnabled = false;
private long getNowToTheMinute() {
if (this.nowToTheMinute < 0) {
resetNowToTheMinute();
enableTimeChangedReceiver();
}
return this.nowToTheMinute;
}
@Override
public void onTimeChanged() {
resetNowToTheMinute();
}
private void resetNowToTheMinute() {
this.nowToTheMinute = TimeUtils.currentTimeToTheMinuteMillis();
notifyDataSetChanged();
}
private void enableTimeChangedReceiver() {
if (!this.timeChangedReceiverEnabled) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
activity.registerReceiver(this.timeChangedReceiver, TimeUtils.TIME_CHANGED_INTENT_FILTER);
}
this.timeChangedReceiverEnabled = true;
}
}
private void disableTimeChangeddReceiver() {
if (this.timeChangedReceiverEnabled) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
activity.unregisterReceiver(this.timeChangedReceiver);
}
this.timeChangedReceiverEnabled = false;
this.nowToTheMinute = -1l;
}
}
private final BroadcastReceiver timeChangedReceiver = new TimeUtils.TimeChangedReceiver(this);
private void addTime(Schedule.Timestamp time) {
int hourOfTheDay = TimeUtils.getHourOfTheDay(time.t);
this.hourToTimes.get(hourOfTheDay).add(time);
this.timesCount++;
}
@Override
public int getCountMT() {
return this.timesCount + HOUR_SEPARATORS_COUNT;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public Object getItem(int position) {
return getItemMT(position);
}
@Override
public Object getItemMT(int position) {
int index = 0;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
index++; // separator
if (position >= index && position < index + this.hourToTimes.get(hourOfTheDay).size()) {
return this.hourToTimes.get(hourOfTheDay).get(position - index);
}
index += this.hourToTimes.get(hourOfTheDay).size();
}
return null;
}
private Calendar todayStartsAt = TimeUtils.getBeginningOfTodayCal();
private Calendar todayEndsAt = null;
public int compareToToday() {
if (this.dayStartsAt.before(this.todayStartsAt)) {
return -1; // past
}
if (this.todayEndsAt == null) {
this.todayEndsAt = TimeUtils.getBeginningOfTomorrowCal();
this.todayEndsAt.add(Calendar.MILLISECOND, -1);
}
if (this.dayStartsAt.after(this.todayEndsAt)) {
return +1; // future
}
return 0; // today
}
public int getPosition(Object item) {
int index = 0;
if (item == null || !(item instanceof Schedule.Timestamp)) {
return index;
}
Schedule.Timestamp time = (Schedule.Timestamp) item;
Date date = new Date(time.t);
Date thatDate;
Date nextDate;
int nextHourOfTheDay;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
index++; // separator
if (this.hourToTimes.get(hourOfTheDay).size() > 0) {
thatDate = this.hours.get(hourOfTheDay);
if (date.after(thatDate)) {
nextHourOfTheDay = hourOfTheDay + 1;
nextDate = nextHourOfTheDay < this.hours.size() ? this.hours.get(nextHourOfTheDay) : null;
if (nextDate == null || date.before(nextDate)) {
for (Schedule.Timestamp hourTime : this.hourToTimes.get(hourOfTheDay)) {
if (time.t == hourTime.t) {
return index;
}
index++; // after
}
} else {
index += this.hourToTimes.get(hourOfTheDay).size(); // after
}
} else {
index += this.hourToTimes.get(hourOfTheDay).size(); // after
}
}
}
return -1;
}
public Integer getItemHourSeparator(int position) {
int index = 0;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
if (index == position) {
return hourOfTheDay;
}
index++;
index += this.hourToTimes.get(hourOfTheDay).size();
}
return null;
}
@Override
public int getItemViewType(int position) {
Object item = getItem(position);
if (item != null && item instanceof Schedule.Timestamp) {
return ITEM_VIEW_TYPE_TIME;
}
return ITEM_VIEW_TYPE_HOUR_SERATORS;
}
@Override
public long getItemIdMT(int position) {
return position;
}
@Override
public View getViewMT(int position, View convertView, ViewGroup parent) {
switch (getItemViewType(position)) {
case ITEM_VIEW_TYPE_HOUR_SERATORS:
return getHourSeparatorView(position, convertView, parent);
case ITEM_VIEW_TYPE_TIME:
return getTimeView(position, convertView, parent);
default:
MTLog.w(this, "Unexpected view type at position '%s'!", position);
return null;
}
}
private View getTimeView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_detail_status_schedule_time, parent, false);
TimeViewHolder holder = new TimeViewHolder();
holder.timeTv = (TextView) convertView.findViewById(R.id.time);
convertView.setTag(holder);
}
updateTimeView(position, convertView);
return convertView;
}
private static final String P2 = ")";
private static final String P1 = " (";
private void updateTimeView(int position, View convertView) {
TimeViewHolder holder = (TimeViewHolder) convertView.getTag();
Schedule.Timestamp timestamp = (Schedule.Timestamp) getItem(position);
Context context = this.activityWR == null ? null : this.activityWR.get();
if (timestamp != null && context != null) {
String userTime = TimeUtils.formatTime(context, timestamp.t);
StringBuilder timeSb = new StringBuilder(userTime);
TimeZone timestampTZ = TimeZone.getTimeZone(timestamp.getLocalTimeZone());
if (timestamp.hasLocalTimeZone() && !this.deviceTimeZone.equals(timestampTZ)) {
String localTime = TimeUtils.formatTime(context, timestamp.t, timestampTZ);
if (!localTime.equalsIgnoreCase(userTime)) {
timeSb.append(P1).append(context.getString(R.string.local_time_and_time, localTime)).append(P2);
}
}
if (timestamp.hasHeadsign()) {
String timestampHeading = timestamp.getHeading(context);
String tripHeading = this.optRts == null ? null : this.optRts.getTrip().getHeading(context);
if (!StringUtils.equals(timestampHeading, tripHeading)) {
timeSb.append(P1).append(timestampHeading).append(P2);
}
}
holder.timeTv.setText(timeSb);
if (this.nextTimeInMs != null && TimeUtils.isSameDay(getNowToTheMinute(), this.nextTimeInMs.t) && this.nextTimeInMs.t == timestamp.t) { // now
holder.timeTv.setTextColor(Schedule.getDefaultNowTextColor(context));
holder.timeTv.setTypeface(Schedule.getDefaultNowTypeface());
} else if (timestamp.t < getNowToTheMinute()) { // past
holder.timeTv.setTextColor(Schedule.getDefaultPastTextColor(context));
holder.timeTv.setTypeface(Schedule.getDefaultPastTypeface());
} else { // future
holder.timeTv.setTextColor(Schedule.getDefaultFutureTextColor(context));
holder.timeTv.setTypeface(Schedule.getDefaultFutureTypeface());
}
} else {
holder.timeTv.setText(null);
}
}
private View getHourSeparatorView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_detail_status_schedule_hour_separator, parent, false);
HourSperatorViewHolder holder = new HourSperatorViewHolder();
holder.hourTv = (TextView) convertView.findViewById(R.id.hour);
convertView.setTag(holder);
}
updateHourSeparatorView(position, convertView);
return convertView;
}
private void updateHourSeparatorView(int position, View convertView) {
HourSperatorViewHolder holder = (HourSperatorViewHolder) convertView.getTag();
Integer hourOfTheDay = getItemHourSeparator(position);
Context context = this.activityWR == null ? null : this.activityWR.get();
if (hourOfTheDay != null && context != null) {
holder.hourTv.setText(getHourFormatter(context).formatThreadSafe(this.hours.get(hourOfTheDay)));
} else {
holder.hourTv.setText(null);
}
}
private static ThreadSafeDateFormatter HOUR_FORMATTER;
private static ThreadSafeDateFormatter getHourFormatter(Context context) {
if (HOUR_FORMATTER == null) {
HOUR_FORMATTER = TimeUtils.getNewHourFormat(context);
}
return HOUR_FORMATTER;
}
public static class TimeViewHolder {
TextView timeTv;
}
public static class HourSperatorViewHolder {
TextView hourTv;
}
}
}
| src/org/mtransit/android/ui/fragment/ScheduleDayFragment.java | package org.mtransit.android.ui.fragment;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.mtransit.android.R;
import org.mtransit.android.commons.BundleUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.StringUtils;
import org.mtransit.android.commons.ThreadSafeDateFormatter;
import org.mtransit.android.commons.TimeUtils;
import org.mtransit.android.commons.data.RouteTripStop;
import org.mtransit.android.commons.data.Schedule;
import org.mtransit.android.commons.provider.POIProviderContract;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.commons.TaskUtils;
import org.mtransit.android.commons.ui.widget.MTBaseAdapter;
import org.mtransit.android.data.DataSourceManager;
import org.mtransit.android.data.DataSourceProvider;
import org.mtransit.android.data.POIManager;
import org.mtransit.android.task.ScheduleTimestampsLoader;
import org.mtransit.android.util.LoaderUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AbsListView;
import android.widget.TextView;
public class ScheduleDayFragment extends MTFragmentV4 implements VisibilityAwareFragment, DataSourceProvider.ModulesUpdateListener,
LoaderManager.LoaderCallbacks<ArrayList<Schedule.Timestamp>> {
private static final String TAG = ScheduleDayFragment.class.getSimpleName();
@Override
public String getLogTag() {
return TAG + "-" + dayStartsAtInMs;
}
private static final String EXTRA_AUTHORITY = "extra_agency_authority";
private static final String EXTRA_POI_UUID = "extra_poi_uuid";
private static final String EXTRA_DAY_START_AT_IN_MS = "extra_day_starts_at_ms";
private static final String EXTRA_FRAGMENT_POSITION = "extra_fragment_position";
private static final String EXTRA_LAST_VISIBLE_FRAGMENT_POSITION = "extra_last_visible_fragment_position";
private static final String EXTRA_SCOLLED_TO_NOW = "extra_scolled_to_now";
public static ScheduleDayFragment newInstance(String uuid, String authority, long dayStartsAtInMs, int fragmentPosition, int lastVisibleFragmentPosition,
RouteTripStop optRts) {
ScheduleDayFragment f = new ScheduleDayFragment();
Bundle args = new Bundle();
args.putString(EXTRA_AUTHORITY, authority);
f.authority = authority;
args.putString(EXTRA_POI_UUID, uuid);
f.uuid = uuid;
f.rts = optRts;
args.putLong(EXTRA_DAY_START_AT_IN_MS, dayStartsAtInMs);
f.dayStartsAtInMs = dayStartsAtInMs;
if (fragmentPosition >= 0) {
args.putInt(EXTRA_FRAGMENT_POSITION, fragmentPosition);
f.fragmentPosition = fragmentPosition;
}
if (lastVisibleFragmentPosition >= 0) {
args.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, lastVisibleFragmentPosition);
f.lastVisibleFragmentPosition = lastVisibleFragmentPosition;
}
f.setArguments(args);
return f;
}
private TimeAdapter adapter;
private int fragmentPosition = -1;
private int lastVisibleFragmentPosition = -1;
private boolean fragmentVisible = false;
private boolean scrolledToNow = false;
private long dayStartsAtInMs = -1l;
private Calendar dayStartsAtCal = null;
private Date dayStartsAtDate;
private void resetDayStarts() {
this.dayStartsAtCal = null;
this.dayStartsAtDate = null;
}
private Calendar getDayStartsAtCal() {
if (this.dayStartsAtCal == null) {
initDayStartsAtCal();
}
return this.dayStartsAtCal;
}
private void initDayStartsAtCal() {
if (this.dayStartsAtInMs > 0l) {
this.dayStartsAtCal = TimeUtils.getNewCalendar(this.dayStartsAtInMs);
}
}
private Date getDayStartsAtDate() {
if (this.dayStartsAtDate == null) {
initDayStartsAtDate();
}
return this.dayStartsAtDate;
}
private void initDayStartsAtDate() {
if (getDayStartsAtCal() != null) {
this.dayStartsAtDate = getDayStartsAtCal().getTime();
}
}
private String authority;
private String uuid;
private RouteTripStop rts;
private boolean hasRts() {
if (this.rts == null) {
initRtsAsync();
return false;
}
return true;
}
private void initRtsAsync() {
if (this.loadRtsTask != null && this.loadRtsTask.getStatus() == MTAsyncTask.Status.RUNNING) {
return;
}
if (TextUtils.isEmpty(this.uuid) || TextUtils.isEmpty(this.authority)) {
return;
}
this.loadRtsTask = new LoadRtsTask();
TaskUtils.execute(this.loadRtsTask);
}
private LoadRtsTask loadRtsTask = null;
private class LoadRtsTask extends MTAsyncTask<Void, Void, Boolean> {
@Override
public String getLogTag() {
return ScheduleDayFragment.this.getLogTag() + ">" + LoadRtsTask.class.getSimpleName();
}
@Override
protected Boolean doInBackgroundMT(Void... params) {
return initRtsSync();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
applyNewRts();
}
}
}
private void resetRts() {
this.rts = null;
}
private RouteTripStop getRtsOrNull() {
if (!hasRts()) {
return null;
}
return this.rts;
}
private boolean initRtsSync() {
if (this.rts != null) {
return false;
}
if (!TextUtils.isEmpty(this.uuid) && !TextUtils.isEmpty(this.authority)) {
POIManager poim = DataSourceManager.findPOI(getActivity(), this.authority, POIProviderContract.Filter.getNewUUIDFilter(this.uuid));
if (poim != null && poim.poi instanceof RouteTripStop) {
this.rts = (RouteTripStop) poim.poi;
}
}
return this.rts != null;
}
private void applyNewRts() {
if (this.rts == null) {
return;
}
if (this.adapter != null) {
this.adapter.setRts(this.rts);
}
if (this.adapter == null || !this.adapter.isInitialized()) {
LoaderUtils.restartLoader(this, SCHEDULE_LOADER, null, this);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
initAdapters(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreInstanceState(savedInstanceState, getArguments());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_schedule_day, container, false);
setupView(view);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (!TextUtils.isEmpty(this.authority)) {
outState.putString(EXTRA_AUTHORITY, this.authority);
}
if (!TextUtils.isEmpty(this.uuid)) {
outState.putString(EXTRA_POI_UUID, this.uuid);
}
if (this.dayStartsAtInMs >= 0l) {
outState.putLong(EXTRA_DAY_START_AT_IN_MS, this.dayStartsAtInMs);
}
if (this.fragmentPosition >= 0) {
outState.putInt(EXTRA_FRAGMENT_POSITION, this.fragmentPosition);
}
if (this.lastVisibleFragmentPosition >= 0) {
outState.putInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, this.lastVisibleFragmentPosition);
}
outState.putBoolean(EXTRA_SCOLLED_TO_NOW, this.scrolledToNow);
super.onSaveInstanceState(outState);
}
private void restoreInstanceState(Bundle... bundles) {
String newAuthority = BundleUtils.getString(EXTRA_AUTHORITY, bundles);
if (!TextUtils.isEmpty(newAuthority) && !newAuthority.equals(this.authority)) {
this.authority = newAuthority;
resetRts();
}
String newUuid = BundleUtils.getString(EXTRA_POI_UUID, bundles);
if (!TextUtils.isEmpty(newUuid) && !newUuid.equals(this.uuid)) {
this.uuid = newUuid;
resetRts();
}
Long newDayStartsAtInMs = BundleUtils.getLong(EXTRA_DAY_START_AT_IN_MS, bundles);
if (newDayStartsAtInMs != null && !newDayStartsAtInMs.equals(this.dayStartsAtInMs)) {
this.dayStartsAtInMs = newDayStartsAtInMs;
resetDayStarts();
}
Integer newFragmentPosition = BundleUtils.getInt(EXTRA_FRAGMENT_POSITION, bundles);
if (newFragmentPosition != null) {
if (newFragmentPosition >= 0) {
this.fragmentPosition = newFragmentPosition;
} else {
this.fragmentPosition = -1;
}
}
Integer newLastVisibleFragmentPosition = BundleUtils.getInt(EXTRA_LAST_VISIBLE_FRAGMENT_POSITION, bundles);
if (newLastVisibleFragmentPosition != null) {
if (newLastVisibleFragmentPosition >= 0) {
this.lastVisibleFragmentPosition = newLastVisibleFragmentPosition;
} else {
this.lastVisibleFragmentPosition = -1;
}
}
Boolean newScrolledToNow = BundleUtils.getBoolean(EXTRA_SCOLLED_TO_NOW, bundles);
if (newScrolledToNow != null) {
this.scrolledToNow = newScrolledToNow;
}
this.adapter.setDayStartsAt(getDayStartsAtCal());
}
public int getFragmentPosition() {
return fragmentPosition;
}
private void setupView(View view) {
if (view == null) {
return;
}
((TextView) view.findViewById(R.id.dayDate)).setText(getDayDateString());
setupAdapter(view);
}
private static final ThreadSafeDateFormatter DAY_DATE_FORMAT = new ThreadSafeDateFormatter("EEEE, MMM d, yyyy");
private CharSequence getDayDateString() {
CharSequence dateS;
if (TimeUtils.isYesterday(this.dayStartsAtInMs)) {
dateS = getString(R.string.yesterday) + " " + DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
} else if (TimeUtils.isToday(this.dayStartsAtInMs)) {
dateS = getString(R.string.today) + " " + DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
} else if (TimeUtils.isTomorrow(this.dayStartsAtInMs)) {
dateS = getString(R.string.tomorrow) + " " + DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
} else {
dateS = DAY_DATE_FORMAT.formatThreadSafe(getDayStartsAtDate());
}
return dateS;
}
private void setupAdapter(View view) {
if (view == null) {
return;
}
inflateList(view);
switchView(view);
linkAdapterWithListView(view);
}
private void linkAdapterWithListView(View view) {
if (view == null || this.adapter == null) {
return;
}
View listView = view.findViewById(R.id.list);
if (listView != null) {
((AbsListView) listView).setAdapter(this.adapter);
}
}
@Override
public void onModulesUpdated() {
}
@Override
public void onPause() {
super.onPause();
onFragmentInvisible();
}
@Override
public void onResume() {
super.onResume();
if (this.fragmentPosition >= 0 && this.fragmentPosition == this.lastVisibleFragmentPosition) {
onFragmentVisible();
} // ELSE would be call later
if (this.adapter != null) {
this.adapter.setActivity(getActivity());
}
}
@Override
public void setFragmentPosition(int fragmentPosition) {
this.fragmentPosition = fragmentPosition;
setFragmentVisibleAtPosition(this.lastVisibleFragmentPosition); // force reset visibility
}
@Override
public void setFragmentVisibleAtPosition(int visibleFragmentPosition) {
if (this.lastVisibleFragmentPosition == visibleFragmentPosition //
&& (//
(this.fragmentPosition == visibleFragmentPosition && this.fragmentVisible) //
|| //
(this.fragmentPosition != visibleFragmentPosition && !this.fragmentVisible) //
) //
) {
return;
}
this.lastVisibleFragmentPosition = visibleFragmentPosition;
if (this.fragmentPosition < 0) {
return;
}
if (this.fragmentPosition == visibleFragmentPosition) {
onFragmentVisible();
} else {
onFragmentInvisible();
}
}
private void onFragmentInvisible() {
if (!this.fragmentVisible) {
return; // already invisible
}
this.fragmentVisible = false;
if (this.adapter != null) {
this.adapter.onPause();
}
}
@Override
public boolean isFragmentVisible() {
return this.fragmentVisible;
}
private void onFragmentVisible() {
if (this.fragmentVisible) {
return; // already visible
}
if (!isResumed()) {
return;
}
this.fragmentVisible = true;
switchView(getView());
if (this.adapter == null || !this.adapter.isInitialized()) {
if (hasRts()) {
LoaderUtils.restartLoader(this, SCHEDULE_LOADER, null, this);
}
} else {
this.adapter.onResume(getActivity());
}
}
private static final int SCHEDULE_LOADER = 0;
@Override
public Loader<ArrayList<Schedule.Timestamp>> onCreateLoader(int id, Bundle args) {
switch (id) {
case SCHEDULE_LOADER:
RouteTripStop rts = getRtsOrNull();
if (this.dayStartsAtInMs <= 0l || rts == null) {
return null;
}
return new ScheduleTimestampsLoader(getActivity(), rts, this.dayStartsAtInMs);
default:
MTLog.w(this, "Loader id '%s' unknown!", id);
return null;
}
}
@Override
public void onLoaderReset(Loader<ArrayList<Schedule.Timestamp>> loader) {
if (this.adapter != null) {
this.adapter.clearTimes();
this.adapter.onPause();
}
}
@Override
public void onLoadFinished(Loader<ArrayList<Schedule.Timestamp>> loader, ArrayList<Schedule.Timestamp> data) {
View view = getView();
if (view == null) {
return; // too late
}
switchView(view);
this.adapter.setTimes(data);
if (!this.scrolledToNow) {
int compareToToday = this.adapter.compareToToday();
int selectPosition;
if (compareToToday < 0) { // past
selectPosition = this.adapter.getCount(); // scroll down
} else if (compareToToday > 0) { // future
selectPosition = 0; // scroll up
} else { // today
selectPosition = getTodaySelectPosition();
}
((AbsListView) view.findViewById(R.id.list)).setSelection(selectPosition);
this.scrolledToNow = true;
}
switchView(view);
}
private int getTodaySelectPosition() {
Schedule.Timestamp nextTime = this.adapter.getNextTimeInMs();
if (nextTime != null) {
int nextTimePosition = this.adapter.getPosition(nextTime);
if (nextTimePosition > 0) {
nextTimePosition--; // show 1 more time on top of the list
if (nextTimePosition > 0) {
nextTimePosition--; // show 1 more time on top of the list
}
}
if (nextTimePosition >= 0) {
return nextTimePosition;
}
}
return 0;
}
private void initAdapters(Activity activity) {
this.adapter = new TimeAdapter(activity, null, null);
}
private void switchView(View view) {
if (view == null) {
return;
}
if (this.adapter == null || !this.adapter.isInitialized()) {
showLoading(view);
} else if (this.adapter.getCount() == 0) {
showEmpty(view);
} else {
showList(view);
}
}
private void showList(View view) {
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
inflateList(view);
view.findViewById(R.id.list).setVisibility(View.VISIBLE); // show
}
private void inflateList(View view) {
if (view.findViewById(R.id.list) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.list_stub)).inflate(); // inflate
}
}
private void showLoading(View view) {
if (view.findViewById(R.id.list) != null) { // IF inflated/present DO
view.findViewById(R.id.list).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show
}
private void showEmpty(View view) {
if (view.findViewById(R.id.list) != null) { // IF inflated/present DO
view.findViewById(R.id.list).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate
}
view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show
}
@Override
public void onDestroy() {
super.onDestroy();
TaskUtils.cancelQuietly(this.loadRtsTask, true);
}
private static class TimeAdapter extends MTBaseAdapter implements TimeUtils.TimeChangedReceiver.TimeChangedListener {
private static final String TAG = ScheduleDayFragment.class.getSimpleName() + ">" + TimeAdapter.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
private static final int ITEM_VIEW_TYPE_HOUR_SERATORS = 0;
private static final int ITEM_VIEW_TYPE_TIME = 1;
private static final int HOUR_SEPARATORS_COUNT = 24;
private int timesCount = 0;
private SparseArray<ArrayList<Schedule.Timestamp>> hourToTimes = new SparseArray<ArrayList<Schedule.Timestamp>>();
private boolean initialized = false;
private ArrayList<Date> hours = new ArrayList<Date>();
private LayoutInflater layoutInflater;
private Calendar dayStartsAt;
private WeakReference<Activity> activityWR;
private Schedule.Timestamp nextTimeInMs = null;
private RouteTripStop optRts;
private TimeZone deviceTimeZone = TimeZone.getDefault();
public TimeAdapter(Activity activity, Calendar dayStartsAt, RouteTripStop optRts) {
super();
setActivity(activity);
this.layoutInflater = LayoutInflater.from(activity);
setDayStartsAt(dayStartsAt);
setRts(optRts);
}
public void setDayStartsAt(Calendar dayStartsAt) {
this.dayStartsAt = dayStartsAt;
resetHours();
if (this.dayStartsAt != null) {
initHours();
}
}
public void setRts(RouteTripStop optRts) {
this.optRts = optRts;
}
public void onResume(Activity activity) {
setActivity(activity);
}
public void setActivity(Activity activity) {
this.activityWR = new WeakReference<Activity>(activity);
}
public void onPause() {
disableTimeChangeddReceiver();
}
private void initHours() {
resetHours();
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
Calendar cal = (Calendar) this.dayStartsAt.clone();
cal.set(Calendar.HOUR_OF_DAY, hourOfTheDay);
this.hours.add(cal.getTime());
this.hourToTimes.put(hourOfTheDay, new ArrayList<Schedule.Timestamp>());
}
}
private void resetHours() {
this.hours.clear();
this.hourToTimes.clear();
}
public void clearTimes() {
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
this.hourToTimes.get(hourOfTheDay).clear();
}
this.timesCount = 0;
this.nextTimeInMs = null;
}
public void setTimes(ArrayList<Schedule.Timestamp> times) {
clearTimes();
for (Schedule.Timestamp time : times) {
addTime(time);
if (this.nextTimeInMs == null && time.t >= getNowToTheMinute()) {
this.nextTimeInMs = time;
MTLog.d(this, "setTimes() > this.nextTimeInMs: %s", this.nextTimeInMs);
}
}
this.initialized = true;
}
public boolean isInitialized() {
return this.initialized;
}
@Override
public void notifyDataSetChanged() {
findNextTimeInMs();
super.notifyDataSetChanged();
}
private void findNextTimeInMs() {
this.nextTimeInMs = null;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
for (Schedule.Timestamp time : this.hourToTimes.get(hourOfTheDay)) {
if (this.nextTimeInMs == null && time.t >= getNowToTheMinute()) {
this.nextTimeInMs = time;
return;
}
}
}
}
public Schedule.Timestamp getNextTimeInMs() {
if (this.nextTimeInMs == null) {
findNextTimeInMs();
}
return nextTimeInMs;
}
private long nowToTheMinute = -1l;
private boolean timeChangedReceiverEnabled = false;
private long getNowToTheMinute() {
if (this.nowToTheMinute < 0) {
resetNowToTheMinute();
enableTimeChangedReceiver();
}
return this.nowToTheMinute;
}
@Override
public void onTimeChanged() {
resetNowToTheMinute();
}
private void resetNowToTheMinute() {
this.nowToTheMinute = TimeUtils.currentTimeToTheMinuteMillis();
notifyDataSetChanged();
}
private void enableTimeChangedReceiver() {
if (!this.timeChangedReceiverEnabled) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
activity.registerReceiver(this.timeChangedReceiver, TimeUtils.TIME_CHANGED_INTENT_FILTER);
}
this.timeChangedReceiverEnabled = true;
}
}
private void disableTimeChangeddReceiver() {
if (this.timeChangedReceiverEnabled) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
activity.unregisterReceiver(this.timeChangedReceiver);
}
this.timeChangedReceiverEnabled = false;
this.nowToTheMinute = -1l;
}
}
private final BroadcastReceiver timeChangedReceiver = new TimeUtils.TimeChangedReceiver(this);
private void addTime(Schedule.Timestamp time) {
int hourOfTheDay = TimeUtils.getHourOfTheDay(time.t);
this.hourToTimes.get(hourOfTheDay).add(time);
this.timesCount++;
}
@Override
public int getCountMT() {
return this.timesCount + HOUR_SEPARATORS_COUNT;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public Object getItem(int position) {
return getItemMT(position);
}
@Override
public Object getItemMT(int position) {
int index = 0;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
index++; // separator
if (position >= index && position < index + this.hourToTimes.get(hourOfTheDay).size()) {
return this.hourToTimes.get(hourOfTheDay).get(position - index);
}
index += this.hourToTimes.get(hourOfTheDay).size();
}
return null;
}
public int compareToToday() {
Calendar todayStartsAt = TimeUtils.getBeginningOfTodayCal();
if (this.dayStartsAt.before(todayStartsAt)) {
return -1; // past
}
Calendar todayEndsAt = TimeUtils.getBeginningOfTomorrowCal();
todayEndsAt.add(Calendar.MILLISECOND, -1);
if (this.dayStartsAt.after(todayEndsAt)) {
return +1; // future
}
return 0; // today
}
public int getPosition(Object item) {
int index = 0;
if (item == null || !(item instanceof Schedule.Timestamp)) {
return index;
}
Schedule.Timestamp time = (Schedule.Timestamp) item;
Date date = new Date(time.t);
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
index++; // separator
if (this.hourToTimes.get(hourOfTheDay).size() > 0) {
Date thatDate = this.hours.get(hourOfTheDay);
if (date.after(thatDate)) {
int nextHourOfTheDay = hourOfTheDay + 1;
Date nextDate = nextHourOfTheDay < this.hours.size() ? this.hours.get(nextHourOfTheDay) : null;
if (nextDate == null || date.before(nextDate)) {
for (Schedule.Timestamp hourTime : this.hourToTimes.get(hourOfTheDay)) {
if (time.t == hourTime.t) {
return index;
}
index++; // after
}
} else {
index += this.hourToTimes.get(hourOfTheDay).size(); // after
}
} else {
index += this.hourToTimes.get(hourOfTheDay).size(); // after
}
}
}
return -1;
}
public Integer getItemHourSeparator(int position) {
int index = 0;
for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
if (index == position) {
return hourOfTheDay;
}
index++;
index += this.hourToTimes.get(hourOfTheDay).size();
}
return null;
}
@Override
public int getItemViewType(int position) {
Object item = getItem(position);
if (item != null && item instanceof Schedule.Timestamp) {
return ITEM_VIEW_TYPE_TIME;
}
return ITEM_VIEW_TYPE_HOUR_SERATORS;
}
@Override
public long getItemIdMT(int position) {
return position;
}
@Override
public View getViewMT(int position, View convertView, ViewGroup parent) {
switch (getItemViewType(position)) {
case ITEM_VIEW_TYPE_HOUR_SERATORS:
return getHourSeparatorView(position, convertView, parent);
case ITEM_VIEW_TYPE_TIME:
return getTimeView(position, convertView, parent);
default:
MTLog.w(this, "Unexpected view type at position '%s'!", position);
return null;
}
}
private View getTimeView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_detail_status_schedule_time, parent, false);
TimeViewHolder holder = new TimeViewHolder();
holder.timeTv = (TextView) convertView.findViewById(R.id.time);
convertView.setTag(holder);
}
updateTimeView(position, convertView);
return convertView;
}
private static final String P2 = ")";
private static final String P1 = " (";
private void updateTimeView(int position, View convertView) {
TimeViewHolder holder = (TimeViewHolder) convertView.getTag();
Schedule.Timestamp timestamp = (Schedule.Timestamp) getItem(position);
Context context = this.activityWR == null ? null : this.activityWR.get();
if (timestamp != null && context != null) {
String userTime = TimeUtils.formatTime(context, timestamp.t);
StringBuilder timeSb = new StringBuilder(userTime);
if (timestamp.hasLocalTimeZone() && !this.deviceTimeZone.equals(TimeZone.getTimeZone(timestamp.getLocalTimeZone()))) {
String localTime = TimeUtils.formatTime(context, timestamp.t, timestamp.getLocalTimeZone());
if (!localTime.equalsIgnoreCase(userTime)) {
timeSb.append(P1).append(context.getString(R.string.local_time_and_time, localTime)).append(P2);
}
}
if (timestamp.hasHeadsign()) {
String timestampHeading = timestamp.getHeading(context);
String tripHeading = this.optRts == null ? null : this.optRts.getTrip().getHeading(context);
if (!StringUtils.equals(timestampHeading, tripHeading)) {
timeSb.append(P1).append(timestampHeading).append(P2);
}
}
holder.timeTv.setText(timeSb);
if (this.nextTimeInMs != null && TimeUtils.isSameDay(getNowToTheMinute(), this.nextTimeInMs.t) && this.nextTimeInMs.t == timestamp.t) { // now
holder.timeTv.setTextColor(Schedule.getDefaultNowTextColor(context));
holder.timeTv.setTypeface(Schedule.getDefaultNowTypeface());
} else if (timestamp.t < getNowToTheMinute()) { // past
holder.timeTv.setTextColor(Schedule.getDefaultPastTextColor(context));
holder.timeTv.setTypeface(Schedule.getDefaultPastTypeface());
} else { // future
holder.timeTv.setTextColor(Schedule.getDefaultFutureTextColor(context));
holder.timeTv.setTypeface(Schedule.getDefaultFutureTypeface());
}
} else {
holder.timeTv.setText(null);
}
}
private View getHourSeparatorView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_detail_status_schedule_hour_separator, parent, false);
HourSperatorViewHolder holder = new HourSperatorViewHolder();
holder.hourTv = (TextView) convertView.findViewById(R.id.hour);
convertView.setTag(holder);
}
updateHourSeparatorView(position, convertView);
return convertView;
}
private void updateHourSeparatorView(int position, View convertView) {
HourSperatorViewHolder holder = (HourSperatorViewHolder) convertView.getTag();
Integer hourOfTheDay = getItemHourSeparator(position);
Context context = this.activityWR == null ? null : this.activityWR.get();
if (hourOfTheDay != null && context != null) {
holder.hourTv.setText(getHourFormatter(context).formatThreadSafe(this.hours.get(hourOfTheDay)));
} else {
holder.hourTv.setText(null);
}
}
private static ThreadSafeDateFormatter HOUR_FORMATTER;
private static ThreadSafeDateFormatter getHourFormatter(Context context) {
if (HOUR_FORMATTER == null) {
HOUR_FORMATTER = TimeUtils.getNewHourFormat(context);
}
return HOUR_FORMATTER;
}
public static class TimeViewHolder {
TextView timeTv;
}
public static class HourSperatorViewHolder {
TextView hourTv;
}
}
}
| Minor performance improvement.
| src/org/mtransit/android/ui/fragment/ScheduleDayFragment.java | Minor performance improvement. | <ide><path>rc/org/mtransit/android/ui/fragment/ScheduleDayFragment.java
<ide>
<ide> private void initHours() {
<ide> resetHours();
<add> Calendar cal;
<ide> for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
<del> Calendar cal = (Calendar) this.dayStartsAt.clone();
<add> cal = (Calendar) this.dayStartsAt.clone();
<ide> cal.set(Calendar.HOUR_OF_DAY, hourOfTheDay);
<ide> this.hours.add(cal.getTime());
<ide> this.hourToTimes.put(hourOfTheDay, new ArrayList<Schedule.Timestamp>());
<ide> return null;
<ide> }
<ide>
<add> private Calendar todayStartsAt = TimeUtils.getBeginningOfTodayCal();
<add> private Calendar todayEndsAt = null;
<add>
<ide> public int compareToToday() {
<del> Calendar todayStartsAt = TimeUtils.getBeginningOfTodayCal();
<del> if (this.dayStartsAt.before(todayStartsAt)) {
<add> if (this.dayStartsAt.before(this.todayStartsAt)) {
<ide> return -1; // past
<ide> }
<del> Calendar todayEndsAt = TimeUtils.getBeginningOfTomorrowCal();
<del> todayEndsAt.add(Calendar.MILLISECOND, -1);
<del> if (this.dayStartsAt.after(todayEndsAt)) {
<add> if (this.todayEndsAt == null) {
<add> this.todayEndsAt = TimeUtils.getBeginningOfTomorrowCal();
<add> this.todayEndsAt.add(Calendar.MILLISECOND, -1);
<add> }
<add> if (this.dayStartsAt.after(this.todayEndsAt)) {
<ide> return +1; // future
<ide> }
<ide> return 0; // today
<ide> }
<ide> Schedule.Timestamp time = (Schedule.Timestamp) item;
<ide> Date date = new Date(time.t);
<add> Date thatDate;
<add> Date nextDate;
<add> int nextHourOfTheDay;
<ide> for (int hourOfTheDay = 0; hourOfTheDay < HOUR_SEPARATORS_COUNT; hourOfTheDay++) {
<ide> index++; // separator
<ide> if (this.hourToTimes.get(hourOfTheDay).size() > 0) {
<del> Date thatDate = this.hours.get(hourOfTheDay);
<add> thatDate = this.hours.get(hourOfTheDay);
<ide> if (date.after(thatDate)) {
<del> int nextHourOfTheDay = hourOfTheDay + 1;
<del> Date nextDate = nextHourOfTheDay < this.hours.size() ? this.hours.get(nextHourOfTheDay) : null;
<add> nextHourOfTheDay = hourOfTheDay + 1;
<add> nextDate = nextHourOfTheDay < this.hours.size() ? this.hours.get(nextHourOfTheDay) : null;
<ide> if (nextDate == null || date.before(nextDate)) {
<ide> for (Schedule.Timestamp hourTime : this.hourToTimes.get(hourOfTheDay)) {
<ide> if (time.t == hourTime.t) {
<ide> if (timestamp != null && context != null) {
<ide> String userTime = TimeUtils.formatTime(context, timestamp.t);
<ide> StringBuilder timeSb = new StringBuilder(userTime);
<del> if (timestamp.hasLocalTimeZone() && !this.deviceTimeZone.equals(TimeZone.getTimeZone(timestamp.getLocalTimeZone()))) {
<del> String localTime = TimeUtils.formatTime(context, timestamp.t, timestamp.getLocalTimeZone());
<add> TimeZone timestampTZ = TimeZone.getTimeZone(timestamp.getLocalTimeZone());
<add> if (timestamp.hasLocalTimeZone() && !this.deviceTimeZone.equals(timestampTZ)) {
<add> String localTime = TimeUtils.formatTime(context, timestamp.t, timestampTZ);
<ide> if (!localTime.equalsIgnoreCase(userTime)) {
<ide> timeSb.append(P1).append(context.getString(R.string.local_time_and_time, localTime)).append(P2);
<ide> } |
|
Java | apache-2.0 | 6a79dcb02e23269da6abfef50a4e51348cdef474 | 0 | ProPra16/programmierpraktikum-abschlussprojekt-team-1,ProPra16/programmierpraktikum-abschlussprojekt-team-1 | package gui;
import data.ConstantsManager;
import data.Project;
import data.Test;
import io.FunPictures;
import io.XMLHandler;
//import io.XMLHandler;
import data.Code;
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TabPane.TabClosingPolicy;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import tracking.ErrorEvent;
import tracking.Event;
import tracking.PhaseStartEvent;
import tracking.TrackingHandler;
/**
* Repräsentiert die Hauptanwendung. Initialisiert das Hauptfenster und für die Hauptanwendung notwendige Komponenten.
*
*/
public class Gui extends Application{
private FunPictures fun; //fun
private Phase phase;
private Timer timer;
private Project project;
CodePane code_pane;
TestPane test_pane;
ConsolePane console_pane;
Button next, run, test, back, settings, save, fun_b;
Text phase1, phase2, phase3;
/** field askForBabysteps: Variable that states if the application should
* continue asking for babysteps setting. Is set to false after a correct
* answer occurred.
*/
private boolean askForBabysteps = true;
private Button compile;
/** Startet das Programm.
* @param args: Eventuell übergebene Kommandozeilenargumente (werden zumindest bisher nicht weiter beachtet).
*/
public static void main(String[] args){
launch();
}
/**Ruft {@link AlertHandler#newProject_alert()} und {@link ConstantsManager#getConstants()} auf.
*
*
*/
public void start(Stage stage){
fun = new FunPictures();
AlertHandler.newProject_alert();
project = ConstantsManager.getConstants().getProject();
switch (AlertHandler.returnValue){
case AlertHandler.NEW_PROJECT:
ProjectSettings projectSettings = new ProjectSettings();//TODO:lukaaas - muss das dahin? oder wird das auch so gespeichert? :)
project = projectSettings.getProject();
ConstantsManager.getConstants().setProject(project);
stage.setScene(main_scene());
fillWithContent(ConstantsManager.getConstants().getProject());
stage.show();
break;
case AlertHandler.LOAD_TEMPLATE:
Catalog catalog = new Catalog();
catalog.showAndWait();
if(catalog.load()){
project = catalog.getProject();
stage.setScene(main_scene());
fillWithContent(project);
stage.show();
}
break;
case AlertHandler.LOAD_PROJECT:
Catalog myTasks = new Catalog("./res/myTasks.xml");
myTasks.showAndWait();
if(myTasks.load()){
project = myTasks.getProject();
stage.setScene(main_scene());
fillWithContent(project);
stage.show();
}
break;
}
if(ConstantsManager.getConstants().getProject().getBabysteps()) {
stage.setOnCloseRequest(e->{
timer.stop();
});
}
}
/** Erstellt ein Scene-Objekt, das ein Borderpane-Objekt mit einem Tabpane im Zentrum ({@link #create_center()})
* und eimem Gridpane auf der rechten Seite{@link #create_right_side()} erthaelt.
*
* @return
*/
private Scene main_scene(){
phase = new Phase();
BorderPane root = new BorderPane();
TabPane main = create_center();
root.setCenter(main);
root.setBottom(create_bottom());
root.setRight(create_right_side());
Scene scene = new Scene(root,700,700); //TODO: groesse von bildschirmgroesse abhaengig machen
return scene;
}
private HBox create_bottom(){
HBox hBox = new HBox();
Button settings = new Button("Settings...");
settings.setOnAction((event) -> {
new ProjectSettings();
});
hBox.getChildren().add(settings);
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setPadding(new Insets(10, 10, 10, 10));
return hBox;
}
/** Erstellt ein Tabpane, das in drei Tabs ein leeres Test-, Code-, und Konsolenpane enthaelt
* Die Tabs koennen nicht geschlossen werden.
* @return gibt das ertellte Tabpane zurueck
*/
private TabPane create_center(){
TabPane menue = new TabPane();
menue.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
code_pane = new CodePane();
test_pane = new TestPane();
console_pane = new ConsolePane();
Tab code = new Tab("Code");
Tab test = new Tab("Tests");
Tab console = new Tab("Konsole");
code.setContent(code_pane);
test.setContent(test_pane);
console.setContent(console_pane);
code.setContent(code_pane);
test.setContent(test_pane);
console.setContent(console_pane);
menue.getTabs().addAll(code, test, console);
return menue;
}
/** Erstellt das Gridpane, das die Bedienelemente und Informationen zur aktuellen Phase enthaelt:
* - Buttons zum compilieren, testen und uebergehen in die naechste Phase
* (ersten beiden bewirken nur Konsolen-Output)
* - eine Grafik, die die aktuelle Phase anzeigt und (bei aktivierten Babysteps) den Timer
* @return gibt das erstellte Gridpane zurueck
*/
private GridPane create_right_side(){
if (project.getBabysteps()){
timer= new Timer(project.getDuration(), phase);
timer.start();
}
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
run = new Button("run");
test = new Button("test");
next = new Button("next");
back = new Button("back");
save = new Button("save");
fun_b = new Button("fun"); //fun
compile = new Button("compile");
phase1 = new Text("Write failing Test");
phase2 = new Text("Write passing Code");
phase3 = new Text("Refactor");
grid.addColumn(1, phase1, phase2, phase3, compile, test, next, back, save, fun_b);
if(project.getBabysteps()) grid.add(timer,2, 2);
setPhaseTest();
fun_b.setOnAction(e->{//fun
fun.showRandom();
});
save.setOnAction(e->{//fun
XMLHandler.writeProject(project);
});
compile.setOnAction(e->{
updateClassProject();
project.compile();
});
test.setOnAction(e->{
updateClassProject();
updateTestProject();
project.test();
});
/**
*
*/
back.setOnAction(e->{
phase.back();
project.backToOldCode(project.CLASS);
project.backToOldCode(project.TEST);
updateGui();
setPhaseTest();
});
next.setOnAction(e->{
updateTestProject();
updateClassProject();
Test test = ((Test)(project.getTestList().get(0)));
if(phase.get()==Phase.TESTS && test.getNewTestCount()==1){
if(project.testHasCompileErrors()){
phase.next();
setPhaseCode();
}
else if(!project.tests_ok()) {
phase.next();
setPhaseCode();
}
}
else if(phase.get() == Phase.CODE && project.tests_ok()){
phase.next();
setPhaseRefactor();
}
else if(phase.get() == Phase.REFACTOR && project.tests_ok()){
phase.next();
setPhaseTest();
}
});
return grid;
}
private void updateTestProject(){
project.setNewTestOrClassCode(0, test_pane.getNewTest(), project.TEST);
}
private void updateClassProject(){
String content = "";
for(int i= 0;i<code_pane.getTabs().size()-1;i++){ //-1, da der letzte der "+"-Tab ist
if(( code_pane.getTabs().get(i).getContent()) != null){
content = ((TextArea) code_pane.getTabs().get(i).getContent()).getText();
};
project.setNewTestOrClassCode(i, content,project.CLASS);
}
}
/** Zeigt die im Project gespeicherten Inhalte im Code- und TestPane an.
* @param project: das aktuelle Projekt
*/
private void fillWithContent(Project project){
for(Code klasse : project.getClassList()){
code_pane.addTabWithContent(klasse.getName(), klasse.getContent());
}
code_pane.run();
if(project.getTestList().size() == 0){
project.addTest(new Test("Test"));
}
test_pane.setText(((Test)project.getTestList().get(0)).getContent());
code_pane.setEditable(false);
}
/**
* Zeigt das aktuelle Projekt in der Gui an.
*/
private void updateGui(){
for(int i = 0; i < project.getClassList().size(); i++){
Code klasse = project.getClassList().get(i);
code_pane.setText(i, klasse.getContent());
}
test_pane.setText(((Test)project.getTestList().get(0)).getContent());
}
/**Fuehrt Handlungen aus, die beim Uebergang in die TestPhase erfolgen
*
* (aendert Infotext & Textfarbe zum anzeigen aktueller Phase, (dis)abelt Textareas,
* aktualisiert Project)
*
*/
private void setPhaseCode(){
if(project.getBabysteps()) timer.reset();
phase1.setFill(Color.BLACK);
phase2.setFill(Color.GREEN);
code_pane.setEditable(true);
test_pane.setEditable(false);
back.setDisable(false);
}
/**Fuehrt Handlungen aus, die beim Uebergang in die Codephase erfolgen
* (aendert Infotext & Textfarbe zum anzeigen aktueller Phase, (dis)abelt Textareas)
*/
private void setPhaseRefactor(){
phase2.setFill(Color.BLACK);
phase3.setFill(Color.GREEN);
project.overrideOldCode(project.CLASS);
back.setDisable(true);
project.overrideOldCode(project.TEST);
updateGui();
}
/**Fuehrt Handlungen aus, die beim Uebergang in die Refactorphase erfolgen
* (aendert Infotext & Textfarbe zum anzeigen aktueller Phase, (dis)abelt Textareas)
*/
private void setPhaseTest(){
if(project.getBabysteps()) timer.reset();
phase3.setFill(Color.BLACK);
phase1.setFill(Color.GREEN);
phase2.setFill(Color.BLACK);
code_pane.setEditable(false);
test_pane.setEditable(true);
project.overrideOldCode(project.CLASS);
back.setDisable(true);
test_pane.clear();
}
} | TDD-Trainer/src/gui/Gui.java | package gui;
import data.ConstantsManager;
import data.Project;
import data.Test;
import io.FunPictures;
//import io.XMLHandler;
import data.Code;
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TabPane.TabClosingPolicy;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import tracking.ErrorEvent;
import tracking.Event;
import tracking.PhaseStartEvent;
import tracking.TrackingHandler;
/**
* Repräsentiert die Hauptanwendung. Initialisiert das Hauptfenster und für die Hauptanwendung notwendige Komponenten.
*
*/
public class Gui extends Application{
private FunPictures fun; //fun
private Phase phase;
private Timer timer;
private Project project;
CodePane code_pane;
TestPane test_pane;
ConsolePane console_pane;
Button next, run, test, back, settings, fun_b;
Text phase1, phase2, phase3;
/** field askForBabysteps: Variable that states if the application should
* continue asking for babysteps setting. Is set to false after a correct
* answer occurred.
*/
private boolean askForBabysteps = true;
private Button compile;
/** Startet das Programm.
* @param args: Eventuell übergebene Kommandozeilenargumente (werden zumindest bisher nicht weiter beachtet).
*/
public static void main(String[] args){
launch();
}
/**Ruft {@link AlertHandler#newProject_alert()} und {@link ConstantsManager#getConstants()} auf.
*
*
*/
public void start(Stage stage){
fun = new FunPictures();
AlertHandler.newProject_alert();
project = ConstantsManager.getConstants().getProject();
switch (AlertHandler.returnValue){
case AlertHandler.NEW_PROJECT:
ProjectSettings projectSettings = new ProjectSettings();//TODO:lukaaas - muss das dahin? oder wird das auch so gespeichert? :)
project = projectSettings.getProject();
ConstantsManager.getConstants().setProject(project);
stage.setScene(main_scene());
fillWithContent(ConstantsManager.getConstants().getProject());
stage.show();
break;
case AlertHandler.LOAD_TEMPLATE:
Catalog catalog = new Catalog();
catalog.showAndWait();
if(catalog.load()){
project = catalog.getProject();
stage.setScene(main_scene());
fillWithContent(project);
stage.show();
}
break;
case AlertHandler.LOAD_PROJECT:
break;
}
if(ConstantsManager.getConstants().getProject().getBabysteps()) {
stage.setOnCloseRequest(e->{
timer.stop();
});
}
}
/** Erstellt ein Scene-Objekt, das ein Borderpane-Objekt mit einem Tabpane im Zentrum ({@link #create_center()})
* und eimem Gridpane auf der rechten Seite{@link #create_right_side()} erthaelt.
*
* @return
*/
private Scene main_scene(){
phase = new Phase();
BorderPane root = new BorderPane();
TabPane main = create_center();
root.setCenter(main);
root.setBottom(create_bottom());
root.setRight(create_right_side());
Scene scene = new Scene(root,700,700); //TODO: groesse von bildschirmgroesse abhaengig machen
return scene;
}
private HBox create_bottom(){
HBox hBox = new HBox();
Button settings = new Button("Settings...");
settings.setOnAction((event) -> {
new ProjectSettings();
});
hBox.getChildren().add(settings);
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setPadding(new Insets(10, 10, 10, 10));
return hBox;
}
/** Erstellt ein Tabpane, das in drei Tabs ein leeres Test-, Code-, und Konsolenpane enthaelt
* Die Tabs koennen nicht geschlossen werden.
* @return gibt das ertellte Tabpane zurueck
*/
private TabPane create_center(){
TabPane menue = new TabPane();
menue.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
code_pane = new CodePane();
test_pane = new TestPane();
console_pane = new ConsolePane();
Tab code = new Tab("Code");
Tab test = new Tab("Tests");
Tab console = new Tab("Konsole");
code.setContent(code_pane);
test.setContent(test_pane);
console.setContent(console_pane);
code.setContent(code_pane);
test.setContent(test_pane);
console.setContent(console_pane);
menue.getTabs().addAll(code, test, console);
return menue;
}
/** Erstellt das Gridpane, das die Bedienelemente und Informationen zur aktuellen Phase enthaelt:
* - Buttons zum compilieren, testen und uebergehen in die naechste Phase
* (ersten beiden bewirken nur Konsolen-Output)
* - eine Grafik, die die aktuelle Phase anzeigt und (bei aktivierten Babysteps) den Timer
* @return gibt das erstellte Gridpane zurueck
*/
private GridPane create_right_side(){
if (project.getBabysteps()){
timer= new Timer(project.getDuration(), phase);
timer.start();
}
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
run = new Button("run");
test = new Button("test");
next = new Button("next");
back = new Button("back");
fun_b = new Button("fun"); //fun
compile = new Button("compile");
phase1 = new Text("Write failing Test");
phase2 = new Text("Write passing Code");
phase3 = new Text("Refactor");
grid.addColumn(1, phase1, phase2, phase3, compile, test, next, back, fun_b);
if(project.getBabysteps()) grid.add(timer,2, 2);
setPhaseTest();
fun_b.setOnAction(e->{//fun
fun.showRandom();
});
compile.setOnAction(e->{
updateClassProject();
project.compile();
});
test.setOnAction(e->{
updateClassProject();
updateTestProject();
project.test();
});
/**
*
*/
back.setOnAction(e->{
phase.back();
project.backToOldCode(project.CLASS);
project.backToOldCode(project.TEST);
updateGui();
setPhaseTest();
});
next.setOnAction(e->{
updateTestProject();
updateClassProject();
Test test = ((Test)(project.getTestList().get(0)));
if(phase.get()==Phase.TESTS && test.getNewTestCount()==1){
if(project.testHasCompileErrors()){
phase.next();
setPhaseCode();
}
else if(!project.tests_ok()) {
phase.next();
setPhaseCode();
}
}
else if(phase.get() == Phase.CODE && project.tests_ok()){
phase.next();
setPhaseRefactor();
}
else if(phase.get() == Phase.REFACTOR && project.tests_ok()){
phase.next();
setPhaseTest();
}
});
return grid;
}
private void updateTestProject(){
project.setNewTestOrClassCode(0, test_pane.getNewTest(), project.TEST);
}
private void updateClassProject(){
String content = "";
for(int i= 0;i<code_pane.getTabs().size()-1;i++){ //-1, da der letzte der "+"-Tab ist
if(( code_pane.getTabs().get(i).getContent()) != null){
content = ((TextArea) code_pane.getTabs().get(i).getContent()).getText();
};
project.setNewTestOrClassCode(i, content,project.CLASS);
}
}
/** Zeigt die im Project gespeicherten Inhalte im Code- und TestPane an.
* @param project: das aktuelle Projekt
*/
private void fillWithContent(Project project){
for(Code klasse : project.getClassList()){
code_pane.addTabWithContent(klasse.getName(), klasse.getContent());
}
code_pane.run();
if(project.getTestList().size() == 0){
project.addTest(new Test("Test"));
}
test_pane.setText(((Test)project.getTestList().get(0)).getContent());
code_pane.setEditable(false);
}
/**
* Zeigt das aktuelle Projekt in der Gui an.
*/
private void updateGui(){
for(int i = 0; i < project.getClassList().size(); i++){
Code klasse = project.getClassList().get(i);
code_pane.setText(i, klasse.getContent());
}
test_pane.setText(((Test)project.getTestList().get(0)).getContent());
}
/**Fuehrt Handlungen aus, die beim Uebergang in die TestPhase erfolgen
*
* (aendert Infotext & Textfarbe zum anzeigen aktueller Phase, (dis)abelt Textareas,
* aktualisiert Project)
*
*/
private void setPhaseCode(){
if(project.getBabysteps()) timer.reset();
phase1.setFill(Color.BLACK);
phase2.setFill(Color.GREEN);
code_pane.setEditable(true);
test_pane.setEditable(false);
back.setDisable(false);
}
/**Fuehrt Handlungen aus, die beim Uebergang in die Codephase erfolgen
* (aendert Infotext & Textfarbe zum anzeigen aktueller Phase, (dis)abelt Textareas)
*/
private void setPhaseRefactor(){
phase2.setFill(Color.BLACK);
phase3.setFill(Color.GREEN);
project.overrideOldCode(project.CLASS);
back.setDisable(true);
project.overrideOldCode(project.TEST);
updateGui();
}
/**Fuehrt Handlungen aus, die beim Uebergang in die Refactorphase erfolgen
* (aendert Infotext & Textfarbe zum anzeigen aktueller Phase, (dis)abelt Textareas)
*/
private void setPhaseTest(){
if(project.getBabysteps()) timer.reset();
phase3.setFill(Color.BLACK);
phase1.setFill(Color.GREEN);
phase2.setFill(Color.BLACK);
code_pane.setEditable(false);
test_pane.setEditable(true);
project.overrideOldCode(project.CLASS);
back.setDisable(true);
test_pane.clear();
}
} | speichern eingebunden | TDD-Trainer/src/gui/Gui.java | speichern eingebunden | <ide><path>DD-Trainer/src/gui/Gui.java
<ide> import data.Project;
<ide> import data.Test;
<ide> import io.FunPictures;
<del>
<add>import io.XMLHandler;
<ide> //import io.XMLHandler;
<ide> import data.Code;
<ide> import javafx.application.Application;
<ide> CodePane code_pane;
<ide> TestPane test_pane;
<ide> ConsolePane console_pane;
<del> Button next, run, test, back, settings, fun_b;
<add> Button next, run, test, back, settings, save, fun_b;
<ide> Text phase1, phase2, phase3;
<ide> /** field askForBabysteps: Variable that states if the application should
<ide> * continue asking for babysteps setting. Is set to false after a correct
<ide> }
<ide> break;
<ide> case AlertHandler.LOAD_PROJECT:
<add> Catalog myTasks = new Catalog("./res/myTasks.xml");
<add> myTasks.showAndWait();
<add> if(myTasks.load()){
<add> project = myTasks.getProject();
<add> stage.setScene(main_scene());
<add> fillWithContent(project);
<add> stage.show();
<add> }
<ide> break;
<ide> }
<ide>
<ide> test = new Button("test");
<ide> next = new Button("next");
<ide> back = new Button("back");
<add> save = new Button("save");
<ide> fun_b = new Button("fun"); //fun
<ide> compile = new Button("compile");
<ide> phase1 = new Text("Write failing Test");
<ide> phase2 = new Text("Write passing Code");
<ide> phase3 = new Text("Refactor");
<del> grid.addColumn(1, phase1, phase2, phase3, compile, test, next, back, fun_b);
<add> grid.addColumn(1, phase1, phase2, phase3, compile, test, next, back, save, fun_b);
<ide> if(project.getBabysteps()) grid.add(timer,2, 2);
<ide>
<ide> setPhaseTest();
<ide> fun_b.setOnAction(e->{//fun
<ide> fun.showRandom();
<add> });
<add>
<add> save.setOnAction(e->{//fun
<add> XMLHandler.writeProject(project);
<ide> });
<ide>
<ide> compile.setOnAction(e->{ |
|
Java | apache-2.0 | 13f7eb5bdb4388cd137867894cc29089f370ca3a | 0 | agwlvssainokuni/sqlapp,agwlvssainokuni/sqlapp,agwlvssainokuni/sqlapp | /*
* Copyright 2014 agwlvssainokuni
*
* 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 cherry.sqlapp.controller.secure.exec;
import static org.springframework.web.util.UriComponentsBuilder.fromPath;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.site.SitePreference;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.UriComponents;
import cherry.sqlapp.service.secure.exec.ExecService;
import cherry.sqlapp.service.secure.exec.MetadataService;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class ExecCsvControllerImpl implements ExecCsvController {
public static final String VIEW_PATH = "secure/exec/csv/index";
public static final String VIEW_PATH_ID = "secure/exec/csv/indexId";
@Autowired
private DataSourceDef dataSourceDef;
@Autowired
private ExecService execService;
@Autowired
private MetadataService metadataService;
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public ExecMetadataForm getMetadata() {
return new ExecMetadataForm();
}
@Override
public ExecCsvForm getForm() {
ExecCsvForm form = new ExecCsvForm();
form.setDatabaseName(dataSourceDef.getDefaultName());
return form;
}
@Override
public ModelAndView index(Integer ref, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView request(ExecCsvForm form, BindingResult binding,
Authentication authentication, Locale locale,
SitePreference sitePreference, HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView create(ExecCsvForm form, BindingResult binding,
Authentication authentication, Locale locale,
SitePreference sitePreference, HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
int id = 0;
ModelAndView mav = new ModelAndView();
mav.setView(new RedirectView(URI_PATH_ID, true));
mav.addObject(PATH_VAR, id);
return mav;
}
@Override
public ModelAndView indexId(int id, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView requestId(int id, ExecCsvForm form,
BindingResult binding, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView update(int id, ExecCsvForm form, BindingResult binding,
Authentication authentication, Locale locale,
SitePreference sitePreference, HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
UriComponents uri = fromPath(URI_PATH).pathSegment(URI_PATH_ID)
.buildAndExpand(id);
ModelAndView mav = new ModelAndView();
mav.setView(new RedirectView(uri.toUriString(), true));
return mav;
}
@Override
public ModelAndView metadata(int id, ExecMetadataForm mdForm,
BindingResult binding, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH_ID);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
UriComponents uri = fromPath(URI_PATH).pathSegment(URI_PATH_ID)
.buildAndExpand(id);
ModelAndView mav = new ModelAndView();
mav.setView(new RedirectView(uri.toUriString(), true));
return mav;
}
}
| src/main/java/cherry/sqlapp/controller/secure/exec/ExecCsvControllerImpl.java | /*
* Copyright 2014 agwlvssainokuni
*
* 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 cherry.sqlapp.controller.secure.exec;
import static org.springframework.web.util.UriComponentsBuilder.fromPath;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.site.SitePreference;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.UriComponents;
import cherry.sqlapp.service.secure.exec.ExecService;
import cherry.sqlapp.service.secure.exec.MetadataService;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ExecCsvControllerImpl implements ExecCsvController {
public static final String VIEW_PATH = "secure/exec/csv/index";
public static final String VIEW_PATH_ID = "secure/exec/csv/indexId";
@Autowired
private DataSourceDef dataSourceDef;
@Autowired
private ExecService execService;
@Autowired
private MetadataService metadataService;
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public ExecMetadataForm getMetadata() {
return new ExecMetadataForm();
}
@Override
public ExecCsvForm getForm() {
ExecCsvForm form = new ExecCsvForm();
form.setDatabaseName(dataSourceDef.getDefaultName());
return form;
}
@Override
public ModelAndView index(Integer ref, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView request(ExecCsvForm form, BindingResult binding,
Authentication authentication, Locale locale,
SitePreference sitePreference, HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView create(ExecCsvForm form, BindingResult binding,
Authentication authentication, Locale locale,
SitePreference sitePreference, HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(dataSourceDef);
return mav;
}
int id = 0;
ModelAndView mav = new ModelAndView();
mav.setView(new RedirectView(URI_PATH_ID, true));
mav.addObject(PATH_VAR, id);
return mav;
}
@Override
public ModelAndView indexId(int id, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView requestId(int id, ExecCsvForm form,
BindingResult binding, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
@Override
public ModelAndView update(int id, ExecCsvForm form, BindingResult binding,
Authentication authentication, Locale locale,
SitePreference sitePreference, HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
UriComponents uri = fromPath(URI_PATH).pathSegment(URI_PATH_ID)
.buildAndExpand(id);
ModelAndView mav = new ModelAndView();
mav.setView(new RedirectView(uri.toUriString(), true));
return mav;
}
@Override
public ModelAndView metadata(int id, ExecMetadataForm mdForm,
BindingResult binding, Authentication authentication,
Locale locale, SitePreference sitePreference,
HttpServletRequest request) {
if (binding.hasErrors()) {
ModelAndView mav = new ModelAndView(VIEW_PATH_ID);
mav.addObject(PATH_VAR, id);
mav.addObject(dataSourceDef);
return mav;
}
UriComponents uri = fromPath(URI_PATH).pathSegment(URI_PATH_ID)
.buildAndExpand(id);
ModelAndView mav = new ModelAndView();
mav.setView(new RedirectView(uri.toUriString(), true));
return mav;
}
}
| SQL実行機能 | src/main/java/cherry/sqlapp/controller/secure/exec/ExecCsvControllerImpl.java | SQL実行機能 | <ide><path>rc/main/java/cherry/sqlapp/controller/secure/exec/ExecCsvControllerImpl.java
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.mobile.device.site.SitePreference;
<ide> import org.springframework.security.core.Authentication;
<add>import org.springframework.stereotype.Component;
<ide> import org.springframework.validation.BindingResult;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide> import org.springframework.web.servlet.view.RedirectView;
<ide>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide>
<add>@Component
<ide> public class ExecCsvControllerImpl implements ExecCsvController {
<ide>
<ide> public static final String VIEW_PATH = "secure/exec/csv/index"; |
|
Java | agpl-3.0 | 76fb4306e2c3b3dd63c3928389eb0b22e969335f | 0 | Hoot215/TheWalls2 | /** TheWalls2: The Walls 2 plugin.
* Copyright (C) 2012 Andrew Stevanus (Hoot215) <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.Hoot215.TheWalls2;
import me.Hoot215.TheWalls2.util.AutoUpdater;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
public class TheWalls2PlayerListener implements Listener {
private TheWalls2 plugin;
public TheWalls2PlayerListener(TheWalls2 instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
TheWalls2GameList gameList = plugin.getGameList();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (gameList == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You can't do that until the game starts!");
return;
}
}
else if (gameList.isInGame(player.getName())) {
if (plugin.getLocationData().isPartOfWall(event.getBlock().getLocation())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
for (Location loc : plugin.getLocationData().getSlots()) {
if (loc.getBlockX() == event.getBlock().getX() && loc.getBlockZ() == event.getBlock().getZ()) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
TheWalls2GameList gameList = plugin.getGameList();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (gameList == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You can't do that until the game starts!");
return;
}
}
else if (gameList.isInGame(player.getName())) {
if (plugin.getLocationData().isPartOfWall(event.getBlock().getLocation())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
if (event.getBlock().getY() > 93) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
for (Location loc : plugin.getLocationData().getSlots()) {
if (loc.getBlockX() == event.getBlock().getX() && loc.getBlockZ() == event.getBlock().getZ()) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (plugin.getGameList() == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You can't do that until the game starts!");
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamage(EntityDamageEvent event) {
if (!(event.getEntity() instanceof Player))
return;
Player player = (Player) event.getEntity();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (plugin.getGameList() == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
TheWalls2RespawnQueue respawnQueue = plugin.getRespawnQueue();
if (gameList == null)
return;
if (gameList.isInGame(playerName)) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW + playerName + ChatColor.RED + " has been defeated in a game of The Walls 2!");
gameList.removeFromGame(playerName);
respawnQueue.addPlayer(playerName, queue.getLastPlayerLocation(playerName));
plugin.checkIfGameIsOver();
return;
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
if (gameList == null) {
if (queue.isInQueue(playerName)) {
queue.removePlayer(playerName, true);
return;
}
return;
}
if (gameList.isInGame(playerName)) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW + playerName + ChatColor.RED + " has quit a game of The Walls 2!");
gameList.removeFromGame(playerName);
queue.removePlayer(playerName, true);
plugin.checkIfGameIsOver();
return;
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
String playerName = player.getName();
TheWalls2RespawnQueue respawnQueue = plugin.getRespawnQueue();
if (respawnQueue.isInRespawnQueue(playerName)) {
event.setRespawnLocation(respawnQueue.getLastPlayerLocation(playerName));
respawnQueue.removePlayer(playerName);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
AutoUpdater autoUpdater = plugin.getAutoUpdater();
synchronized (autoUpdater.getLock()) {
Player player = event.getPlayer();
final String playerName = player.getName();
if (player.hasPermission("thewalls2.notify")) {
if (!AutoUpdater.getIsUpToDate())
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
public void run() {
Player player = plugin.getServer().getPlayer(playerName);
if (player == null)
return;
player.sendMessage(ChatColor.AQUA + "[TheWalls2] "
+ ChatColor.GREEN
+ "An update is available!");
player.sendMessage(ChatColor.WHITE
+ "http://dev.bukkit.org/server-mods/thewalls2/");
player.sendMessage(ChatColor.RED
+ "If you can't find a newer version, " +
"check in the comments section for a " +
"Dropbox link");
}
}, 60L);
}
}
}
} | src/me/Hoot215/TheWalls2/TheWalls2PlayerListener.java | /** TheWalls2: The Walls 2 plugin.
* Copyright (C) 2012 Andrew Stevanus (Hoot215) <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.Hoot215.TheWalls2;
import me.Hoot215.TheWalls2.util.AutoUpdater;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
public class TheWalls2PlayerListener implements Listener {
private TheWalls2 plugin;
public TheWalls2PlayerListener(TheWalls2 instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
TheWalls2GameList gameList = plugin.getGameList();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (gameList == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You can't do that until the game starts!");
return;
}
}
else if (gameList.isInGame(player.getName())) {
if (plugin.getLocationData().isPartOfWall(event.getBlock().getLocation())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
for (Location loc : plugin.getLocationData().getSlots()) {
if (loc.getBlockX() == event.getBlock().getX() && loc.getBlockZ() == event.getBlock().getZ()) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
TheWalls2GameList gameList = plugin.getGameList();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (gameList == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You can't do that until the game starts!");
return;
}
}
else if (gameList.isInGame(player.getName())) {
if (plugin.getLocationData().isPartOfWall(event.getBlock().getLocation())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
if (event.getBlock().getY() > 93) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
for (Location loc : plugin.getLocationData().getSlots()) {
if (loc.getBlockX() == event.getBlock().getX() && loc.getBlockZ() == event.getBlock().getZ()) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Don't break the rules!");
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (plugin.getGameList() == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You can't do that until the game starts!");
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamage(EntityDamageEvent event) {
if (!(event.getEntity() instanceof Player))
return;
Player player = (Player) event.getEntity();
if (player.getWorld().getName().equals(TheWalls2.worldName)) {
if (plugin.getGameList() == null) {
if (plugin.getQueue().isInQueue(player.getName())) {
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
TheWalls2RespawnQueue respawnQueue = plugin.getRespawnQueue();
if (gameList == null)
return;
if (gameList.isInGame(playerName)) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW + playerName + ChatColor.RED + " has been defeated in a game of The Walls 2!");
gameList.removeFromGame(playerName);
respawnQueue.addPlayer(playerName, queue.getLastPlayerLocation(playerName));
plugin.checkIfGameIsOver();
return;
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
String playerName = player.getName();
TheWalls2GameList gameList = plugin.getGameList();
TheWalls2PlayerQueue queue = plugin.getQueue();
if (gameList == null) {
if (queue.isInQueue(playerName)) {
queue.removePlayer(playerName, true);
return;
}
return;
}
if (gameList.isInGame(playerName)) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW + playerName + ChatColor.RED + " has quit a game of The Walls 2!");
gameList.removeFromGame(playerName);
queue.removePlayer(playerName, true);
plugin.checkIfGameIsOver();
return;
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
String playerName = player.getName();
TheWalls2RespawnQueue respawnQueue = plugin.getRespawnQueue();
if (respawnQueue.isInRespawnQueue(playerName)) {
event.setRespawnLocation(respawnQueue.getLastPlayerLocation(playerName));
respawnQueue.removePlayer(playerName);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
AutoUpdater autoUpdater = plugin.getAutoUpdater();
synchronized (autoUpdater.getLock()) {
Player player = event.getPlayer();
final String playerName = player.getName();
if (player.hasPermission("thewalls2.notify")) {
if (!AutoUpdater.getIsUpToDate())
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
public void run() {
Player player = plugin.getServer().getPlayer(playerName);
if (player == null)
return;
player.sendMessage(ChatColor.AQUA + "[TheWalls2] "
+ ChatColor.GREEN
+ "An update is available!");
}
}, 60L);
}
}
}
} | Improved update notification message
| src/me/Hoot215/TheWalls2/TheWalls2PlayerListener.java | Improved update notification message | <ide><path>rc/me/Hoot215/TheWalls2/TheWalls2PlayerListener.java
<ide> player.sendMessage(ChatColor.AQUA + "[TheWalls2] "
<ide> + ChatColor.GREEN
<ide> + "An update is available!");
<add> player.sendMessage(ChatColor.WHITE
<add> + "http://dev.bukkit.org/server-mods/thewalls2/");
<add> player.sendMessage(ChatColor.RED
<add> + "If you can't find a newer version, " +
<add> "check in the comments section for a " +
<add> "Dropbox link");
<ide> }
<ide> }, 60L);
<ide> } |
|
Java | apache-2.0 | 78e6de2c61457d501c1cf72d45e60136356c2908 | 0 | mapcode-foundation/mapcode-rest-service,mapcode-foundation/mapcode-rest-service,mapcode-foundation/mapcode-rest-service | /*
* Copyright (C) 2015 Stichting Mapcode Foundation (http://www.mapcode.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mapcode.services.implementation;
import akka.dispatch.Futures;
import com.google.common.base.Joiner;
import com.mapcode.*;
import com.mapcode.Territory.NameFormat;
import com.mapcode.services.ApiConstants;
import com.mapcode.services.MapcodeResource;
import com.mapcode.services.dto.*;
import com.tomtom.speedtools.apivalidation.ApiDTO;
import com.tomtom.speedtools.apivalidation.exceptions.ApiForbiddenException;
import com.tomtom.speedtools.apivalidation.exceptions.ApiIntegerOutOfRangeException;
import com.tomtom.speedtools.apivalidation.exceptions.ApiInvalidFormatException;
import com.tomtom.speedtools.apivalidation.exceptions.ApiNotFoundException;
import com.tomtom.speedtools.geometry.Geo;
import com.tomtom.speedtools.geometry.GeoPoint;
import com.tomtom.speedtools.rest.ResourceProcessor;
import com.tomtom.speedtools.tracer.Traceable;
import com.tomtom.speedtools.tracer.TracerFactory;
import com.tomtom.speedtools.utils.MathUtils;
import org.jboss.resteasy.spi.AsynchronousResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* This class implements the REST API that deals with TTBin files.
*/
public class MapcodeResourceImpl implements MapcodeResource {
private static final Logger LOG = LoggerFactory.getLogger(MapcodeResourceImpl.class);
private static final Tracer TRACER = TracerFactory.getTracer(MapcodeResourceImpl.class, Tracer.class);
private final ResourceProcessor processor;
private final String listOfAllTerritories = Joiner.on('|').join(Arrays.asList(Territory.values()).stream().
map(x -> x.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS)).collect(Collectors.toList()));
private final String listOfAllTypes = Joiner.on('|').join(Arrays.asList(ParamType.values()).stream().
map(x -> x).collect(Collectors.toList()));
private final String listOfAllIncludes = Joiner.on('|').join(Arrays.asList(ParamInclude.values()).stream().
map(x -> x).collect(Collectors.toList()));
@Inject
public MapcodeResourceImpl(@Nonnull final ResourceProcessor processor) {
assert processor != null;
this.processor = processor;
}
@Override
public void convertLatLonToMapcode(
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
throw new ApiForbiddenException("Missing URL path parameters: /{lat,lon}/{" + listOfAllTypes.toLowerCase() + '}');
}
@Override
public void convertLatLonToMapcode(
final double paramLatDeg,
final double paramLonDeg,
final int paramPrecision,
@Nullable final String paramTerritory,
@Nonnull final String paramInclude,
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
convertLatLonToMapcode(paramLatDeg, paramLonDeg, null, paramPrecision, paramTerritory, paramInclude, response);
}
@Override
public void convertLatLonToMapcode(
final double paramLatDeg,
final double paramLonDeg,
@Nullable final String paramType,
final int paramPrecision,
@Nullable final String paramTerritory,
@Nonnull final String paramInclude,
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
assert response != null;
processor.process("convertLatLonToMapcode", LOG, response, () -> {
LOG.debug("convertLatLonToMapcode: lat={}, lon={}, precision={}, type={}, territory={}, include={}",
paramLatDeg, paramLonDeg, paramPrecision, paramType, paramTerritory, paramInclude);
// Check lat.
final double latDeg = paramLatDeg;
if (!MathUtils.isBetween(latDeg, ApiConstants.API_LAT_MIN, ApiConstants.API_LAT_MAX)) {
throw new ApiInvalidFormatException(PARAM_LAT_DEG, String.valueOf(paramLatDeg),
"[" + ApiConstants.API_LAT_MIN + ", " + ApiConstants.API_LAT_MAX + ']');
}
// Check lon.
final double lonDeg = Geo.mapToLon(paramLonDeg);
// Check precision.
final int precision = paramPrecision;
if (!MathUtils.isBetween(precision, 0, 2)) {
throw new ApiInvalidFormatException(PARAM_PRECISION, String.valueOf(paramPrecision), "[0, 2]");
}
// Check territory.
Territory territory = null;
if (paramTerritory != null) {
try {
final int territoryCode = Integer.valueOf(paramTerritory);
territory = Territory.fromTerritoryCode(territoryCode);
} catch (final IllegalArgumentException ignored) {
try {
territory = Territory.fromString(paramTerritory);
} catch (final UnknownTerritoryException ignored2) {
throw new ApiInvalidFormatException(PARAM_TERRITORY, paramTerritory, listOfAllTerritories);
}
}
}
// Check type.
ParamType type = null;
if (paramType != null) {
try {
type = ParamType.valueOf(paramType.toUpperCase());
} catch (final IllegalArgumentException ignored) {
throw new ApiInvalidFormatException(PARAM_TYPE, paramType, listOfAllTypes.toLowerCase());
}
}
// Check include.
boolean foundIncludeOffset = false;
boolean foundIncludeTerritory = false;
for (final String arg : paramInclude.toUpperCase().split(",")) {
if (!arg.isEmpty()) {
try {
ParamInclude include = ParamInclude.valueOf(arg);
foundIncludeOffset = foundIncludeOffset || (include == ParamInclude.OFFSET);
foundIncludeTerritory = foundIncludeTerritory || (include == ParamInclude.TERRITORY);
} catch (final IllegalArgumentException ignored) {
throw new ApiInvalidFormatException(PARAM_INCLUDE, paramInclude, listOfAllIncludes.toLowerCase());
}
}
}
final boolean includeOffset = foundIncludeOffset;
final boolean includeTerritory = foundIncludeTerritory;
TRACER.eventLatLonToMapcode(latDeg, lonDeg, territory, precision, paramType, paramInclude);
try {
// Get local.
final Mapcode mapcodeLocal;
if (territory == null) {
mapcodeLocal = MapcodeCodec.encodeToShortest(latDeg, lonDeg);
} else {
mapcodeLocal = MapcodeCodec.encodeToShortest(latDeg, lonDeg, territory);
}
// Get international.
final Mapcode mapcodeInternational = MapcodeCodec.encodeToInternational(latDeg, lonDeg);
// Get all.
final List<Mapcode> mapcodesAll;
if (territory == null) {
mapcodesAll = MapcodeCodec.encode(latDeg, lonDeg);
} else {
mapcodesAll = MapcodeCodec.encode(latDeg, lonDeg, territory);
}
// Create result body.
final Object result;
if (type == null) {
final ApiDTO dto = new MapcodesDTO(getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeLocal),
getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeInternational),
mapcodesAll.stream().
map(mapcode -> getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcode)).
collect(Collectors.toList()));
dto.validate();
result = dto;
} else {
switch (type) {
case LOCAL: {
final ApiDTO dto = getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeLocal);
dto.validate();
result = dto;
break;
}
case INTERNATIONAL: {
final ApiDTO dto = getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeInternational);
dto.validate();
result = dto;
break;
}
case ALL: {
final MapcodeListDTO dto = new MapcodeListDTO(mapcodesAll.stream().
map(mapcode -> getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcode)).
collect(Collectors.toList()));
dto.validate();
result = dto.getMapcodes(); // Return ONLY the list, not the parent object.
break;
}
default:
assert false;
result = null;
}
}
response.setResponse(Response.ok(result).build());
} catch (final UnknownMapcodeException ignored) {
throw new ApiNotFoundException("No mapcode found for lat=" + latDeg + ", lon=" + lonDeg + ", territory=" + territory);
}
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Override
public void convertMapcodeToLatLon(
@Nonnull final AsynchronousResponse response) throws ApiNotFoundException, ApiInvalidFormatException {
throw new ApiForbiddenException("Missing URL path parameters: /{mapcode}");
}
@Override
public void convertMapcodeToLatLon(
@Nonnull final String paramMapcode,
@Nullable final String paramTerritory,
@Nonnull final AsynchronousResponse response) throws ApiNotFoundException, ApiInvalidFormatException {
assert paramMapcode != null;
assert response != null;
processor.process("convertMapcodeToLatLon", LOG, response, () -> {
LOG.debug("convertMapcodeToLatLon: mapcode={}, territory={}", paramMapcode, paramTerritory);
Territory territory = null;
if (paramTerritory != null) {
try {
final int territoryCode = Integer.valueOf(paramTerritory);
territory = Territory.fromTerritoryCode(territoryCode);
} catch (final IllegalArgumentException ignored) {
try {
territory = Territory.fromString(paramTerritory.toUpperCase());
} catch (final UnknownTerritoryException ignored2) {
throw new ApiInvalidFormatException("territory", paramTerritory, listOfAllTerritories);
}
}
}
if (!Mapcode.isValidMapcodeFormat(paramMapcode)) {
throw new ApiInvalidFormatException("mapcode", paramMapcode, Mapcode.REGEX_MAPCODE_FORMAT);
}
TRACER.eventMapcodeToLatLon(paramMapcode, territory);
// Create result body.
try {
final Point point;
if (territory == null) {
point = MapcodeCodec.decode(paramMapcode);
} else {
point = MapcodeCodec.decode(paramMapcode, territory);
}
final PointDTO result = new PointDTO(point.getLatDeg(), point.getLonDeg());
result.validate();
response.setResponse(Response.ok(result).build());
} catch (final UnknownMapcodeException e) {
throw new ApiNotFoundException("No mapcode found for mapcode='" + paramMapcode + "', territory=" + territory);
}
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Override
public void getTerritories(
final int offset,
final int count,
@Nonnull final AsynchronousResponse response) throws ApiIntegerOutOfRangeException {
assert response != null;
processor.process("getTerritories", LOG, response, () -> {
LOG.debug("getTerritories");
if (count < 0) {
throw new ApiIntegerOutOfRangeException(PARAM_COUNT, count, 0, Integer.MAX_VALUE);
}
assert count >= 0;
Joiner.on('|').join(Arrays.asList(Territory.values()).stream().
map(x -> x.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS)).collect(Collectors.toList()));
final List<TerritoryDTO> allTerritories = Arrays.asList(Territory.values()).stream().
map(x -> {
final Territory parentTerritory = x.getParentTerritory();
return new TerritoryDTO(
x.getTerritoryCode(),
x.getFullName(),
(parentTerritory == null) ? null : parentTerritory.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS),
x.getAliases(),
x.getFullNameAliases());
}).
collect(Collectors.toList());
// Create the response and validate it.
final int nrTerritories = allTerritories.size();
final int fromIndex = (offset < 0) ? Math.max(0, nrTerritories + offset) : Math.min(nrTerritories, offset);
final int toIndex = Math.min(nrTerritories, fromIndex + count);
final TerritoriesDTO result = new TerritoriesDTO(allTerritories.subList(fromIndex, toIndex));
result.validate();
response.setResponse(Response.ok(result).build());
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Override
public void getTerritory(
@Nullable final String paramTerritory,
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
assert paramTerritory != null;
assert response != null;
processor.process("getTerritory", LOG, response, () -> {
LOG.debug("getTerritory: territory={}", paramTerritory);
Territory territory = null;
try {
final int territoryCode = Integer.valueOf(paramTerritory);
territory = Territory.fromTerritoryCode(territoryCode);
} catch (final IllegalArgumentException ignored) {
try {
territory = Territory.fromString(paramTerritory);
} catch (final UnknownTerritoryException ignored2) {
throw new ApiInvalidFormatException("territory", paramTerritory, listOfAllTerritories);
}
}
final Territory parentTerritory = territory.getParentTerritory();
final TerritoryDTO result = new TerritoryDTO(
territory.getTerritoryCode(),
territory.getFullName(),
(parentTerritory == null) ? null : parentTerritory.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS),
territory.getAliases(),
territory.getFullNameAliases()
);
result.validate();
response.setResponse(Response.ok(result).build());
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Nonnull
private static MapcodeDTO getMapcodeDTO(double latDeg, double lonDeg, int precision,
boolean includeOffset, boolean includeTerritory,
@Nonnull final Mapcode mapcode) {
return new MapcodeDTO(
getMapcodePrecision(mapcode, precision),
(includeTerritory || (mapcode.getTerritory() != Territory.AAA)) ?
mapcode.getTerritory().toNameFormat(NameFormat.INTERNATIONAL) : null,
includeOffset ? offsetFromLatLonInMeters(latDeg, lonDeg, mapcode, precision) : null);
}
private static double offsetFromLatLonInMeters(
final double latDeg,
final double lonDeg,
@Nonnull final Mapcode mapcode,
final int precision) {
assert mapcode != null;
final GeoPoint position = new GeoPoint(latDeg, lonDeg);
try {
final Point point = MapcodeCodec.decode(getMapcodePrecision(mapcode, precision), mapcode.getTerritory());
final GeoPoint center = new GeoPoint(point.getLatDeg(), point.getLonDeg());
final double distanceMeters = Geo.distanceInMeters(position, center);
return Math.round(distanceMeters * 100.0) / 100.0;
} catch (final UnknownMapcodeException ignore) {
// Simply ignore.
return 0.0;
}
}
@Nonnull
private static String getMapcodePrecision(@Nonnull final Mapcode mapcode, final int precision) {
switch (precision) {
case 1:
return mapcode.getMapcodePrecision1();
case 2:
return mapcode.getMapcodePrecision2();
default:
return mapcode.getMapcodePrecision0();
}
}
/**
* This interface defines a Tracer interface for mapcode service events.
*/
public interface Tracer extends Traceable {
// A request to translate a lat/lon to a mapcode is made.
void eventLatLonToMapcode(double latDeg, double lonDeg, @Nullable Territory territory,
int precision, @Nullable String type, @Nonnull String include);
// A request to translate a mapcode to a lat/lon is made.
void eventMapcodeToLatLon(@Nonnull String mapcode, @Nullable Territory territory);
}
}
| src/main/java/com/mapcode/services/implementation/MapcodeResourceImpl.java | /*
* Copyright (C) 2015 Stichting Mapcode Foundation (http://www.mapcode.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mapcode.services.implementation;
import akka.dispatch.Futures;
import com.google.common.base.Joiner;
import com.mapcode.*;
import com.mapcode.Territory.NameFormat;
import com.mapcode.services.ApiConstants;
import com.mapcode.services.MapcodeResource;
import com.mapcode.services.dto.*;
import com.tomtom.speedtools.apivalidation.ApiDTO;
import com.tomtom.speedtools.apivalidation.exceptions.ApiForbiddenException;
import com.tomtom.speedtools.apivalidation.exceptions.ApiIntegerOutOfRangeException;
import com.tomtom.speedtools.apivalidation.exceptions.ApiInvalidFormatException;
import com.tomtom.speedtools.apivalidation.exceptions.ApiNotFoundException;
import com.tomtom.speedtools.geometry.Geo;
import com.tomtom.speedtools.geometry.GeoPoint;
import com.tomtom.speedtools.rest.ResourceProcessor;
import com.tomtom.speedtools.tracer.Traceable;
import com.tomtom.speedtools.tracer.TracerFactory;
import com.tomtom.speedtools.utils.MathUtils;
import org.jboss.resteasy.spi.AsynchronousResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* This class implements the REST API that deals with TTBin files.
*/
public class MapcodeResourceImpl implements MapcodeResource {
private static final Logger LOG = LoggerFactory.getLogger(MapcodeResourceImpl.class);
private static final Tracer TRACER = TracerFactory.getTracer(MapcodeResourceImpl.class, Tracer.class);
private final ResourceProcessor processor;
private final String listOfAllTerritories = Joiner.on('|').join(Arrays.asList(Territory.values()).stream().
map(x -> x.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS)).collect(Collectors.toList()));
private final String listOfAllTypes = Joiner.on('|').join(Arrays.asList(ParamType.values()).stream().
map(x -> x).collect(Collectors.toList()));
private final String listOfAllIncludes = Joiner.on('|').join(Arrays.asList(ParamInclude.values()).stream().
map(x -> x).collect(Collectors.toList()));
@Inject
public MapcodeResourceImpl(@Nonnull final ResourceProcessor processor) {
assert processor != null;
this.processor = processor;
}
@Override
public void convertLatLonToMapcode(
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
throw new ApiForbiddenException("Missing URL path parameters: /{lat,lon}/{" + listOfAllTypes.toLowerCase() + '}');
}
@Override
public void convertLatLonToMapcode(
final double paramLatDeg,
final double paramLonDeg,
final int paramPrecision,
@Nullable final String paramTerritory,
@Nonnull final String paramInclude,
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
convertLatLonToMapcode(paramLatDeg, paramLonDeg, null, paramPrecision, paramTerritory, paramInclude, response);
}
@Override
public void convertLatLonToMapcode(
final double paramLatDeg,
final double paramLonDeg,
@Nullable final String paramType,
final int paramPrecision,
@Nullable final String paramTerritory,
@Nonnull final String paramInclude,
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
assert response != null;
processor.process("convertLatLonToMapcode", LOG, response, () -> {
LOG.debug("convertLatLonToMapcode: lat={}, lon={}, precision={}, type={}, territory={}, include={}",
paramLatDeg, paramLonDeg, paramPrecision, paramType, paramTerritory, paramInclude);
// Check lat.
final double latDeg = paramLatDeg;
if (!MathUtils.isBetween(latDeg, ApiConstants.API_LAT_MIN, ApiConstants.API_LAT_MAX)) {
throw new ApiInvalidFormatException(PARAM_LAT_DEG, String.valueOf(paramLatDeg),
"[" + ApiConstants.API_LAT_MIN + ", " + ApiConstants.API_LAT_MAX + ']');
}
// Check lon.
final double lonDeg = Geo.mapToLon(paramLonDeg);
// Check precision.
final int precision = paramPrecision;
if (!MathUtils.isBetween(precision, 0, 2)) {
throw new ApiInvalidFormatException(PARAM_PRECISION, String.valueOf(paramPrecision), "[0, 2]");
}
// Check territory.
Territory territory = null;
if (paramTerritory != null) {
try {
final int territoryCode = Integer.valueOf(paramTerritory);
territory = Territory.fromTerritoryCode(territoryCode);
} catch (final IllegalArgumentException ignored) {
try {
territory = Territory.fromString(paramTerritory);
} catch (final UnknownTerritoryException ignored2) {
throw new ApiInvalidFormatException(PARAM_TERRITORY, paramTerritory, listOfAllTerritories);
}
}
}
// Check type.
ParamType type = null;
if (paramType != null) {
try {
type = ParamType.valueOf(paramType.toUpperCase());
} catch (final IllegalArgumentException ignored) {
throw new ApiInvalidFormatException(PARAM_TYPE, paramType, listOfAllTypes.toLowerCase());
}
}
// Check include.
boolean foundIncludeOffset = false;
boolean foundIncludeTerritory = false;
for (final String arg : paramInclude.toUpperCase().split(",")) {
if (!arg.isEmpty()) {
try {
ParamInclude include = ParamInclude.valueOf(arg);
foundIncludeOffset = foundIncludeOffset || (include == ParamInclude.OFFSET);
foundIncludeTerritory = foundIncludeTerritory || (include == ParamInclude.TERRITORY);
} catch (final IllegalArgumentException ignored) {
throw new ApiInvalidFormatException(PARAM_INCLUDE, paramInclude, listOfAllIncludes.toLowerCase());
}
}
}
final boolean includeOffset = foundIncludeOffset;
final boolean includeTerritory = foundIncludeTerritory;
TRACER.eventLatLonToMapcode(latDeg, lonDeg, territory, precision, paramType, paramInclude);
try {
// Get local.
final Mapcode mapcodeLocal;
if (territory == null) {
mapcodeLocal = MapcodeCodec.encodeToShortest(latDeg, lonDeg);
} else {
mapcodeLocal = MapcodeCodec.encodeToShortest(latDeg, lonDeg, territory);
}
// Get international.
final Mapcode mapcodeInternational = MapcodeCodec.encodeToInternational(latDeg, lonDeg);
// Get all.
final List<Mapcode> mapcodesAll;
if (territory == null) {
mapcodesAll = MapcodeCodec.encode(latDeg, lonDeg);
} else {
mapcodesAll = MapcodeCodec.encode(latDeg, lonDeg, territory);
}
// Create result body.
final Object result;
if (type == null) {
final ApiDTO dto = new MapcodesDTO(getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeLocal),
getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeInternational),
mapcodesAll.stream().
map(mapcode -> getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcode)).
collect(Collectors.toList()));
dto.validate();
result = dto;
} else {
switch (type) {
case LOCAL: {
final ApiDTO dto = getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeLocal);
dto.validate();
result = dto;
break;
}
case INTERNATIONAL: {
final ApiDTO dto = getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcodeInternational);
dto.validate();
result = dto;
break;
}
case ALL: {
final MapcodeListDTO dto = new MapcodeListDTO(mapcodesAll.stream().
map(mapcode -> getMapcodeDTO(latDeg, lonDeg, precision, includeOffset, includeTerritory, mapcode)).
collect(Collectors.toList()));
dto.validate();
result = dto.getMapcodes(); // Return ONLY the list, not the parent object.
break;
}
default:
assert false;
result = null;
}
}
response.setResponse(Response.ok(result).build());
} catch (final UnknownMapcodeException ignored) {
throw new ApiNotFoundException("No mapcode found for lat=" + latDeg + ", lon=" + lonDeg + ", territory=" + territory);
}
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Override
public void convertMapcodeToLatLon(
@Nonnull final AsynchronousResponse response) throws ApiNotFoundException, ApiInvalidFormatException {
throw new ApiForbiddenException("Missing URL path parameters: /{mapcode}");
}
@Override
public void convertMapcodeToLatLon(
@Nonnull final String paramMapcode,
@Nullable final String paramTerritory,
@Nonnull final AsynchronousResponse response) throws ApiNotFoundException, ApiInvalidFormatException {
assert paramMapcode != null;
assert response != null;
processor.process("convertMapcodeToLatLon", LOG, response, () -> {
LOG.debug("convertMapcodeToLatLon: mapcode={}, territory={}", paramMapcode, paramTerritory);
Territory territory = null;
if (paramTerritory != null) {
try {
final int territoryCode = Integer.valueOf(paramTerritory);
territory = Territory.fromTerritoryCode(territoryCode);
} catch (final IllegalArgumentException ignored) {
try {
territory = Territory.fromString(paramTerritory);
} catch (final UnknownTerritoryException ignored2) {
throw new ApiInvalidFormatException("territory", paramTerritory, listOfAllTerritories);
}
}
}
if (!Mapcode.isValidMapcodeFormat(paramMapcode)) {
throw new ApiInvalidFormatException("mapcode", paramMapcode, Mapcode.REGEX_MAPCODE_FORMAT);
}
TRACER.eventMapcodeToLatLon(paramMapcode, territory);
// Create result body.
try {
final Point point;
if (territory == null) {
point = MapcodeCodec.decode(paramMapcode);
} else {
point = MapcodeCodec.decode(paramMapcode, territory);
}
final PointDTO result = new PointDTO(point.getLatDeg(), point.getLonDeg());
result.validate();
response.setResponse(Response.ok(result).build());
} catch (final UnknownMapcodeException e) {
throw new ApiNotFoundException("No mapcode found for mapcode='" + paramMapcode + "', territory=" + territory);
}
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Override
public void getTerritories(
final int offset,
final int count,
@Nonnull final AsynchronousResponse response) throws ApiIntegerOutOfRangeException {
assert response != null;
processor.process("getTerritories", LOG, response, () -> {
LOG.debug("getTerritories");
if (count < 0) {
throw new ApiIntegerOutOfRangeException(PARAM_COUNT, count, 0, Integer.MAX_VALUE);
}
assert count >= 0;
Joiner.on('|').join(Arrays.asList(Territory.values()).stream().
map(x -> x.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS)).collect(Collectors.toList()));
final List<TerritoryDTO> allTerritories = Arrays.asList(Territory.values()).stream().
map(x -> {
final Territory parentTerritory = x.getParentTerritory();
return new TerritoryDTO(
x.getTerritoryCode(),
x.getFullName(),
(parentTerritory == null) ? null : parentTerritory.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS),
x.getAliases(),
x.getFullNameAliases());
}).
collect(Collectors.toList());
// Create the response and validate it.
final int nrTerritories = allTerritories.size();
final int fromIndex = (offset < 0) ? Math.max(0, nrTerritories + offset) : Math.min(nrTerritories, offset);
final int toIndex = Math.min(nrTerritories, fromIndex + count);
final TerritoriesDTO result = new TerritoriesDTO(allTerritories.subList(fromIndex, toIndex));
result.validate();
response.setResponse(Response.ok(result).build());
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Override
public void getTerritory(
@Nullable final String paramTerritory,
@Nonnull final AsynchronousResponse response) throws ApiInvalidFormatException {
assert paramTerritory != null;
assert response != null;
processor.process("getTerritory", LOG, response, () -> {
LOG.debug("getTerritory: territory={}", paramTerritory);
Territory territory = null;
try {
final int territoryCode = Integer.valueOf(paramTerritory);
territory = Territory.fromTerritoryCode(territoryCode);
} catch (final IllegalArgumentException ignored) {
try {
territory = Territory.fromString(paramTerritory);
} catch (final UnknownTerritoryException ignored2) {
throw new ApiInvalidFormatException("territory", paramTerritory, listOfAllTerritories);
}
}
final Territory parentTerritory = territory.getParentTerritory();
final TerritoryDTO result = new TerritoryDTO(
territory.getTerritoryCode(),
territory.getFullName(),
(parentTerritory == null) ? null : parentTerritory.toNameFormat(NameFormat.MINIMAL_UNAMBIGUOUS),
territory.getAliases(),
territory.getFullNameAliases()
);
result.validate();
response.setResponse(Response.ok(result).build());
// The response is already set within this method body.
return Futures.successful(null);
});
}
@Nonnull
private static MapcodeDTO getMapcodeDTO(double latDeg, double lonDeg, int precision,
boolean includeOffset, boolean includeTerritory,
@Nonnull final Mapcode mapcode) {
return new MapcodeDTO(
getMapcodePrecision(mapcode, precision),
(includeTerritory || (mapcode.getTerritory() != Territory.AAA)) ?
mapcode.getTerritory().toNameFormat(NameFormat.INTERNATIONAL) : null,
includeOffset ? offsetFromLatLonInMeters(latDeg, lonDeg, mapcode, precision) : null);
}
private static double offsetFromLatLonInMeters(
final double latDeg,
final double lonDeg,
@Nonnull final Mapcode mapcode,
final int precision) {
assert mapcode != null;
final GeoPoint position = new GeoPoint(latDeg, lonDeg);
try {
final Point point = MapcodeCodec.decode(getMapcodePrecision(mapcode, precision), mapcode.getTerritory());
final GeoPoint center = new GeoPoint(point.getLatDeg(), point.getLonDeg());
final double distanceMeters = Geo.distanceInMeters(position, center);
return Math.round(distanceMeters * 100.0) / 100.0;
} catch (final UnknownMapcodeException ignore) {
// Simply ignore.
return 0.0;
}
}
@Nonnull
private static String getMapcodePrecision(@Nonnull final Mapcode mapcode, final int precision) {
switch (precision) {
case 1:
return mapcode.getMapcodePrecision1();
case 2:
return mapcode.getMapcodePrecision2();
default:
return mapcode.getMapcodePrecision0();
}
}
/**
* This interface defines a Tracer interface for mapcode service events.
*/
public interface Tracer extends Traceable {
// A request to translate a lat/lon to a mapcode is made.
void eventLatLonToMapcode(double latDeg, double lonDeg, @Nullable Territory territory,
int precision, @Nullable String type, @Nonnull String include);
// A request to translate a mapcode to a lat/lon is made.
void eventMapcodeToLatLon(@Nonnull String mapcode, @Nullable Territory territory);
}
}
| Check territory format
| src/main/java/com/mapcode/services/implementation/MapcodeResourceImpl.java | Check territory format | <ide><path>rc/main/java/com/mapcode/services/implementation/MapcodeResourceImpl.java
<ide> territory = Territory.fromTerritoryCode(territoryCode);
<ide> } catch (final IllegalArgumentException ignored) {
<ide> try {
<del> territory = Territory.fromString(paramTerritory);
<add> territory = Territory.fromString(paramTerritory.toUpperCase());
<ide> } catch (final UnknownTerritoryException ignored2) {
<ide> throw new ApiInvalidFormatException("territory", paramTerritory, listOfAllTerritories);
<ide> } |
|
Java | apache-2.0 | 94e4e502682bee678ff0b41b0849c579a76b83a6 | 0 | mpi2/PhenotypeArchive,mpi2/PhenotypeArchive,mpi2/PhenotypeArchive | /*******************************************************************************
* Copyright 2015 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*******************************************************************************/
package uk.ac.ebi.phenotype.solr.indexer;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import uk.ac.ebi.phenotype.service.ImageService;
import uk.ac.ebi.phenotype.service.dto.*;
import uk.ac.ebi.phenotype.solr.indexer.exceptions.IndexerException;
import uk.ac.ebi.phenotype.solr.indexer.exceptions.ValidationException;
import uk.ac.ebi.phenotype.solr.indexer.utils.IndexerMap;
import uk.ac.ebi.phenotype.solr.indexer.utils.SolrUtils;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* Populate the MA core
*/
public class GeneIndexer extends AbstractIndexer {
private static final Logger logger = LoggerFactory.getLogger(GeneIndexer.class);
private Connection komp2DbConnection;
@Autowired
@Qualifier("komp2DataSource")
DataSource komp2DataSource;
@Autowired
@Qualifier("observationIndexing")
private SolrServer observationService;
@Autowired
@Qualifier("alleleIndexing")
SolrServer alleleCore;
@Autowired
@Qualifier("geneIndexing")
SolrServer geneCore;
@Autowired
@Qualifier("mpIndexing")
SolrServer mpCore;
@Autowired
@Qualifier("sangerImagesIndexing")
SolrServer imagesCore;
@Autowired
@Qualifier("impcImagesIndexing")
SolrServer impcImagesCore;
private Map<String, List<Map<String, String>>> phenotypeSummaryGeneAccessionsToPipelineInfo = new HashMap<>();
private Map<String, List<SangerImageDTO>> sangerImages = new HashMap<>();
private Map<String, List<ImageDTO>> impcImages = new HashMap<>();
private Map<String, List<MpDTO>> mgiAccessionToMP = new HashMap<>();
public GeneIndexer() {
}
@Override
public void validateBuild() throws IndexerException {
Long numFound = getDocumentCount(geneCore);
if (numFound <= MINIMUM_DOCUMENT_COUNT)
throw new IndexerException(new ValidationException("Actual gene document count is " + numFound + "."));
if (numFound != documentCount)
logger.warn("WARNING: Added " + documentCount + " gene documents but SOLR reports " + numFound + " documents.");
else
logger.info("validateBuild(): Indexed " + documentCount + " gene documents.");
}
@Override
public void initialise(String[] args) throws IndexerException {
super.initialise(args);
applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
try {
komp2DbConnection = komp2DataSource.getConnection();
} catch (SQLException sqle) {
logger.error("Caught SQL Exception initialising database connections: {}", sqle.getMessage());
throw new IndexerException(sqle);
}
}
@Override
public void run() throws IndexerException, SQLException {
long startTime = System.currentTimeMillis();
try {
logger.info("Starting Gene Indexer...");
initialiseSupportingBeans();
int count = 0;
List<AlleleDTO> alleles = IndexerMap.getAlleles(alleleCore);
logger.info("alleles size=" + alleles.size());
geneCore.deleteByQuery("*:*");
for (AlleleDTO allele : alleles) {
//System.out.println("allele="+allele.getMarkerSymbol());
GeneDTO gene = new GeneDTO();
gene.setMgiAccessionId(allele.getMgiAccessionId());
gene.setDataType(allele.getDataType());
gene.setMarkerType(allele.getMarkerType());
gene.setMarkerSymbol(allele.getMarkerSymbol());
gene.setMarkerSynonym(allele.getMarkerSynonym());
gene.setMarkerName(allele.getMarkerName());
gene.setHumanGeneSymbol(allele.getHumanGeneSymbol());
gene.setEnsemblGeneIds(allele.getEnsemblGeneIds());
gene.setLatestEsCellStatus(allele.getLatestEsCellStatus());
gene.setImitsPhenotypeStarted(allele.getImitsPhenotypeStarted());
gene.setImitsPhenotypeComplete(allele.getImitsPhenotypeComplete());
gene.setImitsPhenotypeStatus(allele.getImitsPhenotypeStatus());
gene.setLatestMouseStatus(allele.getLatestMouseStatus());
gene.setLatestProjectStatus(allele.getLatestProjectStatus());
gene.setStatus(allele.getStatus());
gene.setLatestPhenotypeStatus(allele.getLatestPhenotypeStatus());
gene.setLegacy_phenotype_status(allele.getLegacyPhenotypeStatus());
gene.setLatestProductionCentre(allele.getLatestProductionCentre());
gene.setLatestPhenotypingCentre(allele.getLatestPhenotypingCentre());
gene.setAlleleName(allele.getAlleleName());
gene.setEsCellStatus(allele.getEsCellStatus());
gene.setMouseStatus(allele.getMouseStatus());
gene.setPhenotypeStatus(allele.getPhenotypeStatus());
gene.setProductionCentre(allele.getProductionCentre());
gene.setPhenotypingCentre(allele.getPhenotypingCentre());
gene.setType(allele.getType());
gene.setDiseaseSource(allele.getDiseaseSource());
gene.setDiseaseId(allele.getDiseaseId());
gene.setDiseaseTerm(allele.getDiseaseTerm());
gene.setDiseaseAlts(allele.getDiseaseAlts());
gene.setDiseaseClasses(allele.getDiseaseClasses());
gene.setHumanCurated(allele.getHumanCurated());
gene.setMouseCurated(allele.getMouseCurated());
gene.setMgiPredicted(allele.getMgiPredicted());
gene.setImpcPredicted(allele.getImpcPredicted());
gene.setMgiPredicted(allele.getMgiPredicted());
gene.setMgiPredictedKnonwGene(allele.getMgiPredictedKnownGene());
gene.setImpcNovelPredictedInLocus(allele.getImpcNovelPredictedInLocus());
gene.setDiseaseHumanPhenotypes(allele.getDiseaseHumanPhenotypes());
// GO stuff
gene.setGoTermIds(allele.getGoTermIds());
gene.setGoTermNames(allele.getGoTermNames());
// gene.getGoTermDefs().addAll(allele.getGoTermDefs());
gene.setGoTermEvids(allele.getGoTermEvids());
gene.setGoTermDomains(allele.getGoTermDomains());
gene.setEvidCodeRank(allele.getEvidCodeRank());
gene.setGoCount(allele.getGoCount());
gene.setGoUniprot(allele.getGoUniprot());
// pfam stuff
gene.setUniprotAccs(allele.getUniprotAccs());
gene.setScdbIds(allele.getScdbIds());
gene.setScdbLinks(allele.getScdbLinks());
gene.setClanIds(allele.getClanIds());
gene.setClanAccs(allele.getClanAccs());
gene.setClanDescs(allele.getClanDescs());
gene.setPfamaIds(allele.getPfamaIds());
gene.setPfamaAccs(allele.getPfamaAccs());
gene.setPfamaGoIds(allele.getPfamaGoIds());
gene.setPfamaGoTerms(allele.getPfamaGoTerms());
gene.setPfamaGoCats(allele.getPfamaGoCats());
gene.setPfamaJsons(allele.getPfamaJsons());
//gene.setMpId(allele.getM)
// Populate pipeline and procedure info if we have a phenotypeCallSummary entry for this allele/gene
if (phenotypeSummaryGeneAccessionsToPipelineInfo.containsKey(allele.getMgiAccessionId())) {
List<Map<String, String>> rows = phenotypeSummaryGeneAccessionsToPipelineInfo.get(allele.getMgiAccessionId());
List<String> pipelineNames = new ArrayList<>();
List<String> pipelineStableIds = new ArrayList<>();
List<String> procedureNames = new ArrayList<>();
List<String> procedureStableIds = new ArrayList<>();
List<String> parameterNames = new ArrayList<>();
List<String> parameterStableIds = new ArrayList<>();
for (Map<String, String> row : rows) {
pipelineNames.add(row.get(ObservationDTO.PIPELINE_NAME));
pipelineStableIds.add(row.get(ObservationDTO.PIPELINE_STABLE_ID));
procedureNames.add(row.get(ObservationDTO.PROCEDURE_NAME));
procedureStableIds.add(row.get(ObservationDTO.PROCEDURE_STABLE_ID));
parameterNames.add(row.get(ObservationDTO.PARAMETER_NAME));
parameterStableIds.add(row.get(ObservationDTO.PARAMETER_STABLE_ID));
}
gene.setPipelineName(pipelineNames);
gene.setPipelineStableId(pipelineStableIds);
gene.setProcedureName(procedureNames);
gene.setProcedureStableId(procedureStableIds);
gene.setParameterName(parameterNames);
gene.setParameterStableId(parameterStableIds);
}
//do images core data
// Initialize all the ontology term lists
gene.setMpId(new ArrayList<String>());
gene.setMpTerm(new ArrayList<String>());
gene.setMpTermSynonym(new ArrayList<String>());
gene.setMpTermDefinition(new ArrayList<String>());
gene.setOntologySubset(new ArrayList<String>());
gene.setMaId(new ArrayList<String>());
gene.setMaTerm(new ArrayList<String>());
gene.setMaTermSynonym(new ArrayList<String>());
gene.setMaTermDefinition(new ArrayList<String>());
gene.setHpId(new ArrayList<String>());
gene.setHpTerm(new ArrayList<String>());
gene.setTopLevelMpId(new ArrayList<String>());
gene.setTopLevelMpTerm(new ArrayList<String>());
gene.setTopLevelMpTermSynonym(new ArrayList<String>());
gene.setIntermediateMpId(new ArrayList<String>());
gene.setIntermediateMpTerm(new ArrayList<String>());
gene.setIntermediateMpTermSynonym(new ArrayList<String>());
gene.setChildMpId(new ArrayList<String>());
gene.setChildMpTerm(new ArrayList<String>());
gene.setChildMpTermSynonym(new ArrayList<String>());
gene.setChildMpId(new ArrayList<String>());
gene.setChildMpTerm(new ArrayList<String>());
gene.setChildMpTermSynonym(new ArrayList<String>());
gene.setInferredMaId(new ArrayList<String>());
gene.setInferredMaTerm(new ArrayList<String>());
gene.setInferredMaTermSynonym(new ArrayList<String>());
gene.setSelectedTopLevelMaId(new ArrayList<String>());
gene.setSelectedTopLevelMaTerm(new ArrayList<String>());
gene.setSelectedTopLevelMaTermSynonym(new ArrayList<String>());
gene.setInferredChildMaId(new ArrayList<String>());
gene.setInferredChildMaTerm(new ArrayList<String>());
gene.setInferredChildMaTermSynonym(new ArrayList<String>());
gene.setInferredSelectedTopLevelMaId(new ArrayList<String>());
gene.setInferredSelectedTopLevelMaTerm(new ArrayList<String>());
gene.setInferredSelectedTopLevelMaTermSynonym(new ArrayList<String>());
// Add all ontology information from images associated to this gene
if (sangerImages.containsKey(allele.getMgiAccessionId())) {
List<SangerImageDTO> list = sangerImages.get(allele.getMgiAccessionId());
for (SangerImageDTO image : list) {
if (image.getMp_id() != null && ! gene.getMpId().contains(image.getMp_id())) {
gene.getMpId().addAll(image.getMp_id());
gene.getMpTerm().addAll(image.getMpTerm());
if (image.getMpSyns() != null) {
gene.getMpTermSynonym().addAll(image.getMpSyns());
}
if (image.getAnnotatedHigherLevelMpTermId() != null) {
gene.getTopLevelMpId().addAll(image.getAnnotatedHigherLevelMpTermId());
}
if (image.getAnnotatedHigherLevelMpTermName() != null) {
gene.getTopLevelMpTerm().addAll(image.getAnnotatedHigherLevelMpTermName());
}
if (image.getTopLevelMpTermSynonym() != null) {
gene.getTopLevelMpTermSynonym().addAll(image.getTopLevelMpTermSynonym());
}
if (image.getIntermediateMpId() != null) {
gene.getIntermediateMpId().addAll(image.getIntermediateMpId());
}
if (image.getIntermediateMpTerm() != null) {
gene.getIntermediateMpTerm().addAll(image.getIntermediateMpTerm());
}
if (image.getIntermediateMpTermSyn() != null) {
gene.getIntermediateMpTermSynonym().addAll(image.getIntermediateMpTermSyn());
}
}
if (image.getMaTermId() != null) {
gene.getMaId().addAll(image.getMaTermId());
gene.getMaTerm().addAll(image.getMaTermName());
if (image.getMaTermSynonym() != null) {
gene.getMaTermSynonym().addAll(image.getMaTermSynonym());
}
if (image.getSelectedTopLevelMaTermId() != null) {
gene.setSelectedTopLevelMaId(image.getSelectedTopLevelMaTermId());
}
if (image.getSelectedTopLevelMaTerm() != null) {
gene.setSelectedTopLevelMaTerm(image.getSelectedTopLevelMaTerm());
}
if (image.getSelectedTopLevelMaTermSynonym() != null) {
gene.setSelectedTopLevelMaTermSynonym(image.getSelectedTopLevelMaTermSynonym());
}
}
}
}
// impcImages associated with genes, MAs, pipelines/procedures/parameters
if ( impcImages.containsKey(allele.getMgiAccessionId()) ){
//if ( impcImage.getGeneAccession() != null && ! impcImage.getGeneAccession().equals(ma.getMgiAccessionId()) ){
List<ImageDTO> impcImagesList = impcImages.get(allele.getMgiAccessionId());
for( ImageDTO impcImage : impcImagesList ){
// MAs
if (gene.getMaId() == null){
gene.setMaId(impcImage.getMaTermId());
gene.setMaTerm(impcImage.getMaTerm());
gene.setMaTermSynonym(impcImage.getMarkerSynonym());
//System.out.println("***selected top level ma id: "+ impcImage.getTopLevelMaIds());
gene.setSelectedTopLevelMaId(impcImage.getTopLevelMaIds());
gene.setSelectedTopLevelMaTerm(impcImage.getTopLeveMaTerm());
gene.setSelectedTopLevelMaTermSynonym(impcImage.getTopLevelMaTermSynonym());
}
else {
Set<String> maids = new HashSet<>();
if (gene.getMaId()!=null){maids.addAll(gene.getMaId()); }
if (impcImage.getMaTermId()!=null){maids.addAll(impcImage.getMaTermId()); }
if (maids.size()>0) {
gene.setMaId(new ArrayList(maids));
}
Set<String> materms = new HashSet<>();
if (gene.getMaTerm()!=null){materms.addAll(gene.getMaTerm()); }
if (impcImage.getMaTerm()!=null){materms.addAll(impcImage.getMaTerm()); }
if (materms.size()>0) {
gene.setMaTerm(new ArrayList(materms));
}
Set<String> matermsyns = new HashSet<>();
if (gene.getMaTermSynonym()!=null){matermsyns.addAll(gene.getMaTermSynonym()); }
if (impcImage.getMaTermSynonym()!=null){matermsyns.addAll(impcImage.getMaTermSynonym()); }
if (matermsyns.size()>0) {
gene.setMaTermSynonym(new ArrayList(matermsyns));
}
Set<String> topmaids = new HashSet<>();
if (gene.getSelectedTopLevelMaId()!=null){topmaids.addAll(gene.getSelectedTopLevelMaId()); }
if (impcImage.getTopLevelMaIds()!=null){topmaids.addAll(impcImage.getTopLevelMaIds()); }
if (topmaids.size()>0) {
gene.setSelectedTopLevelMaId(new ArrayList(topmaids));
}
Set<String> topmaterms = new HashSet<>();
if (gene.getSelectedTopLevelMaTerm()!=null){topmaterms.addAll(gene.getSelectedTopLevelMaTerm()); }
if (impcImage.getTopLeveMaTerm()!=null){topmaterms.addAll(impcImage.getTopLeveMaTerm()); }
if (topmaterms.size()>0) {
gene.setSelectedTopLevelMaTerm(new ArrayList(topmaterms));
}
Set<String> topmatermsyns = new HashSet<>();
if (gene.getSelectedTopLevelMaTermSynonym()!=null){topmatermsyns.addAll(gene.getSelectedTopLevelMaTermSynonym()); }
if (impcImage.getTopLevelMaTermSynonym()!=null){topmatermsyns.addAll(impcImage.getTopLevelMaTermSynonym()); }
if (topmatermsyns.size()>0) {
gene.setSelectedTopLevelMaTermSynonym(new ArrayList(topmatermsyns));
}
}
// pipeline
if ( gene.getPipelineStableId() == null ){
gene.setPipelineStableId(Arrays.asList(impcImage.getPipelineStableId()));
gene.setPipelineName(Arrays.asList(impcImage.getPipelineName()));
}
else {
Set<String> pipenames = new HashSet<>();
if (gene.getPipelineName()!=null){pipenames.addAll(gene.getPipelineName()); }
if (impcImage.getPipelineName()!=null){pipenames.add(impcImage.getPipelineName()); }
if (pipenames.size()>0) {
gene.setTopLevelMpTermSynonym(new ArrayList(pipenames));
}
Set<String> pipesid = new HashSet<>();
if (gene.getPipelineStableId()!=null){pipesid.addAll(gene.getPipelineStableId()); }
if (impcImage.getPipelineStableId()!=null){pipesid.add(impcImage.getPipelineStableId()); }
if (pipesid.size()>0) {
gene.setPipelineStableId(new ArrayList(pipesid));
}
}
// procedure
if ( gene.getProcedureStableId() == null ){
gene.setProcedureStableId(Arrays.asList(impcImage.getProcedureStableId()));
gene.setProcedureName(Arrays.asList(impcImage.getProcedureName()));
}
else {
Set<String> procnames = new HashSet<>();
if (gene.getProcedureName() !=null){procnames.addAll(gene.getProcedureName()); }
if (impcImage.getProcedureName()!=null){procnames.add(impcImage.getProcedureName()); }
if (procnames.size()>0) {
gene.setProcedureName(new ArrayList(procnames));
}
Set<String> procsids = new HashSet<>();
if (gene.getProcedureStableId() !=null){procsids.addAll(gene.getProcedureStableId()); }
if (impcImage.getProcedureStableId()!=null){procsids.add(impcImage.getProcedureStableId()); }
if (procsids.size()>0) {
gene.setProcedureStableId(new ArrayList(procsids));
}
}
// parameter
if ( gene.getParameterStableId() == null ){
gene.setParameterStableId(Arrays.asList(impcImage.getParameterStableId()));
gene.setParameterStableId(Arrays.asList(impcImage.getParameterStableId()));
}
else {
Set<String> paramnames = new HashSet<>();
if (gene.getParameterName() !=null){paramnames.addAll(gene.getParameterName()); }
if (impcImage.getParameterName()!=null){paramnames.add(impcImage.getParameterName()); }
if (paramnames.size()>0) {
gene.setParameterName(new ArrayList(paramnames));
}
Set<String> paramsids = new HashSet<>();
if (gene.getParameterStableId() !=null){paramsids.addAll(gene.getParameterStableId()); }
if (impcImage.getParameterStableId()!=null){paramsids.add(impcImage.getParameterStableId()); }
if (paramsids.size()>0) {
gene.setParameterStableId(new ArrayList(paramsids));
}
}
}
}
// Add all ontology information directly associated from MP to this gene
if (StringUtils.isNotEmpty(allele.getMgiAccessionId())) {
if (mgiAccessionToMP.containsKey(allele.getMgiAccessionId())) {
List<MpDTO> mps = mgiAccessionToMP.get(allele.getMgiAccessionId());
for (MpDTO mp : mps) {
gene.getMpId().add(mp.getMpId());
gene.getMpTerm().add(mp.getMpTerm());
if (mp.getMpTermSynonym() != null) {
gene.getMpTermSynonym().addAll(mp.getMpTermSynonym());
}
if (mp.getOntologySubset() != null) {
gene.getOntologySubset().addAll(mp.getOntologySubset());
}
if (mp.getHpId() != null) {
gene.getHpId().addAll(mp.getHpId());
gene.getHpTerm().addAll(mp.getHpTerm());
}
if (mp.getTopLevelMpId() != null) {
gene.getTopLevelMpId().addAll(mp.getTopLevelMpId());
gene.getTopLevelMpTerm().addAll(mp.getTopLevelMpTerm());
}
if (mp.getTopLevelMpTermSynonym() != null) {
gene.getTopLevelMpTermSynonym().addAll(mp.getTopLevelMpTermSynonym());
}
if (mp.getIntermediateMpId() != null) {
gene.getIntermediateMpId().addAll(mp.getIntermediateMpId());
gene.getIntermediateMpTerm().addAll(mp.getIntermediateMpTerm());
}
if (mp.getIntermediateMpTermSynonym() != null) {
gene.getIntermediateMpTermSynonym().addAll(mp.getIntermediateMpTermSynonym());
}
if (mp.getChildMpId() != null) {
gene.getChildMpId().addAll(mp.getChildMpId());
gene.getChildMpTerm().addAll(mp.getChildMpTerm());
}
if (mp.getChildMpTermSynonym() != null) {
gene.getChildMpTermSynonym().addAll(mp.getChildMpTermSynonym());
}
if (mp.getInferredMaId() != null) {
gene.getInferredMaId().addAll(mp.getInferredMaId());
gene.getInferredMaTerm().addAll(mp.getInferredMaTerm());
}
if (mp.getInferredMaTermSynonym() != null) {
gene.getInferredMaTermSynonym().addAll(mp.getInferredMaTermSynonym());
}
if (mp.getInferredSelectedTopLevelMaId() != null) {
gene.getInferredSelectedTopLevelMaId().addAll(mp.getInferredSelectedTopLevelMaId());
gene.getInferredSelectedTopLevelMaTerm().addAll(mp.getInferredSelectedTopLevelMaTerm());
}
if (mp.getInferredSelectedTopLevelMaTermSynonym() != null) {
gene.getInferredSelectedTopLevelMaTermSynonym().addAll(mp.getInferredSelectedTopLevelMaTermSynonym());
}
if (mp.getInferredChildMaId() != null) {
gene.getInferredChildMaId().addAll(mp.getInferredChildMaId());
gene.getInferredChildMaTerm().addAll(mp.getInferredChildMaTerm());
}
if (mp.getInferredChildMaTermSynonym() != null) {
gene.getInferredChildMaTermSynonym().addAll(mp.getInferredChildMaTermSynonym());
}
}
}
}
/**
* Unique all the sets
*/
gene.setMpId(new ArrayList<>(new HashSet<>(gene.getMpId())));
gene.setMpTerm(new ArrayList<>(new HashSet<>(gene.getMpTerm())));
gene.setMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getMpTermSynonym())));
gene.setMpTermDefinition(new ArrayList<>(new HashSet<>(gene.getMpTermDefinition())));
gene.setOntologySubset(new ArrayList<>(new HashSet<>(gene.getOntologySubset())));
gene.setMaId(new ArrayList<>(new HashSet<>(gene.getMaId())));
gene.setMaTerm(new ArrayList<>(new HashSet<>(gene.getMaTerm())));
gene.setMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getMaTermSynonym())));
gene.setMaTermDefinition(new ArrayList<>(new HashSet<>(gene.getMaTermDefinition())));
gene.setHpId(new ArrayList<>(new HashSet<>(gene.getHpId())));
gene.setHpTerm(new ArrayList<>(new HashSet<>(gene.getHpTerm())));
gene.setTopLevelMpId(new ArrayList<>(new HashSet<>(gene.getTopLevelMpId())));
gene.setTopLevelMpTerm(new ArrayList<>(new HashSet<>(gene.getTopLevelMpTerm())));
gene.setTopLevelMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getTopLevelMpTermSynonym())));
gene.setIntermediateMpId(new ArrayList<>(new HashSet<>(gene.getIntermediateMpId())));
gene.setIntermediateMpTerm(new ArrayList<>(new HashSet<>(gene.getIntermediateMpTerm())));
gene.setIntermediateMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getIntermediateMpTermSynonym())));
gene.setChildMpId(new ArrayList<>(new HashSet<>(gene.getChildMpId())));
gene.setChildMpTerm(new ArrayList<>(new HashSet<>(gene.getChildMpTerm())));
gene.setChildMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getChildMpTermSynonym())));
gene.setChildMpId(new ArrayList<>(new HashSet<>(gene.getChildMpId())));
gene.setChildMpTerm(new ArrayList<>(new HashSet<>(gene.getChildMpTerm())));
gene.setChildMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getChildMpTermSynonym())));
gene.setInferredMaId(new ArrayList<>(new HashSet<>(gene.getInferredMaId())));
gene.setInferredMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredMaTerm())));
gene.setInferredMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredMaTermSynonym())));
gene.setSelectedTopLevelMaId(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaId())));
gene.setSelectedTopLevelMaTerm(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaTerm())));
gene.setSelectedTopLevelMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaTermSynonym())));
gene.setInferredChildMaId(new ArrayList<>(new HashSet<>(gene.getInferredChildMaId())));
gene.setInferredChildMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredChildMaTerm())));
gene.setInferredChildMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredChildMaTermSynonym())));
gene.setInferredSelectedTopLevelMaId(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaId())));
gene.setInferredSelectedTopLevelMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaTerm())));
gene.setInferredSelectedTopLevelMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaTermSynonym())));
documentCount++;
geneCore.addBean(gene, 60000);
count ++;
if (count % 10000 == 0) {
logger.info(" added " + count + " beans");
}
}
logger.info("Committing to gene core for last time");
geneCore.commit();
} catch (IOException | SolrServerException e) {
e.printStackTrace();
throw new IndexerException(e);
}
long endTime = System.currentTimeMillis();
logger.info("time was " + (endTime - startTime) / 1000);
logger.info("Gene Indexer complete!");
}
// PROTECTED METHODS
@Override
protected Logger getLogger() {
return logger;
}
// PRIVATE METHODS
private void initialiseSupportingBeans() throws IndexerException, SolrServerException, IOException, SQLException {
phenotypeSummaryGeneAccessionsToPipelineInfo = populatePhenotypeCallSummaryGeneAccessions();
sangerImages = IndexerMap.getSangerImagesByMgiAccession(imagesCore);
impcImages = populateImpcImages();
mgiAccessionToMP = populateMgiAccessionToMp();
logger.info("mgiAccessionToMP size=" + mgiAccessionToMP.size());
}
private Map<String, List<MpDTO>> populateMgiAccessionToMp() throws IndexerException {
return SolrUtils.populateMgiAccessionToMp(mpCore);
}
private Map<String, List<ImageDTO>> populateImpcImages() throws SolrServerException, IOException, SQLException {
List<String> impcImagesFields = Arrays.asList(
ImageDTO.GENE_ACCESSION_ID,
ImageDTO.MA_ID,
ImageDTO.MA_TERM,
ImageDTO.MA_TERM_SYNONYM,
ImageDTO.SELECTED_TOP_LEVEL_MA_ID,
ImageDTO.SELECTED_TOP_LEVEL_MA_TERM,
ImageDTO.SELECTED_TOP_LEVEL_MA_TERM_SYNONYM,
ImageDTO.PIPELINE_NAME,
ImageDTO.PIPELINE_STABLE_ID,
ImageDTO.PROCEDURE_NAME,
ImageDTO.PROCEDURE_STABLE_ID,
ImageDTO.PARAMETER_NAME,
ImageDTO.PARAMETER_STABLE_ID
);
SolrQuery impcImgesQuery = new SolrQuery()
.setQuery("*:*")
.setFields(StringUtils.join(impcImagesFields, ","))
.setRows(Integer.MAX_VALUE);
List<ImageDTO> impcImagesList = impcImagesCore.query(impcImgesQuery).getBeans(ImageDTO.class);
for (ImageDTO impcImage : impcImagesList) {
String geneAccId = impcImage. getGeneAccession();
if ( geneAccId == null ){
continue;
}
if ( !impcImages.containsKey(geneAccId) ){
impcImages.put(geneAccId, new ArrayList<ImageDTO>());
}
impcImages.get(geneAccId).add(impcImage);
}
logger.info("Finished populating impcImages using mgi_accession_id as key");
return impcImages;
}
private Map<String, List<Map<String, String>>> populatePhenotypeCallSummaryGeneAccessions() {
logger.info("populating PCS pipeline info");
String queryString = "select pcs.*, param.name, param.stable_id, proc.stable_id, proc.name, pipe.stable_id, pipe.name"
+ " from phenotype_call_summary pcs"
+ " inner join ontology_term term on term.acc=mp_acc"
+ " inner join genomic_feature gf on gf.acc=pcs.gf_acc"
+ " inner join phenotype_parameter param on param.id=pcs.parameter_id"
+ " inner join phenotype_procedure proc on proc.id=pcs.procedure_id"
+ " inner join phenotype_pipeline pipe on pipe.id=pcs.pipeline_id";
try (PreparedStatement p = komp2DbConnection.prepareStatement(queryString)) {
ResultSet resultSet = p.executeQuery();
while (resultSet.next()) {
String gf_acc = resultSet.getString("gf_acc");
Map<String, String> rowMap = new HashMap<>();
rowMap.put(ObservationDTO.PARAMETER_NAME, resultSet.getString("param.name"));
rowMap.put(ObservationDTO.PARAMETER_STABLE_ID, resultSet.getString("param.stable_id"));
rowMap.put(ObservationDTO.PROCEDURE_STABLE_ID, resultSet.getString("proc.stable_id"));
rowMap.put(ObservationDTO.PROCEDURE_NAME, resultSet.getString("proc.name"));
rowMap.put(ObservationDTO.PIPELINE_STABLE_ID, resultSet.getString("pipe.stable_id"));
rowMap.put(ObservationDTO.PIPELINE_NAME, resultSet.getString("pipe.name"));
rowMap.put("proc_param_name", resultSet.getString("proc.name") + "___" + resultSet.getString("param.name"));
rowMap.put("proc_param_stable_id", resultSet.getString("proc.stable_id") + "___" + resultSet.getString("param.stable_id"));
List<Map<String, String>> rows = null;
if (phenotypeSummaryGeneAccessionsToPipelineInfo.containsKey(gf_acc)) {
rows = phenotypeSummaryGeneAccessionsToPipelineInfo.get(gf_acc);
} else {
rows = new ArrayList<>();
}
rows.add(rowMap);
phenotypeSummaryGeneAccessionsToPipelineInfo.put(gf_acc, rows);
}
} catch (Exception e) {
e.printStackTrace();
}
return phenotypeSummaryGeneAccessionsToPipelineInfo;
}
public static void main(String[] args) throws IndexerException, SQLException {
GeneIndexer indexer = new GeneIndexer();
indexer.initialise(args);
indexer.run();
indexer.validateBuild();
logger.info("Process finished. Exiting.");
}
}
| src/main/java/uk/ac/ebi/phenotype/solr/indexer/GeneIndexer.java | /*******************************************************************************
* Copyright 2015 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*******************************************************************************/
package uk.ac.ebi.phenotype.solr.indexer;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import uk.ac.ebi.phenotype.service.ImageService;
import uk.ac.ebi.phenotype.service.dto.*;
import uk.ac.ebi.phenotype.solr.indexer.exceptions.IndexerException;
import uk.ac.ebi.phenotype.solr.indexer.exceptions.ValidationException;
import uk.ac.ebi.phenotype.solr.indexer.utils.IndexerMap;
import uk.ac.ebi.phenotype.solr.indexer.utils.SolrUtils;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* Populate the MA core
*/
public class GeneIndexer extends AbstractIndexer {
private static final Logger logger = LoggerFactory.getLogger(GeneIndexer.class);
private Connection komp2DbConnection;
@Autowired
@Qualifier("komp2DataSource")
DataSource komp2DataSource;
@Autowired
@Qualifier("observationIndexing")
private SolrServer observationService;
@Autowired
@Qualifier("alleleIndexing")
SolrServer alleleCore;
@Autowired
@Qualifier("geneIndexing")
SolrServer geneCore;
@Autowired
@Qualifier("mpIndexing")
SolrServer mpCore;
@Autowired
@Qualifier("sangerImagesIndexing")
SolrServer imagesCore;
@Autowired
@Qualifier("impcImagesIndexing")
SolrServer impcImagesCore;
private Map<String, List<Map<String, String>>> phenotypeSummaryGeneAccessionsToPipelineInfo = new HashMap<>();
private Map<String, List<SangerImageDTO>> sangerImages = new HashMap<>();
private Map<String, List<ImageDTO>> impcImages = new HashMap<>();
private Map<String, List<MpDTO>> mgiAccessionToMP = new HashMap<>();
public GeneIndexer() {
}
@Override
public void validateBuild() throws IndexerException {
Long numFound = getDocumentCount(geneCore);
if (numFound <= MINIMUM_DOCUMENT_COUNT)
throw new IndexerException(new ValidationException("Actual gene document count is " + numFound + "."));
if (numFound != documentCount)
logger.warn("WARNING: Added " + documentCount + " gene documents but SOLR reports " + numFound + " documents.");
else
logger.info("validateBuild(): Indexed " + documentCount + " gene documents.");
}
@Override
public void initialise(String[] args) throws IndexerException {
super.initialise(args);
applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
try {
komp2DbConnection = komp2DataSource.getConnection();
} catch (SQLException sqle) {
logger.error("Caught SQL Exception initialising database connections: {}", sqle.getMessage());
throw new IndexerException(sqle);
}
}
@Override
public void run() throws IndexerException, SQLException {
long startTime = System.currentTimeMillis();
try {
logger.info("Starting Gene Indexer...");
initialiseSupportingBeans();
int count = 0;
List<AlleleDTO> alleles = IndexerMap.getAlleles(alleleCore);
logger.info("alleles size=" + alleles.size());
geneCore.deleteByQuery("*:*");
for (AlleleDTO allele : alleles) {
//System.out.println("allele="+allele.getMarkerSymbol());
GeneDTO gene = new GeneDTO();
gene.setMgiAccessionId(allele.getMgiAccessionId());
gene.setDataType(allele.getDataType());
gene.setMarkerType(allele.getMarkerType());
gene.setMarkerSymbol(allele.getMarkerSymbol());
gene.setMarkerSynonym(allele.getMarkerSynonym());
gene.setMarkerName(allele.getMarkerName());
gene.setHumanGeneSymbol(allele.getHumanGeneSymbol());
gene.setEnsemblGeneIds(allele.getEnsemblGeneIds());
gene.setLatestEsCellStatus(allele.getLatestEsCellStatus());
gene.setImitsPhenotypeStarted(allele.getImitsPhenotypeStarted());
gene.setImitsPhenotypeComplete(allele.getImitsPhenotypeComplete());
gene.setImitsPhenotypeStatus(allele.getImitsPhenotypeStatus());
gene.setLatestMouseStatus(allele.getLatestMouseStatus());
gene.setLatestProjectStatus(allele.getLatestProjectStatus());
gene.setStatus(allele.getStatus());
gene.setLatestPhenotypeStatus(allele.getLatestPhenotypeStatus());
gene.setLegacy_phenotype_status(allele.getLegacyPhenotypeStatus());
gene.setLatestProductionCentre(allele.getLatestProductionCentre());
gene.setLatestPhenotypingCentre(allele.getLatestPhenotypingCentre());
gene.setAlleleName(allele.getAlleleName());
gene.setEsCellStatus(allele.getEsCellStatus());
gene.setMouseStatus(allele.getMouseStatus());
gene.setPhenotypeStatus(allele.getPhenotypeStatus());
gene.setProductionCentre(allele.getProductionCentre());
gene.setPhenotypingCentre(allele.getPhenotypingCentre());
gene.setType(allele.getType());
gene.setDiseaseSource(allele.getDiseaseSource());
gene.setDiseaseId(allele.getDiseaseId());
gene.setDiseaseTerm(allele.getDiseaseTerm());
gene.setDiseaseAlts(allele.getDiseaseAlts());
gene.setDiseaseClasses(allele.getDiseaseClasses());
gene.setHumanCurated(allele.getHumanCurated());
gene.setMouseCurated(allele.getMouseCurated());
gene.setMgiPredicted(allele.getMgiPredicted());
gene.setImpcPredicted(allele.getImpcPredicted());
gene.setMgiPredicted(allele.getMgiPredicted());
gene.setMgiPredictedKnonwGene(allele.getMgiPredictedKnownGene());
gene.setImpcNovelPredictedInLocus(allele.getImpcNovelPredictedInLocus());
gene.setDiseaseHumanPhenotypes(allele.getDiseaseHumanPhenotypes());
// GO stuff
gene.setGoTermIds(allele.getGoTermIds());
gene.setGoTermNames(allele.getGoTermNames());
// gene.getGoTermDefs().addAll(allele.getGoTermDefs());
gene.setGoTermEvids(allele.getGoTermEvids());
gene.setGoTermDomains(allele.getGoTermDomains());
gene.setEvidCodeRank(allele.getEvidCodeRank());
gene.setGoCount(allele.getGoCount());
gene.setGoUniprot(allele.getGoUniprot());
// pfam stuff
gene.setUniprotAccs(allele.getUniprotAccs());
gene.setScdbIds(allele.getScdbIds());
gene.setScdbLinks(allele.getScdbLinks());
gene.setClanIds(allele.getClanIds());
gene.setClanAccs(allele.getClanAccs());
gene.setClanDescs(allele.getClanDescs());
gene.setPfamaIds(allele.getPfamaIds());
gene.setPfamaAccs(allele.getPfamaAccs());
gene.setPfamaGoIds(allele.getPfamaGoIds());
gene.setPfamaGoTerms(allele.getPfamaGoTerms());
gene.setPfamaGoCats(allele.getPfamaGoCats());
gene.setPfamaJsons(allele.getPfamaJsons());
//gene.setMpId(allele.getM)
// Populate pipeline and procedure info if we have a phenotypeCallSummary entry for this allele/gene
if (phenotypeSummaryGeneAccessionsToPipelineInfo.containsKey(allele.getMgiAccessionId())) {
List<Map<String, String>> rows = phenotypeSummaryGeneAccessionsToPipelineInfo.get(allele.getMgiAccessionId());
List<String> pipelineNames = new ArrayList<>();
List<String> pipelineStableIds = new ArrayList<>();
List<String> procedureNames = new ArrayList<>();
List<String> procedureStableIds = new ArrayList<>();
List<String> parameterNames = new ArrayList<>();
List<String> parameterStableIds = new ArrayList<>();
for (Map<String, String> row : rows) {
pipelineNames.add(row.get(ObservationDTO.PIPELINE_NAME));
pipelineStableIds.add(row.get(ObservationDTO.PIPELINE_STABLE_ID));
procedureNames.add(row.get(ObservationDTO.PROCEDURE_NAME));
procedureStableIds.add(row.get(ObservationDTO.PROCEDURE_STABLE_ID));
parameterNames.add(row.get(ObservationDTO.PARAMETER_NAME));
parameterStableIds.add(row.get(ObservationDTO.PARAMETER_STABLE_ID));
}
gene.setPipelineName(pipelineNames);
gene.setPipelineStableId(pipelineStableIds);
gene.setProcedureName(procedureNames);
gene.setProcedureStableId(procedureStableIds);
gene.setParameterName(parameterNames);
gene.setParameterStableId(parameterStableIds);
}
//do images core data
// Initialize all the ontology term lists
gene.setMpId(new ArrayList<String>());
gene.setMpTerm(new ArrayList<String>());
gene.setMpTermSynonym(new ArrayList<String>());
gene.setMpTermDefinition(new ArrayList<String>());
gene.setOntologySubset(new ArrayList<String>());
gene.setMaId(new ArrayList<String>());
gene.setMaTerm(new ArrayList<String>());
gene.setMaTermSynonym(new ArrayList<String>());
gene.setMaTermDefinition(new ArrayList<String>());
gene.setHpId(new ArrayList<String>());
gene.setHpTerm(new ArrayList<String>());
gene.setTopLevelMpId(new ArrayList<String>());
gene.setTopLevelMpTerm(new ArrayList<String>());
gene.setTopLevelMpTermSynonym(new ArrayList<String>());
gene.setIntermediateMpId(new ArrayList<String>());
gene.setIntermediateMpTerm(new ArrayList<String>());
gene.setIntermediateMpTermSynonym(new ArrayList<String>());
gene.setChildMpId(new ArrayList<String>());
gene.setChildMpTerm(new ArrayList<String>());
gene.setChildMpTermSynonym(new ArrayList<String>());
gene.setChildMpId(new ArrayList<String>());
gene.setChildMpTerm(new ArrayList<String>());
gene.setChildMpTermSynonym(new ArrayList<String>());
gene.setInferredMaId(new ArrayList<String>());
gene.setInferredMaTerm(new ArrayList<String>());
gene.setInferredMaTermSynonym(new ArrayList<String>());
gene.setSelectedTopLevelMaId(new ArrayList<String>());
gene.setSelectedTopLevelMaTerm(new ArrayList<String>());
gene.setSelectedTopLevelMaTermSynonym(new ArrayList<String>());
gene.setInferredChildMaId(new ArrayList<String>());
gene.setInferredChildMaTerm(new ArrayList<String>());
gene.setInferredChildMaTermSynonym(new ArrayList<String>());
gene.setInferredSelectedTopLevelMaId(new ArrayList<String>());
gene.setInferredSelectedTopLevelMaTerm(new ArrayList<String>());
gene.setInferredSelectedTopLevelMaTermSynonym(new ArrayList<String>());
// Add all ontology information from images associated to this gene
if (sangerImages.containsKey(allele.getMgiAccessionId())) {
List<SangerImageDTO> list = sangerImages.get(allele.getMgiAccessionId());
for (SangerImageDTO image : list) {
if (image.getMp_id() != null && ! gene.getMpId().contains(image.getMp_id())) {
gene.getMpId().addAll(image.getMp_id());
gene.getMpTerm().addAll(image.getMpTerm());
if (image.getMpSyns() != null) {
gene.getMpTermSynonym().addAll(image.getMpSyns());
}
if (image.getAnnotatedHigherLevelMpTermId() != null) {
gene.getTopLevelMpId().addAll(image.getAnnotatedHigherLevelMpTermId());
}
if (image.getAnnotatedHigherLevelMpTermName() != null) {
gene.getTopLevelMpTerm().addAll(image.getAnnotatedHigherLevelMpTermName());
}
if (image.getTopLevelMpTermSynonym() != null) {
gene.getTopLevelMpTermSynonym().addAll(image.getTopLevelMpTermSynonym());
}
if (image.getIntermediateMpId() != null) {
gene.getIntermediateMpId().addAll(image.getIntermediateMpId());
}
if (image.getIntermediateMpTerm() != null) {
gene.getIntermediateMpTerm().addAll(image.getIntermediateMpTerm());
}
if (image.getIntermediateMpTermSyn() != null) {
gene.getIntermediateMpTermSynonym().addAll(image.getIntermediateMpTermSyn());
}
}
if (image.getMaTermId() != null) {
gene.getMaId().addAll(image.getMaTermId());
gene.getMaTerm().addAll(image.getMaTermName());
if (image.getMaTermSynonym() != null) {
gene.getMaTermSynonym().addAll(image.getMaTermSynonym());
}
if (image.getSelectedTopLevelMaTermId() != null) {
gene.setSelectedTopLevelMaId(image.getSelectedTopLevelMaTermId());
}
if (image.getSelectedTopLevelMaTerm() != null) {
gene.setSelectedTopLevelMaTerm(image.getSelectedTopLevelMaTerm());
}
if (image.getSelectedTopLevelMaTermSynonym() != null) {
gene.setSelectedTopLevelMaTermSynonym(image.getSelectedTopLevelMaTermSynonym());
}
}
}
}
// impcImages associated with genes, MAs, pipelines/procedures/parameters
if ( impcImages.containsKey(allele.getMgiAccessionId()) ){
//if ( impcImage.getGeneAccession() != null && ! impcImage.getGeneAccession().equals(ma.getMgiAccessionId()) ){
List<ImageDTO> impcImagesList = impcImages.get(allele.getMgiAccessionId());
for( ImageDTO impcImage : impcImagesList ){
// MAs
if (gene.getMaId() == null){
gene.setMaId(impcImage.getMaTermId());
gene.setMaTerm(impcImage.getMaTerm());
gene.setMaTermSynonym(impcImage.getMarkerSynonym());
gene.setTopLevelMpId(impcImage.getTopLevelMaIds());
gene.setTopLevelMpTerm(impcImage.getTopLeveMaTerm());
gene.setTopLevelMpTermSynonym(impcImage.getTopLevelMaTermSynonym());
}
else {
Set<String> maids = new HashSet<>();
if (gene.getMaId()!=null){maids.addAll(gene.getMaId()); }
if (impcImage.getMaTermId()!=null){maids.addAll(impcImage.getMaTermId()); }
if (maids.size()>0) {
gene.setMaId(new ArrayList(maids));
}
Set<String> materms = new HashSet<>();
if (gene.getMaTerm()!=null){materms.addAll(gene.getMaTerm()); }
if (impcImage.getMaTerm()!=null){materms.addAll(impcImage.getMaTerm()); }
if (materms.size()>0) {
gene.setMaTerm(new ArrayList(materms));
}
Set<String> matermsyns = new HashSet<>();
if (gene.getMaTermSynonym()!=null){matermsyns.addAll(gene.getMaTermSynonym()); }
if (impcImage.getMaTermSynonym()!=null){matermsyns.addAll(impcImage.getMaTermSynonym()); }
if (matermsyns.size()>0) {
gene.setMaTermSynonym(new ArrayList(matermsyns));
}
Set<String> topmaids = new HashSet<>();
if (gene.getTopLevelMpId()!=null){topmaids.addAll(gene.getTopLevelMpId()); }
if (impcImage.getTopLevelMaIds()!=null){topmaids.addAll(impcImage.getTopLevelMaIds()); }
if (topmaids.size()>0) {
gene.setTopLevelMpId(new ArrayList(topmaids));
}
Set<String> topmaterms = new HashSet<>();
if (gene.getTopLevelMpTerm()!=null){topmaterms.addAll(gene.getTopLevelMpTerm()); }
if (impcImage.getTopLeveMaTerm()!=null){topmaterms.addAll(impcImage.getTopLeveMaTerm()); }
if (topmaterms.size()>0) {
gene.setTopLevelMpTerm(new ArrayList(topmaterms));
}
Set<String> topmatermsyns = new HashSet<>();
if (gene.getTopLevelMpTermSynonym()!=null){topmatermsyns.addAll(gene.getTopLevelMpTermSynonym()); }
if (impcImage.getTopLevelMaTermSynonym()!=null){topmatermsyns.addAll(impcImage.getTopLevelMaTermSynonym()); }
if (topmatermsyns.size()>0) {
gene.setTopLevelMpTermSynonym(new ArrayList(topmatermsyns));
}
}
// pipeline
if ( gene.getPipelineStableId() == null ){
gene.setPipelineStableId(Arrays.asList(impcImage.getPipelineStableId()));
gene.setPipelineName(Arrays.asList(impcImage.getPipelineName()));
}
else {
Set<String> pipenames = new HashSet<>();
if (gene.getPipelineName()!=null){pipenames.addAll(gene.getPipelineName()); }
if (impcImage.getPipelineName()!=null){pipenames.add(impcImage.getPipelineName()); }
if (pipenames.size()>0) {
gene.setTopLevelMpTermSynonym(new ArrayList(pipenames));
}
Set<String> pipesid = new HashSet<>();
if (gene.getPipelineStableId()!=null){pipesid.addAll(gene.getPipelineStableId()); }
if (impcImage.getPipelineStableId()!=null){pipesid.add(impcImage.getPipelineStableId()); }
if (pipesid.size()>0) {
gene.setPipelineStableId(new ArrayList(pipesid));
}
}
// procedure
if ( gene.getProcedureStableId() == null ){
gene.setProcedureStableId(Arrays.asList(impcImage.getProcedureStableId()));
gene.setProcedureName(Arrays.asList(impcImage.getProcedureName()));
}
else {
Set<String> procnames = new HashSet<>();
if (gene.getProcedureName() !=null){procnames.addAll(gene.getProcedureName()); }
if (impcImage.getProcedureName()!=null){procnames.add(impcImage.getProcedureName()); }
if (procnames.size()>0) {
gene.setProcedureName(new ArrayList(procnames));
}
Set<String> procsids = new HashSet<>();
if (gene.getProcedureStableId() !=null){procsids.addAll(gene.getProcedureStableId()); }
if (impcImage.getProcedureStableId()!=null){procsids.add(impcImage.getProcedureStableId()); }
if (procsids.size()>0) {
gene.setProcedureStableId(new ArrayList(procsids));
}
}
// parameter
if ( gene.getParameterStableId() == null ){
gene.setParameterStableId(Arrays.asList(impcImage.getParameterStableId()));
gene.setParameterStableId(Arrays.asList(impcImage.getParameterStableId()));
}
else {
Set<String> paramnames = new HashSet<>();
if (gene.getParameterName() !=null){paramnames.addAll(gene.getParameterName()); }
if (impcImage.getParameterName()!=null){paramnames.add(impcImage.getParameterName()); }
if (paramnames.size()>0) {
gene.setParameterName(new ArrayList(paramnames));
}
Set<String> paramsids = new HashSet<>();
if (gene.getParameterStableId() !=null){paramsids.addAll(gene.getParameterStableId()); }
if (impcImage.getParameterStableId()!=null){paramsids.add(impcImage.getParameterStableId()); }
if (paramsids.size()>0) {
gene.setParameterStableId(new ArrayList(paramsids));
}
}
}
}
// Add all ontology information directly associated from MP to this gene
if (StringUtils.isNotEmpty(allele.getMgiAccessionId())) {
if (mgiAccessionToMP.containsKey(allele.getMgiAccessionId())) {
List<MpDTO> mps = mgiAccessionToMP.get(allele.getMgiAccessionId());
for (MpDTO mp : mps) {
gene.getMpId().add(mp.getMpId());
gene.getMpTerm().add(mp.getMpTerm());
if (mp.getMpTermSynonym() != null) {
gene.getMpTermSynonym().addAll(mp.getMpTermSynonym());
}
if (mp.getOntologySubset() != null) {
gene.getOntologySubset().addAll(mp.getOntologySubset());
}
if (mp.getHpId() != null) {
gene.getHpId().addAll(mp.getHpId());
gene.getHpTerm().addAll(mp.getHpTerm());
}
if (mp.getTopLevelMpId() != null) {
gene.getTopLevelMpId().addAll(mp.getTopLevelMpId());
gene.getTopLevelMpTerm().addAll(mp.getTopLevelMpTerm());
}
if (mp.getTopLevelMpTermSynonym() != null) {
gene.getTopLevelMpTermSynonym().addAll(mp.getTopLevelMpTermSynonym());
}
if (mp.getIntermediateMpId() != null) {
gene.getIntermediateMpId().addAll(mp.getIntermediateMpId());
gene.getIntermediateMpTerm().addAll(mp.getIntermediateMpTerm());
}
if (mp.getIntermediateMpTermSynonym() != null) {
gene.getIntermediateMpTermSynonym().addAll(mp.getIntermediateMpTermSynonym());
}
if (mp.getChildMpId() != null) {
gene.getChildMpId().addAll(mp.getChildMpId());
gene.getChildMpTerm().addAll(mp.getChildMpTerm());
}
if (mp.getChildMpTermSynonym() != null) {
gene.getChildMpTermSynonym().addAll(mp.getChildMpTermSynonym());
}
if (mp.getInferredMaId() != null) {
gene.getInferredMaId().addAll(mp.getInferredMaId());
gene.getInferredMaTerm().addAll(mp.getInferredMaTerm());
}
if (mp.getInferredMaTermSynonym() != null) {
gene.getInferredMaTermSynonym().addAll(mp.getInferredMaTermSynonym());
}
if (mp.getInferredSelectedTopLevelMaId() != null) {
gene.getInferredSelectedTopLevelMaId().addAll(mp.getInferredSelectedTopLevelMaId());
gene.getInferredSelectedTopLevelMaTerm().addAll(mp.getInferredSelectedTopLevelMaTerm());
}
if (mp.getInferredSelectedTopLevelMaTermSynonym() != null) {
gene.getInferredSelectedTopLevelMaTermSynonym().addAll(mp.getInferredSelectedTopLevelMaTermSynonym());
}
if (mp.getInferredChildMaId() != null) {
gene.getInferredChildMaId().addAll(mp.getInferredChildMaId());
gene.getInferredChildMaTerm().addAll(mp.getInferredChildMaTerm());
}
if (mp.getInferredChildMaTermSynonym() != null) {
gene.getInferredChildMaTermSynonym().addAll(mp.getInferredChildMaTermSynonym());
}
}
}
}
/**
* Unique all the sets
*/
gene.setMpId(new ArrayList<>(new HashSet<>(gene.getMpId())));
gene.setMpTerm(new ArrayList<>(new HashSet<>(gene.getMpTerm())));
gene.setMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getMpTermSynonym())));
gene.setMpTermDefinition(new ArrayList<>(new HashSet<>(gene.getMpTermDefinition())));
gene.setOntologySubset(new ArrayList<>(new HashSet<>(gene.getOntologySubset())));
gene.setMaId(new ArrayList<>(new HashSet<>(gene.getMaId())));
gene.setMaTerm(new ArrayList<>(new HashSet<>(gene.getMaTerm())));
gene.setMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getMaTermSynonym())));
gene.setMaTermDefinition(new ArrayList<>(new HashSet<>(gene.getMaTermDefinition())));
gene.setHpId(new ArrayList<>(new HashSet<>(gene.getHpId())));
gene.setHpTerm(new ArrayList<>(new HashSet<>(gene.getHpTerm())));
gene.setTopLevelMpId(new ArrayList<>(new HashSet<>(gene.getTopLevelMpId())));
gene.setTopLevelMpTerm(new ArrayList<>(new HashSet<>(gene.getTopLevelMpTerm())));
gene.setTopLevelMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getTopLevelMpTermSynonym())));
gene.setIntermediateMpId(new ArrayList<>(new HashSet<>(gene.getIntermediateMpId())));
gene.setIntermediateMpTerm(new ArrayList<>(new HashSet<>(gene.getIntermediateMpTerm())));
gene.setIntermediateMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getIntermediateMpTermSynonym())));
gene.setChildMpId(new ArrayList<>(new HashSet<>(gene.getChildMpId())));
gene.setChildMpTerm(new ArrayList<>(new HashSet<>(gene.getChildMpTerm())));
gene.setChildMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getChildMpTermSynonym())));
gene.setChildMpId(new ArrayList<>(new HashSet<>(gene.getChildMpId())));
gene.setChildMpTerm(new ArrayList<>(new HashSet<>(gene.getChildMpTerm())));
gene.setChildMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getChildMpTermSynonym())));
gene.setInferredMaId(new ArrayList<>(new HashSet<>(gene.getInferredMaId())));
gene.setInferredMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredMaTerm())));
gene.setInferredMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredMaTermSynonym())));
gene.setSelectedTopLevelMaId(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaId())));
gene.setSelectedTopLevelMaTerm(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaTerm())));
gene.setSelectedTopLevelMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaTermSynonym())));
gene.setInferredChildMaId(new ArrayList<>(new HashSet<>(gene.getInferredChildMaId())));
gene.setInferredChildMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredChildMaTerm())));
gene.setInferredChildMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredChildMaTermSynonym())));
gene.setInferredSelectedTopLevelMaId(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaId())));
gene.setInferredSelectedTopLevelMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaTerm())));
gene.setInferredSelectedTopLevelMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaTermSynonym())));
documentCount++;
geneCore.addBean(gene, 60000);
count ++;
if (count % 10000 == 0) {
logger.info(" added " + count + " beans");
}
}
logger.info("Committing to gene core for last time");
geneCore.commit();
} catch (IOException | SolrServerException e) {
e.printStackTrace();
throw new IndexerException(e);
}
long endTime = System.currentTimeMillis();
logger.info("time was " + (endTime - startTime) / 1000);
logger.info("Gene Indexer complete!");
}
// PROTECTED METHODS
@Override
protected Logger getLogger() {
return logger;
}
// PRIVATE METHODS
private void initialiseSupportingBeans() throws IndexerException, SolrServerException, IOException, SQLException {
phenotypeSummaryGeneAccessionsToPipelineInfo = populatePhenotypeCallSummaryGeneAccessions();
sangerImages = IndexerMap.getSangerImagesByMgiAccession(imagesCore);
impcImages = populateImpcImages();
mgiAccessionToMP = populateMgiAccessionToMp();
logger.info("mgiAccessionToMP size=" + mgiAccessionToMP.size());
}
private Map<String, List<MpDTO>> populateMgiAccessionToMp() throws IndexerException {
return SolrUtils.populateMgiAccessionToMp(mpCore);
}
private Map<String, List<ImageDTO>> populateImpcImages() throws SolrServerException, IOException, SQLException {
List<String> impcImagesFields = Arrays.asList(
ImageDTO.GENE_ACCESSION_ID,
ImageDTO.MA_ID,
ImageDTO.MA_TERM,
ImageDTO.MA_TERM_SYNONYM,
ImageDTO.SELECTED_TOP_LEVEL_MA_ID,
ImageDTO.SELECTED_TOP_LEVEL_MA_TERM_SYNONYM,
ImageDTO.PIPELINE_NAME,
ImageDTO.PIPELINE_STABLE_ID,
ImageDTO.PROCEDURE_NAME,
ImageDTO.PROCEDURE_STABLE_ID,
ImageDTO.PARAMETER_NAME,
ImageDTO.PARAMETER_STABLE_ID
);
SolrQuery impcImgesQuery = new SolrQuery()
.setQuery("*:*")
.setFields(StringUtils.join(impcImagesFields, ","))
.setRows(Integer.MAX_VALUE);
List<ImageDTO> impcImagesList = impcImagesCore.query(impcImgesQuery).getBeans(ImageDTO.class);
for (ImageDTO impcImage : impcImagesList) {
String geneAccId = impcImage. getGeneAccession();
if ( geneAccId == null ){
continue;
}
if ( !impcImages.containsKey(geneAccId) ){
impcImages.put(geneAccId, new ArrayList<ImageDTO>());
}
impcImages.get(geneAccId).add(impcImage);
}
logger.info("Finished populating impcImages using mgi_accession_id as key");
return impcImages;
}
private Map<String, List<Map<String, String>>> populatePhenotypeCallSummaryGeneAccessions() {
logger.info("populating PCS pipeline info");
String queryString = "select pcs.*, param.name, param.stable_id, proc.stable_id, proc.name, pipe.stable_id, pipe.name"
+ " from phenotype_call_summary pcs"
+ " inner join ontology_term term on term.acc=mp_acc"
+ " inner join genomic_feature gf on gf.acc=pcs.gf_acc"
+ " inner join phenotype_parameter param on param.id=pcs.parameter_id"
+ " inner join phenotype_procedure proc on proc.id=pcs.procedure_id"
+ " inner join phenotype_pipeline pipe on pipe.id=pcs.pipeline_id";
try (PreparedStatement p = komp2DbConnection.prepareStatement(queryString)) {
ResultSet resultSet = p.executeQuery();
while (resultSet.next()) {
String gf_acc = resultSet.getString("gf_acc");
Map<String, String> rowMap = new HashMap<>();
rowMap.put(ObservationDTO.PARAMETER_NAME, resultSet.getString("param.name"));
rowMap.put(ObservationDTO.PARAMETER_STABLE_ID, resultSet.getString("param.stable_id"));
rowMap.put(ObservationDTO.PROCEDURE_STABLE_ID, resultSet.getString("proc.stable_id"));
rowMap.put(ObservationDTO.PROCEDURE_NAME, resultSet.getString("proc.name"));
rowMap.put(ObservationDTO.PIPELINE_STABLE_ID, resultSet.getString("pipe.stable_id"));
rowMap.put(ObservationDTO.PIPELINE_NAME, resultSet.getString("pipe.name"));
rowMap.put("proc_param_name", resultSet.getString("proc.name") + "___" + resultSet.getString("param.name"));
rowMap.put("proc_param_stable_id", resultSet.getString("proc.stable_id") + "___" + resultSet.getString("param.stable_id"));
List<Map<String, String>> rows = null;
if (phenotypeSummaryGeneAccessionsToPipelineInfo.containsKey(gf_acc)) {
rows = phenotypeSummaryGeneAccessionsToPipelineInfo.get(gf_acc);
} else {
rows = new ArrayList<>();
}
rows.add(rowMap);
phenotypeSummaryGeneAccessionsToPipelineInfo.put(gf_acc, rows);
}
} catch (Exception e) {
e.printStackTrace();
}
return phenotypeSummaryGeneAccessionsToPipelineInfo;
}
public static void main(String[] args) throws IndexerException, SQLException {
GeneIndexer indexer = new GeneIndexer();
indexer.initialise(args);
indexer.run();
indexer.validateBuild();
logger.info("Process finished. Exiting.");
}
}
| added impcImages to gene core | src/main/java/uk/ac/ebi/phenotype/solr/indexer/GeneIndexer.java | added impcImages to gene core | <ide><path>rc/main/java/uk/ac/ebi/phenotype/solr/indexer/GeneIndexer.java
<ide> long startTime = System.currentTimeMillis();
<ide> try {
<ide> logger.info("Starting Gene Indexer...");
<del>
<add>
<ide> initialiseSupportingBeans();
<ide>
<ide> int count = 0;
<ide> List<AlleleDTO> alleles = IndexerMap.getAlleles(alleleCore);
<ide> logger.info("alleles size=" + alleles.size());
<del>
<add>
<ide> geneCore.deleteByQuery("*:*");
<ide>
<ide> for (AlleleDTO allele : alleles) {
<ide> if (image.getMaTermSynonym() != null) {
<ide> gene.getMaTermSynonym().addAll(image.getMaTermSynonym());
<ide> }
<del>
<add>
<ide> if (image.getSelectedTopLevelMaTermId() != null) {
<ide> gene.setSelectedTopLevelMaId(image.getSelectedTopLevelMaTermId());
<ide> }
<add>
<ide> if (image.getSelectedTopLevelMaTerm() != null) {
<ide> gene.setSelectedTopLevelMaTerm(image.getSelectedTopLevelMaTerm());
<ide> }
<ide> gene.setMaId(impcImage.getMaTermId());
<ide> gene.setMaTerm(impcImage.getMaTerm());
<ide> gene.setMaTermSynonym(impcImage.getMarkerSynonym());
<del> gene.setTopLevelMpId(impcImage.getTopLevelMaIds());
<del> gene.setTopLevelMpTerm(impcImage.getTopLeveMaTerm());
<del> gene.setTopLevelMpTermSynonym(impcImage.getTopLevelMaTermSynonym());
<add> //System.out.println("***selected top level ma id: "+ impcImage.getTopLevelMaIds());
<add> gene.setSelectedTopLevelMaId(impcImage.getTopLevelMaIds());
<add> gene.setSelectedTopLevelMaTerm(impcImage.getTopLeveMaTerm());
<add> gene.setSelectedTopLevelMaTermSynonym(impcImage.getTopLevelMaTermSynonym());
<ide> }
<ide> else {
<ide>
<ide> gene.setMaTermSynonym(new ArrayList(matermsyns));
<ide> }
<ide> Set<String> topmaids = new HashSet<>();
<del> if (gene.getTopLevelMpId()!=null){topmaids.addAll(gene.getTopLevelMpId()); }
<add> if (gene.getSelectedTopLevelMaId()!=null){topmaids.addAll(gene.getSelectedTopLevelMaId()); }
<ide> if (impcImage.getTopLevelMaIds()!=null){topmaids.addAll(impcImage.getTopLevelMaIds()); }
<ide> if (topmaids.size()>0) {
<del> gene.setTopLevelMpId(new ArrayList(topmaids));
<add> gene.setSelectedTopLevelMaId(new ArrayList(topmaids));
<ide> }
<ide> Set<String> topmaterms = new HashSet<>();
<del> if (gene.getTopLevelMpTerm()!=null){topmaterms.addAll(gene.getTopLevelMpTerm()); }
<add> if (gene.getSelectedTopLevelMaTerm()!=null){topmaterms.addAll(gene.getSelectedTopLevelMaTerm()); }
<ide> if (impcImage.getTopLeveMaTerm()!=null){topmaterms.addAll(impcImage.getTopLeveMaTerm()); }
<ide> if (topmaterms.size()>0) {
<del> gene.setTopLevelMpTerm(new ArrayList(topmaterms));
<add> gene.setSelectedTopLevelMaTerm(new ArrayList(topmaterms));
<ide> }
<ide> Set<String> topmatermsyns = new HashSet<>();
<del> if (gene.getTopLevelMpTermSynonym()!=null){topmatermsyns.addAll(gene.getTopLevelMpTermSynonym()); }
<add> if (gene.getSelectedTopLevelMaTermSynonym()!=null){topmatermsyns.addAll(gene.getSelectedTopLevelMaTermSynonym()); }
<ide> if (impcImage.getTopLevelMaTermSynonym()!=null){topmatermsyns.addAll(impcImage.getTopLevelMaTermSynonym()); }
<ide> if (topmatermsyns.size()>0) {
<del> gene.setTopLevelMpTermSynonym(new ArrayList(topmatermsyns));
<add> gene.setSelectedTopLevelMaTermSynonym(new ArrayList(topmatermsyns));
<ide> }
<ide>
<ide> }
<ide> ImageDTO.MA_TERM,
<ide> ImageDTO.MA_TERM_SYNONYM,
<ide> ImageDTO.SELECTED_TOP_LEVEL_MA_ID,
<add> ImageDTO.SELECTED_TOP_LEVEL_MA_TERM,
<ide> ImageDTO.SELECTED_TOP_LEVEL_MA_TERM_SYNONYM,
<ide>
<ide> ImageDTO.PIPELINE_NAME, |
|
Java | apache-2.0 | 8f29b162fd1ed3ce9c4d66e4916a22037219f907 | 0 | realityforge/arez,realityforge/arez,realityforge/arez | package org.realityforge.arez.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import org.realityforge.arez.annotations.Container;
/**
* Annotation processor that analyzes Arez annotated source and generates Observable models.
*/
@AutoService( Processor.class )
@SupportedAnnotationTypes( { "org.realityforge.arez.annotations.Action",
"org.realityforge.arez.annotations.Computed",
"org.realityforge.arez.annotations.Container",
"org.realityforge.arez.annotations.ContainerId",
"org.realityforge.arez.annotations.Observable" } )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public final class ArezProcessor
extends AbstractJavaPoetProcessor
{
private static final ClassName AREZ_CONTEXT_CLASSNAME = ClassName.get( "org.realityforge.arez", "ArezContext" );
private static final ClassName OBSERVABLE_CLASSNAME = ClassName.get( "org.realityforge.arez", "Observable" );
private static final String FIELD_PREFIX = "$$arez$$_";
private static final String CONTEXT_FIELD_NAME = FIELD_PREFIX + "context";
/**
* {@inheritDoc}
*/
@Override
public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment env )
{
final Set<? extends Element> elements = env.getElementsAnnotatedWith( Container.class );
processElements( elements );
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected void process( @Nonnull final Element element )
throws IOException, ArezProcessorException
{
final ContainerDescriptor descriptor =
ContainerDescriptorParser.parse( element, processingEnv.getElementUtils(), processingEnv.getTypeUtils() );
emitTypeSpec( descriptor.getPackageElement().getQualifiedName().toString(), builder( descriptor ) );
}
/**
* Build the enhanced class for specified container.
*/
@Nonnull
private TypeSpec builder( @Nonnull final ContainerDescriptor descriptor )
throws ArezProcessorException
{
final TypeElement element = descriptor.getElement();
final AnnotationSpec generatedAnnotation =
AnnotationSpec.builder( Generated.class ).addMember( "value", "$S", getClass().getName() ).build();
final TypeSpec.Builder builder = TypeSpec.classBuilder( "Arez_" + element.getSimpleName() ).
superclass( TypeName.get( element.asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( descriptor.asDeclaredType() ) ).
addModifiers( Modifier.FINAL ).
addAnnotation( generatedAnnotation );
ProcessorUtil.copyAccessModifiers( element, builder );
buildFields( descriptor, builder );
buildConstructors( descriptor, builder );
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
builder.addMethod( buildObservableGetter( observable ) );
}
return builder.build();
}
/**
* Generate the getter that reports that ensures that the access is reported as Observable.
*/
@Nonnull
private MethodSpec buildObservableGetter( @Nonnull final ObservableDescriptor observable )
throws ArezProcessorException
{
final ExecutableElement getter = observable.getGetter();
final MethodSpec.Builder builder = MethodSpec.methodBuilder( getter.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( getter, builder );
builder.addAnnotation( Override.class );
builder.returns( TypeName.get( getter.getReturnType() ) );
final StringBuilder superCall = new StringBuilder();
superCall.append( "return super." );
superCall.append( getter.getSimpleName() );
superCall.append( "(" );
final ArrayList<String> parameterNames = new ArrayList<>();
boolean firstParam = true;
for ( final VariableElement element : getter.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( "this.$N.reportObserved()", fieldName( observable ) );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
return builder.build();
}
/**
* Build the fields required to make class Observable. This involves;
* <ul>
* <li>the context field if there is any @Action methods.</li>
* <li>the observable object for every @Observable.</li>
* <li>the ComputedValue object for every @Computed method.</li>
* </ul>
*/
private void buildFields( @Nonnull final ContainerDescriptor descriptor, @Nonnull final TypeSpec.Builder builder )
{
// Create the field that contains the context variable if it is needed
if ( descriptor.shouldStoreContext() )
{
final FieldSpec.Builder field =
FieldSpec.builder( AREZ_CONTEXT_CLASSNAME, CONTEXT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
final FieldSpec.Builder field =
FieldSpec.builder( OBSERVABLE_CLASSNAME, fieldName( observable ), Modifier.FINAL, Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
}
/**
* Return the name of the field for specified Observable.
*/
@Nonnull
private String fieldName( @Nonnull final ObservableDescriptor observable )
{
return FIELD_PREFIX + observable.getName();
}
/**
* Build all constructors as they appear on the Container class.
* Arez Observable fields are populated as required and parameters are passed up to superclass.
*/
private void buildConstructors( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final TypeSpec.Builder builder )
{
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( descriptor.getElement() ) )
{
builder.addMethod( buildConstructor( descriptor, constructor ) );
}
}
/**
* Build a constructor based on the supplied constructor
*/
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final ExecutableElement constructor )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
ProcessorUtil.copyAccessModifiers( constructor, builder );
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
// Add the first context class parameter
{
final ParameterSpec.Builder param =
ParameterSpec.builder( AREZ_CONTEXT_CLASSNAME, CONTEXT_FIELD_NAME, Modifier.FINAL ).
addAnnotation( Nonnull.class );
builder.addParameter( param.build() );
}
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
if ( descriptor.shouldStoreContext() )
{
builder.addStatement( "this.$N = $N", CONTEXT_FIELD_NAME, CONTEXT_FIELD_NAME );
}
final String prefix = descriptor.getName().isEmpty() ? "" : descriptor.getName() + ".";
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
builder.addStatement( "this.$N = $N.createObservable( $S )",
fieldName( observable ),
CONTEXT_FIELD_NAME,
prefix + observable.getName() );
}
return builder.build();
}
}
| processor/src/main/java/org/realityforge/arez/processor/ArezProcessor.java | package org.realityforge.arez.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import org.realityforge.arez.annotations.Container;
/**
* Annotation processor that analyzes Arez annotated source and generates Observable models.
*/
@AutoService( Processor.class )
@SupportedAnnotationTypes( { "org.realityforge.arez.annotations.Action",
"org.realityforge.arez.annotations.Computed",
"org.realityforge.arez.annotations.Container",
"org.realityforge.arez.annotations.ContainerId",
"org.realityforge.arez.annotations.Observable" } )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public final class ArezProcessor
extends AbstractJavaPoetProcessor
{
private static final ClassName AREZ_CONTEXT_CLASSNAME = ClassName.get( "org.realityforge.arez", "ArezContext" );
private static final ClassName OBSERVABLE_CLASSNAME = ClassName.get( "org.realityforge.arez", "Observable" );
private static final String FIELD_PREFIX = "$$arez$$_";
private static final String CONTEXT_FIELD_NAME = FIELD_PREFIX + "context";
/**
* {@inheritDoc}
*/
@Override
public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment env )
{
final Set<? extends Element> elements = env.getElementsAnnotatedWith( Container.class );
processElements( elements );
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected void process( @Nonnull final Element element )
throws IOException, ArezProcessorException
{
final ContainerDescriptor descriptor =
ContainerDescriptorParser.parse( element, processingEnv.getElementUtils(), processingEnv.getTypeUtils() );
emitTypeSpec( descriptor.getPackageElement().getQualifiedName().toString(), builder( descriptor ) );
}
/**
* Build the enhanced class for specified container.
*/
@Nonnull
private TypeSpec builder( @Nonnull final ContainerDescriptor descriptor )
throws ArezProcessorException
{
final TypeElement element = descriptor.getElement();
final AnnotationSpec generatedAnnotation =
AnnotationSpec.builder( Generated.class ).addMember( "value", "$S", getClass().getName() ).build();
final TypeSpec.Builder builder = TypeSpec.classBuilder( "Arez_" + element.getSimpleName() ).
superclass( TypeName.get( element.asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( descriptor.asDeclaredType() ) ).
addModifiers( Modifier.FINAL ).
addAnnotation( generatedAnnotation );
ProcessorUtil.copyAccessModifiers( element, builder );
buildFields( descriptor, builder );
buildConstructors( descriptor, builder );
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
builder.addMethod( buildObservableGetter( descriptor, observable ) );
}
return builder.build();
}
/**
* Generate the getter that reports that ensures that the access is reported as Observable.
*/
@Nonnull
private MethodSpec buildObservableGetter( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final ObservableDescriptor observable )
throws ArezProcessorException
{
final ExecutableElement getter = observable.getGetter();
final MethodSpec.Builder builder = MethodSpec.methodBuilder( getter.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( getter, builder );
builder.addAnnotation( Override.class );
builder.returns( TypeName.get( getter.getReturnType() ) );
final StringBuilder superCall = new StringBuilder();
superCall.append( "return super." );
superCall.append( getter.getSimpleName() );
superCall.append( "(" );
final ArrayList<String> parameterNames = new ArrayList<>();
boolean firstParam = true;
for ( final VariableElement element : getter.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( "this.$N.reportObserved()", fieldName( observable ) );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
return builder.build();
}
/**
* Build the fields required to make class Observable. This involves;
* <ul>
* <li>the context field if there is any @Action methods.</li>
* <li>the observable object for every @Observable.</li>
* <li>the ComputedValue object for every @Computed method.</li>
* </ul>
*/
private void buildFields( @Nonnull final ContainerDescriptor descriptor, @Nonnull final TypeSpec.Builder builder )
{
// Create the field that contains the context variable if it is needed
if ( descriptor.shouldStoreContext() )
{
final FieldSpec.Builder field =
FieldSpec.builder( AREZ_CONTEXT_CLASSNAME, CONTEXT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
final FieldSpec.Builder field =
FieldSpec.builder( OBSERVABLE_CLASSNAME, fieldName( observable ), Modifier.FINAL, Modifier.PRIVATE ).
addAnnotation( Nonnull.class );
builder.addField( field.build() );
}
}
/**
* Return the name of the field for specified Observable.
*/
@Nonnull
private String fieldName( @Nonnull final ObservableDescriptor observable )
{
return FIELD_PREFIX + observable.getName();
}
/**
* Build all constructors as they appear on the Container class.
* Arez Observable fields are populated as required and parameters are passed up to superclass.
*/
private void buildConstructors( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final TypeSpec.Builder builder )
{
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( descriptor.getElement() ) )
{
builder.addMethod( buildConstructor( descriptor, constructor ) );
}
}
/**
* Build a constructor based on the supplied constructor
*/
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ContainerDescriptor descriptor,
@Nonnull final ExecutableElement constructor )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
ProcessorUtil.copyAccessModifiers( constructor, builder );
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
// Add the first context class parameter
{
final ParameterSpec.Builder param =
ParameterSpec.builder( AREZ_CONTEXT_CLASSNAME, CONTEXT_FIELD_NAME, Modifier.FINAL ).
addAnnotation( Nonnull.class );
builder.addParameter( param.build() );
}
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
if ( descriptor.shouldStoreContext() )
{
builder.addStatement( "this.$N = $N", CONTEXT_FIELD_NAME, CONTEXT_FIELD_NAME );
}
final String prefix = descriptor.getName().isEmpty() ? "" : descriptor.getName() + ".";
for ( final ObservableDescriptor observable : descriptor.getObservables() )
{
builder.addStatement( "this.$N = $N.createObservable( $S )",
fieldName( observable ),
CONTEXT_FIELD_NAME,
prefix + observable.getName() );
}
return builder.build();
}
}
| Remove unused parameter
| processor/src/main/java/org/realityforge/arez/processor/ArezProcessor.java | Remove unused parameter | <ide><path>rocessor/src/main/java/org/realityforge/arez/processor/ArezProcessor.java
<ide>
<ide> for ( final ObservableDescriptor observable : descriptor.getObservables() )
<ide> {
<del> builder.addMethod( buildObservableGetter( descriptor, observable ) );
<add> builder.addMethod( buildObservableGetter( observable ) );
<ide> }
<ide>
<ide> return builder.build();
<ide> * Generate the getter that reports that ensures that the access is reported as Observable.
<ide> */
<ide> @Nonnull
<del> private MethodSpec buildObservableGetter( @Nonnull final ContainerDescriptor descriptor,
<del> @Nonnull final ObservableDescriptor observable )
<add> private MethodSpec buildObservableGetter( @Nonnull final ObservableDescriptor observable )
<ide> throws ArezProcessorException
<ide> {
<ide> final ExecutableElement getter = observable.getGetter(); |
|
Java | apache-2.0 | 83fd13b20bc0d6f91a969911b4582992139b1118 | 0 | zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro,zolyfarkas/avro | /**
* 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.avro.generic;
import java.util.Set;
/** An enum symbol. */
public interface GenericEnumSymbol<E extends GenericEnumSymbol<E>>
extends GenericContainer, Comparable<E> {
default Set<String> getAliasses() {
return getSchema().getEnumSymbolAliases().get(toString());
}
default String getSymbol() {
return toString();
}
/** Return the symbol. */
String toString();
}
| lang/java/avro/src/main/java/org/apache/avro/generic/GenericEnumSymbol.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.avro.generic;
import java.util.Set;
/** An enum symbol. */
public interface GenericEnumSymbol<T extends GenericEnumSymbol>
extends GenericContainer, Comparable<T> {
default Set<String> getAliasses() {
return getSchema().getEnumSymbolAliases().get(toString());
}
default String getSymbol() {
return toString();
}
/** Return the symbol. */
String toString();
}
| [cleanup] | lang/java/avro/src/main/java/org/apache/avro/generic/GenericEnumSymbol.java | [cleanup] | <ide><path>ang/java/avro/src/main/java/org/apache/avro/generic/GenericEnumSymbol.java
<ide>
<ide>
<ide> /** An enum symbol. */
<del>public interface GenericEnumSymbol<T extends GenericEnumSymbol>
<del> extends GenericContainer, Comparable<T> {
<add>public interface GenericEnumSymbol<E extends GenericEnumSymbol<E>>
<add> extends GenericContainer, Comparable<E> {
<ide>
<ide> default Set<String> getAliasses() {
<ide> return getSchema().getEnumSymbolAliases().get(toString()); |
|
Java | apache-2.0 | f548be901a9b77c3681b3fc79d2546c82fd6fadf | 0 | lilredindy/selenium,carlosroh/selenium,MeetMe/selenium,mach6/selenium,dandv/selenium,chrisblock/selenium,mestihudson/selenium,blackboarddd/selenium,jabbrwcky/selenium,sag-enorman/selenium,gorlemik/selenium,gurayinan/selenium,SeleniumHQ/selenium,jsakamoto/selenium,doungni/selenium,s2oBCN/selenium,quoideneuf/selenium,houchj/selenium,gurayinan/selenium,amar-sharma/selenium,lilredindy/selenium,gregerrag/selenium,krmahadevan/selenium,markodolancic/selenium,davehunt/selenium,mestihudson/selenium,lilredindy/selenium,o-schneider/selenium,DrMarcII/selenium,o-schneider/selenium,oddui/selenium,AutomatedTester/selenium,jerome-jacob/selenium,tarlabs/selenium,skurochkin/selenium,carsonmcdonald/selenium,lmtierney/selenium,xmhubj/selenium,Dude-X/selenium,JosephCastro/selenium,actmd/selenium,carsonmcdonald/selenium,dimacus/selenium,TikhomirovSergey/selenium,Sravyaksr/selenium,eric-stanley/selenium,slongwang/selenium,Herst/selenium,dcjohnson1989/selenium,juangj/selenium,gregerrag/selenium,valfirst/selenium,Dude-X/selenium,wambat/selenium,DrMarcII/selenium,lrowe/selenium,alexec/selenium,rrussell39/selenium,TheBlackTuxCorp/selenium,bartolkaruza/selenium,knorrium/selenium,xsyntrex/selenium,asolntsev/selenium,Jarob22/selenium,mach6/selenium,rplevka/selenium,kalyanjvn1/selenium,actmd/selenium,chrisblock/selenium,DrMarcII/selenium,TikhomirovSergey/selenium,slongwang/selenium,rplevka/selenium,p0deje/selenium,bartolkaruza/selenium,lukeis/selenium,titusfortner/selenium,tbeadle/selenium,rrussell39/selenium,mojwang/selenium,rplevka/selenium,asashour/selenium,wambat/selenium,carsonmcdonald/selenium,knorrium/selenium,markodolancic/selenium,minhthuanit/selenium,titusfortner/selenium,krmahadevan/selenium,lmtierney/selenium,xmhubj/selenium,titusfortner/selenium,carsonmcdonald/selenium,carlosroh/selenium,s2oBCN/selenium,xsyntrex/selenium,SeleniumHQ/selenium,bayandin/selenium,mojwang/selenium,dimacus/selenium,yukaReal/selenium,vveliev/selenium,eric-stanley/selenium,zenefits/selenium,dcjohnson1989/selenium,gurayinan/selenium,dbo/selenium,bartolkaruza/selenium,kalyanjvn1/selenium,kalyanjvn1/selenium,joshmgrant/selenium,vveliev/selenium,oddui/selenium,bmannix/selenium,5hawnknight/selenium,bayandin/selenium,BlackSmith/selenium,zenefits/selenium,rovner/selenium,krosenvold/selenium,lmtierney/selenium,amar-sharma/selenium,amikey/selenium,krosenvold/selenium,stupidnetizen/selenium,minhthuanit/selenium,jabbrwcky/selenium,TheBlackTuxCorp/selenium,minhthuanit/selenium,meksh/selenium,yukaReal/selenium,minhthuanit/selenium,amikey/selenium,jabbrwcky/selenium,knorrium/selenium,gotcha/selenium,dkentw/selenium,slongwang/selenium,juangj/selenium,davehunt/selenium,gotcha/selenium,i17c/selenium,joshbruning/selenium,AutomatedTester/selenium,krmahadevan/selenium,Jarob22/selenium,bayandin/selenium,mestihudson/selenium,Herst/selenium,JosephCastro/selenium,HtmlUnit/selenium,Sravyaksr/selenium,joshmgrant/selenium,amikey/selenium,uchida/selenium,tarlabs/selenium,Appdynamics/selenium,Tom-Trumper/selenium,wambat/selenium,tbeadle/selenium,uchida/selenium,krmahadevan/selenium,dkentw/selenium,gotcha/selenium,stupidnetizen/selenium,mojwang/selenium,wambat/selenium,lilredindy/selenium,davehunt/selenium,krmahadevan/selenium,joshmgrant/selenium,MCGallaspy/selenium,Tom-Trumper/selenium,AutomatedTester/selenium,anshumanchatterji/selenium,bayandin/selenium,sag-enorman/selenium,jerome-jacob/selenium,SouWilliams/selenium,Appdynamics/selenium,p0deje/selenium,xmhubj/selenium,wambat/selenium,HtmlUnit/selenium,xmhubj/selenium,quoideneuf/selenium,customcommander/selenium,AutomatedTester/selenium,knorrium/selenium,mojwang/selenium,Ardesco/selenium,stupidnetizen/selenium,krmahadevan/selenium,sri85/selenium,Appdynamics/selenium,Dude-X/selenium,lmtierney/selenium,lmtierney/selenium,amikey/selenium,krosenvold/selenium,thanhpete/selenium,BlackSmith/selenium,blackboarddd/selenium,lrowe/selenium,dbo/selenium,SeleniumHQ/selenium,Ardesco/selenium,tbeadle/selenium,gregerrag/selenium,sri85/selenium,tbeadle/selenium,rovner/selenium,dcjohnson1989/selenium,rovner/selenium,uchida/selenium,dbo/selenium,quoideneuf/selenium,gabrielsimas/selenium,Appdynamics/selenium,asashour/selenium,actmd/selenium,twalpole/selenium,sag-enorman/selenium,davehunt/selenium,Herst/selenium,jabbrwcky/selenium,Jarob22/selenium,rrussell39/selenium,GorK-ChO/selenium,knorrium/selenium,gabrielsimas/selenium,TikhomirovSergey/selenium,clavery/selenium,Ardesco/selenium,jsakamoto/selenium,asolntsev/selenium,dkentw/selenium,TikhomirovSergey/selenium,meksh/selenium,amikey/selenium,lukeis/selenium,p0deje/selenium,bartolkaruza/selenium,gorlemik/selenium,bmannix/selenium,dibagga/selenium,tbeadle/selenium,Sravyaksr/selenium,gotcha/selenium,markodolancic/selenium,asolntsev/selenium,amikey/selenium,jerome-jacob/selenium,zenefits/selenium,uchida/selenium,dimacus/selenium,petruc/selenium,lrowe/selenium,eric-stanley/selenium,thanhpete/selenium,SeleniumHQ/selenium,meksh/selenium,rplevka/selenium,gotcha/selenium,markodolancic/selenium,gorlemik/selenium,minhthuanit/selenium,5hawnknight/selenium,gurayinan/selenium,lrowe/selenium,carsonmcdonald/selenium,Sravyaksr/selenium,gotcha/selenium,jsakamoto/selenium,tbeadle/selenium,valfirst/selenium,dbo/selenium,gabrielsimas/selenium,Jarob22/selenium,yukaReal/selenium,bayandin/selenium,dibagga/selenium,jsakamoto/selenium,doungni/selenium,gregerrag/selenium,titusfortner/selenium,actmd/selenium,krmahadevan/selenium,dimacus/selenium,carlosroh/selenium,mach6/selenium,p0deje/selenium,TikhomirovSergey/selenium,rrussell39/selenium,HtmlUnit/selenium,Tom-Trumper/selenium,SouWilliams/selenium,dibagga/selenium,rplevka/selenium,lukeis/selenium,i17c/selenium,gorlemik/selenium,5hawnknight/selenium,customcommander/selenium,yukaReal/selenium,GorK-ChO/selenium,Dude-X/selenium,kalyanjvn1/selenium,houchj/selenium,GorK-ChO/selenium,MCGallaspy/selenium,dandv/selenium,twalpole/selenium,sri85/selenium,sri85/selenium,mestihudson/selenium,titusfortner/selenium,uchida/selenium,joshbruning/selenium,Herst/selenium,clavery/selenium,gurayinan/selenium,Tom-Trumper/selenium,thanhpete/selenium,customcommander/selenium,valfirst/selenium,doungni/selenium,Tom-Trumper/selenium,bartolkaruza/selenium,customcommander/selenium,asashour/selenium,SeleniumHQ/selenium,twalpole/selenium,houchj/selenium,sankha93/selenium,oddui/selenium,TheBlackTuxCorp/selenium,arunsingh/selenium,stupidnetizen/selenium,MeetMe/selenium,HtmlUnit/selenium,blackboarddd/selenium,jerome-jacob/selenium,knorrium/selenium,clavery/selenium,actmd/selenium,lilredindy/selenium,yukaReal/selenium,stupidnetizen/selenium,petruc/selenium,TheBlackTuxCorp/selenium,amikey/selenium,tkurnosova/selenium,chrisblock/selenium,uchida/selenium,TheBlackTuxCorp/selenium,DrMarcII/selenium,juangj/selenium,AutomatedTester/selenium,blackboarddd/selenium,HtmlUnit/selenium,asolntsev/selenium,actmd/selenium,TikhomirovSergey/selenium,5hawnknight/selenium,titusfortner/selenium,o-schneider/selenium,Dude-X/selenium,clavery/selenium,actmd/selenium,MCGallaspy/selenium,gabrielsimas/selenium,sri85/selenium,skurochkin/selenium,gurayinan/selenium,thanhpete/selenium,s2oBCN/selenium,skurochkin/selenium,houchj/selenium,Sravyaksr/selenium,MCGallaspy/selenium,blackboarddd/selenium,xsyntrex/selenium,asolntsev/selenium,i17c/selenium,lmtierney/selenium,gotcha/selenium,thanhpete/selenium,gregerrag/selenium,BlackSmith/selenium,joshbruning/selenium,dandv/selenium,SouWilliams/selenium,BlackSmith/selenium,AutomatedTester/selenium,actmd/selenium,MCGallaspy/selenium,lrowe/selenium,markodolancic/selenium,TikhomirovSergey/selenium,stupidnetizen/selenium,5hawnknight/selenium,Sravyaksr/selenium,Appdynamics/selenium,DrMarcII/selenium,houchj/selenium,krosenvold/selenium,mach6/selenium,gorlemik/selenium,Dude-X/selenium,valfirst/selenium,arunsingh/selenium,skurochkin/selenium,dibagga/selenium,mestihudson/selenium,chrisblock/selenium,thanhpete/selenium,asashour/selenium,joshmgrant/selenium,customcommander/selenium,dkentw/selenium,meksh/selenium,joshuaduffy/selenium,titusfortner/selenium,petruc/selenium,dibagga/selenium,Ardesco/selenium,mach6/selenium,bartolkaruza/selenium,o-schneider/selenium,amar-sharma/selenium,yukaReal/selenium,gregerrag/selenium,carlosroh/selenium,bmannix/selenium,asashour/selenium,lmtierney/selenium,alexec/selenium,dbo/selenium,tkurnosova/selenium,anshumanchatterji/selenium,rovner/selenium,SouWilliams/selenium,rrussell39/selenium,thanhpete/selenium,arunsingh/selenium,chrisblock/selenium,MCGallaspy/selenium,tbeadle/selenium,houchj/selenium,zenefits/selenium,valfirst/selenium,asolntsev/selenium,krmahadevan/selenium,vveliev/selenium,dkentw/selenium,Tom-Trumper/selenium,MeetMe/selenium,dbo/selenium,markodolancic/selenium,rrussell39/selenium,alexec/selenium,petruc/selenium,anshumanchatterji/selenium,SouWilliams/selenium,Appdynamics/selenium,doungni/selenium,davehunt/selenium,gregerrag/selenium,carlosroh/selenium,TheBlackTuxCorp/selenium,gregerrag/selenium,lmtierney/selenium,gabrielsimas/selenium,skurochkin/selenium,bayandin/selenium,alexec/selenium,i17c/selenium,mojwang/selenium,gurayinan/selenium,zenefits/selenium,arunsingh/selenium,xsyntrex/selenium,sankha93/selenium,juangj/selenium,tkurnosova/selenium,quoideneuf/selenium,amar-sharma/selenium,gurayinan/selenium,anshumanchatterji/selenium,Herst/selenium,rplevka/selenium,quoideneuf/selenium,Herst/selenium,JosephCastro/selenium,o-schneider/selenium,MeetMe/selenium,bayandin/selenium,dcjohnson1989/selenium,carsonmcdonald/selenium,meksh/selenium,Jarob22/selenium,carlosroh/selenium,mojwang/selenium,twalpole/selenium,AutomatedTester/selenium,joshmgrant/selenium,Tom-Trumper/selenium,joshmgrant/selenium,wambat/selenium,BlackSmith/selenium,alexec/selenium,petruc/selenium,joshuaduffy/selenium,arunsingh/selenium,twalpole/selenium,dcjohnson1989/selenium,joshuaduffy/selenium,AutomatedTester/selenium,DrMarcII/selenium,dcjohnson1989/selenium,gotcha/selenium,sankha93/selenium,o-schneider/selenium,Appdynamics/selenium,xmhubj/selenium,juangj/selenium,GorK-ChO/selenium,Appdynamics/selenium,oddui/selenium,blackboarddd/selenium,joshmgrant/selenium,customcommander/selenium,valfirst/selenium,vveliev/selenium,mestihudson/selenium,SeleniumHQ/selenium,mach6/selenium,alb-i986/selenium,slongwang/selenium,tarlabs/selenium,asashour/selenium,lukeis/selenium,zenefits/selenium,slongwang/selenium,i17c/selenium,TheBlackTuxCorp/selenium,sag-enorman/selenium,uchida/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,mach6/selenium,eric-stanley/selenium,tkurnosova/selenium,markodolancic/selenium,petruc/selenium,amar-sharma/selenium,MeetMe/selenium,jabbrwcky/selenium,jsakamoto/selenium,Dude-X/selenium,valfirst/selenium,dibagga/selenium,alexec/selenium,clavery/selenium,blackboarddd/selenium,tarlabs/selenium,alb-i986/selenium,TikhomirovSergey/selenium,lrowe/selenium,customcommander/selenium,jabbrwcky/selenium,rovner/selenium,oddui/selenium,dcjohnson1989/selenium,HtmlUnit/selenium,tkurnosova/selenium,meksh/selenium,kalyanjvn1/selenium,asashour/selenium,uchida/selenium,p0deje/selenium,bmannix/selenium,sri85/selenium,dkentw/selenium,zenefits/selenium,MCGallaspy/selenium,krmahadevan/selenium,juangj/selenium,quoideneuf/selenium,quoideneuf/selenium,uchida/selenium,anshumanchatterji/selenium,rovner/selenium,dibagga/selenium,skurochkin/selenium,bmannix/selenium,DrMarcII/selenium,BlackSmith/selenium,juangj/selenium,MCGallaspy/selenium,twalpole/selenium,bayandin/selenium,carlosroh/selenium,arunsingh/selenium,Sravyaksr/selenium,amar-sharma/selenium,sag-enorman/selenium,bmannix/selenium,rplevka/selenium,5hawnknight/selenium,gabrielsimas/selenium,rrussell39/selenium,vveliev/selenium,s2oBCN/selenium,alb-i986/selenium,dkentw/selenium,anshumanchatterji/selenium,Herst/selenium,Jarob22/selenium,sri85/selenium,davehunt/selenium,bmannix/selenium,valfirst/selenium,MeetMe/selenium,joshbruning/selenium,stupidnetizen/selenium,arunsingh/selenium,meksh/selenium,sag-enorman/selenium,vveliev/selenium,lrowe/selenium,jsakamoto/selenium,gotcha/selenium,arunsingh/selenium,customcommander/selenium,MCGallaspy/selenium,jabbrwcky/selenium,tarlabs/selenium,tkurnosova/selenium,anshumanchatterji/selenium,joshbruning/selenium,TheBlackTuxCorp/selenium,asolntsev/selenium,twalpole/selenium,lilredindy/selenium,actmd/selenium,dibagga/selenium,lukeis/selenium,JosephCastro/selenium,mach6/selenium,skurochkin/selenium,knorrium/selenium,tbeadle/selenium,MeetMe/selenium,sankha93/selenium,houchj/selenium,lrowe/selenium,joshmgrant/selenium,doungni/selenium,vveliev/selenium,amar-sharma/selenium,minhthuanit/selenium,carlosroh/selenium,clavery/selenium,dandv/selenium,BlackSmith/selenium,stupidnetizen/selenium,petruc/selenium,xsyntrex/selenium,juangj/selenium,gabrielsimas/selenium,slongwang/selenium,sag-enorman/selenium,doungni/selenium,clavery/selenium,DrMarcII/selenium,mestihudson/selenium,s2oBCN/selenium,vveliev/selenium,jsakamoto/selenium,o-schneider/selenium,joshmgrant/selenium,krosenvold/selenium,wambat/selenium,tarlabs/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,skurochkin/selenium,blackboarddd/selenium,i17c/selenium,lukeis/selenium,JosephCastro/selenium,Dude-X/selenium,sankha93/selenium,slongwang/selenium,valfirst/selenium,lilredindy/selenium,sankha93/selenium,alexec/selenium,yukaReal/selenium,wambat/selenium,xmhubj/selenium,krosenvold/selenium,joshuaduffy/selenium,MeetMe/selenium,bmannix/selenium,minhthuanit/selenium,dcjohnson1989/selenium,sri85/selenium,Appdynamics/selenium,yukaReal/selenium,carlosroh/selenium,dbo/selenium,dandv/selenium,kalyanjvn1/selenium,Ardesco/selenium,amikey/selenium,gorlemik/selenium,TheBlackTuxCorp/selenium,bartolkaruza/selenium,knorrium/selenium,customcommander/selenium,mach6/selenium,alb-i986/selenium,DrMarcII/selenium,titusfortner/selenium,xsyntrex/selenium,eric-stanley/selenium,dbo/selenium,xsyntrex/selenium,skurochkin/selenium,jerome-jacob/selenium,SouWilliams/selenium,lilredindy/selenium,eric-stanley/selenium,oddui/selenium,i17c/selenium,5hawnknight/selenium,i17c/selenium,xmhubj/selenium,oddui/selenium,tkurnosova/selenium,lmtierney/selenium,zenefits/selenium,markodolancic/selenium,alb-i986/selenium,xmhubj/selenium,chrisblock/selenium,joshuaduffy/selenium,twalpole/selenium,Tom-Trumper/selenium,quoideneuf/selenium,jerome-jacob/selenium,amar-sharma/selenium,anshumanchatterji/selenium,xsyntrex/selenium,sag-enorman/selenium,BlackSmith/selenium,meksh/selenium,minhthuanit/selenium,gorlemik/selenium,xmhubj/selenium,carsonmcdonald/selenium,i17c/selenium,rovner/selenium,Jarob22/selenium,gregerrag/selenium,dkentw/selenium,GorK-ChO/selenium,asolntsev/selenium,dibagga/selenium,TikhomirovSergey/selenium,JosephCastro/selenium,gurayinan/selenium,alexec/selenium,dandv/selenium,mojwang/selenium,Jarob22/selenium,s2oBCN/selenium,quoideneuf/selenium,jerome-jacob/selenium,dandv/selenium,chrisblock/selenium,alb-i986/selenium,juangj/selenium,joshmgrant/selenium,xsyntrex/selenium,s2oBCN/selenium,SouWilliams/selenium,arunsingh/selenium,s2oBCN/selenium,doungni/selenium,Sravyaksr/selenium,petruc/selenium,alb-i986/selenium,GorK-ChO/selenium,clavery/selenium,gorlemik/selenium,5hawnknight/selenium,AutomatedTester/selenium,carsonmcdonald/selenium,jerome-jacob/selenium,s2oBCN/selenium,eric-stanley/selenium,GorK-ChO/selenium,tarlabs/selenium,krosenvold/selenium,asolntsev/selenium,Herst/selenium,dbo/selenium,rovner/selenium,alexec/selenium,jsakamoto/selenium,sag-enorman/selenium,houchj/selenium,minhthuanit/selenium,GorK-ChO/selenium,joshbruning/selenium,SouWilliams/selenium,clavery/selenium,p0deje/selenium,MeetMe/selenium,joshmgrant/selenium,dkentw/selenium,dimacus/selenium,krosenvold/selenium,anshumanchatterji/selenium,jsakamoto/selenium,davehunt/selenium,dimacus/selenium,bartolkaruza/selenium,eric-stanley/selenium,titusfortner/selenium,doungni/selenium,twalpole/selenium,Jarob22/selenium,bayandin/selenium,dandv/selenium,mojwang/selenium,jabbrwcky/selenium,knorrium/selenium,thanhpete/selenium,lukeis/selenium,p0deje/selenium,jabbrwcky/selenium,dcjohnson1989/selenium,lukeis/selenium,dimacus/selenium,valfirst/selenium,Sravyaksr/selenium,Dude-X/selenium,5hawnknight/selenium,mojwang/selenium,chrisblock/selenium,titusfortner/selenium,rplevka/selenium,rovner/selenium,jerome-jacob/selenium,o-schneider/selenium,joshbruning/selenium,joshbruning/selenium,joshuaduffy/selenium,carsonmcdonald/selenium,tkurnosova/selenium,gabrielsimas/selenium,rplevka/selenium,sankha93/selenium,HtmlUnit/selenium,p0deje/selenium,asashour/selenium,kalyanjvn1/selenium,blackboarddd/selenium,mestihudson/selenium,joshuaduffy/selenium,Tom-Trumper/selenium,alb-i986/selenium,HtmlUnit/selenium,zenefits/selenium,Ardesco/selenium,markodolancic/selenium,asashour/selenium,valfirst/selenium,Herst/selenium,joshuaduffy/selenium,davehunt/selenium,eric-stanley/selenium,joshuaduffy/selenium,yukaReal/selenium,wambat/selenium,lrowe/selenium,stupidnetizen/selenium,alb-i986/selenium,rrussell39/selenium,houchj/selenium,kalyanjvn1/selenium,bartolkaruza/selenium,petruc/selenium,JosephCastro/selenium,Ardesco/selenium,titusfortner/selenium,amar-sharma/selenium,GorK-ChO/selenium,rrussell39/selenium,tbeadle/selenium,slongwang/selenium,dimacus/selenium,gorlemik/selenium,JosephCastro/selenium,gabrielsimas/selenium,sankha93/selenium,thanhpete/selenium,tarlabs/selenium,oddui/selenium,SeleniumHQ/selenium,p0deje/selenium,slongwang/selenium,lukeis/selenium,sankha93/selenium,mestihudson/selenium,vveliev/selenium,chrisblock/selenium,bmannix/selenium,dandv/selenium,tarlabs/selenium,amikey/selenium,tkurnosova/selenium,krosenvold/selenium,kalyanjvn1/selenium,HtmlUnit/selenium,joshbruning/selenium,SeleniumHQ/selenium,lilredindy/selenium,oddui/selenium,Ardesco/selenium,dimacus/selenium,sri85/selenium,meksh/selenium,doungni/selenium,Ardesco/selenium,BlackSmith/selenium,davehunt/selenium,JosephCastro/selenium,SouWilliams/selenium,o-schneider/selenium | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.htmlunit;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomText;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlLabel;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPreformattedText;
import com.gargoylesoftware.htmlunit.html.HtmlScript;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextArea;
import com.gargoylesoftware.htmlunit.javascript.host.Event;
import net.sourceforge.htmlunit.corejs.javascript.Undefined;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.InvalidElementStateException;
import org.openqa.selenium.InvalidSelectorException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.FindsByCssSelector;
import org.openqa.selenium.internal.FindsById;
import org.openqa.selenium.internal.FindsByLinkText;
import org.openqa.selenium.internal.FindsByTagName;
import org.openqa.selenium.internal.FindsByXPath;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.internal.WrapsElement;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
public class HtmlUnitWebElement implements WrapsDriver,
FindsById, FindsByLinkText, FindsByXPath, FindsByTagName,
FindsByCssSelector, Locatable, WebElement {
protected final HtmlUnitDriver parent;
protected final HtmlElement element;
private static final char nbspChar = 160;
private static final String[] blockLevelsTagNames =
{"p", "h1", "h2", "h3", "h4", "h5", "h6", "dl", "div", "noscript",
"blockquote", "form", "hr", "table", "fieldset", "address", "ul", "ol", "pre", "br"};
private static final String[] booleanAttributes = {
"async",
"autofocus",
"autoplay",
"checked",
"compact",
"complete",
"controls",
"declare",
"defaultchecked",
"defaultselected",
"defer",
"disabled",
"draggable",
"ended",
"formnovalidate",
"hidden",
"indeterminate",
"iscontenteditable",
"ismap",
"itemscope",
"loop",
"multiple",
"muted",
"nohref",
"noresize",
"noshade",
"novalidate",
"nowrap",
"open",
"paused",
"pubdate",
"readonly",
"required",
"reversed",
"scoped",
"seamless",
"seeking",
"selected",
"spellcheck",
"truespeed",
"willvalidate"
};
private String toString;
public HtmlUnitWebElement(HtmlUnitDriver parent, HtmlElement element) {
this.parent = parent;
this.element = element;
}
@Override
public void click() {
try {
verifyCanInteractWithElement();
} catch (InvalidElementStateException e) {
Throwables.propagateIfInstanceOf(e, ElementNotVisibleException.class);
// Swallow disabled element case
// Clicking disabled elements should still be passed through,
// we just don't expect any state change
// TODO: The javadoc for this method implies we shouldn't throw for
// element not visible either
}
HtmlUnitMouse mouse = (HtmlUnitMouse) parent.getMouse();
mouse.click(getCoordinates());
if (element instanceof HtmlLabel) {
HtmlElement referencedElement = ((HtmlLabel)element).getReferencedElement();
if (referencedElement != null) {
new HtmlUnitWebElement(parent, referencedElement).click();
}
}
}
@Override
public void submit() {
try {
if (element instanceof HtmlForm) {
submitForm((HtmlForm) element);
return;
} else if ((element instanceof HtmlSubmitInput) || (element instanceof HtmlImageInput)) {
element.click();
return;
} else if (element instanceof HtmlInput) {
HtmlForm form = element.getEnclosingForm();
if (form == null) {
throw new NoSuchElementException("Unable to find the containing form");
}
submitForm(form);
return;
}
WebElement form = findParentForm();
if (form == null) {
throw new NoSuchElementException("Unable to find the containing form");
}
form.submit();
} catch (IOException e) {
throw new WebDriverException(e);
}
}
private void submitForm(HtmlForm form) {
assertElementNotStale();
List<String> names = new ArrayList<String>();
names.add("input");
names.add("button");
List<? extends HtmlElement> allElements = form.getHtmlElementsByTagNames(names);
HtmlElement submit = null;
for (HtmlElement element : allElements) {
if (!isSubmitElement(element)) {
continue;
}
if (submit == null) {
submit = element;
}
}
if (submit == null) {
if (parent.isJavascriptEnabled()) {
ScriptResult eventResult = form.fireEvent("submit");
if (!ScriptResult.isFalse(eventResult)) {
parent.executeScript("arguments[0].submit()", form);
}
return;
}
throw new WebDriverException("Cannot locate element used to submit form");
}
try {
submit.click();
} catch (IOException e) {
throw new WebDriverException(e);
}
}
private boolean isSubmitElement(HtmlElement element) {
HtmlElement candidate = null;
if (element instanceof HtmlSubmitInput && !((HtmlSubmitInput) element).isDisabled()) {
candidate = element;
} else if (element instanceof HtmlImageInput && !((HtmlImageInput) element).isDisabled()) {
candidate = element;
} else if (element instanceof HtmlButton) {
HtmlButton button = (HtmlButton) element;
if ("submit".equalsIgnoreCase(button.getTypeAttribute()) && !button.isDisabled()) {
candidate = element;
}
}
return candidate != null;
}
@Override
public void clear() {
assertElementNotStale();
if (element instanceof HtmlInput) {
HtmlInput htmlInput = (HtmlInput) element;
if (htmlInput.isReadOnly()) {
throw new InvalidElementStateException("You may only edit editable elements");
}
if (htmlInput.isDisabled()) {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
htmlInput.setValueAttribute("");
} else if (element instanceof HtmlTextArea) {
HtmlTextArea htmlTextArea = (HtmlTextArea) element;
if (htmlTextArea.isReadOnly()) {
throw new InvalidElementStateException("You may only edit editable elements");
}
if (htmlTextArea.isDisabled()) {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
htmlTextArea.setText("");
} else if (element.getAttribute("contenteditable") != HtmlElement.ATTRIBUTE_NOT_DEFINED) {
element.setTextContent("");
}
}
private void verifyCanInteractWithElement() {
assertElementNotStale();
Boolean displayed = parent.implicitlyWaitFor(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return isDisplayed();
}
});
if (displayed == null || !displayed.booleanValue()) {
throw new ElementNotVisibleException("You may only interact with visible elements");
}
if (!isEnabled()) {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
}
private void switchFocusToThisIfNeeded() {
HtmlUnitWebElement oldActiveElement =
((HtmlUnitWebElement) parent.switchTo().activeElement());
boolean jsEnabled = parent.isJavascriptEnabled();
boolean oldActiveEqualsCurrent = oldActiveElement.equals(this);
try {
boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body");
if (jsEnabled &&
!oldActiveEqualsCurrent &&
!isBody) {
oldActiveElement.element.blur();
}
} catch (StaleElementReferenceException ex) {
// old element has gone, do nothing
}
element.focus();
}
/**
* @deprecated Visibility will soon be reduced.
*/
public void sendKeyDownEvent(CharSequence modifierKey) {
sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_DOWN);
}
/**
* @deprecated Visibility will soon be reduced.
*/
public void sendKeyUpEvent(CharSequence modifierKey) {
sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_UP);
}
private void sendSingleKeyEvent(CharSequence modifierKey, String eventDescription) {
verifyCanInteractWithElement();
switchFocusToThisIfNeeded();
HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard();
keyboard.performSingleKeyAction(getElement(), modifierKey, eventDescription);
}
@Override
public void sendKeys(CharSequence... value) {
verifyCanInteractWithElement();
InputKeysContainer keysContainer = new InputKeysContainer(isInputElement(), value);
switchFocusToThisIfNeeded();
HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard();
keyboard.sendKeys(element, getAttribute("value"), keysContainer);
if (isInputElement() && keysContainer.wasSubmitKeyFound()) {
submit();
}
}
private boolean isInputElement() {
return element instanceof HtmlInput;
}
@Override
public String getTagName() {
assertElementNotStale();
return element.getNodeName();
}
@Override
public String getAttribute(String name) {
assertElementNotStale();
final String lowerName = name.toLowerCase();
String value = element.getAttribute(name);
if (element instanceof HtmlInput &&
("selected".equals(lowerName) || "checked".equals(lowerName))) {
return trueOrNull(((HtmlInput) element).isChecked());
}
if ("href".equals(lowerName) || "src".equals(lowerName)) {
if (!element.hasAttribute(name)) {
return null;
}
String link = element.getAttribute(name).trim();
HtmlPage page = (HtmlPage) element.getPage();
try {
return page.getFullyQualifiedUrl(link).toString();
} catch (MalformedURLException e) {
return null;
}
}
if ("disabled".equals(lowerName)) {
return trueOrNull(! isEnabled());
}
if ("multiple".equals(lowerName) && element instanceof HtmlSelect) {
String multipleAttribute = ((HtmlSelect) element).getMultipleAttribute();
if ("".equals(multipleAttribute)) {
return trueOrNull(element.hasAttribute("multiple"));
}
return "true";
}
for (String booleanAttribute : booleanAttributes) {
if (booleanAttribute.equals(lowerName)) {
return trueOrNull(element.hasAttribute(lowerName));
}
}
if ("index".equals(lowerName) && element instanceof HtmlOption) {
HtmlSelect select = ((HtmlOption) element).getEnclosingSelect();
List<HtmlOption> allOptions = select.getOptions();
for (int i = 0; i < allOptions.size(); i++) {
HtmlOption option = select.getOption(i);
if (element.equals(option)) {
return String.valueOf(i);
}
}
return null;
}
if ("readonly".equalsIgnoreCase(lowerName)) {
if (element instanceof HtmlInput) {
return trueOrNull(((HtmlInput) element).isReadOnly());
}
if (element instanceof HtmlTextArea) {
return trueOrNull("".equals(((HtmlTextArea) element).getReadOnlyAttribute()));
}
return null;
}
if ("value".equals(lowerName)) {
if (element instanceof HtmlTextArea) {
return ((HtmlTextArea) element).getText();
}
// According to
// http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-value-OPTION
// if the value attribute doesn't exist, getting the "value" attribute defers to the
// option's content.
if (element instanceof HtmlOption && !element.hasAttribute("value")) {
return element.getTextContent();
}
return value == null ? "" : value;
}
if (!"".equals(value)) {
return value;
}
if (element.hasAttribute(name)) {
return "";
}
final Object slotVal = element.getScriptObject().get(name);
if (slotVal instanceof String) {
String strVal = (String) slotVal;
if (!Strings.isNullOrEmpty(strVal)) {
return strVal;
}
}
return null;
}
private String trueOrNull(boolean condition) {
return condition ? "true" : null;
}
@Override
public boolean isSelected() {
assertElementNotStale();
if (element instanceof HtmlInput) {
return ((HtmlInput) element).isChecked();
} else if (element instanceof HtmlOption) {
return ((HtmlOption) element).isSelected();
}
throw new UnsupportedOperationException(
"Unable to determine if element is selected. Tag name is: " + element.getTagName());
}
@Override
public boolean isEnabled() {
assertElementNotStale();
return !element.hasAttribute("disabled");
}
@Override
public boolean isDisplayed() {
assertElementNotStale();
return element.isDisplayed();
}
@Override
public Point getLocation() {
assertElementNotStale();
try {
return new Point(readAndRound("left"), readAndRound("top"));
} catch (Exception e) {
throw new WebDriverException("Cannot determine size of element", e);
}
}
@Override
public Dimension getSize() {
assertElementNotStale();
try {
final int width = readAndRound("width");
final int height = readAndRound("height");
return new Dimension(width, height);
} catch (Exception e) {
throw new WebDriverException("Cannot determine size of element", e);
}
}
private int readAndRound(final String property) {
final String cssValue = getCssValue(property).replaceAll("[^0-9\\.]", "");
if (cssValue.length() == 0) {
return 5; // wrong... but better than nothing
}
return Math.round(Float.parseFloat(cssValue));
}
// This isn't very pretty. Sorry.
@Override
public String getText() {
assertElementNotStale();
StringBuffer toReturn = new StringBuffer();
StringBuffer textSoFar = new StringBuffer();
boolean isPreformatted = element instanceof HtmlPreformattedText;
getTextFromNode(element, toReturn, textSoFar, isPreformatted);
String text = toReturn.toString() + collapseWhitespace(textSoFar);
if (!isPreformatted) {
text = text.trim();
} else {
if (text.endsWith("\n")) {
text = text.substring(0, text.length()-1);
}
}
return text.replace(nbspChar, ' ');
}
protected HtmlUnitDriver getParent() {
return parent;
}
protected HtmlElement getElement() {
return element;
}
private void getTextFromNode(DomNode node, StringBuffer toReturn, StringBuffer textSoFar,
boolean isPreformatted) {
if (node instanceof HtmlScript) {
return;
}
if (isPreformatted) {
getPreformattedText(node, toReturn);
} else {
for (DomNode child : node.getChildren()) {
// Do we need to collapse the text so far?
if (child instanceof HtmlPreformattedText) {
if (child.isDisplayed()) {
String textToAdd = collapseWhitespace(textSoFar);
if (! " ".equals(textToAdd)) {
toReturn.append(textToAdd);
}
textSoFar.delete(0, textSoFar.length());
}
getTextFromNode(child, toReturn, textSoFar, true);
continue;
}
// Or is this just plain text?
if (child instanceof DomText) {
if (child.isDisplayed()) {
String textToAdd = ((DomText) child).getData();
textSoFar.append(textToAdd);
}
continue;
}
// Treat as another child node.
getTextFromNode(child, toReturn, textSoFar, false);
}
}
if (isBlockLevel(node)) {
toReturn.append(collapseWhitespace(textSoFar).trim()).append("\n");
textSoFar.delete(0, textSoFar.length());
}
}
private boolean isBlockLevel(DomNode node) {
// From the HTML spec (http://www.w3.org/TR/html401/sgml/dtd.html#block)
// <!ENTITY % block
// "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT | BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS">
// <!ENTITY % heading "H1|H2|H3|H4|H5|H6">
// <!ENTITY % list "UL | OL">
// <!ENTITY % preformatted "PRE">
if (!(node instanceof HtmlElement)) {
return false;
}
String tagName = ((HtmlElement) node).getTagName().toLowerCase();
for (String blockLevelsTagName : blockLevelsTagNames) {
if (blockLevelsTagName.equals(tagName)) {
return true;
}
}
return false;
}
private String collapseWhitespace(StringBuffer textSoFar) {
String textToAdd = textSoFar.toString();
return textToAdd.replaceAll("\\p{javaWhitespace}+", " ").replaceAll("\r", "");
}
private void getPreformattedText(DomNode node, StringBuffer toReturn) {
if (node.isDisplayed()) {
toReturn.append(node.getTextContent());
}
}
public List<WebElement> getElementsByTagName(String tagName) {
assertElementNotStale();
List<?> allChildren = element.getByXPath(".//" + tagName);
List<WebElement> elements = new ArrayList<WebElement>();
for (Object o : allChildren) {
if (!(o instanceof HtmlElement)) {
continue;
}
HtmlElement child = (HtmlElement) o;
elements.add(getParent().newHtmlUnitWebElement(child));
}
return elements;
}
@Override
public WebElement findElement(By by) {
assertElementNotStale();
return parent.findElement(by, this);
}
@Override
public List<WebElement> findElements(By by) {
assertElementNotStale();
return parent.findElements(by, this);
}
@Override
public WebElement findElementById(String id) {
assertElementNotStale();
return findElementByXPath(".//*[@id = '" + id + "']");
}
@Override
public List<WebElement> findElementsById(String id) {
assertElementNotStale();
return findElementsByXPath(".//*[@id = '" + id + "']");
}
@Override
public List<WebElement> findElementsByCssSelector(String using) {
List<WebElement> allElements = parent.findElementsByCssSelector(using);
return findChildNodes(allElements);
}
@Override
public WebElement findElementByCssSelector(String using) {
List<WebElement> allElements = parent.findElementsByCssSelector(using);
allElements = findChildNodes(allElements);
if (allElements.isEmpty()) {
throw new NoSuchElementException("Cannot find child element using css: " + using);
}
return allElements.get(0);
}
private List<WebElement> findChildNodes(List<WebElement> allElements) {
List<WebElement> toReturn = new LinkedList<WebElement>();
for (WebElement current : allElements) {
HtmlElement candidate = ((HtmlUnitWebElement) current).element;
if (element.isAncestorOf(candidate) && element != candidate) {
toReturn.add(current);
}
}
return toReturn;
}
@Override
public WebElement findElementByXPath(String xpathExpr) {
assertElementNotStale();
Object node;
try {
node = element.getFirstByXPath(xpathExpr);
} catch (Exception ex) {
// The xpath expression cannot be evaluated, so the expression is invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex);
}
if (node == null) {
throw new NoSuchElementException("Unable to find an element with xpath " + xpathExpr);
}
if (node instanceof HtmlElement) {
return getParent().newHtmlUnitWebElement((HtmlElement) node);
}
// The xpath selector selected something different than a WebElement. The selector is therefore
// invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDSELECTIONERROR, xpathExpr, node.getClass().toString()));
}
@Override
public List<WebElement> findElementsByXPath(String xpathExpr) {
assertElementNotStale();
List<WebElement> webElements = new ArrayList<WebElement>();
List<?> htmlElements;
try {
htmlElements = element.getByXPath(xpathExpr);
} catch (Exception ex) {
// The xpath expression cannot be evaluated, so the expression is invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex);
}
for (Object e : htmlElements) {
if (e instanceof HtmlElement) {
webElements.add(getParent().newHtmlUnitWebElement((HtmlElement) e));
}
else {
// The xpath selector selected something different than a WebElement. The selector is
// therefore invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDSELECTIONERROR,
xpathExpr, e.getClass().toString()));
}
}
return webElements;
}
@Override
public WebElement findElementByLinkText(String linkText) {
assertElementNotStale();
List<WebElement> elements = findElementsByLinkText(linkText);
if (elements.isEmpty()) {
throw new NoSuchElementException("Unable to find element with linkText " + linkText);
}
return elements.get(0);
}
@Override
public List<WebElement> findElementsByLinkText(String linkText) {
assertElementNotStale();
String expectedText = linkText.trim();
List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a");
List<WebElement> webElements = new ArrayList<WebElement>();
for (HtmlElement e : htmlElements) {
if (expectedText.equals(e.getTextContent().trim()) && e.getAttribute("href") != null) {
webElements.add(getParent().newHtmlUnitWebElement(e));
}
}
return webElements;
}
@Override
public WebElement findElementByPartialLinkText(String linkText) {
assertElementNotStale();
List<WebElement> elements = findElementsByPartialLinkText(linkText);
if (elements.isEmpty()) {
throw new NoSuchElementException(
"Unable to find element with linkText " + linkText);
}
return elements.size() > 0 ? elements.get(0) : null;
}
@Override
public List<WebElement> findElementsByPartialLinkText(String linkText) {
assertElementNotStale();
List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a");
List<WebElement> webElements = new ArrayList<WebElement>();
for (HtmlElement e : htmlElements) {
if (e.getTextContent().contains(linkText)
&& e.getAttribute("href") != null) {
webElements.add(getParent().newHtmlUnitWebElement(e));
}
}
return webElements;
}
@Override
public WebElement findElementByTagName(String name) {
assertElementNotStale();
List<WebElement> elements = findElementsByTagName(name);
if (elements.isEmpty()) {
throw new NoSuchElementException("Cannot find element with tag name: " + name);
}
return elements.get(0);
}
@Override
public List<WebElement> findElementsByTagName(String name) {
assertElementNotStale();
List<HtmlElement> elements = element.getHtmlElementsByTagName(name);
List<WebElement> toReturn = new ArrayList<WebElement>(elements.size());
for (HtmlElement element : elements) {
toReturn.add(parent.newHtmlUnitWebElement(element));
}
return toReturn;
}
private WebElement findParentForm() {
DomNode current = element;
while (!(current == null || current instanceof HtmlForm)) {
current = current.getParentNode();
}
return getParent().newHtmlUnitWebElement((HtmlForm) current);
}
@Override
public String toString() {
if (toString == null) {
StringBuilder sb = new StringBuilder();
sb.append('<').append(element.getTagName());
NamedNodeMap attributes = element.getAttributes();
int n = attributes.getLength();
for (int i = 0; i < n; ++i) {
Attr a = (Attr) attributes.item(i);
sb.append(' ').append(a.getName()).append("=\"")
.append(a.getValue().replace("\"", """)).append("\"");
}
if (element.hasChildNodes()) {
sb.append('>');
} else {
sb.append(" />");
}
toString = sb.toString();
}
return toString;
}
protected void assertElementNotStale() {
parent.assertElementNotStale(element);
}
@Override
public String getCssValue(String propertyName) {
assertElementNotStale();
return getEffectiveStyle(element, propertyName);
}
private String getEffectiveStyle(HtmlElement htmlElement, String propertyName) {
HtmlElement current = htmlElement;
String value = "inherit";
while ("inherit".equals(value)) {
// Hat-tip to the Selenium team
Object result =
parent
.executeScript(
"if (window.getComputedStyle) { "
+
" return window.getComputedStyle(arguments[0], null).getPropertyValue(arguments[1]); "
+
"} "
+
"if (arguments[0].currentStyle) { "
+
" return arguments[0].currentStyle[arguments[1]]; "
+
"} "
+
"if (window.document.defaultView && window.document.defaultView.getComputedStyle) { "
+
" return window.document.defaultView.getComputedStyle(arguments[0], null)[arguments[1]]; "
+
"} ",
current, propertyName
);
if (!(result instanceof Undefined)) {
value = String.valueOf(result);
}
current = (HtmlElement) current.getParentNode();
}
return value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WebElement)) {
return false;
}
WebElement other = (WebElement) obj;
if (other instanceof WrapsElement) {
other = ((WrapsElement) obj).getWrappedElement();
}
return other instanceof HtmlUnitWebElement &&
element.equals(((HtmlUnitWebElement) other).element);
}
@Override
public int hashCode() {
return element.hashCode();
}
/*
* (non-Javadoc)
*
* @see org.openqa.selenium.internal.WrapsDriver#getContainingDriver()
*/
@Override
public WebDriver getWrappedDriver() {
return parent;
}
@Override
public Coordinates getCoordinates() {
return new Coordinates() {
@Override
public Point onScreen() {
throw new UnsupportedOperationException("Not displayed, no screen location.");
}
@Override
public Point inViewPort() {
return getLocation();
}
@Override
public Point onPage() {
return getLocation();
}
@Override
public Object getAuxiliary() {
return getElement();
}
};
}
}
| java/client/src/org/openqa/selenium/htmlunit/HtmlUnitWebElement.java | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.htmlunit;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomText;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlLabel;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPreformattedText;
import com.gargoylesoftware.htmlunit.html.HtmlScript;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextArea;
import com.gargoylesoftware.htmlunit.javascript.host.Event;
import net.sourceforge.htmlunit.corejs.javascript.Undefined;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.InvalidElementStateException;
import org.openqa.selenium.InvalidSelectorException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.FindsByCssSelector;
import org.openqa.selenium.internal.FindsById;
import org.openqa.selenium.internal.FindsByLinkText;
import org.openqa.selenium.internal.FindsByTagName;
import org.openqa.selenium.internal.FindsByXPath;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.internal.WrapsElement;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
public class HtmlUnitWebElement implements WrapsDriver,
FindsById, FindsByLinkText, FindsByXPath, FindsByTagName,
FindsByCssSelector, Locatable, WebElement {
protected final HtmlUnitDriver parent;
protected final HtmlElement element;
private static final char nbspChar = 160;
private static final String[] blockLevelsTagNames =
{"p", "h1", "h2", "h3", "h4", "h5", "h6", "dl", "div", "noscript",
"blockquote", "form", "hr", "table", "fieldset", "address", "ul", "ol", "pre", "br"};
private static final String[] booleanAttributes = {
"async",
"autofocus",
"autoplay",
"checked",
"compact",
"complete",
"controls",
"declare",
"defaultchecked",
"defaultselected",
"defer",
"disabled",
"draggable",
"ended",
"formnovalidate",
"hidden",
"indeterminate",
"iscontenteditable",
"ismap",
"itemscope",
"loop",
"multiple",
"muted",
"nohref",
"noresize",
"noshade",
"novalidate",
"nowrap",
"open",
"paused",
"pubdate",
"readonly",
"required",
"reversed",
"scoped",
"seamless",
"seeking",
"selected",
"spellcheck",
"truespeed",
"willvalidate"
};
private String toString;
public HtmlUnitWebElement(HtmlUnitDriver parent, HtmlElement element) {
this.parent = parent;
this.element = element;
}
@Override
public void click() {
try {
verifyCanInteractWithElement();
} catch (InvalidElementStateException e) {
Throwables.propagateIfInstanceOf(e, ElementNotVisibleException.class);
// Swallow disabled element case
// Clicking disabled elements should still be passed through,
// we just don't expect any state change
// TODO: The javadoc for this method implies we shouldn't throw for
// element not visible either
}
if (element instanceof HtmlButton) {
String type = element.getAttribute("type");
if (type == DomElement.ATTRIBUTE_NOT_DEFINED || type == DomElement.ATTRIBUTE_VALUE_EMPTY) {
element.setAttribute("type", "submit");
}
}
HtmlUnitMouse mouse = (HtmlUnitMouse) parent.getMouse();
mouse.click(getCoordinates());
if (element instanceof HtmlLabel) {
HtmlElement referencedElement = ((HtmlLabel)element).getReferencedElement();
if (referencedElement != null) {
new HtmlUnitWebElement(parent, referencedElement).click();
}
}
}
@Override
public void submit() {
try {
if (element instanceof HtmlForm) {
submitForm((HtmlForm) element);
return;
} else if ((element instanceof HtmlSubmitInput) || (element instanceof HtmlImageInput)) {
element.click();
return;
} else if (element instanceof HtmlInput) {
HtmlForm form = element.getEnclosingForm();
if (form == null) {
throw new NoSuchElementException("Unable to find the containing form");
}
submitForm(form);
return;
}
WebElement form = findParentForm();
if (form == null) {
throw new NoSuchElementException("Unable to find the containing form");
}
form.submit();
} catch (IOException e) {
throw new WebDriverException(e);
}
}
private void submitForm(HtmlForm form) {
assertElementNotStale();
List<String> names = new ArrayList<String>();
names.add("input");
names.add("button");
List<? extends HtmlElement> allElements = form.getHtmlElementsByTagNames(names);
HtmlElement submit = null;
for (HtmlElement element : allElements) {
if (!isSubmitElement(element)) {
continue;
}
if (isBefore(submit)) {
submit = element;
}
}
if (submit == null) {
if (parent.isJavascriptEnabled()) {
ScriptResult eventResult = form.fireEvent("submit");
if (!ScriptResult.isFalse(eventResult)) {
parent.executeScript("arguments[0].submit()", form);
}
return;
}
throw new WebDriverException("Cannot locate element used to submit form");
}
try {
submit.click();
} catch (IOException e) {
throw new WebDriverException(e);
}
}
private boolean isSubmitElement(HtmlElement element) {
HtmlElement candidate = null;
if (element instanceof HtmlSubmitInput && !((HtmlSubmitInput) element).isDisabled()) {
candidate = element;
} else if (element instanceof HtmlImageInput && !((HtmlImageInput) element).isDisabled()) {
candidate = element;
} else if (element instanceof HtmlButton) {
HtmlButton button = (HtmlButton) element;
if ("submit".equalsIgnoreCase(button.getTypeAttribute()) && !button.isDisabled()) {
candidate = element;
}
}
return candidate != null;
}
private boolean isBefore(HtmlElement submit) {
return submit == null;
}
@Override
public void clear() {
assertElementNotStale();
if (element instanceof HtmlInput) {
HtmlInput htmlInput = (HtmlInput) element;
if (htmlInput.isReadOnly()) {
throw new InvalidElementStateException("You may only edit editable elements");
}
if (htmlInput.isDisabled()) {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
htmlInput.setValueAttribute("");
} else if (element instanceof HtmlTextArea) {
HtmlTextArea htmlTextArea = (HtmlTextArea) element;
if (htmlTextArea.isReadOnly()) {
throw new InvalidElementStateException("You may only edit editable elements");
}
if (htmlTextArea.isDisabled()) {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
htmlTextArea.setText("");
} else if (element.getAttribute("contenteditable") != HtmlElement.ATTRIBUTE_NOT_DEFINED) {
element.setTextContent("");
}
}
private void verifyCanInteractWithElement() {
assertElementNotStale();
Boolean displayed = parent.implicitlyWaitFor(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return isDisplayed();
}
});
if (displayed == null || !displayed.booleanValue()) {
throw new ElementNotVisibleException("You may only interact with visible elements");
}
if (!isEnabled()) {
throw new InvalidElementStateException("You may only interact with enabled elements");
}
}
private void switchFocusToThisIfNeeded() {
HtmlUnitWebElement oldActiveElement =
((HtmlUnitWebElement) parent.switchTo().activeElement());
boolean jsEnabled = parent.isJavascriptEnabled();
boolean oldActiveEqualsCurrent = oldActiveElement.equals(this);
try {
boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body");
if (jsEnabled &&
!oldActiveEqualsCurrent &&
!isBody) {
oldActiveElement.element.blur();
}
} catch (StaleElementReferenceException ex) {
// old element has gone, do nothing
}
element.focus();
}
/**
* @deprecated Visibility will soon be reduced.
*/
public void sendKeyDownEvent(CharSequence modifierKey) {
sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_DOWN);
}
/**
* @deprecated Visibility will soon be reduced.
*/
public void sendKeyUpEvent(CharSequence modifierKey) {
sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_UP);
}
private void sendSingleKeyEvent(CharSequence modifierKey, String eventDescription) {
verifyCanInteractWithElement();
switchFocusToThisIfNeeded();
HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard();
keyboard.performSingleKeyAction(getElement(), modifierKey, eventDescription);
}
@Override
public void sendKeys(CharSequence... value) {
verifyCanInteractWithElement();
InputKeysContainer keysContainer = new InputKeysContainer(isInputElement(), value);
switchFocusToThisIfNeeded();
HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard();
keyboard.sendKeys(element, getAttribute("value"), keysContainer);
if (isInputElement() && keysContainer.wasSubmitKeyFound()) {
submit();
}
}
private boolean isInputElement() {
return element instanceof HtmlInput;
}
@Override
public String getTagName() {
assertElementNotStale();
return element.getNodeName();
}
@Override
public String getAttribute(String name) {
assertElementNotStale();
final String lowerName = name.toLowerCase();
String value = element.getAttribute(name);
if (element instanceof HtmlInput &&
("selected".equals(lowerName) || "checked".equals(lowerName))) {
return trueOrNull(((HtmlInput) element).isChecked());
}
if ("href".equals(lowerName) || "src".equals(lowerName)) {
if (!element.hasAttribute(name)) {
return null;
}
String link = element.getAttribute(name).trim();
HtmlPage page = (HtmlPage) element.getPage();
try {
return page.getFullyQualifiedUrl(link).toString();
} catch (MalformedURLException e) {
return null;
}
}
if ("disabled".equals(lowerName)) {
return trueOrNull(! isEnabled());
}
if ("multiple".equals(lowerName) && element instanceof HtmlSelect) {
String multipleAttribute = ((HtmlSelect) element).getMultipleAttribute();
if ("".equals(multipleAttribute)) {
return trueOrNull(element.hasAttribute("multiple"));
}
return "true";
}
for (String booleanAttribute : booleanAttributes) {
if (booleanAttribute.equals(lowerName)) {
return trueOrNull(element.hasAttribute(lowerName));
}
}
if ("index".equals(lowerName) && element instanceof HtmlOption) {
HtmlSelect select = ((HtmlOption) element).getEnclosingSelect();
List<HtmlOption> allOptions = select.getOptions();
for (int i = 0; i < allOptions.size(); i++) {
HtmlOption option = select.getOption(i);
if (element.equals(option)) {
return String.valueOf(i);
}
}
return null;
}
if ("readonly".equalsIgnoreCase(lowerName)) {
if (element instanceof HtmlInput) {
return trueOrNull(((HtmlInput) element).isReadOnly());
}
if (element instanceof HtmlTextArea) {
return trueOrNull("".equals(((HtmlTextArea) element).getReadOnlyAttribute()));
}
return null;
}
if ("value".equals(lowerName)) {
if (element instanceof HtmlTextArea) {
return ((HtmlTextArea) element).getText();
}
// According to
// http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-value-OPTION
// if the value attribute doesn't exist, getting the "value" attribute defers to the
// option's content.
if (element instanceof HtmlOption && !element.hasAttribute("value")) {
return element.getTextContent();
}
return value == null ? "" : value;
}
if (!"".equals(value)) {
return value;
}
if (element.hasAttribute(name)) {
return "";
}
final Object slotVal = element.getScriptObject().get(name);
if (slotVal instanceof String) {
String strVal = (String) slotVal;
if (!Strings.isNullOrEmpty(strVal)) {
return strVal;
}
}
return null;
}
private String trueOrNull(boolean condition) {
return condition ? "true" : null;
}
@Override
public boolean isSelected() {
assertElementNotStale();
if (element instanceof HtmlInput) {
return ((HtmlInput) element).isChecked();
} else if (element instanceof HtmlOption) {
return ((HtmlOption) element).isSelected();
}
throw new UnsupportedOperationException(
"Unable to determine if element is selected. Tag name is: " + element.getTagName());
}
@Override
public boolean isEnabled() {
assertElementNotStale();
return !element.hasAttribute("disabled");
}
@Override
public boolean isDisplayed() {
assertElementNotStale();
return element.isDisplayed();
}
@Override
public Point getLocation() {
assertElementNotStale();
try {
return new Point(readAndRound("left"), readAndRound("top"));
} catch (Exception e) {
throw new WebDriverException("Cannot determine size of element", e);
}
}
@Override
public Dimension getSize() {
assertElementNotStale();
try {
final int width = readAndRound("width");
final int height = readAndRound("height");
return new Dimension(width, height);
} catch (Exception e) {
throw new WebDriverException("Cannot determine size of element", e);
}
}
private int readAndRound(final String property) {
final String cssValue = getCssValue(property).replaceAll("[^0-9\\.]", "");
if (cssValue.length() == 0) {
return 5; // wrong... but better than nothing
}
return Math.round(Float.parseFloat(cssValue));
}
// This isn't very pretty. Sorry.
@Override
public String getText() {
assertElementNotStale();
StringBuffer toReturn = new StringBuffer();
StringBuffer textSoFar = new StringBuffer();
boolean isPreformatted = element instanceof HtmlPreformattedText;
getTextFromNode(element, toReturn, textSoFar, isPreformatted);
String text = toReturn.toString() + collapseWhitespace(textSoFar);
if (!isPreformatted) {
text = text.trim();
} else {
if (text.endsWith("\n")) {
text = text.substring(0, text.length()-1);
}
}
return text.replace(nbspChar, ' ');
}
protected HtmlUnitDriver getParent() {
return parent;
}
protected HtmlElement getElement() {
return element;
}
private void getTextFromNode(DomNode node, StringBuffer toReturn, StringBuffer textSoFar,
boolean isPreformatted) {
if (node instanceof HtmlScript) {
return;
}
if (isPreformatted) {
getPreformattedText(node, toReturn);
} else {
for (DomNode child : node.getChildren()) {
// Do we need to collapse the text so far?
if (child instanceof HtmlPreformattedText) {
if (child.isDisplayed()) {
String textToAdd = collapseWhitespace(textSoFar);
if (! " ".equals(textToAdd)) {
toReturn.append(textToAdd);
}
textSoFar.delete(0, textSoFar.length());
}
getTextFromNode(child, toReturn, textSoFar, true);
continue;
}
// Or is this just plain text?
if (child instanceof DomText) {
if (child.isDisplayed()) {
String textToAdd = ((DomText) child).getData();
textSoFar.append(textToAdd);
}
continue;
}
// Treat as another child node.
getTextFromNode(child, toReturn, textSoFar, false);
}
}
if (isBlockLevel(node)) {
toReturn.append(collapseWhitespace(textSoFar).trim()).append("\n");
textSoFar.delete(0, textSoFar.length());
}
}
private boolean isBlockLevel(DomNode node) {
// From the HTML spec (http://www.w3.org/TR/html401/sgml/dtd.html#block)
// <!ENTITY % block
// "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT | BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS">
// <!ENTITY % heading "H1|H2|H3|H4|H5|H6">
// <!ENTITY % list "UL | OL">
// <!ENTITY % preformatted "PRE">
if (!(node instanceof HtmlElement)) {
return false;
}
String tagName = ((HtmlElement) node).getTagName().toLowerCase();
for (String blockLevelsTagName : blockLevelsTagNames) {
if (blockLevelsTagName.equals(tagName)) {
return true;
}
}
return false;
}
private String collapseWhitespace(StringBuffer textSoFar) {
String textToAdd = textSoFar.toString();
return textToAdd.replaceAll("\\p{javaWhitespace}+", " ").replaceAll("\r", "");
}
private void getPreformattedText(DomNode node, StringBuffer toReturn) {
if (node.isDisplayed()) {
toReturn.append(node.getTextContent());
}
}
public List<WebElement> getElementsByTagName(String tagName) {
assertElementNotStale();
List<?> allChildren = element.getByXPath(".//" + tagName);
List<WebElement> elements = new ArrayList<WebElement>();
for (Object o : allChildren) {
if (!(o instanceof HtmlElement)) {
continue;
}
HtmlElement child = (HtmlElement) o;
elements.add(getParent().newHtmlUnitWebElement(child));
}
return elements;
}
@Override
public WebElement findElement(By by) {
assertElementNotStale();
return parent.findElement(by, this);
}
@Override
public List<WebElement> findElements(By by) {
assertElementNotStale();
return parent.findElements(by, this);
}
@Override
public WebElement findElementById(String id) {
assertElementNotStale();
return findElementByXPath(".//*[@id = '" + id + "']");
}
@Override
public List<WebElement> findElementsById(String id) {
assertElementNotStale();
return findElementsByXPath(".//*[@id = '" + id + "']");
}
@Override
public List<WebElement> findElementsByCssSelector(String using) {
List<WebElement> allElements = parent.findElementsByCssSelector(using);
return findChildNodes(allElements);
}
@Override
public WebElement findElementByCssSelector(String using) {
List<WebElement> allElements = parent.findElementsByCssSelector(using);
allElements = findChildNodes(allElements);
if (allElements.isEmpty()) {
throw new NoSuchElementException("Cannot find child element using css: " + using);
}
return allElements.get(0);
}
private List<WebElement> findChildNodes(List<WebElement> allElements) {
List<WebElement> toReturn = new LinkedList<WebElement>();
for (WebElement current : allElements) {
HtmlElement candidate = ((HtmlUnitWebElement) current).element;
if (element.isAncestorOf(candidate) && element != candidate) {
toReturn.add(current);
}
}
return toReturn;
}
@Override
public WebElement findElementByXPath(String xpathExpr) {
assertElementNotStale();
Object node;
try {
node = element.getFirstByXPath(xpathExpr);
} catch (Exception ex) {
// The xpath expression cannot be evaluated, so the expression is invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex);
}
if (node == null) {
throw new NoSuchElementException("Unable to find an element with xpath " + xpathExpr);
}
if (node instanceof HtmlElement) {
return getParent().newHtmlUnitWebElement((HtmlElement) node);
}
// The xpath selector selected something different than a WebElement. The selector is therefore
// invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDSELECTIONERROR, xpathExpr, node.getClass().toString()));
}
@Override
public List<WebElement> findElementsByXPath(String xpathExpr) {
assertElementNotStale();
List<WebElement> webElements = new ArrayList<WebElement>();
List<?> htmlElements;
try {
htmlElements = element.getByXPath(xpathExpr);
} catch (Exception ex) {
// The xpath expression cannot be evaluated, so the expression is invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex);
}
for (Object e : htmlElements) {
if (e instanceof HtmlElement) {
webElements.add(getParent().newHtmlUnitWebElement((HtmlElement) e));
}
else {
// The xpath selector selected something different than a WebElement. The selector is
// therefore invalid
throw new InvalidSelectorException(
String.format(HtmlUnitDriver.INVALIDSELECTIONERROR,
xpathExpr, e.getClass().toString()));
}
}
return webElements;
}
@Override
public WebElement findElementByLinkText(String linkText) {
assertElementNotStale();
List<WebElement> elements = findElementsByLinkText(linkText);
if (elements.isEmpty()) {
throw new NoSuchElementException("Unable to find element with linkText " + linkText);
}
return elements.get(0);
}
@Override
public List<WebElement> findElementsByLinkText(String linkText) {
assertElementNotStale();
String expectedText = linkText.trim();
List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a");
List<WebElement> webElements = new ArrayList<WebElement>();
for (HtmlElement e : htmlElements) {
if (expectedText.equals(e.getTextContent().trim()) && e.getAttribute("href") != null) {
webElements.add(getParent().newHtmlUnitWebElement(e));
}
}
return webElements;
}
@Override
public WebElement findElementByPartialLinkText(String linkText) {
assertElementNotStale();
List<WebElement> elements = findElementsByPartialLinkText(linkText);
if (elements.isEmpty()) {
throw new NoSuchElementException(
"Unable to find element with linkText " + linkText);
}
return elements.size() > 0 ? elements.get(0) : null;
}
@Override
public List<WebElement> findElementsByPartialLinkText(String linkText) {
assertElementNotStale();
List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a");
List<WebElement> webElements = new ArrayList<WebElement>();
for (HtmlElement e : htmlElements) {
if (e.getTextContent().contains(linkText)
&& e.getAttribute("href") != null) {
webElements.add(getParent().newHtmlUnitWebElement(e));
}
}
return webElements;
}
@Override
public WebElement findElementByTagName(String name) {
assertElementNotStale();
List<WebElement> elements = findElementsByTagName(name);
if (elements.isEmpty()) {
throw new NoSuchElementException("Cannot find element with tag name: " + name);
}
return elements.get(0);
}
@Override
public List<WebElement> findElementsByTagName(String name) {
assertElementNotStale();
List<HtmlElement> elements = element.getHtmlElementsByTagName(name);
List<WebElement> toReturn = new ArrayList<WebElement>(elements.size());
for (HtmlElement element : elements) {
toReturn.add(parent.newHtmlUnitWebElement(element));
}
return toReturn;
}
private WebElement findParentForm() {
DomNode current = element;
while (!(current == null || current instanceof HtmlForm)) {
current = current.getParentNode();
}
return getParent().newHtmlUnitWebElement((HtmlForm) current);
}
@Override
public String toString() {
if (toString == null) {
StringBuilder sb = new StringBuilder();
sb.append('<').append(element.getTagName());
NamedNodeMap attributes = element.getAttributes();
int n = attributes.getLength();
for (int i = 0; i < n; ++i) {
Attr a = (Attr) attributes.item(i);
sb.append(' ').append(a.getName()).append("=\"")
.append(a.getValue().replace("\"", """)).append("\"");
}
if (element.hasChildNodes()) {
sb.append('>');
} else {
sb.append(" />");
}
toString = sb.toString();
}
return toString;
}
protected void assertElementNotStale() {
parent.assertElementNotStale(element);
}
@Override
public String getCssValue(String propertyName) {
assertElementNotStale();
return getEffectiveStyle(element, propertyName);
}
private String getEffectiveStyle(HtmlElement htmlElement, String propertyName) {
HtmlElement current = htmlElement;
String value = "inherit";
while ("inherit".equals(value)) {
// Hat-tip to the Selenium team
Object result =
parent
.executeScript(
"if (window.getComputedStyle) { "
+
" return window.getComputedStyle(arguments[0], null).getPropertyValue(arguments[1]); "
+
"} "
+
"if (arguments[0].currentStyle) { "
+
" return arguments[0].currentStyle[arguments[1]]; "
+
"} "
+
"if (window.document.defaultView && window.document.defaultView.getComputedStyle) { "
+
" return window.document.defaultView.getComputedStyle(arguments[0], null)[arguments[1]]; "
+
"} ",
current, propertyName
);
if (!(result instanceof Undefined)) {
value = String.valueOf(result);
}
current = (HtmlElement) current.getParentNode();
}
return value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WebElement)) {
return false;
}
WebElement other = (WebElement) obj;
if (other instanceof WrapsElement) {
other = ((WrapsElement) obj).getWrappedElement();
}
return other instanceof HtmlUnitWebElement &&
element.equals(((HtmlUnitWebElement) other).element);
}
@Override
public int hashCode() {
return element.hashCode();
}
/*
* (non-Javadoc)
*
* @see org.openqa.selenium.internal.WrapsDriver#getContainingDriver()
*/
@Override
public WebDriver getWrappedDriver() {
return parent;
}
@Override
public Coordinates getCoordinates() {
return new Coordinates() {
@Override
public Point onScreen() {
throw new UnsupportedOperationException("Not displayed, no screen location.");
}
@Override
public Point inViewPort() {
return getLocation();
}
@Override
public Point onPage() {
return getLocation();
}
@Override
public Object getAuxiliary() {
return getElement();
}
};
}
}
| Form handling in htmlunit works correct without any additional tricks
Signed-off-by: Alexei Barantsev <[email protected]>
| java/client/src/org/openqa/selenium/htmlunit/HtmlUnitWebElement.java | Form handling in htmlunit works correct without any additional tricks | <ide><path>ava/client/src/org/openqa/selenium/htmlunit/HtmlUnitWebElement.java
<ide> // element not visible either
<ide> }
<ide>
<del> if (element instanceof HtmlButton) {
<del> String type = element.getAttribute("type");
<del> if (type == DomElement.ATTRIBUTE_NOT_DEFINED || type == DomElement.ATTRIBUTE_VALUE_EMPTY) {
<del> element.setAttribute("type", "submit");
<del> }
<del> }
<del>
<ide> HtmlUnitMouse mouse = (HtmlUnitMouse) parent.getMouse();
<ide> mouse.click(getCoordinates());
<ide>
<ide> continue;
<ide> }
<ide>
<del> if (isBefore(submit)) {
<add> if (submit == null) {
<ide> submit = element;
<ide> }
<ide> }
<ide> }
<ide>
<ide> return candidate != null;
<del> }
<del>
<del> private boolean isBefore(HtmlElement submit) {
<del> return submit == null;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 2b62c965f36ef4935ea2b236c5bb67405865723d | 0 | jbee/silk | package build;
import de.sormuras.bach.Bach;
import de.sormuras.bach.Configuration;
import de.sormuras.bach.Flag;
import de.sormuras.bach.Project;
import de.sormuras.bach.project.Feature;
import java.lang.System.Logger.Level;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/** Silk's build program. */
class Build {
public static void main(String... args) throws Exception {
var version = "19.1-ea";
var silk =
Project.of()
.name("silk")
.version(version)
// <main>
.module("src/se.jbee.inject/main/java-9", 8)
.module("src/se.jbee.inject.action/main/java-9", 8)
.module("src/se.jbee.inject.api/main/java-9", 8)
.module("src/se.jbee.inject.bind/main/java-9", 8)
.module("src/se.jbee.inject.bootstrap/main/java-9", 8)
.module("src/se.jbee.inject.container/main/java-9", 8)
.module("src/se.jbee.inject.convert/main/java-9", 8)
.module("src/se.jbee.inject.event/main/java-9", 8)
.module("src/se.jbee.inject.lang/main/java-9", 8)
.without(Feature.CREATE_CUSTOM_RUNTIME_IMAGE)
.tweakJavacCall(
javac -> javac.without("-Xlint").with("-Xlint:-serial,-rawtypes,-varargs"))
.tweakJavadocCall(
javadoc -> javadoc.without("-Xdoclint").with("-Xdoclint:-missing"))
// test
.withTestModule("src/test.integration/test/java") // extra-module tests
.withTestModule("src/com.example.app/test/java") // silk's first client
// lib/
.withLibraryRequires(
"org.hamcrest", "org.junit.vintage.engine", "org.junit.platform.console");
var configuration = Configuration.ofSystem().with(Level.INFO).with(Flag.SUMMARY_LINES_UNCUT);
new Bach(configuration, silk).build(bach -> {
bach.deleteClassesDirectories();
bach.executeDefaultBuildActions();
});
generateMavenPomXml(version);
}
private static void generateMavenPomXml(String version) throws Exception {
Files.write(
Path.of(".bach/workspace/se.jbee.inject@" + version + ".pom.xml"),
List.of(
"<?xml version='1.0' encoding='UTF-8'?>",
"<project xmlns='http://maven.apache.org/POM/4.0.0'",
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'",
" xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'>",
" <modelVersion>4.0.0</modelVersion>",
"",
" <groupId>se.jbee</groupId>",
" <artifactId>se.jbee.inject</artifactId>",
" <version>" + version + "</version>",
"",
" <name>Silk DI</name>",
" <description>Silk Java dependency injection framework</description>",
"",
" <url>http://www.silkdi.com</url>",
" <licenses>",
" <license>",
" <name>Apache License, Version 2.0</name>",
" <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>",
" <distribution>repo</distribution>",
" </license>",
" </licenses>",
" <scm>",
" <url>https://github.com/jbee/silk</url>",
" <connection>https://github.com/jbee/silk.git</connection>",
" </scm>",
"",
" <developers>",
" <developer>",
" <id>jan</id>",
" <name>Jan Bernitt</name>",
" <email>[email protected]</email>",
" </developer>",
" </developers>",
"</project>"));
}
}
| .bach/src/build/build/Build.java | package build;
import de.sormuras.bach.Bach;
import de.sormuras.bach.Configuration;
import de.sormuras.bach.Flag;
import de.sormuras.bach.Project;
import de.sormuras.bach.project.MainSpace;
import java.lang.System.Logger.Level;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/** Silk's build program. */
class Build {
public static void main(String... args) throws Exception {
var version = "19.1-ea";
var silk =
Project.of()
.name("silk")
.version(version)
// <main>
.withMainSpaceUnit("src/se.jbee.inject/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.action/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.api/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.bind/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.bootstrap/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.container/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.convert/main/java-9", 8)
.withMainSpaceUnit("src/se.jbee.inject.event/main/java-9", 8)
.without(MainSpace.Modifier.CUSTOM_RUNTIME_IMAGE)
.withMainSpaceJavacTweak(
javac -> javac.without("-Xlint").with("-Xlint:-serial,-rawtypes,-varargs")
.without("--class-path").with("--class-path",
".bach/workspace/classes/11/se.jbee.inject.action" +
":.bach/workspace/classes/11/se.jbee.inject.api" +
":.bach/workspace/classes/11/se.jbee.inject.bind" +
":.bach/workspace/classes/11/se.jbee.inject.bootstrap" +
":.bach/workspace/classes/11/se.jbee.inject.container" +
":.bach/workspace/classes/11/se.jbee.inject.convert" +
":.bach/workspace/classes/11/se.jbee.inject.event")
)
.withMainSpaceJavadocTweak(
javadoc -> javadoc.without("-Xdoclint").with("-Xdoclint:all,-missing"))
// test
.withTestSpaceUnit("src/test.integration/test/java") // extra-module tests
.withTestSpaceUnit("src/com.example.app/test/java") // silk's first client
// lib/
.withLibraryRequires(
"org.hamcrest", "org.junit.vintage.engine", "org.junit.platform.console");
var configuration = Configuration.ofSystem().with(Level.INFO).with(Flag.SUMMARY_LINES_UNCUT);
new Bach(configuration, silk).build();
generateMavenPomXml(version);
}
private static void generateMavenPomXml(String version) throws Exception {
Files.write(
Path.of(".bach/workspace/se.jbee.inject@" + version + ".pom.xml"),
List.of(
"<?xml version='1.0' encoding='UTF-8'?>",
"<project xmlns='http://maven.apache.org/POM/4.0.0'",
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'",
" xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'>",
" <modelVersion>4.0.0</modelVersion>",
"",
" <groupId>se.jbee</groupId>",
" <artifactId>se.jbee.inject</artifactId>",
" <version>" + version + "</version>",
"",
" <name>Silk DI</name>",
" <description>Silk Java dependency injection framework</description>",
"",
" <url>http://www.silkdi.com</url>",
" <licenses>",
" <license>",
" <name>Apache License, Version 2.0</name>",
" <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>",
" <distribution>repo</distribution>",
" </license>",
" </licenses>",
" <scm>",
" <url>https://github.com/jbee/silk</url>",
" <connection>https://github.com/jbee/silk.git</connection>",
" </scm>",
"",
" <developers>",
" <developer>",
" <id>jan</id>",
" <name>Jan Bernitt</name>",
" <email>[email protected]</email>",
" </developer>",
" </developers>",
"</project>"));
}
}
| fixes build
| .bach/src/build/build/Build.java | fixes build | <ide><path>bach/src/build/build/Build.java
<ide> import de.sormuras.bach.Configuration;
<ide> import de.sormuras.bach.Flag;
<ide> import de.sormuras.bach.Project;
<del>import de.sormuras.bach.project.MainSpace;
<add>import de.sormuras.bach.project.Feature;
<ide> import java.lang.System.Logger.Level;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<ide> var version = "19.1-ea";
<ide>
<ide> var silk =
<del> Project.of()
<del> .name("silk")
<del> .version(version)
<del> // <main>
<del> .withMainSpaceUnit("src/se.jbee.inject/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.action/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.api/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.bind/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.bootstrap/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.container/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.convert/main/java-9", 8)
<del> .withMainSpaceUnit("src/se.jbee.inject.event/main/java-9", 8)
<add> Project.of()
<add> .name("silk")
<add> .version(version)
<add> // <main>
<add> .module("src/se.jbee.inject/main/java-9", 8)
<add> .module("src/se.jbee.inject.action/main/java-9", 8)
<add> .module("src/se.jbee.inject.api/main/java-9", 8)
<add> .module("src/se.jbee.inject.bind/main/java-9", 8)
<add> .module("src/se.jbee.inject.bootstrap/main/java-9", 8)
<add> .module("src/se.jbee.inject.container/main/java-9", 8)
<add> .module("src/se.jbee.inject.convert/main/java-9", 8)
<add> .module("src/se.jbee.inject.event/main/java-9", 8)
<add> .module("src/se.jbee.inject.lang/main/java-9", 8)
<ide>
<del> .without(MainSpace.Modifier.CUSTOM_RUNTIME_IMAGE)
<del> .withMainSpaceJavacTweak(
<del> javac -> javac.without("-Xlint").with("-Xlint:-serial,-rawtypes,-varargs")
<del> .without("--class-path").with("--class-path",
<del> ".bach/workspace/classes/11/se.jbee.inject.action" +
<del> ":.bach/workspace/classes/11/se.jbee.inject.api" +
<del> ":.bach/workspace/classes/11/se.jbee.inject.bind" +
<del> ":.bach/workspace/classes/11/se.jbee.inject.bootstrap" +
<del> ":.bach/workspace/classes/11/se.jbee.inject.container" +
<del> ":.bach/workspace/classes/11/se.jbee.inject.convert" +
<del> ":.bach/workspace/classes/11/se.jbee.inject.event")
<del> )
<add> .without(Feature.CREATE_CUSTOM_RUNTIME_IMAGE)
<add> .tweakJavacCall(
<add> javac -> javac.without("-Xlint").with("-Xlint:-serial,-rawtypes,-varargs"))
<ide>
<del> .withMainSpaceJavadocTweak(
<del> javadoc -> javadoc.without("-Xdoclint").with("-Xdoclint:all,-missing"))
<del> // test
<del> .withTestSpaceUnit("src/test.integration/test/java") // extra-module tests
<del> .withTestSpaceUnit("src/com.example.app/test/java") // silk's first client
<del> // lib/
<del> .withLibraryRequires(
<del> "org.hamcrest", "org.junit.vintage.engine", "org.junit.platform.console");
<add> .tweakJavadocCall(
<add> javadoc -> javadoc.without("-Xdoclint").with("-Xdoclint:-missing"))
<add> // test
<add> .withTestModule("src/test.integration/test/java") // extra-module tests
<add> .withTestModule("src/com.example.app/test/java") // silk's first client
<add> // lib/
<add> .withLibraryRequires(
<add> "org.hamcrest", "org.junit.vintage.engine", "org.junit.platform.console");
<ide>
<ide> var configuration = Configuration.ofSystem().with(Level.INFO).with(Flag.SUMMARY_LINES_UNCUT);
<del> new Bach(configuration, silk).build();
<add> new Bach(configuration, silk).build(bach -> {
<add> bach.deleteClassesDirectories();
<add> bach.executeDefaultBuildActions();
<add> });
<ide>
<ide> generateMavenPomXml(version);
<ide> }
<ide>
<ide> private static void generateMavenPomXml(String version) throws Exception {
<ide> Files.write(
<del> Path.of(".bach/workspace/se.jbee.inject@" + version + ".pom.xml"),
<del> List.of(
<del> "<?xml version='1.0' encoding='UTF-8'?>",
<del> "<project xmlns='http://maven.apache.org/POM/4.0.0'",
<del> " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'",
<del> " xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'>",
<del> " <modelVersion>4.0.0</modelVersion>",
<del> "",
<del> " <groupId>se.jbee</groupId>",
<del> " <artifactId>se.jbee.inject</artifactId>",
<del> " <version>" + version + "</version>",
<del> "",
<del> " <name>Silk DI</name>",
<del> " <description>Silk Java dependency injection framework</description>",
<del> "",
<del> " <url>http://www.silkdi.com</url>",
<del> " <licenses>",
<del> " <license>",
<del> " <name>Apache License, Version 2.0</name>",
<del> " <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>",
<del> " <distribution>repo</distribution>",
<del> " </license>",
<del> " </licenses>",
<del> " <scm>",
<del> " <url>https://github.com/jbee/silk</url>",
<del> " <connection>https://github.com/jbee/silk.git</connection>",
<del> " </scm>",
<del> "",
<del> " <developers>",
<del> " <developer>",
<del> " <id>jan</id>",
<del> " <name>Jan Bernitt</name>",
<del> " <email>[email protected]</email>",
<del> " </developer>",
<del> " </developers>",
<del> "</project>"));
<add> Path.of(".bach/workspace/se.jbee.inject@" + version + ".pom.xml"),
<add> List.of(
<add> "<?xml version='1.0' encoding='UTF-8'?>",
<add> "<project xmlns='http://maven.apache.org/POM/4.0.0'",
<add> " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'",
<add> " xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'>",
<add> " <modelVersion>4.0.0</modelVersion>",
<add> "",
<add> " <groupId>se.jbee</groupId>",
<add> " <artifactId>se.jbee.inject</artifactId>",
<add> " <version>" + version + "</version>",
<add> "",
<add> " <name>Silk DI</name>",
<add> " <description>Silk Java dependency injection framework</description>",
<add> "",
<add> " <url>http://www.silkdi.com</url>",
<add> " <licenses>",
<add> " <license>",
<add> " <name>Apache License, Version 2.0</name>",
<add> " <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>",
<add> " <distribution>repo</distribution>",
<add> " </license>",
<add> " </licenses>",
<add> " <scm>",
<add> " <url>https://github.com/jbee/silk</url>",
<add> " <connection>https://github.com/jbee/silk.git</connection>",
<add> " </scm>",
<add> "",
<add> " <developers>",
<add> " <developer>",
<add> " <id>jan</id>",
<add> " <name>Jan Bernitt</name>",
<add> " <email>[email protected]</email>",
<add> " </developer>",
<add> " </developers>",
<add> "</project>"));
<ide> }
<ide> } |
|
JavaScript | isc | aeb2e26fa006067fea24228368e56d8d49f25c1a | 0 | ngageoint/hootenanny-ui,edpop/iD,1ec5/iD,openstreetmap/iD,edpop/iD,kartta-labs/iD,openstreetmap/iD,openstreetmap/iD,ngageoint/hootenanny-ui,morray/iD,AndreasHae/iD,1ec5/iD,1ec5/iD,bagage/iD,edpop/iD,AndreasHae/iD,mapmeld/iD,bagage/iD,bagage/iD,digidem/iD,AndreasHae/iD,ngageoint/hootenanny-ui,digidem/iD,morray/iD,mapmeld/iD,kartta-labs/iD,kartta-labs/iD,mapmeld/iD | import * as d3 from 'd3';
import { getSetValue } from '../../util/get_set_value';
import { rebind } from '../../util/rebind';
import { t } from '../../util/locale';
export function textarea(field) {
var dispatch = d3.dispatch('change'),
input = d3.select(null);
function textarea(selection) {
input = selection.selectAll('textarea')
.data([0]);
input = input.enter()
.append('textarea')
.attr('id', 'preset-input-' + field.id)
.attr('placeholder', field.placeholder() || t('inspector.unknown'))
.attr('maxlength', 255)
.on('input', change(true))
.on('blur', change())
.on('change', change())
.merge(input);
}
function change(onInput) {
return function() {
var t = {};
t[field.key] = getSetValue(input) || undefined;
dispatch.call('change', this, t, onInput);
};
}
textarea.tags = function(tags) {
getSetValue(input, tags[field.key] || '');
};
textarea.focus = function() {
input.node().focus();
};
return rebind(textarea, dispatch, 'on');
}
| modules/ui/fields/textarea.js | import * as d3 from 'd3';
import { getSetValue } from '../../util/get_set_value';
import { rebind } from '../../util/rebind';
import { t } from '../../util/locale';
export function textarea(field) {
var dispatch = d3.dispatch('change'),
input = d3.select(null);
function textarea(selection) {
input = selection.selectAll('textarea')
.data([0]);
input.enter()
.append('textarea')
.attr('id', 'preset-input-' + field.id)
.attr('placeholder', field.placeholder() || t('inspector.unknown'))
.attr('maxlength', 255)
.merge(input);
input
.on('input', change(true))
.on('blur', change())
.on('change', change());
}
function change(onInput) {
return function() {
var t = {};
t[field.key] = getSetValue(input) || undefined;
dispatch.call('change', this, t, onInput);
};
}
textarea.tags = function(tags) {
getSetValue(input, tags[field.key] || '');
};
textarea.focus = function() {
input.node().focus();
};
return rebind(textarea, dispatch, 'on');
}
| Reassign `input` variable to the update selection after merge
| modules/ui/fields/textarea.js | Reassign `input` variable to the update selection after merge | <ide><path>odules/ui/fields/textarea.js
<ide> input = selection.selectAll('textarea')
<ide> .data([0]);
<ide>
<del> input.enter()
<add> input = input.enter()
<ide> .append('textarea')
<ide> .attr('id', 'preset-input-' + field.id)
<ide> .attr('placeholder', field.placeholder() || t('inspector.unknown'))
<ide> .attr('maxlength', 255)
<del> .merge(input);
<del>
<del> input
<ide> .on('input', change(true))
<ide> .on('blur', change())
<del> .on('change', change());
<add> .on('change', change())
<add> .merge(input);
<ide> }
<ide>
<ide> |
|
Java | epl-1.0 | 22eb565b6e3cf59eba17e7e0d098d0a21fefb5a0 | 0 | BraintagsGmbH/netrelay,BraintagsGmbH/netrelay | /*
* #%L
* netrelay
* %%
* Copyright (C) 2015 Braintags GmbH
* %%
* 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
* #L%
*/
package de.braintags.netrelay.controller;
import java.util.Objects;
import java.util.Properties;
import de.braintags.netrelay.routing.RouterDefinition;
import de.braintags.vertx.services.base.util.EclipseDetection;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.sstore.ClusteredSessionStore;
import io.vertx.ext.web.sstore.LocalSessionStore;
/**
* SessionController uses a {@link SessionHandler} internally to implement session handling for all browser sessions
*
* <br>
* <br>
* Config-Parameter:<br/>
* <UL>
* <LI>{@value #SESSION_STORE_PROP}<br/>
* <LI>{@value #EXPIRATION_STORE_PROP}<br/>
* <LI>{@value #SESSION_MAP_NAME_PROP}<br/>
* </UL>
* <br>
* Request-Parameter:<br/>
* <br/>
* Result-Parameter:<br/>
* <br/>
*
* @author Michael Remme
*/
public class SessionController extends AbstractController {
/**
* The name of the property which defines, which {@link io.vertx.ext.web.sstore.SessionStore} shall be used.
* References to {@link SessionStore}. Possible values are {@link SessionStore#LOCAL_SESSION_STORE} and
* {@link SessionStore#CLUSTERED_SESSION_STORE}
*/
public static final String SESSION_STORE_PROP = "sessionStore";
/**
* The name of the property, which defines in a time unit, when a session expires. Possible definitions are:
* 30000 = milliseconds
* 30 m = 30 minutes
*/
public static final String EXPIRATION_STORE_PROP = "expiration";
/**
* The name of the property which defines the name of the Map, where inside sessions are stored
*/
public static final String SESSION_MAP_NAME_PROP = "sessionMapName";
/**
* The default time, when a session expires in milliseconds
*/
public static final String DEFAULT_SESSION_EXPIRATION = "30 m";
private SessionHandler sessionHandler;
/**
*
*/
public SessionController() {
}
@Override
public void initProperties(Properties properties) {
String storeDef = (String) properties.get(SESSION_STORE_PROP);
Objects.requireNonNull(storeDef);
SessionStore store = SessionStore.valueOf(storeDef);
switch (store) {
case LOCAL_SESSION_STORE:
sessionHandler = SessionHandler
.create(LocalSessionStore.create(getVertx(), getSessionMapName(properties), parseExpiration(properties)))
.setCookieHttpOnlyFlag(true).setCookieSecureFlag(!EclipseDetection.isTest());
break;
case CLUSTERED_SESSION_STORE:
sessionHandler = SessionHandler.create(ClusteredSessionStore.create(getVertx(), getSessionMapName(properties)));
break;
default:
throw new UnsupportedOperationException(store.toString());
}
}
private long parseExpiration(Properties properties) {
String timeString = (String) properties.getOrDefault(EXPIRATION_STORE_PROP, DEFAULT_SESSION_EXPIRATION);
if (timeString.endsWith("m")) {
return Long.parseLong(timeString.substring(0, timeString.length() - 1).trim()) * 60 * 1000;
} else {
return Long.parseLong(timeString);
}
}
private String getSessionMapName(Properties properties) {
return (String) properties.getOrDefault(SESSION_MAP_NAME_PROP, "sessionMap");
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.Handler#handle(java.lang.Object)
*/
@Override
public void handleController(RoutingContext context) {
sessionHandler.handle(context);
}
/**
* Creates a default definition for the current instance
*
* @return
*/
public static RouterDefinition createDefaultRouterDefinition() {
RouterDefinition def = new RouterDefinition();
def.setName(SessionController.class.getSimpleName());
def.setBlocking(false);
def.setController(SessionController.class);
def.setHandlerProperties(getDefaultProperties());
return def;
}
/**
* Get the default properties for an implementation of StaticController
*
* @return
*/
public static Properties getDefaultProperties() {
Properties json = new Properties();
json.put(SESSION_STORE_PROP, SessionStore.LOCAL_SESSION_STORE.toString());
json.put(EXPIRATION_STORE_PROP, String.valueOf(DEFAULT_SESSION_EXPIRATION));
return json;
}
}
| src/main/java/de/braintags/netrelay/controller/SessionController.java | /*
* #%L
* netrelay
* %%
* Copyright (C) 2015 Braintags GmbH
* %%
* 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
* #L%
*/
package de.braintags.netrelay.controller;
import java.util.Objects;
import java.util.Properties;
import de.braintags.netrelay.routing.RouterDefinition;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.sstore.ClusteredSessionStore;
import io.vertx.ext.web.sstore.LocalSessionStore;
/**
* SessionController uses a {@link SessionHandler} internally to implement session handling for all browser sessions
*
* <br>
* <br>
* Config-Parameter:<br/>
* <UL>
* <LI>{@value #SESSION_STORE_PROP}<br/>
* <LI>{@value #EXPIRATION_STORE_PROP}<br/>
* <LI>{@value #SESSION_MAP_NAME_PROP}<br/>
* </UL>
* <br>
* Request-Parameter:<br/>
* <br/>
* Result-Parameter:<br/>
* <br/>
*
* @author Michael Remme
*/
public class SessionController extends AbstractController {
/**
* The name of the property which defines, which {@link io.vertx.ext.web.sstore.SessionStore} shall be used.
* References to {@link SessionStore}. Possible values are {@link SessionStore#LOCAL_SESSION_STORE} and
* {@link SessionStore#CLUSTERED_SESSION_STORE}
*/
public static final String SESSION_STORE_PROP = "sessionStore";
/**
* The name of the property, which defines in a time unit, when a session expires. Possible definitions are:
* 30000 = milliseconds
* 30 m = 30 minutes
*/
public static final String EXPIRATION_STORE_PROP = "expiration";
/**
* The name of the property which defines the name of the Map, where inside sessions are stored
*/
public static final String SESSION_MAP_NAME_PROP = "sessionMapName";
/**
* The default time, when a session expires in milliseconds
*/
public static final String DEFAULT_SESSION_EXPIRATION = "30 m";
private SessionHandler sessionHandler;
/**
*
*/
public SessionController() {
}
@Override
public void initProperties(Properties properties) {
String storeDef = (String) properties.get(SESSION_STORE_PROP);
Objects.requireNonNull(storeDef);
SessionStore store = SessionStore.valueOf(storeDef);
switch (store) {
case LOCAL_SESSION_STORE:
sessionHandler = SessionHandler
.create(LocalSessionStore.create(getVertx(), getSessionMapName(properties), parseExpiration(properties)))
.setCookieHttpOnlyFlag(true).setCookieSecureFlag(true);
break;
case CLUSTERED_SESSION_STORE:
sessionHandler = SessionHandler.create(ClusteredSessionStore.create(getVertx(), getSessionMapName(properties)));
break;
default:
throw new UnsupportedOperationException(store.toString());
}
}
private long parseExpiration(Properties properties) {
String timeString = (String) properties.getOrDefault(EXPIRATION_STORE_PROP, DEFAULT_SESSION_EXPIRATION);
if (timeString.endsWith("m")) {
return Long.parseLong(timeString.substring(0, timeString.length() - 1).trim()) * 60 * 1000;
} else {
return Long.parseLong(timeString);
}
}
private String getSessionMapName(Properties properties) {
return (String) properties.getOrDefault(SESSION_MAP_NAME_PROP, "sessionMap");
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.Handler#handle(java.lang.Object)
*/
@Override
public void handleController(RoutingContext context) {
sessionHandler.handle(context);
}
/**
* Creates a default definition for the current instance
*
* @return
*/
public static RouterDefinition createDefaultRouterDefinition() {
RouterDefinition def = new RouterDefinition();
def.setName(SessionController.class.getSimpleName());
def.setBlocking(false);
def.setController(SessionController.class);
def.setHandlerProperties(getDefaultProperties());
return def;
}
/**
* Get the default properties for an implementation of StaticController
*
* @return
*/
public static Properties getDefaultProperties() {
Properties json = new Properties();
json.put(SESSION_STORE_PROP, SessionStore.LOCAL_SESSION_STORE.toString());
json.put(EXPIRATION_STORE_PROP, String.valueOf(DEFAULT_SESSION_EXPIRATION));
return json;
}
}
| relax cookies secure in test mode
| src/main/java/de/braintags/netrelay/controller/SessionController.java | relax cookies secure in test mode | <ide><path>rc/main/java/de/braintags/netrelay/controller/SessionController.java
<ide> import java.util.Properties;
<ide>
<ide> import de.braintags.netrelay.routing.RouterDefinition;
<add>import de.braintags.vertx.services.base.util.EclipseDetection;
<ide> import io.vertx.ext.web.RoutingContext;
<ide> import io.vertx.ext.web.handler.SessionHandler;
<ide> import io.vertx.ext.web.sstore.ClusteredSessionStore;
<ide> case LOCAL_SESSION_STORE:
<ide> sessionHandler = SessionHandler
<ide> .create(LocalSessionStore.create(getVertx(), getSessionMapName(properties), parseExpiration(properties)))
<del> .setCookieHttpOnlyFlag(true).setCookieSecureFlag(true);
<add> .setCookieHttpOnlyFlag(true).setCookieSecureFlag(!EclipseDetection.isTest());
<ide> break;
<ide>
<ide> case CLUSTERED_SESSION_STORE: |
|
Java | mit | fd8b4660b6d2a8b4c574970de15f5305ced71798 | 0 | rantianhua/AsymmetricGridView,yulongxiao/AsymmetricGridView,lichuanzhi7909/AsymmetricGridView,AlexanderMazaletskiy/AsymmetricGridView,HiWong/AsymmetricGridView,changjiashuai/AsymmetricGridView,letanloc/AsymmetricGridView,hgl888/AsymmetricGridView,ErNaveen/AsymmetricGridView,shyamkumarm/AsymmetricGridView,jiyuren/AsymmetricGridView,felipecsl/AsymmetricGridView,jyushion/AsymmetricGridView,fjolliver/AsymmetricGridView,felipecsl/AsymmetricGridView | package com.felipecsl.asymmetricgridview.library.widget;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import com.felipecsl.asymmetricgridview.library.R;
import com.felipecsl.asymmetricgridview.library.Utils;
import com.felipecsl.asymmetricgridview.library.model.AsymmetricItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AsymmetricGridViewAdapter<T extends AsymmetricItem> extends ArrayAdapter<T> {
private class RowInfo {
private final List<T> items;
private final int rowHeight;
private final float spaceLeft;
public RowInfo(final int rowHeight,
final List<T> items,
final float spaceLeft) {
this.rowHeight = rowHeight;
this.items = items;
this.spaceLeft = spaceLeft;
}
public List<T> getItems() {
return items;
}
public int getRowHeight() {
return rowHeight;
}
public float getSpaceLeft() {
return spaceLeft;
}
}
private static final String TAG = "AsymmetricGridViewAdapter";
protected static final boolean DEBUG = true;
protected final AsymmetricGridView listView;
protected final Context context;
protected final List<T> items;
private final Map<Integer, RowInfo> itemsPerRow = new HashMap<>();
public AsymmetricGridViewAdapter(final Context context,
final AsymmetricGridView listView,
final List<T> items) {
super(context, 0, items);
this.items = items;
this.context = context;
this.listView = listView;
}
public abstract View getActualView(final int position, final View convertView, final ViewGroup parent);
protected int getRowHeight(final AsymmetricItem item) {
final int rowHeight = listView.getColumnWidth() * item.getRowSpan();
// when the item spans multiple rows, we need to account for the vertical padding
// and add that to the total final height
return rowHeight + ((item.getRowSpan() - 1) * listView.getRequestedVerticalSpacing());
}
protected int getRowWidth(final AsymmetricItem item) {
final int rowWidth = listView.getColumnWidth() * item.getColumnSpan();
// when the item spans multiple columns, we need to account for the horizontal padding
// and add that to the total final width
return Math.min(rowWidth + ((item.getColumnSpan() - 1) * listView.getRequestedHorizontalSpacing()), Utils.getScreenWidth(getContext()));
}
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
LinearLayout layout = findOrInitializeLayout(convertView);
final RowInfo rowInfo = itemsPerRow.get(position);
final List<AsymmetricItem> rowItems = new ArrayList<>();
rowItems.addAll(rowInfo.getItems());
// Index to control the current position
// of the current column in this row
int columnIndex = 0;
// Index to control the current position
// in the array of all the items available for this row
int currentIndex = 0;
// Index to control the current position
// within the current column
int currentColumnIndex = 0;
int spaceLeftInColumn = rowInfo.getRowHeight();
while (!rowItems.isEmpty() && columnIndex < listView.getNumColumns()) {
final AsymmetricItem currentItem = rowItems.get(currentIndex);
if (spaceLeftInColumn == 0) {
// No more space in this column. Move to next one
columnIndex++;
currentIndex = 0;
currentColumnIndex = 0;
spaceLeftInColumn = rowInfo.getRowHeight();
continue;
}
// Is there enough space in this column to accommodate currentItem?
if (spaceLeftInColumn >= currentItem.getRowSpan()) {
rowItems.remove(currentItem);
final LinearLayout childLayout = findOrInitializeChildLayout(layout, columnIndex);
final View childConvertView = childLayout.getChildAt(currentColumnIndex);
final View v = getActualView(items.indexOf(currentItem), childConvertView, parent);
currentColumnIndex += currentItem.getRowSpan();
spaceLeftInColumn -= currentItem.getRowSpan();
currentIndex = 0;
if (childConvertView == null)
childLayout.addView(v);
} else if (currentIndex < rowItems.size() - 1) {
// Try again with next item
currentIndex++;
} else {
break;
}
}
return layout;
}
private LinearLayout findOrInitializeLayout(final View convertView) {
LinearLayout layout;
if (convertView == null) {
layout = new LinearLayout(context);
if (DEBUG)
layout.setBackgroundColor(Color.parseColor("#00ff00"));
if (Build.VERSION.SDK_INT >= 11) {
layout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
layout.setDividerDrawable(context.getResources().getDrawable(R.drawable.item_divider_horizontal));
}
layout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT));
} else
layout = (LinearLayout) convertView;
// Clear all layout children before starting
for (int j = 0; j < layout.getChildCount(); j++) {
LinearLayout tempChild = (LinearLayout) layout.getChildAt(j);
tempChild.removeAllViews();
}
layout.removeAllViews();
return layout;
}
private LinearLayout findOrInitializeChildLayout(final LinearLayout parentLayout, final int childIndex) {
LinearLayout childLayout = (LinearLayout) parentLayout.getChildAt(childIndex);
if (childLayout == null) {
childLayout = new LinearLayout(context);
childLayout.setOrientation(LinearLayout.VERTICAL);
if (DEBUG)
childLayout.setBackgroundColor(Color.parseColor("#0000ff"));
if (Build.VERSION.SDK_INT >= 11) {
childLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
childLayout.setDividerDrawable(context.getResources().getDrawable(R.drawable.item_divider_vertical));
}
childLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.MATCH_PARENT));
parentLayout.addView(childLayout);
}
return childLayout;
}
public void setItems(List<T> newItems) {
items.clear();
items.addAll(newItems);
recalculateItemsPerRow();
notifyDataSetChanged();
}
public void appendItems(List<T> newItems) {
items.addAll(newItems);
final int lastRow = getCount() - 1;
final RowInfo rowInfo = itemsPerRow.get(lastRow);
final float spaceLeftInLastRow = rowInfo.getSpaceLeft();
if (DEBUG)
Log.d(TAG, "Space left in last row: " + spaceLeftInLastRow);
// Try to add new items into the last row, if there is any space left
if (spaceLeftInLastRow > 0) {
for (final T i : rowInfo.getItems())
newItems.add(0, i);
final RowInfo itemsThatFit = calculateItemsForRow(newItems);
if (!itemsThatFit.getItems().isEmpty()) {
for (int i = 0; i < itemsThatFit.getItems().size(); i++)
newItems.remove(0);
itemsPerRow.put(lastRow, itemsThatFit);
}
}
calculateItemsPerRow(getCount(), newItems);
notifyDataSetChanged();
}
@Override
public int getCount() {
// Returns the row count for ListView display purposes
return itemsPerRow.size();
}
public void recalculateItemsPerRow() {
itemsPerRow.clear();
final List<T> itemsToAdd = new ArrayList<>();
itemsToAdd.addAll(items);
calculateItemsPerRow(0, itemsToAdd);
}
private void calculateItemsPerRow(int currentRow, List<T> itemsToAdd) {
while (!itemsToAdd.isEmpty()) {
final RowInfo itemsThatFit = calculateItemsForRow(itemsToAdd);
if (itemsThatFit.getItems().isEmpty()) {
// we can't fit a single item inside a row.
// bail out.
break;
}
for (int i = 0; i < itemsThatFit.getItems().size(); i++)
itemsToAdd.remove(0);
itemsPerRow.put(currentRow, itemsThatFit);
currentRow++;
}
if (DEBUG) {
for (Map.Entry<Integer, RowInfo> e : itemsPerRow.entrySet())
Log.d(TAG, "row: " + e.getKey() + ", items: " + e.getValue().getItems().size());
}
}
private RowInfo calculateItemsForRow(final List<T> items) {
return calculateItemsForRow(items, listView.getNumColumns());
}
private RowInfo calculateItemsForRow(final List<T> items, final float initialSpaceLeft) {
final List<T> itemsThatFit = new ArrayList<>();
int currentItem = 0;
int rowHeight = 1;
float spaceLeft = initialSpaceLeft;
while (spaceLeft > 0 && currentItem < items.size()) {
final T item = items.get(currentItem++);
if (item.getColumnSpan() == 1) {
// 1x sized items
float spaceConsumption = (float) (1.0 / rowHeight);
if (spaceLeft >= spaceConsumption) {
spaceLeft -= spaceConsumption;
itemsThatFit.add(item);
}
} else {
// 2x sizes items
float spaceConsumption = 2;
if (rowHeight == 1) {
// restart with double height
itemsThatFit.clear();
rowHeight = 2;
currentItem = 0;
spaceLeft = initialSpaceLeft;
} else if (spaceLeft >= spaceConsumption) {
spaceLeft -= spaceConsumption;
itemsThatFit.add(item);
} else {
// no more space left in this row
break;
}
}
}
return new RowInfo(rowHeight, itemsThatFit, spaceLeft);
}
}
| library/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridViewAdapter.java | package com.felipecsl.asymmetricgridview.library.widget;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import com.felipecsl.asymmetricgridview.library.R;
import com.felipecsl.asymmetricgridview.library.Utils;
import com.felipecsl.asymmetricgridview.library.model.AsymmetricItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AsymmetricGridViewAdapter<T extends AsymmetricItem> extends ArrayAdapter<T> {
private class RowInfo {
private final List<T> items;
private final int rowHeight;
private final float spaceLeft;
public RowInfo(final int rowHeight,
final List<T> items,
final float spaceLeft) {
this.rowHeight = rowHeight;
this.items = items;
this.spaceLeft = spaceLeft;
}
public List<T> getItems() {
return items;
}
public int getRowHeight() {
return rowHeight;
}
public float getSpaceLeft() {
return spaceLeft;
}
}
private static final String TAG = "AsymmetricGridViewAdapter";
private static final boolean DEBUG = true;
protected final AsymmetricGridView listView;
private final Context context;
private final List<T> items;
private final Map<Integer, RowInfo> itemsPerRow = new HashMap<>();
protected AsymmetricGridViewAdapter(final Context context,
final AsymmetricGridView listView,
final List<T> items) {
super(context, 0, items);
this.items = items;
this.context = context;
this.listView = listView;
}
public abstract View getActualView(final int position, final View convertView, final ViewGroup parent);
protected int getRowHeight(final AsymmetricItem item) {
final int rowHeight = listView.getColumnWidth() * item.getRowSpan();
// when the item spans multiple rows, we need to account for the vertical padding
// and add that to the total final height
return rowHeight + ((item.getRowSpan() - 1) * listView.getRequestedVerticalSpacing());
}
protected int getRowWidth(final AsymmetricItem item) {
final int rowWidth = listView.getColumnWidth() * item.getColumnSpan();
// when the item spans multiple columns, we need to account for the horizontal padding
// and add that to the total final width
return Math.min(rowWidth + ((item.getColumnSpan() - 1) * listView.getRequestedHorizontalSpacing()), Utils.getScreenWidth(getContext()));
}
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
LinearLayout layout = findOrInitializeLayout(convertView);
final RowInfo rowInfo = itemsPerRow.get(position);
final List<AsymmetricItem> rowItems = new ArrayList<>();
rowItems.addAll(rowInfo.getItems());
// Index to control the current position
// of the current column in this row
int columnIndex = 0;
// Index to control the current position
// in the array of all the items available for this row
int currentIndex = 0;
// Index to control the current position
// within the current column
int currentColumnIndex = 0;
int spaceLeftInColumn = rowInfo.getRowHeight();
while (!rowItems.isEmpty() && columnIndex < listView.getNumColumns()) {
final AsymmetricItem currentItem = rowItems.get(currentIndex);
if (spaceLeftInColumn == 0) {
// No more space in this column. Move to next one
columnIndex++;
currentIndex = 0;
currentColumnIndex = 0;
spaceLeftInColumn = rowInfo.getRowHeight();
continue;
}
// Is there enough space in this column to accommodate currentItem?
if (spaceLeftInColumn >= currentItem.getRowSpan()) {
rowItems.remove(currentItem);
final LinearLayout childLayout = findOrInitializeChildLayout(layout, columnIndex);
final View childConvertView = childLayout.getChildAt(currentColumnIndex);
final View v = getActualView(items.indexOf(currentItem), childConvertView, parent);
currentColumnIndex += currentItem.getRowSpan();
spaceLeftInColumn -= currentItem.getRowSpan();
currentIndex = 0;
if (childConvertView == null)
childLayout.addView(v);
} else if (currentIndex < rowItems.size() - 1) {
// Try again with next item
currentIndex++;
} else {
break;
}
}
return layout;
}
private LinearLayout findOrInitializeLayout(final View convertView) {
LinearLayout layout;
if (convertView == null) {
layout = new LinearLayout(context);
if (DEBUG)
layout.setBackgroundColor(Color.parseColor("#00ff00"));
if (Build.VERSION.SDK_INT >= 11) {
layout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
layout.setDividerDrawable(context.getResources().getDrawable(R.drawable.item_divider_horizontal));
}
layout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT));
} else
layout = (LinearLayout) convertView;
// Clear all layout children before starting
for (int j = 0; j < layout.getChildCount(); j++) {
LinearLayout tempChild = (LinearLayout) layout.getChildAt(j);
tempChild.removeAllViews();
}
layout.removeAllViews();
return layout;
}
private LinearLayout findOrInitializeChildLayout(final LinearLayout parentLayout, final int childIndex) {
LinearLayout childLayout = (LinearLayout) parentLayout.getChildAt(childIndex);
if (childLayout == null) {
childLayout = new LinearLayout(context);
childLayout.setOrientation(LinearLayout.VERTICAL);
if (DEBUG)
childLayout.setBackgroundColor(Color.parseColor("#0000ff"));
if (Build.VERSION.SDK_INT >= 11) {
childLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
childLayout.setDividerDrawable(context.getResources().getDrawable(R.drawable.item_divider_vertical));
}
childLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.MATCH_PARENT));
parentLayout.addView(childLayout);
}
return childLayout;
}
public void setItems(List<T> newItems) {
items.clear();
items.addAll(newItems);
recalculateItemsPerRow();
notifyDataSetChanged();
}
public void appendItems(List<T> newItems) {
items.addAll(newItems);
final int lastRow = getCount() - 1;
final RowInfo rowInfo = itemsPerRow.get(lastRow);
final float spaceLeftInLastRow = rowInfo.getSpaceLeft();
if (DEBUG)
Log.d(TAG, "Space left in last row: " + spaceLeftInLastRow);
// Try to add new items into the last row, if there is any space left
if (spaceLeftInLastRow > 0) {
for (final T i : rowInfo.getItems())
newItems.add(0, i);
final RowInfo itemsThatFit = calculateItemsForRow(newItems);
if (!itemsThatFit.getItems().isEmpty()) {
for (int i = 0; i < itemsThatFit.getItems().size(); i++)
newItems.remove(0);
itemsPerRow.put(lastRow, itemsThatFit);
}
}
calculateItemsPerRow(getCount(), newItems);
notifyDataSetChanged();
}
@Override
public int getCount() {
// Returns the row count for ListView display purposes
return itemsPerRow.size();
}
public void recalculateItemsPerRow() {
itemsPerRow.clear();
final List<T> itemsToAdd = new ArrayList<>();
itemsToAdd.addAll(items);
calculateItemsPerRow(0, itemsToAdd);
}
private void calculateItemsPerRow(int currentRow, List<T> itemsToAdd) {
while (!itemsToAdd.isEmpty()) {
final RowInfo itemsThatFit = calculateItemsForRow(itemsToAdd);
if (itemsThatFit.getItems().isEmpty()) {
// we can't fit a single item inside a row.
// bail out.
break;
}
for (int i = 0; i < itemsThatFit.getItems().size(); i++)
itemsToAdd.remove(0);
itemsPerRow.put(currentRow, itemsThatFit);
currentRow++;
}
if (DEBUG) {
for (Map.Entry<Integer, RowInfo> e : itemsPerRow.entrySet())
Log.d(TAG, "row: " + e.getKey() + ", items: " + e.getValue().getItems().size());
}
}
private RowInfo calculateItemsForRow(final List<T> items) {
return calculateItemsForRow(items, listView.getNumColumns());
}
private RowInfo calculateItemsForRow(final List<T> items, final float initialSpaceLeft) {
final List<T> itemsThatFit = new ArrayList<>();
int currentItem = 0;
int rowHeight = 1;
float spaceLeft = initialSpaceLeft;
while (spaceLeft > 0 && currentItem < items.size()) {
final T item = items.get(currentItem++);
if (item.getColumnSpan() == 1) {
// 1x sized items
float spaceConsumption = (float) (1.0 / rowHeight);
if (spaceLeft >= spaceConsumption) {
spaceLeft -= spaceConsumption;
itemsThatFit.add(item);
}
} else {
// 2x sizes items
float spaceConsumption = 2;
if (rowHeight == 1) {
// restart with double height
itemsThatFit.clear();
rowHeight = 2;
currentItem = 0;
spaceLeft = initialSpaceLeft;
} else if (spaceLeft >= spaceConsumption) {
spaceLeft -= spaceConsumption;
itemsThatFit.add(item);
} else {
// no more space left in this row
break;
}
}
}
return new RowInfo(rowHeight, itemsThatFit, spaceLeft);
}
}
| Makes adapter members protected
| library/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridViewAdapter.java | Makes adapter members protected | <ide><path>ibrary/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridViewAdapter.java
<ide> }
<ide>
<ide> private static final String TAG = "AsymmetricGridViewAdapter";
<del> private static final boolean DEBUG = true;
<add> protected static final boolean DEBUG = true;
<ide> protected final AsymmetricGridView listView;
<del> private final Context context;
<del> private final List<T> items;
<add> protected final Context context;
<add> protected final List<T> items;
<ide> private final Map<Integer, RowInfo> itemsPerRow = new HashMap<>();
<ide>
<del> protected AsymmetricGridViewAdapter(final Context context,
<del> final AsymmetricGridView listView,
<del> final List<T> items) {
<add> public AsymmetricGridViewAdapter(final Context context,
<add> final AsymmetricGridView listView,
<add> final List<T> items) {
<ide>
<ide> super(context, 0, items);
<ide> |
|
JavaScript | mit | a2b9c6ceb8616cc603b23382d3846b75e2ac4037 | 0 | rhyolight/soda-tap,rhyolight/soda-tap,rhyolight/soda-tap | $(function() {
var DEFAULT_DATA_LIMIT = 100;
var SCALAR_DATA_LIMIT = 5000;
var GEO_DATA_LIMIT = 1000;
function graphData(id, data, graphLabels, temporalField, typeIndex) {
var graphInput = [];
_.each(data, function(point) {
var row = [];
row.push(new Date(point[temporalField]));
for (var i = 1; i < graphLabels.length; i++) {
row.push(new Number(point[graphLabels[i]]))
}
graphInput.push(row);
});
new Dygraph(
document.getElementById(id + '-viz'),
graphInput,
{
labels: graphLabels,
width: $('.panel-body').width()
}
);
}
function renderMap(id, data, temporalField) {
var vizContainer = $('#' + id + '-viz');
vizContainer.html('<div class="map" id="' + id + '-map"></div>');
var markers = [];
var map = new google.maps.Map(document.getElementById(id + '-map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var lats = []
var lons = []
_.each(data, function(point) {
var lat, lon;
if (point.latitude && point.longitude) {
lat = point.latitude;
lon = point.longitude;
} else {
_.each(point, function(val, key) {
if (val.type && val.type == 'Point') {
lat = val.coordinates[1];
lon = val.coordinates[0];
} else if (val.latitude) {
lat = val.latitude;
lon = val.longitude;
}
});
}
if (lat && lon) {
var myLatLng = {
lat: parseFloat(lat),
lng: parseFloat(lon)
};
markers.push(new google.maps.Marker({
position: myLatLng,
map: map,
title: point[temporalField]
}));
lats.push(lat);
lons.push(lon);
}
});
map.setCenter({
lat: _.sum(lats) / lats.length,
lng: _.sum(lons) / lons.length
});
}
function renderDataTable(id, data, tableHeaders, temporalField, typeIndex) {
var $table = $('#' + id + '-table');
var $thead = $table.find('thead');
var $tbody = $table.find('tbody');
var html = '';
var row = '';
// Header row
row += '<tr>';
_.each(tableHeaders, function(header) {
row += '<th>' + header + ' (' + typeIndex[header] + ')</th>\n';
});
row += '</tr>\n';
$thead.html(row);
// Only put 10 rows of data into the HTML table.
data = data.slice(0, 10);
_.each(data, function(point) {
row = '<tr>';
_.each(tableHeaders, function(header) {
var dataType = typeIndex[header]
var value = point[header]
if (dataType == 'location' && value != undefined) {
value = value.coordinates.join(', ')
}
row += '<td>' + value + '</td>\n';
});
row += '</tr>\n';
html += row;
});
$tbody.html(html);
}
function enableNavigationButtons() {
// Enable navigation buttons
var url = window.location.href;
var splitUrl = url.split('/');
var currentPage = parseInt(splitUrl.pop());
var urlNoPage = splitUrl.join('/');
var nextPage = currentPage + 1;
var prevPage = currentPage - 1;
var hasQuery = url.indexOf('?') > 0
var prevUrl = urlNoPage + '/' + prevPage;
var nextUrl = urlNoPage + '/' + nextPage;
if (hasQuery) {
prevUrl += '?' + url.split('?').pop();
nextUrl += '?' + url.split('?').pop();
}
if (prevPage > -1) {
$('.prev-nav-container').html('<a href="' + prevUrl + '">Page ' + prevPage + '</a>');
}
$('.next-nav-container').html('<a href="' + nextUrl + '">Page ' + nextPage + '</a>');
}
function renderVisualizations() {
// Renders visualizations for each resource on the page.
$('.viz').each(function(i, el) {
var dataAttrs = $(el).data()
var id = dataAttrs.id;
var temporalField = dataAttrs.temporalField;
var dataLimit = DEFAULT_DATA_LIMIT;
if (_.contains(window.location.href, 'resource')) {
dataLimit = SCALAR_DATA_LIMIT;
}
var typeIndex = {};
var dataType = dataAttrs.type;
if (dataType == 'geospatial') {
dataLimit = GEO_DATA_LIMIT;
}
var jsonUrl = dataAttrs.jsonUrl
+ '?$order=' + temporalField + ' DESC'
+ '&$limit=' + dataLimit;
// The rest of the data attributes are field types.
_.each(dataAttrs, function(value, name) {
if (! _.contains(['id', 'jsonUrl', 'temporalField', 'type'], name)) {
typeIndex[name] = value;
}
});
$.getJSON(jsonUrl, function(data) {
var graphLabels, tableHeaders;
// Reverse the data because it came in descending order.
data = data.reverse();
// The temporal field is always first because it contains the date
graphLabels = [temporalField];
tableHeaders = [temporalField];
_.each(typeIndex, function(type, name) {
// We will graph all number types
if (_.contains(['int', 'float'], type)) {
graphLabels.push(name);
}
if (name != temporalField) {
tableHeaders.push(name);
}
});
if (dataType == 'scalar') {
graphData(id, data, graphLabels, temporalField, typeIndex);
} else {
renderMap(id, data, temporalField);
}
renderDataTable(id, data, tableHeaders, temporalField, typeIndex);
});
});
}
enableNavigationButtons();
renderVisualizations();
}());
| static/js/catalog.js | $(function() {
var DEFAULT_DATA_LIMIT = 100;
var SCALAR_DATA_LIMIT = 5000;
var GEO_DATA_LIMIT = 1000;
function graphData(id, data, graphLabels, temporalField, typeIndex) {
var graphInput = [];
_.each(data, function(point) {
var row = [];
row.push(new Date(point[temporalField]));
for (var i = 1; i < graphLabels.length; i++) {
row.push(new Number(point[graphLabels[i]]))
}
graphInput.push(row);
});
new Dygraph(
document.getElementById(id + '-viz'),
graphInput,
{
labels: graphLabels,
width: $('.panel-body').width()
}
);
}
function renderMap(id, data, temporalField) {
var vizContainer = $('#' + id + '-viz');
vizContainer.html('<div class="map" id="' + id + '-map"></div>');
var markers = [];
var map = new google.maps.Map(document.getElementById(id + '-map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var lats = []
var lons = []
_.each(data, function(point) {
var lat, lon;
if (point.latitude && point.longitude) {
lat = point.latitude;
lon = point.longitude;
} else {
_.each(point, function(val, key) {
if (val.type && val.type == 'Point') {
lat = val.coordinates[1];
lon = val.coordinates[0];
} else if (val.latitude) {
lat = val.latitude;
lon = val.longitude;
}
});
}
if (lat && lon) {
var myLatLng = {
lat: parseFloat(lat),
lng: parseFloat(lon)
};
markers.push(new google.maps.Marker({
position: myLatLng,
map: map,
title: point[temporalField]
}));
lats.push(lat);
lons.push(lon);
}
});
map.setCenter({
lat: _.sum(lats) / lats.length,
lng: _.sum(lons) / lons.length
});
}
function renderDataTable(id, data, tableHeaders, temporalField, typeIndex) {
var $table = $('#' + id + '-table');
var $thead = $table.find('thead');
var $tbody = $table.find('tbody');
var html = '';
var row = '';
// Header row
row += '<tr>';
_.each(tableHeaders, function(header) {
row += '<th>' + header + ' (' + typeIndex[header] + ')</th>\n';
});
row += '</tr>\n';
$thead.html(row);
// Only put 10 rows of data into the HTML table.
data = data.slice(0, 10);
_.each(data, function(point) {
row = '<tr>';
_.each(tableHeaders, function(header) {
var dataType = typeIndex[header]
var value = point[header]
if (dataType == 'location' && value != undefined) {
value = value.coordinates.join(', ')
}
row += '<td>' + value + '</td>\n';
});
row += '</tr>\n';
html += row;
});
$tbody.html(html);
}
function enableNavigationButtons() {
// Enable navigation buttons
var url = window.location.href;
var splitUrl = url.split('/');
var currentPage = parseInt(splitUrl.pop());
var urlNoPage = splitUrl.join('/');
var nextPage = currentPage + 1;
var prevPage = currentPage - 1;
var hasQuery = url.indexOf('?') > 0
var prevUrl = urlNoPage + '/' + prevPage;
var nextUrl = urlNoPage + '/' + nextPage;
if (hasQuery) {
prevUrl += '?' + url.split('?').pop();
nextUrl += '?' + url.split('?').pop();
}
if (prevPage > -1) {
$('.prev-nav-container').html('<a href="' + prevUrl + '">Page ' + prevPage + '</a>');
}
$('.next-nav-container').html('<a href="' + nextUrl + '">Page ' + nextPage + '</a>');
}
function renderVisualizations() {
// Renders visualizations for each resource on the page.
$('.viz').each(function(i, el) {
var dataAttrs = $(el).data()
var id = dataAttrs.id;
var temporalField = dataAttrs.temporalField;
var dataLimit = DEFAULT_DATA_LIMIT;
if (_.contains(window.location.href, 'resource')) {
dataLimit = SCALAR_DATA_LIMIT;
}
var typeIndex = {};
var dataType = dataAttrs.type;
if (dataType == 'geospatial') {
dataLimit = GEO_DATA_LIMIT;
}
var jsonUrl = dataAttrs.jsonUrl
+ '?$order=' + temporalField + ' DESC'
+ '&$limit=' + dataLimit;
if (dataAttrs.seriesId) {
alert(id + ": " + dataAttrs.seriesId);
}
// The rest of the data attributes are field types.
_.each(dataAttrs, function(value, name) {
if (! _.contains(['id', 'jsonUrl', 'temporalField', 'type'], name)) {
typeIndex[name] = value;
}
});
$.getJSON(jsonUrl, function(data) {
var graphLabels, tableHeaders;
// Reverse the data because it came in descending order.
data = data.reverse();
// The temporal field is always first because it contains the date
graphLabels = [temporalField];
tableHeaders = [temporalField];
_.each(typeIndex, function(type, name) {
// We will graph all number types
if (_.contains(['int', 'float'], type)) {
graphLabels.push(name);
}
if (name != temporalField) {
tableHeaders.push(name);
}
});
if (dataType == 'scalar') {
graphData(id, data, graphLabels, temporalField, typeIndex);
} else {
renderMap(id, data, temporalField);
}
renderDataTable(id, data, tableHeaders, temporalField, typeIndex);
});
});
}
enableNavigationButtons();
renderVisualizations();
}());
| Removed dumb alert
| static/js/catalog.js | Removed dumb alert | <ide><path>tatic/js/catalog.js
<ide> + '?$order=' + temporalField + ' DESC'
<ide> + '&$limit=' + dataLimit;
<ide>
<del> if (dataAttrs.seriesId) {
<del> alert(id + ": " + dataAttrs.seriesId);
<del> }
<del>
<ide> // The rest of the data attributes are field types.
<ide> _.each(dataAttrs, function(value, name) {
<ide> if (! _.contains(['id', 'jsonUrl', 'temporalField', 'type'], name)) { |
|
Java | apache-2.0 | a3b0ec72f21631f74e3288c93a5abc3b7e76aefb | 0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | /**
* Copyright 2007-2008 University Of Southern California
*
* 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.isi.pegasus.planner.code.generator;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.planner.code.CodeGeneratorException;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.code.GridStart;
import edu.isi.pegasus.planner.code.GridStartFactory;
import edu.isi.pegasus.planner.code.POSTScript;
import org.griphyn.cPlanner.classes.ADag;
import org.griphyn.cPlanner.classes.SubInfo;
import org.griphyn.cPlanner.classes.PegasusBag;
import org.griphyn.cPlanner.common.DefaultStreamGobblerCallback;
import org.griphyn.cPlanner.common.StreamGobbler;
import org.griphyn.cPlanner.common.StreamGobblerCallback;
import org.griphyn.cPlanner.namespace.Condor;
import org.griphyn.cPlanner.namespace.Dagman;
import org.griphyn.cPlanner.partitioner.graph.Adapter;
import org.griphyn.cPlanner.partitioner.graph.Graph;
import org.griphyn.cPlanner.partitioner.graph.GraphNode;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This code generator generates a shell script in the submit directory.
* The shell script can be executed on the submit host to run the workflow
* locally.
*
* @author Karan Vahi
* @version $Revision$
*/
public class Shell extends Abstract {
/**
* The prefix for events associated with job in jobstate.log file
*/
public static final String JOBSTATE_JOB_PREFIX = "JOB";
/**
* The prefix for events associated with POST_SCRIPT in jobstate.log file
*/
public static final String JOBSTATE_POST_SCRIPT_PREFIX = "POST_SCRIPT";
/**
* The prefix for events associated with job in jobstate.log file
*/
public static final String JOBSTATE_PRE_SCRIPT_PREFIX = "PRE_SCRIPT";
/**
* The handle to the output file that is being written to.
*/
private PrintWriter mWriteHandle;
/**
* Handle to the Site Store.
*/
private SiteStore mSiteStore;
/**
* The handle to the GridStart Factory.
*/
protected GridStartFactory mGridStartFactory;
/**
* A boolean indicating whether grid start has been initialized or not.
*/
protected boolean mInitializeGridStart;
/**
* The default constructor.
*/
public Shell( ){
super();
mInitializeGridStart = true;
mGridStartFactory = new GridStartFactory();
}
/**
* Initializes the Code Generator implementation.
*
* @param bag the bag of initialization objects.
*
* @throws CodeGeneratorException in case of any error occuring code generation.
*/
public void initialize( PegasusBag bag ) throws CodeGeneratorException{
super.initialize( bag );
mLogger = bag.getLogger();
//create the base directory recovery
File wdir = new File(mSubmitFileDir);
wdir.mkdirs();
//get the handle to pool file
mSiteStore = bag.getHandleToSiteStore();
}
/**
* Generates the code for the concrete workflow in the GRMS input format.
* The GRMS input format is xml based. One XML file is generated per
* workflow.
*
* @param dag the concrete workflow.
*
* @return handle to the GRMS output file.
*
* @throws CodeGeneratorException in case of any error occuring code generation.
*/
public Collection<File> generateCode( ADag dag ) throws CodeGeneratorException{
String opFileName = this.getPathToShellScript( dag ) ;
initializeWriteHandle( opFileName );
Collection result = new ArrayList( 1 );
result.add( new File( opFileName ) );
//write out the script header
writeString(this.getScriptHeader( mSubmitFileDir ) );
//we first need to convert internally into graph format
Graph workflow = Adapter.convert( dag );
//traverse the workflow in topological sort order
for( Iterator<GraphNode> it = workflow.topologicalSortIterator(); it.hasNext(); ){
GraphNode node = it.next();
SubInfo job = (SubInfo)node.getContent();
generateCode( dag, job );
}
//write out the footer
writeString(this.getScriptFooter());
mWriteHandle.close();
//set the XBit on the generated shell script
setXBitOnFile( opFileName );
//write out the braindump file
this.writeOutBraindump( dag );
return result;
}
/**
* Generates the code for a single job in the input format of the workflow
* executor being used.
*
* @param dag the dag of which the job is a part of.
* @param job the <code>SubInfo</code> object holding the information about
* that particular job.
*
* @throws CodeGeneratorException in case of any error occuring code generation.
*/
public void generateCode( ADag dag, SubInfo job ) throws CodeGeneratorException{
mLogger.log( "Generating code for job " + job.getID() , LogManager.DEBUG_MESSAGE_LEVEL );
//sanity check
if( !job.getSiteHandle().equals( "local" ) ){
throw new CodeGeneratorException( "Shell Code generator only works for jobs scheduled to site local" );
}
//initialize GridStart if required.
if ( mInitializeGridStart ){
mGridStartFactory.initialize( mBag, dag );
mInitializeGridStart = false;
}
//determine the work directory for the job
String execDir = getExecutionDirectory( job );
//for local jobs we need initialdir
//instead of remote_initialdir
job.condorVariables.construct("initialdir", execDir );
job.condorVariables.construct( "universe", "local" );
SiteCatalogEntry site = mSiteStore.lookup( job.getSiteHandle() );
String gridStartPath = site.getKickstartPath();
GridStart gridStart = mGridStartFactory.loadGridStart( job , gridStartPath );
//enable the job
if( !gridStart.enable( job,false ) ){
String msg = "Job " + job.getName() + " cannot be enabled by " +
gridStart.shortDescribe() + " to run at " +
job.getSiteHandle();
mLogger.log( msg, LogManager.FATAL_MESSAGE_LEVEL );
throw new CodeGeneratorException( msg );
}
//apply the appropriate POSTScript
POSTScript ps = mGridStartFactory.loadPOSTScript( job, gridStart );
boolean constructed = ps.construct( job, Dagman.POST_SCRIPT_KEY );
//generate call to executeJob
writeString( generateCallToExecuteJob( job, execDir, this.mSubmitFileDir ) );
if( constructed ){
//execute postscript and check for exitcode
writeString( generateCallToExecutePostScript( job, mSubmitFileDir ) );
writeString( generateCallToCheckExitcode( job, JOBSTATE_POST_SCRIPT_PREFIX ) );
}
else{
//no postscript generated
//generate the call to check_exitcode
//check_exitcode test1 JOB $?
writeString( generateCallToCheckExitcode( job, JOBSTATE_JOB_PREFIX ) );
}
writeString( "" );
}
/**
* Returns a Map containing additional braindump entries that are specific
* to a Code Generator
*
* @param workflow the executable workflow
*
* @return Map
*/
public Map<String, String> getAdditionalBraindumpEntries( ADag workflow ) {
Map entries = new HashMap();
entries.put( Braindump.GENERATOR_TYPE_KEY, "shell" );
entries.put( "script", this.getPathToShellScript( workflow ) );
return entries;
}
/**
* Generates a call to check_exitcode function that is used
*
* @param job the associated job
* @param prefix the prefix for the jobstate.log events
*
* @return the call to execute job function.
*/
protected String generateCallToCheckExitcode( SubInfo job,
String prefix ){
StringBuffer sb = new StringBuffer();
sb.append( "check_exitcode" ).append( " " ).
append( job.getID() ).append( " " ).
append( prefix ).append( " " ).
append( "$?" );
return sb.toString();
}
/**
* Generates a call to execute_post_script function , that is used to launch
* a job from the shell script.
*
* @param job the job to be launched
* @param directory the directory in which the job needs to be launched.
*
* @return the call to execute job function.
*/
protected String generateCallToExecutePostScript( SubInfo job,
String directory ){
StringBuffer sb = new StringBuffer();
//gridstart modules right now store the executable
//and arguments as condor profiles. Should be fixed.
//This setting should happen only in Condor Generator
String executable = (String) job.dagmanVariables.get( Dagman.POST_SCRIPT_KEY );
StringBuffer args = new StringBuffer();
args.append( (String)job.dagmanVariables.get( Dagman.POST_SCRIPT_ARGUMENTS_KEY ) ).
append( " " ).append( (String)job.dagmanVariables.get( Dagman.OUTPUT_KEY) );
String arguments = args.toString();
//generate the call to execute job function
//execute_job $jobstate test1 /tmp /bin/echo "Karan Vahi" "stdin file" "k=v" "g=m"
sb.append( "execute_post_script" ).append( " " ).
append( job.getID() ).append( " " ).//the job id
append( directory ).append( " " ). //the directory in which we want the job to execute
append( executable ).append( " " ). //the executable to be invoked
append( "\"" ).append( arguments ).append( "\"" ).append( " " );//the arguments
//handle stdin
sb.append( "\"\"" );
sb.append( " " );
//add the environment variables
return sb.toString();
}
/**
* Generates a call to execute_job function , that is used to launch
* a job from the shell script.
*
* @param job the job to be launched
* @param scratchDirectory the workflow specific execution directory created during running of the workflow
* @param submitDirectory the submit directory of the workflow
*
* @return the call to execute job function.
*/
protected String generateCallToExecuteJob( SubInfo job,
String scratchDirectory,
String submitDirectory ){
StringBuffer sb = new StringBuffer();
//gridstart modules right now store the executable
//and arguments as condor profiles. Should be fixed.
//This setting should happen only in Condor Generator
String executable = (String) job.condorVariables.get( "executable" );
String arguments = (String)job.condorVariables.get( Condor.ARGUMENTS_KEY );
arguments = ( arguments == null ) ? "" : arguments;
String directory = job.runInWorkDirectory() ? scratchDirectory : submitDirectory;
//generate the call to execute job function
//execute_job $jobstate test1 /tmp /bin/echo "Karan Vahi" "stdin file" "k=v" "g=m"
sb.append( "execute_job" ).append( " " ).
append( job.getID() ).append( " " ).//the job id
append( directory ).append( " " ). //the directory in which we want the job to execute
append( executable ).append( " " ). //the executable to be invoked
append( "\"" ).append( arguments ).append( "\"" ).append( " " );//the arguments
//handle stdin for jobs
String stdin = job.getStdIn();
if( stdin == null || stdin.length() == 0 ){
sb.append( "\"\"" );
}
else{
if( stdin.startsWith( File.separator ) ){
sb.append( stdin );
}
else{
sb.append( this.mSubmitFileDir ).append( File.separator ).append( stdin );
}
}
sb.append( " " );
//add the environment variables
for( Iterator it = job.envVariables.getProfileKeyIterator(); it.hasNext(); ){
String key = (String)it.next();
sb.append( "\"" ).
append( key ).append( "=" ).append( job.envVariables.get( key ) ).
append( "\"" ).append( " " );
}
return sb.toString();
}
/**
* Returns the header for the generated shell script. The header contains
* the code block that sources the common plan script from $PEGASUS_HOME/bin
* and initializes the jobstate.log file.
*
* @param submitDirectory the submit directory for the workflow.
*
* @return the script header
*/
protected String getScriptHeader( String submitDirectory ){
StringBuffer sb = new StringBuffer();
sb.append( "#!/bin/bash" ).append( "\n" ).
append( "#" ).append( "\n" ).
append( "# executes the workflow in shell mode " ).append( "\n" ).
append( "#" ).append( "\n" ).
append( "\n");
//check for PEGASUS_HOME
sb.append( "if [ \"X${PEGASUS_HOME}\" = \"X\" ]; then" ).append( "\n" ).
append( " echo \"ERROR: Set your PEGASUS_HOME variable\" 1>&2").append( "\n" ).
append( " exit 1" ).append( "\n" ).
append( "fi" ).append( "\n" ).
append( "\n" );
//check for common shell script before sourcing
sb.append( "if [ ! -e ${PEGASUS_HOME}/libexec/shell-runner-functions.sh ];then" ).append( "\n" ).
append( " echo \"Unable to find shell-runner-functions.sh file.\"" ).append( "\n" ).
append( " echo \"You need to use Pegasus Version 3.0 or higher\"").append( "\n" ).
append( " exit 1 " ).append( "\n" ).
append( "fi" ).append( "\n" );
//source the common shell script
sb.append( ". ${PEGASUS_HOME}/libexec/shell-runner-functions.sh" ).append( "\n" ).
append( "" ).append( "\n" );
sb.append( "PEGASUS_SUBMIT_DIR" ).append( "=" ).append( submitDirectory ).append( "\n" );
sb.append( "#initialize jobstate.log file" ).append( "\n" ).
append( "JOBSTATE_LOG=jobstate.log" ).append( "\n" ).
append( "touch $JOBSTATE_LOG" ).append( "\n" ).
append( "echo \"INTERNAL *** SHELL_SCRIPT_STARTED ***\" >> $JOBSTATE_LOG" ).append( "\n" );
return sb.toString();
}
/**
* Returns the footer for the generated shell script.
*
* @return the script footer.
*/
protected String getScriptFooter(){
StringBuffer sb = new StringBuffer();
sb.append( "echo \"INTERNAL *** SHELL_SCRIPT_FINISHED 0 ***\" >> $JOBSTATE_LOG" );
return sb.toString();
}
/**
* Returns path to the shell script that is generated
*
* @param dag the workflow
* @return path
*/
protected String getPathToShellScript(ADag dag) {
StringBuffer script = new StringBuffer();
script.append( this.mSubmitFileDir ).append( File.separator ).
append( dag.dagInfo.nameOfADag ).append( ".sh" );
return script.toString();
}
/**
* It initializes the write handle to the output file.
*
* @param filename the name of the file to which you want the write handle.
*/
private void initializeWriteHandle(String filename) throws CodeGeneratorException{
try {
File f = new File( filename );
mWriteHandle = new PrintWriter(new FileWriter( f ));
mLogger.log("Writing to file " + filename , LogManager.DEBUG_MESSAGE_LEVEL);
}
catch (Exception e) {
throw new CodeGeneratorException( "Unable to initialize file handle for shell script ", e );
}
}
/**
* Writes a string to the associated write handle with the class
*
* @param st the string to be written.
*/
protected void writeString(String st){
//try{
//write the xml header
mWriteHandle.println(st);
/*}
catch(IOException ex){
System.out.println("Error while writing to xml " + ex.getMessage());
}*/
}
/**
* Returns the directory in which a job should be executed.
*
* @param job the job.
*
* @return the directory
*/
protected String getExecutionDirectory(SubInfo job) {
String execSiteWorkDir = mSiteStore.getWorkDirectory(job);
String workdir = (String) job.globusRSL.removeKey("directory"); // returns old value
workdir = (workdir == null)?execSiteWorkDir:workdir;
return workdir;
}
/**
* Sets the xbit on the file.
*
* @param file the file for which the xbit is to be set
*
* @return boolean indicating whether xbit was set or not.
*/
protected boolean setXBitOnFile( String file ) {
boolean result = false;
//do some sanity checks on the source and the destination
File f = new File( file );
if( !f.exists() || !f.canRead()){
mLogger.log("The file does not exist " + file,
LogManager.ERROR_MESSAGE_LEVEL);
return result;
}
try{
//set the callback and run the grep command
Runtime r = Runtime.getRuntime();
String command = "chmod +x " + file;
mLogger.log("Setting xbit " + command,
LogManager.DEBUG_MESSAGE_LEVEL);
Process p = r.exec(command);
//the default gobbler callback always log to debug level
StreamGobblerCallback callback =
new DefaultStreamGobblerCallback(LogManager.DEBUG_MESSAGE_LEVEL);
//spawn off the gobblers with the already initialized default callback
StreamGobbler ips =
new StreamGobbler(p.getInputStream(), callback);
StreamGobbler eps =
new StreamGobbler(p.getErrorStream(), callback);
ips.start();
eps.start();
//wait for the threads to finish off
ips.join();
eps.join();
//get the status
int status = p.waitFor();
if( status != 0){
mLogger.log("Command " + command + " exited with status " + status,
LogManager.DEBUG_MESSAGE_LEVEL);
return result;
}
result = true;
}
catch(IOException ioe){
mLogger.log("IOException while creating symbolic links ", ioe,
LogManager.ERROR_MESSAGE_LEVEL);
}
catch( InterruptedException ie){
//ignore
}
return result;
}
}
| src/edu/isi/pegasus/planner/code/generator/Shell.java | /**
* Copyright 2007-2008 University Of Southern California
*
* 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.isi.pegasus.planner.code.generator;
import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.planner.code.CodeGeneratorException;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.code.GridStart;
import edu.isi.pegasus.planner.code.GridStartFactory;
import edu.isi.pegasus.planner.code.POSTScript;
import org.griphyn.cPlanner.classes.ADag;
import org.griphyn.cPlanner.classes.SubInfo;
import org.griphyn.cPlanner.classes.PegasusBag;
import org.griphyn.cPlanner.common.DefaultStreamGobblerCallback;
import org.griphyn.cPlanner.common.StreamGobbler;
import org.griphyn.cPlanner.common.StreamGobblerCallback;
import org.griphyn.cPlanner.namespace.Condor;
import org.griphyn.cPlanner.namespace.Dagman;
import org.griphyn.cPlanner.partitioner.graph.Adapter;
import org.griphyn.cPlanner.partitioner.graph.Graph;
import org.griphyn.cPlanner.partitioner.graph.GraphNode;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This code generator generates a shell script in the submit directory.
* The shell script can be executed on the submit host to run the workflow
* locally.
*
* @author Karan Vahi
* @version $Revision$
*/
public class Shell extends Abstract {
/**
* The prefix for events associated with job in jobstate.log file
*/
public static final String JOBSTATE_JOB_PREFIX = "JOB";
/**
* The prefix for events associated with POST_SCRIPT in jobstate.log file
*/
public static final String JOBSTATE_POST_SCRIPT_PREFIX = "POST_SCRIPT";
/**
* The prefix for events associated with job in jobstate.log file
*/
public static final String JOBSTATE_PRE_SCRIPT_PREFIX = "PRE_SCRIPT";
/**
* The handle to the output file that is being written to.
*/
private PrintWriter mWriteHandle;
/**
* Handle to the Site Store.
*/
private SiteStore mSiteStore;
/**
* The handle to the GridStart Factory.
*/
protected GridStartFactory mGridStartFactory;
/**
* A boolean indicating whether grid start has been initialized or not.
*/
protected boolean mInitializeGridStart;
/**
* The default constructor.
*/
public Shell( ){
super();
mInitializeGridStart = true;
mGridStartFactory = new GridStartFactory();
}
/**
* Initializes the Code Generator implementation.
*
* @param bag the bag of initialization objects.
*
* @throws CodeGeneratorException in case of any error occuring code generation.
*/
public void initialize( PegasusBag bag ) throws CodeGeneratorException{
super.initialize( bag );
mLogger = bag.getLogger();
//create the base directory recovery
File wdir = new File(mSubmitFileDir);
wdir.mkdirs();
//get the handle to pool file
mSiteStore = bag.getHandleToSiteStore();
}
/**
* Generates the code for the concrete workflow in the GRMS input format.
* The GRMS input format is xml based. One XML file is generated per
* workflow.
*
* @param dag the concrete workflow.
*
* @return handle to the GRMS output file.
*
* @throws CodeGeneratorException in case of any error occuring code generation.
*/
public Collection<File> generateCode( ADag dag ) throws CodeGeneratorException{
String opFileName = this.getPathToShellScript( dag ) ;
initializeWriteHandle( opFileName );
Collection result = new ArrayList( 1 );
result.add( new File( opFileName ) );
//write out the script header
writeString(this.getScriptHeader( mSubmitFileDir ) );
//we first need to convert internally into graph format
Graph workflow = Adapter.convert( dag );
//traverse the workflow in topological sort order
for( Iterator<GraphNode> it = workflow.topologicalSortIterator(); it.hasNext(); ){
GraphNode node = it.next();
SubInfo job = (SubInfo)node.getContent();
generateCode( dag, job );
}
//write out the footer
writeString(this.getScriptFooter());
mWriteHandle.close();
//set the XBit on the generated shell script
setXBitOnFile( opFileName );
//write out the braindump file
this.writeOutBraindump( dag );
return result;
}
/**
* Generates the code for a single job in the input format of the workflow
* executor being used.
*
* @param dag the dag of which the job is a part of.
* @param job the <code>SubInfo</code> object holding the information about
* that particular job.
*
* @throws CodeGeneratorException in case of any error occuring code generation.
*/
public void generateCode( ADag dag, SubInfo job ) throws CodeGeneratorException{
mLogger.log( "Generating code for job " + job.getID() , LogManager.DEBUG_MESSAGE_LEVEL );
//sanity check
if( !job.getSiteHandle().equals( "local" ) ){
throw new CodeGeneratorException( "Shell Code generator only works for jobs scheduled to site local" );
}
//initialize GridStart if required.
if ( mInitializeGridStart ){
mGridStartFactory.initialize( mBag, dag );
mInitializeGridStart = false;
}
//determine the work directory for the job
String execDir = getExecutionDirectory( job );
//for local jobs we need initialdir
//instead of remote_initialdir
job.condorVariables.construct("initialdir", execDir );
job.condorVariables.construct( "universe", "local" );
SiteCatalogEntry site = mSiteStore.lookup( job.getSiteHandle() );
String gridStartPath = site.getKickstartPath();
GridStart gridStart = mGridStartFactory.loadGridStart( job , gridStartPath );
//enable the job
if( !gridStart.enable( job,false ) ){
String msg = "Job " + job.getName() + " cannot be enabled by " +
gridStart.shortDescribe() + " to run at " +
job.getSiteHandle();
mLogger.log( msg, LogManager.FATAL_MESSAGE_LEVEL );
throw new CodeGeneratorException( msg );
}
//apply the appropriate POSTScript
POSTScript ps = mGridStartFactory.loadPOSTScript( job, gridStart );
boolean constructed = ps.construct( job, Dagman.POST_SCRIPT_KEY );
//generate call to executeJob
writeString( generateCallToExecuteJob( job, execDir, this.mSubmitFileDir ) );
if( constructed ){
//execute postscript and check for exitcode
writeString( generateCallToExecutePostScript( job, mSubmitFileDir ) );
writeString( generateCallToCheckExitcode( job, JOBSTATE_POST_SCRIPT_PREFIX ) );
}
else{
//no postscript generated
//generate the call to check_exitcode
//check_exitcode test1 JOB $?
writeString( generateCallToCheckExitcode( job, JOBSTATE_JOB_PREFIX ) );
}
writeString( "" );
}
/**
* Returns a Map containing additional braindump entries that are specific
* to a Code Generator
*
* @param workflow the executable workflow
*
* @return Map
*/
public Map<String, String> getAdditionalBraindumpEntries( ADag workflow ) {
Map entries = new HashMap();
entries.put( Braindump.GENERATOR_TYPE_KEY, "shell" );
entries.put( "script", this.getPathToShellScript( workflow ) );
return entries;
}
/**
* Generates a call to check_exitcode function that is used
*
* @param job the associated job
* @param prefix the prefix for the jobstate.log events
*
* @return the call to execute job function.
*/
protected String generateCallToCheckExitcode( SubInfo job,
String prefix ){
StringBuffer sb = new StringBuffer();
sb.append( "check_exitcode" ).append( " " ).
append( job.getID() ).append( " " ).
append( prefix ).append( " " ).
append( "$?" );
return sb.toString();
}
/**
* Generates a call to execute_post_script function , that is used to launch
* a job from the shell script.
*
* @param job the job to be launched
* @param directory the directory in which the job needs to be launched.
*
* @return the call to execute job function.
*/
protected String generateCallToExecutePostScript( SubInfo job,
String directory ){
StringBuffer sb = new StringBuffer();
//gridstart modules right now store the executable
//and arguments as condor profiles. Should be fixed.
//This setting should happen only in Condor Generator
String executable = (String) job.dagmanVariables.get( Dagman.POST_SCRIPT_KEY );
StringBuffer args = new StringBuffer();
args.append( (String)job.dagmanVariables.get( Dagman.POST_SCRIPT_ARGUMENTS_KEY ) ).
append( " " ).append( (String)job.dagmanVariables.get( Dagman.OUTPUT_KEY) );
String arguments = args.toString();
//generate the call to execute job function
//execute_job $jobstate test1 /tmp /bin/echo "Karan Vahi" "stdin file" "k=v" "g=m"
sb.append( "execute_post_script" ).append( " " ).
append( job.getID() ).append( " " ).//the job id
append( directory ).append( " " ). //the directory in which we want the job to execute
append( executable ).append( " " ). //the executable to be invoked
append( "\"" ).append( arguments ).append( "\"" ).append( " " );//the arguments
//handle stdin
sb.append( "\"\"" );
sb.append( " " );
//add the environment variables
return sb.toString();
}
/**
* Generates a call to execute_job function , that is used to launch
* a job from the shell script.
*
* @param job the job to be launched
* @param scratchDirectory the workflow specific execution directory created during running of the workflow
* @param submitDirectory the submit directory of the workflow
*
* @return the call to execute job function.
*/
protected String generateCallToExecuteJob( SubInfo job,
String scratchDirectory,
String submitDirectory ){
StringBuffer sb = new StringBuffer();
//gridstart modules right now store the executable
//and arguments as condor profiles. Should be fixed.
//This setting should happen only in Condor Generator
String executable = (String) job.condorVariables.get( "executable" );
String arguments = (String)job.condorVariables.get( Condor.ARGUMENTS_KEY );
arguments = ( arguments == null ) ? "" : arguments;
String directory = job.runInWorkDirectory() ? scratchDirectory : submitDirectory;
//generate the call to execute job function
//execute_job $jobstate test1 /tmp /bin/echo "Karan Vahi" "stdin file" "k=v" "g=m"
sb.append( "execute_job" ).append( " " ).
append( job.getID() ).append( " " ).//the job id
append( directory ).append( " " ). //the directory in which we want the job to execute
append( executable ).append( " " ). //the executable to be invoked
append( "\"" ).append( arguments ).append( "\"" ).append( " " );//the arguments
//handle stdin for jobs
String stdin = job.getStdIn();
if( stdin == null || stdin.length() == 0 ){
sb.append( "\"\"" );
}
else{
if( stdin.startsWith( File.separator ) ){
sb.append( stdin );
}
else{
sb.append( this.mSubmitFileDir ).append( File.separator ).append( stdin );
}
}
sb.append( " " );
//add the environment variables
for( Iterator it = job.envVariables.getProfileKeyIterator(); it.hasNext(); ){
String key = (String)it.next();
sb.append( "\"" ).
append( key ).append( "=" ).append( job.envVariables.get( key ) ).
append( "\"" ).append( " " );
}
return sb.toString();
}
/**
* Returns the header for the generated shell script. The header contains
* the code block that sources the common plan script from $PEGASUS_HOME/bin
* and initializes the jobstate.log file.
*
* @param submitDirectory the submit directory for the workflow.
*
* @return the script header
*/
protected String getScriptHeader( String submitDirectory ){
StringBuffer sb = new StringBuffer();
sb.append( "#!/bin/bash" ).append( "\n" ).
append( "#" ).append( "\n" ).
append( "# executes the workflow in shell mode " ).append( "\n" ).
append( "#" ).append( "\n" ).
append( "\n");
//check for PEGASUS_HOME
sb.append( "if [ \"X${PEGASUS_HOME}\" = \"X\" ]; then" ).append( "\n" ).
append( " echo \"ERROR: Set your PEGASUS_HOME variable\" 1>&2").append( "\n" ).
append( " exit 1" ).append( "\n" ).
append( "fi" ).append( "\n" ).
append( "\n" );
//check for common shell script before sourcing
sb.append( "if [ ! -e ${PEGASUS_HOME}/bin/common-sh-plan.sh ];then" ).append( "\n" ).
append( " echo \"Unable to find common-sh-plan.sh file.\"" ).append( "\n" ).
append( " echo \"You need to use Pegasus Version 3.0 or higher\"").append( "\n" ).
append( " exit 1 " ).append( "\n" ).
append( "fi" ).append( "\n" );
//source the common shell script
sb.append( ". ${PEGASUS_HOME}/libexec/shell-runner-functions.sh" ).append( "\n" ).
append( "" ).append( "\n" );
sb.append( "PEGASUS_SUBMIT_DIR" ).append( "=" ).append( submitDirectory ).append( "\n" );
sb.append( "#initialize jobstate.log file" ).append( "\n" ).
append( "JOBSTATE_LOG=jobstate.log" ).append( "\n" ).
append( "touch $JOBSTATE_LOG" ).append( "\n" ).
append( "echo \"INTERNAL *** SHELL_SCRIPT_STARTED ***\" >> $JOBSTATE_LOG" ).append( "\n" );
return sb.toString();
}
/**
* Returns the footer for the generated shell script.
*
* @return the script footer.
*/
protected String getScriptFooter(){
StringBuffer sb = new StringBuffer();
sb.append( "echo \"INTERNAL *** SHELL_SCRIPT_FINISHED 0 ***\" >> $JOBSTATE_LOG" );
return sb.toString();
}
/**
* Returns path to the shell script that is generated
*
* @param dag the workflow
* @return path
*/
protected String getPathToShellScript(ADag dag) {
StringBuffer script = new StringBuffer();
script.append( this.mSubmitFileDir ).append( File.separator ).
append( dag.dagInfo.nameOfADag ).append( ".sh" );
return script.toString();
}
/**
* It initializes the write handle to the output file.
*
* @param filename the name of the file to which you want the write handle.
*/
private void initializeWriteHandle(String filename) throws CodeGeneratorException{
try {
File f = new File( filename );
mWriteHandle = new PrintWriter(new FileWriter( f ));
mLogger.log("Writing to file " + filename , LogManager.DEBUG_MESSAGE_LEVEL);
}
catch (Exception e) {
throw new CodeGeneratorException( "Unable to initialize file handle for shell script ", e );
}
}
/**
* Writes a string to the associated write handle with the class
*
* @param st the string to be written.
*/
protected void writeString(String st){
//try{
//write the xml header
mWriteHandle.println(st);
/*}
catch(IOException ex){
System.out.println("Error while writing to xml " + ex.getMessage());
}*/
}
/**
* Returns the directory in which a job should be executed.
*
* @param job the job.
*
* @return the directory
*/
protected String getExecutionDirectory(SubInfo job) {
String execSiteWorkDir = mSiteStore.getWorkDirectory(job);
String workdir = (String) job.globusRSL.removeKey("directory"); // returns old value
workdir = (workdir == null)?execSiteWorkDir:workdir;
return workdir;
}
/**
* Sets the xbit on the file.
*
* @param file the file for which the xbit is to be set
*
* @return boolean indicating whether xbit was set or not.
*/
protected boolean setXBitOnFile( String file ) {
boolean result = false;
//do some sanity checks on the source and the destination
File f = new File( file );
if( !f.exists() || !f.canRead()){
mLogger.log("The file does not exist " + file,
LogManager.ERROR_MESSAGE_LEVEL);
return result;
}
try{
//set the callback and run the grep command
Runtime r = Runtime.getRuntime();
String command = "chmod +x " + file;
mLogger.log("Setting xbit " + command,
LogManager.DEBUG_MESSAGE_LEVEL);
Process p = r.exec(command);
//the default gobbler callback always log to debug level
StreamGobblerCallback callback =
new DefaultStreamGobblerCallback(LogManager.DEBUG_MESSAGE_LEVEL);
//spawn off the gobblers with the already initialized default callback
StreamGobbler ips =
new StreamGobbler(p.getInputStream(), callback);
StreamGobbler eps =
new StreamGobbler(p.getErrorStream(), callback);
ips.start();
eps.start();
//wait for the threads to finish off
ips.join();
eps.join();
//get the status
int status = p.waitFor();
if( status != 0){
mLogger.log("Command " + command + " exited with status " + status,
LogManager.DEBUG_MESSAGE_LEVEL);
return result;
}
result = true;
}
catch(IOException ioe){
mLogger.log("IOException while creating symbolic links ", ioe,
LogManager.ERROR_MESSAGE_LEVEL);
}
catch( InterruptedException ie){
//ignore
}
return result;
}
}
| Related to JIRA PM-110 and PM-131
had missed a reference to common-plan.sh that had to be updated.
| src/edu/isi/pegasus/planner/code/generator/Shell.java | Related to JIRA PM-110 and PM-131 | <ide><path>rc/edu/isi/pegasus/planner/code/generator/Shell.java
<ide>
<ide>
<ide> //check for common shell script before sourcing
<del> sb.append( "if [ ! -e ${PEGASUS_HOME}/bin/common-sh-plan.sh ];then" ).append( "\n" ).
<del> append( " echo \"Unable to find common-sh-plan.sh file.\"" ).append( "\n" ).
<add> sb.append( "if [ ! -e ${PEGASUS_HOME}/libexec/shell-runner-functions.sh ];then" ).append( "\n" ).
<add> append( " echo \"Unable to find shell-runner-functions.sh file.\"" ).append( "\n" ).
<ide> append( " echo \"You need to use Pegasus Version 3.0 or higher\"").append( "\n" ).
<ide> append( " exit 1 " ).append( "\n" ).
<ide> append( "fi" ).append( "\n" ); |
|
JavaScript | apache-2.0 | ca2b4aec73b732adc66adf698830a9345379c31c | 0 | XDATA-Year-3/clique-propaganda,XDATA-Year-3/clique-propaganda,XDATA-Year-3/clique-propaganda | /*jshint browser: true, jquery: true */
/*global clique, _, tangelo, d3 */
$(function () {
"use strict";
var cfg,
launch;
launch = function (_cfg) {
var mongoStore,
graph,
view,
info,
colormap,
ungroup,
linkColormap,
expandNode;
cfg = _cfg;
mongoStore = {
host: cfg.host || "localhost",
database: cfg.database,
collection: cfg.collection
};
window.graph = graph = new clique.Graph({
adapter: new tangelo.plugin.mongo.Mongo(mongoStore)
});
ungroup = function (node) {
var fromLinks,
toLinks,
restoredNodes;
// Get all links involving the group node.
fromLinks = this.graph.adapter.findLinks({
source: node.key()
});
toLinks = this.graph.adapter.findLinks({
target: node.key()
});
$.when(fromLinks, toLinks).then(_.bind(function (from, to) {
var inclusion,
reqs;
// Find the "inclusion" links originating from the
// group node.
inclusion = _.filter(from, function (link) {
return link.getData("grouping");
});
// Store the node keys associated to these links.
restoredNodes = _.invoke(inclusion, "target");
// Delete all the links.
reqs = _.map(from.concat(to), _.bind(this.graph.adapter.destroyLink, this.graph.adapter));
return $.apply($, reqs);
}, this)).then(_.bind(function () {
// Remove the node from the graph.
this.graph.removeNode(node);
// Delete the node itself.
return this.graph.adapter.destroyNode(node);
}, this)).then(_.bind(function () {
var reqs;
// Get mutators for the restored nodes.
reqs = _.map(restoredNodes, this.graph.adapter.findNodeByKey, this.graph.adapter);
return $.when.apply($, reqs);
}, this)).then(_.bind(function () {
var nodes = _.toArray(arguments);
// Clear the deleted flag from the nodes.
_.each(nodes, function (node) {
node.clearData("deleted");
}, this);
// Add the nodes to the graph.
this.graph.addNodes(nodes);
}, this));
};
$("#submit").on("click", function () {
var userid = $("#userid").val(),
spec = {};
if (userid === "") {
return;
}
spec = {
twitter_id: userid
};
graph.adapter.findNode(spec).then(_.bind(graph.addNode, graph));
});
colormap = d3.scale.category10();
// This is a 3-color categorical colormap from colorbrewer
// (http://colorbrewer2.org/?type=qualitative&scheme=Paired&n=3) to
// encode interaction types: mention, reply, and retweet.
linkColormap = d3.scale.ordinal();
linkColormap.range(["#a6cee3","#1f78b4","#b2df8a"]);
window.view = view = new clique.view.Cola({
model: graph,
el: "#content",
label: function (d) {
return d.data.twitter_id;
},
fill: function (d) {
// Red for propagandists; blue for audience.
return d.data.type === "propagandist" ? "#ef8a62" : "#67a9cf";
},
nodeRadius: function (d, r) {
return d.data && d.data.grouped ? 2*r : r;
},
postLinkAdd: function (s) {
var cmap = function (d) {
return linkColormap(d.data.interaction);
};
s.style("fill", cmap)
.style("stroke", cmap);
},
transitionTime: 500,
focusColor: "pink",
rootColor: "gold"
});
if (false) {
(function () {
var orig = view.renderNodes;
view.renderNodes = _.bind(function (nodes) {
orig(nodes);
nodes.each(function (d) {
var that = d3.select(this).select("circle");
console.log("that", that);
graph.adapter.neighborCount(graph.adapter.getAccessor(d.key)).then(function (count) {
console.log("count", count);
var r = that.attr("r");
console.log("r", r);
console.log("r after", r + Math.sqrt(count));
that.transition()
.duration(150)
.attr("r", 10 + Math.sqrt(count));
});
});
}, view);
}());
}
expandNode = function (node) {
graph.adapter.neighborhood(node, 1, 10).then(function (nbd) {
_.each(nbd.nodes, function (n) {
graph.addNode(n, nbd.links);
});
});
};
view.on("render", function () {
var $cm,
getMenuPosition;
$cm = $("#contextmenu");
// This returns a position near the mouse pointer, unless it is too
// near the right or bottom edge of the window, in which case it
// returns a position far enough inside the window to display the
// menu in question.
getMenuPosition = function (mouse, direction, scrollDir) {
var win = $(window)[direction](),
scroll = $(window)[scrollDir](),
menu = $("#contextmenu")[direction](),
position = mouse + scroll;
if (mouse + menu > win && menu < mouse) {
position -= menu;
}
return position;
};
// Attach a contextmenu action to all the nodes - it populates the
// menu element with appropriate data, then shows it at the
// appropriate position.
d3.select(view.el)
.selectAll("g.node")
.on("contextmenu", function (d) {
var cm = d3.select("#contextmenu"),
ul = cm.select("ul"),
node = graph.adapter.getAccessor(d.key),
left,
def,
top;
left = getMenuPosition(d3.event.clientX, "width", "scrollLeft");
top = getMenuPosition(d3.event.clientY, "height", "scrollTop");
ul.select("li.nodelabel")
.text(function () {
return "ID: " + d.data.twitter_id;
});
ul.select("a.context-hide")
.on("click", _.bind(clique.view.SelectionInfo.hideNode, info, node));
ul.select("a.context-expand")
.on("click", _.partial(expandNode, node));
ul.select("a.context-collapse")
.on("click", _.bind(clique.view.SelectionInfo.collapseNode, info, node));
ul.select("a.context-ungroup")
.style("display", d.data.grouped ? null : "none")
.on("click", _.bind(ungroup, info, node));
if (cfg.intentService && d.data.usernames) {
def = $.getJSON(cfg.intentService, {
username: d.data.usernames[0]
});
} else {
def = $.when({});
}
def.then(function (apps) {
apps = _.map(apps, function (data, app) {
return _.extend(data, {name: app});
});
cm.select("ul")
.selectAll("li.external")
.remove();
cm.select("ul")
.selectAll("li.external-header")
.remove();
if (_.size(apps) > 0) {
cm.select("ul")
.append("li")
.classed("external-header", true)
.classed("dropdown-header", true)
.text("External Applications");
cm.select("ul")
.selectAll("li.external")
.data(apps)
.enter()
.append("li")
.classed("external", true)
.append("a")
.attr("tabindex", -1)
.attr("href", function (d) {
return d.username;
})
.attr("target", "_blank")
.text(function (d) {
return d.name;
})
.on("click", function () {
$cm.hide();
});
}
$cm.show()
.css({
left: left,
top: top
});
});
});
// Clicking anywhere else will close any open context menu. Use the
// mouseup event (bound to only the left mouse button) to ensure the
// menu disappears even on a selection event (which does not
// generate a click event).
d3.select(document.body)
.on("mouseup.menuhide", function () {
if (d3.event.which !== 1) {
return;
}
$cm.hide();
});
});
window.info = info = new clique.view.SelectionInfo({
model: view.selection,
graph: graph
});
view.selection.on("focused", function (focusKey) {
var node,
data;
if (_.isUndefined(focusKey)) {
d3.select("#urls-title")
.classed("hidden", true);
d3.select("#times-title")
.classed("hidden", true);
d3.select("#places-title")
.classed("hidden", true);
d3.select("#urls")
.selectAll("*")
.remove();
d3.select("#times")
.selectAll("*")
.remove();
d3.select("#places")
.selectAll("*")
.remove();
return;
}
node = graph.adapter.getAccessor(focusKey);
data = node.getData("propaganda_urls_exposed_to");
if (data) {
d3.select("#urls-title")
.classed("hidden", false);
d3.select("#urls")
.selectAll("a")
.data(data)
.enter()
.append("a")
.attr("href", _.identity)
.text(function (d, i) {
return "url" + (i+1) + " ";
});
}
data = node.getData("timestamps_of_propaganda");
if (data) {
d3.select("#times-title")
.classed("hidden", false);
d3.select("#times")
.selectAll("span")
.data(data)
.enter()
.append("span")
.html(function (d) {
return new Date(d) + "<br>";
});
}
data = node.getData("geos");
if (data) {
d3.select("#places-title")
.classed("hidden", false);
d3.select("#places")
.selectAll("span")
.data(data)
.enter()
.append("span")
.html(function (d) {
return "(" + d[0] + ", " + d[1] + ")" + "<br>";
});
}
});
if (cfg.titan && cfg.graphCentrality) {
$("button.nodecentrality").on("click", function () {
var rexster = window.location.origin + ["", "plugin", "mongo", "rexster", "graphs", cfg.database + "," + cfg.collection].join("/");
$.getJSON("assets/tangelo/romanesco/degree_centrality/workflow", {
sourceGraph: rexster,
titan: cfg.titan
}).then(function (result) {
console.log(result);
});
});
} else {
d3.selectAll(".nodecentrality")
.remove();
}
$("#textmode").on("click", function () {
view.toggleLabels();
});
// Process the query arguments.
var args = tangelo.queryArguments();
// If a node is requested in the query arguments, look for it and add it
// if found.
if (_.has(args, "id")) {
graph.adapter.findNode({
twitter_id: args.id
}).then(function (node) {
if (node) {
graph.addNode(node);
expandNode(node);
}
});
}
};
$.getJSON("config.json")
.then(launch, _.bind(launch, {}));
});
| src/js/index.js | /*jshint browser: true, jquery: true */
/*global clique, _, tangelo, d3 */
$(function () {
"use strict";
var cfg,
launch;
launch = function (_cfg) {
var mongoStore,
graph,
view,
info,
linkInfo,
colormap,
ungroup,
linkColormap,
expandNode;
cfg = _cfg;
mongoStore = {
host: cfg.host || "localhost",
database: cfg.database,
collection: cfg.collection
};
window.graph = graph = new clique.Graph({
adapter: new tangelo.plugin.mongo.Mongo(mongoStore)
});
ungroup = function (node) {
var fromLinks,
toLinks,
restoredNodes;
// Get all links involving the group node.
fromLinks = this.graph.adapter.findLinks({
source: node.key()
});
toLinks = this.graph.adapter.findLinks({
target: node.key()
});
$.when(fromLinks, toLinks).then(_.bind(function (from, to) {
var inclusion,
reqs;
// Find the "inclusion" links originating from the
// group node.
inclusion = _.filter(from, function (link) {
return link.getData("grouping");
});
// Store the node keys associated to these links.
restoredNodes = _.invoke(inclusion, "target");
// Delete all the links.
reqs = _.map(from.concat(to), _.bind(this.graph.adapter.destroyLink, this.graph.adapter));
return $.apply($, reqs);
}, this)).then(_.bind(function () {
// Remove the node from the graph.
this.graph.removeNode(node);
// Delete the node itself.
return this.graph.adapter.destroyNode(node);
}, this)).then(_.bind(function () {
var reqs;
// Get mutators for the restored nodes.
reqs = _.map(restoredNodes, this.graph.adapter.findNodeByKey, this.graph.adapter);
return $.when.apply($, reqs);
}, this)).then(_.bind(function () {
var nodes = _.toArray(arguments);
// Clear the deleted flag from the nodes.
_.each(nodes, function (node) {
node.clearData("deleted");
}, this);
// Add the nodes to the graph.
this.graph.addNodes(nodes);
}, this));
};
$("#submit").on("click", function () {
var userid = $("#userid").val(),
spec = {};
if (userid === "") {
return;
}
spec = {
twitter_id: userid
};
graph.adapter.findNode(spec).then(_.bind(graph.addNode, graph));
});
colormap = d3.scale.category10();
// This is a 3-color categorical colormap from colorbrewer
// (http://colorbrewer2.org/?type=qualitative&scheme=Paired&n=3) to
// encode interaction types: mention, reply, and retweet.
linkColormap = d3.scale.ordinal();
linkColormap.range(["#a6cee3","#1f78b4","#b2df8a"]);
window.view = view = new clique.view.Cola({
model: graph,
el: "#content",
label: function (d) {
return d.data.twitter_id;
},
fill: function (d) {
// Red for propagandists; blue for audience.
return d.data.type === "propagandist" ? "#ef8a62" : "#67a9cf";
},
nodeRadius: function (d, r) {
return d.data && d.data.grouped ? 2*r : r;
},
postLinkAdd: function (s) {
var cmap = function (d) {
return linkColormap(d.data.interaction);
};
s.style("fill", cmap)
.style("stroke", cmap);
},
transitionTime: 500,
focusColor: "pink",
rootColor: "gold"
});
if (false) {
(function () {
var orig = view.renderNodes;
view.renderNodes = _.bind(function (nodes) {
orig(nodes);
nodes.each(function (d) {
var that = d3.select(this).select("circle");
console.log("that", that);
graph.adapter.neighborCount(graph.adapter.getAccessor(d.key)).then(function (count) {
console.log("count", count);
var r = that.attr("r");
console.log("r", r);
console.log("r after", r + Math.sqrt(count));
that.transition()
.duration(150)
.attr("r", 10 + Math.sqrt(count));
});
});
}, view);
}());
}
expandNode = function (node) {
graph.adapter.neighborhood(node, 1, 10).then(function (nbd) {
_.each(nbd.nodes, function (n) {
graph.addNode(n, nbd.links);
});
});
};
view.on("render", function () {
var $cm,
getMenuPosition;
$cm = $("#contextmenu");
// This returns a position near the mouse pointer, unless it is too
// near the right or bottom edge of the window, in which case it
// returns a position far enough inside the window to display the
// menu in question.
getMenuPosition = function (mouse, direction, scrollDir) {
var win = $(window)[direction](),
scroll = $(window)[scrollDir](),
menu = $("#contextmenu")[direction](),
position = mouse + scroll;
if (mouse + menu > win && menu < mouse) {
position -= menu;
}
return position;
};
// Attach a contextmenu action to all the nodes - it populates the
// menu element with appropriate data, then shows it at the
// appropriate position.
d3.select(view.el)
.selectAll("g.node")
.on("contextmenu", function (d) {
var cm = d3.select("#contextmenu"),
ul = cm.select("ul"),
node = graph.adapter.getAccessor(d.key),
left,
def,
top;
left = getMenuPosition(d3.event.clientX, "width", "scrollLeft");
top = getMenuPosition(d3.event.clientY, "height", "scrollTop");
ul.select("li.nodelabel")
.text(function () {
return "ID: " + d.data.twitter_id;
});
ul.select("a.context-hide")
.on("click", _.bind(clique.view.SelectionInfo.hideNode, info, node));
ul.select("a.context-expand")
.on("click", _.partial(expandNode, node));
ul.select("a.context-collapse")
.on("click", _.bind(clique.view.SelectionInfo.collapseNode, info, node));
ul.select("a.context-ungroup")
.style("display", d.data.grouped ? null : "none")
.on("click", _.bind(ungroup, info, node));
if (cfg.intentService && d.data.usernames) {
def = $.getJSON(cfg.intentService, {
username: d.data.usernames[0]
});
} else {
def = $.when({});
}
def.then(function (apps) {
apps = _.map(apps, function (data, app) {
return _.extend(data, {name: app});
});
cm.select("ul")
.selectAll("li.external")
.remove();
cm.select("ul")
.selectAll("li.external-header")
.remove();
if (_.size(apps) > 0) {
cm.select("ul")
.append("li")
.classed("external-header", true)
.classed("dropdown-header", true)
.text("External Applications");
cm.select("ul")
.selectAll("li.external")
.data(apps)
.enter()
.append("li")
.classed("external", true)
.append("a")
.attr("tabindex", -1)
.attr("href", function (d) {
return d.username;
})
.attr("target", "_blank")
.text(function (d) {
return d.name;
})
.on("click", function () {
$cm.hide();
});
}
$cm.show()
.css({
left: left,
top: top
});
});
});
// Clicking anywhere else will close any open context menu. Use the
// mouseup event (bound to only the left mouse button) to ensure the
// menu disappears even on a selection event (which does not
// generate a click event).
d3.select(document.body)
.on("mouseup.menuhide", function () {
if (d3.event.which !== 1) {
return;
}
$cm.hide();
});
});
window.info = info = new clique.view.SelectionInfo({
model: view.selection,
graph: graph
});
linkInfo = new clique.view.LinkInfo({
model: view.linkSelection,
el: "#link-info",
graph: graph
});
linkInfo.render();
var fixup = _.debounce(_.partial(_.delay, function () {
d3.select(linkInfo.el).selectAll("td")
.each(function () {
var me = d3.select(this),
text = me.html();
if (!me.classed("text-right") && text.startsWith("http")) {
me.html("")
.style("max-width", "0px")
.style("word-wrap", "break-word")
.append("a")
.attr("href", text)
.attr("target", "_blank")
.text(text);
} else if (me.classed("text-right") && text === "<strong>msg</strong>") {
var html = [];
me = d3.select($(this).next().get(0));
text = me.html();
_.each(text.split(" "), function (tok) {
if (_.size(tok) > 2 && tok[0] === "@") {
html.push("<a href=\"https://twitter.com/" + tok.slice(1) + "\" target=\"_blank\">" + tok + "</a>");
} else if (tok.startsWith("http")) {
html.push("<a href=\"" + tok + "\" target=\"_blank\">" + tok + "</a>");
} else {
html.push(tok);
}
});
me.html(html.join(" "));
}
});
}, 100), 100);
linkInfo.model.on("change", fixup);
linkInfo.graph.on("change", fixup);
view.selection.on("focused", function (focusKey) {
var node,
data;
if (_.isUndefined(focusKey)) {
d3.select("#urls-title")
.classed("hidden", true);
d3.select("#times-title")
.classed("hidden", true);
d3.select("#places-title")
.classed("hidden", true);
d3.select("#urls")
.selectAll("*")
.remove();
d3.select("#times")
.selectAll("*")
.remove();
d3.select("#places")
.selectAll("*")
.remove();
return;
}
node = graph.adapter.getAccessor(focusKey);
data = node.getData("propaganda_urls_exposed_to");
if (data) {
d3.select("#urls-title")
.classed("hidden", false);
d3.select("#urls")
.selectAll("a")
.data(data)
.enter()
.append("a")
.attr("href", _.identity)
.text(function (d, i) {
return "url" + (i+1) + " ";
});
}
data = node.getData("timestamps_of_propaganda");
if (data) {
d3.select("#times-title")
.classed("hidden", false);
d3.select("#times")
.selectAll("span")
.data(data)
.enter()
.append("span")
.html(function (d) {
return new Date(d) + "<br>";
});
}
data = node.getData("geos");
if (data) {
d3.select("#places-title")
.classed("hidden", false);
d3.select("#places")
.selectAll("span")
.data(data)
.enter()
.append("span")
.html(function (d) {
return "(" + d[0] + ", " + d[1] + ")" + "<br>";
});
}
});
if (cfg.titan && cfg.graphCentrality) {
$("button.nodecentrality").on("click", function () {
var rexster = window.location.origin + ["", "plugin", "mongo", "rexster", "graphs", cfg.database + "," + cfg.collection].join("/");
$.getJSON("assets/tangelo/romanesco/degree_centrality/workflow", {
sourceGraph: rexster,
titan: cfg.titan
}).then(function (result) {
console.log(result);
});
});
} else {
d3.selectAll(".nodecentrality")
.remove();
}
$("#textmode").on("click", function () {
view.toggleLabels();
});
// Process the query arguments.
var args = tangelo.queryArguments();
// If a node is requested in the query arguments, look for it and add it
// if found.
if (_.has(args, "id")) {
graph.adapter.findNode({
twitter_id: args.id
}).then(function (node) {
if (node) {
graph.addNode(node);
expandNode(node);
}
});
}
};
$.getJSON("config.json")
.then(launch, _.bind(launch, {}));
});
| Remove linkInfo code
| src/js/index.js | Remove linkInfo code | <ide><path>rc/js/index.js
<ide> graph,
<ide> view,
<ide> info,
<del> linkInfo,
<ide> colormap,
<ide> ungroup,
<ide> linkColormap,
<ide> graph: graph
<ide> });
<ide>
<del> linkInfo = new clique.view.LinkInfo({
<del> model: view.linkSelection,
<del> el: "#link-info",
<del> graph: graph
<del> });
<del> linkInfo.render();
<del>
<del> var fixup = _.debounce(_.partial(_.delay, function () {
<del> d3.select(linkInfo.el).selectAll("td")
<del> .each(function () {
<del> var me = d3.select(this),
<del> text = me.html();
<del>
<del> if (!me.classed("text-right") && text.startsWith("http")) {
<del> me.html("")
<del> .style("max-width", "0px")
<del> .style("word-wrap", "break-word")
<del> .append("a")
<del> .attr("href", text)
<del> .attr("target", "_blank")
<del> .text(text);
<del> } else if (me.classed("text-right") && text === "<strong>msg</strong>") {
<del> var html = [];
<del>
<del> me = d3.select($(this).next().get(0));
<del> text = me.html();
<del>
<del> _.each(text.split(" "), function (tok) {
<del> if (_.size(tok) > 2 && tok[0] === "@") {
<del> html.push("<a href=\"https://twitter.com/" + tok.slice(1) + "\" target=\"_blank\">" + tok + "</a>");
<del> } else if (tok.startsWith("http")) {
<del> html.push("<a href=\"" + tok + "\" target=\"_blank\">" + tok + "</a>");
<del> } else {
<del> html.push(tok);
<del> }
<del> });
<del>
<del> me.html(html.join(" "));
<del> }
<del> });
<del> }, 100), 100);
<del>
<del> linkInfo.model.on("change", fixup);
<del> linkInfo.graph.on("change", fixup);
<del>
<ide> view.selection.on("focused", function (focusKey) {
<ide> var node,
<ide> data; |
|
Java | mit | 31096eff5efbe4390cc6f4b070ee337a99e0110e | 0 | jenkinsci/remoting,jenkinsci/remoting | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.remoting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.remoting.Channel.Mode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.concurrent.NotThreadSafe;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.HandshakeResponse;
import javax.websocket.Session;
import org.jenkinsci.remoting.engine.JnlpEndpointResolver;
import org.jenkinsci.remoting.engine.Jnlp4ConnectionState;
import org.jenkinsci.remoting.engine.JnlpAgentEndpoint;
import org.jenkinsci.remoting.engine.JnlpAgentEndpointConfigurator;
import org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver;
import org.jenkinsci.remoting.engine.JnlpConnectionState;
import org.jenkinsci.remoting.engine.JnlpConnectionStateListener;
import org.jenkinsci.remoting.engine.JnlpProtocolHandler;
import org.jenkinsci.remoting.engine.JnlpProtocolHandlerFactory;
import org.jenkinsci.remoting.engine.WorkDirManager;
import org.jenkinsci.remoting.protocol.IOHub;
import org.jenkinsci.remoting.protocol.cert.BlindTrustX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.cert.DelegatingX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.cert.PublicKeyMatchingX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException;
import org.jenkinsci.remoting.util.KeyUtils;
import org.jenkinsci.remoting.util.VersionNumber;
/**
* Agent engine that proactively connects to Jenkins controller.
*
* @author Kohsuke Kawaguchi
*/
@NotThreadSafe // the fields in this class should not be modified by multiple threads concurrently
public class Engine extends Thread {
/**
* HTTP header sent by Jenkins to indicate the earliest version of Remoting it is prepared to accept connections from.
*/
public static final String REMOTING_MINIMUM_VERSION_HEADER = "X-Remoting-Minimum-Version";
/**
* Thread pool that sets {@link #CURRENT}.
*/
private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(@NonNull final Runnable r) {
Thread thread = defaultFactory.newThread(() -> {
CURRENT.set(Engine.this);
r.run();
});
thread.setDaemon(true);
thread.setUncaughtExceptionHandler((t, e) -> LOGGER.log(Level.SEVERE, e, () -> "Uncaught exception in thread " + t));
return thread;
}
});
/**
* @deprecated
* Use {@link #events}.
*/
@Deprecated
public final EngineListener listener;
private final EngineListenerSplitter events = new EngineListenerSplitter();
/**
* To make Jenkins more graceful against user error,
* JNLP agent can try to connect to multiple possible Jenkins URLs.
* This field specifies those candidate URLs, such as
* "http://foo.bar/jenkins/".
*/
private final List<URL> candidateUrls;
/**
* The list of {@link X509Certificate} instances to trust when connecting to any of the {@link #candidateUrls}
* or {@code null} to use the JVM default trust store.
*/
private List<X509Certificate> candidateCertificates;
/**
* URL that points to Jenkins's tcp agent listener, like <tt>http://myhost/hudson/</tt>
*
* <p>
* This value is determined from {@link #candidateUrls} after a successful connection.
* Note that this URL <b>DOES NOT</b> have "tcpSlaveAgentListener" in it.
*/
@CheckForNull
private URL hudsonUrl;
private final String secretKey;
private final String agentName;
private boolean webSocket;
private Map<String, String> webSocketHeaders;
private String credentials;
private String protocolName;
private String proxyCredentials = System.getProperty("proxyCredentials");
/**
* See {@link hudson.remoting.jnlp.Main#tunnel} for the documentation.
*/
@CheckForNull
private String tunnel;
private boolean disableHttpsCertValidation = false;
private boolean noReconnect = false;
/**
* Determines whether the socket will have {@link Socket#setKeepAlive(boolean)} set or not.
*
* @since 2.62.1
*/
private boolean keepAlive = true;
@CheckForNull
private JarCache jarCache = null;
/**
* Specifies a destination for the agent log.
* If specified, this option overrides the default destination within {@link #workDir}.
* If both this options and {@link #workDir} is not set, the log will not be generated.
* @since 3.8
*/
@CheckForNull
private Path agentLog;
/**
* Specified location of the property file with JUL settings.
* @since 3.8
*/
@CheckForNull
private Path loggingConfigFilePath = null;
/**
* Specifies a default working directory of the remoting instance.
* If specified, this directory will be used to store logs, JAR cache, etc.
* <p>
* In order to retain compatibility, the option is disabled by default.
* <p>
* Jenkins specifics: This working directory is expected to be equal to the agent root specified in Jenkins configuration.
* @since 3.8
*/
@CheckForNull
public Path workDir = null;
/**
* Specifies a directory within {@link #workDir}, which stores all the remoting-internal files.
* <p>
* This option is not expected to be used frequently, but it allows remoting users to specify a custom
* storage directory if the default {@code remoting} directory is consumed by other stuff.
* @since 3.8
*/
@NonNull
public String internalDir = WorkDirManager.DirType.INTERNAL_DIR.getDefaultLocation();
/**
* Fail the initialization if the workDir or internalDir are missing.
* This option presumes that the workspace structure gets initialized previously in order to ensure that we do not start up with a borked instance
* (e.g. if a filesystem mount gets disconnected).
* @since 3.8
*/
public boolean failIfWorkDirIsMissing = WorkDirManager.DEFAULT_FAIL_IF_WORKDIR_IS_MISSING;
private final DelegatingX509ExtendedTrustManager agentTrustManager = new DelegatingX509ExtendedTrustManager(new BlindTrustX509ExtendedTrustManager());
private final String directConnection;
private final String instanceIdentity;
private final Set<String> protocols;
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String agentName) {
this(listener, hudsonUrls, secretKey, agentName, null, null, null);
}
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String agentName, String directConnection, String instanceIdentity,
Set<String> protocols) {
this.listener = listener;
this.directConnection = directConnection;
this.events.add(listener);
this.candidateUrls = hudsonUrls.stream().map(Engine::ensureTrailingSlash).collect(Collectors.toList());
this.secretKey = secretKey;
this.agentName = agentName;
this.instanceIdentity = instanceIdentity;
this.protocols = protocols;
if(candidateUrls.isEmpty() && instanceIdentity == null) {
throw new IllegalArgumentException("No URLs given");
}
setUncaughtExceptionHandler((t, e) -> {
LOGGER.log(Level.SEVERE, e, () -> "Uncaught exception in Engine thread " + t);
interrupt();
});
}
private static URL ensureTrailingSlash(URL u) {
if (u.toString().endsWith("/")) {
return u;
} else {
try {
return new URL(u + "/");
} catch (MalformedURLException x) {
throw new IllegalArgumentException(x);
}
}
}
/**
* Starts the engine.
* The procedure initializes the working directory and all the required environment
* @throws IOException Initialization error
* @since 3.9
*/
public synchronized void startEngine() throws IOException {
startEngine(false);
}
/**
* Starts engine.
* @param dryRun If {@code true}, do not actually start the engine.
* This method can be used for testing startup logic.
*/
/*package*/ void startEngine(boolean dryRun) throws IOException {
LOGGER.log(Level.INFO, "Using Remoting version: {0}", Launcher.VERSION);
@CheckForNull File jarCacheDirectory = null;
// Prepare the working directory if required
if (workDir != null) {
final WorkDirManager workDirManager = WorkDirManager.getInstance();
if (jarCache != null) {
// Somebody has already specificed Jar Cache, hence we do not need it in the workspace.
workDirManager.disable(WorkDirManager.DirType.JAR_CACHE_DIR);
}
if (loggingConfigFilePath != null) {
workDirManager.setLoggingConfig(loggingConfigFilePath.toFile());
}
final Path path = workDirManager.initializeWorkDir(workDir.toFile(), internalDir, failIfWorkDirIsMissing);
jarCacheDirectory = workDirManager.getLocation(WorkDirManager.DirType.JAR_CACHE_DIR);
workDirManager.setupLogging(path, agentLog);
} else if (jarCache == null) {
LOGGER.log(Level.WARNING, "No Working Directory. Using the legacy JAR Cache location: {0}", JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION);
jarCacheDirectory = JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION;
}
if (jarCache == null){
if (jarCacheDirectory == null) {
// Should never happen in the current code
throw new IOException("Cannot find the JAR Cache location");
}
LOGGER.log(Level.FINE, "Using standard File System JAR Cache. Root Directory is {0}", jarCacheDirectory);
try {
jarCache = new FileSystemJarCache(jarCacheDirectory, true);
} catch (IllegalArgumentException ex) {
throw new IOException("Failed to initialize FileSystem JAR Cache in " + jarCacheDirectory, ex);
}
} else {
LOGGER.log(Level.INFO, "Using custom JAR Cache: {0}", jarCache);
}
// Start the engine thread
if (!dryRun) {
this.start();
}
}
/**
* Configures custom JAR Cache location.
* This option disables JAR Caching in the working directory.
* @param jarCache JAR Cache to be used
* @since 2.24
*/
public void setJarCache(@NonNull JarCache jarCache) {
this.jarCache = jarCache;
}
/**
* Sets path to the property file with JUL settings.
* @param filePath JAR Cache to be used
* @since 3.8
*/
public void setLoggingConfigFile(@NonNull Path filePath) {
this.loggingConfigFilePath = filePath;
}
/**
* Provides Jenkins URL if available.
* @return Jenkins URL. May return {@code null} if the connection is not established or if the URL cannot be determined
* in the {@link JnlpAgentEndpointResolver}.
*/
@CheckForNull
public URL getHudsonUrl() {
return hudsonUrl;
}
public void setWebSocket(boolean webSocket) {
this.webSocket = webSocket;
}
/**
* Sets map of custom websocket headers. These headers will be applied to the websocket connection to Jenkins.
*
* @param webSocketHeaders a map of the headers to apply to the websocket connection
*/
public void setWebSocketHeaders(@NonNull Map<String, String> webSocketHeaders) {
this.webSocketHeaders = webSocketHeaders;
}
/**
* If set, connect to the specified host and port instead of connecting directly to Jenkins.
* @param tunnel Value. {@code null} to disable tunneling
*/
public void setTunnel(@CheckForNull String tunnel) {
this.tunnel = tunnel;
}
public void setCredentials(String creds) {
this.credentials = creds;
}
public void setProxyCredentials(String proxyCredentials) {
this.proxyCredentials = proxyCredentials;
}
public void setNoReconnect(boolean noReconnect) {
this.noReconnect = noReconnect;
}
/**
* Determines if JNLPAgentEndpointResolver will not perform certificate validation in the HTTPs mode.
*
* @return {@code true} if the certificate validation is disabled.
*/
public boolean isDisableHttpsCertValidation() {
return disableHttpsCertValidation;
}
/**
* Sets if JNLPAgentEndpointResolver will not perform certificate validation in the HTTPs mode.
*
* @param disableHttpsCertValidation {@code true} if the certificate validation is disabled.
*/
public void setDisableHttpsCertValidation(boolean disableHttpsCertValidation) {
this.disableHttpsCertValidation = disableHttpsCertValidation;
}
/**
* Sets the destination for agent logs.
* @param agentLog Path to the agent log.
* If {@code null}, the engine will pick the default behavior depending on the {@link #workDir} value
* @since 3.8
*/
public void setAgentLog(@CheckForNull Path agentLog) {
this.agentLog = agentLog;
}
/**
* Specified a path to the work directory.
* @param workDir Path to the working directory of the remoting instance.
* {@code null} Disables the working directory.
* @since 3.8
*/
public void setWorkDir(@CheckForNull Path workDir) {
this.workDir = workDir;
}
/**
* Specifies name of the internal data directory within {@link #workDir}.
* @param internalDir Directory name
* @since 3.8
*/
public void setInternalDir(@NonNull String internalDir) {
this.internalDir = internalDir;
}
/**
* Sets up behavior if the workDir or internalDir are missing during the startup.
* This option presumes that the workspace structure gets initialized previously in order to ensure that we do not start up with a borked instance
* (e.g. if a filesystem mount gets disconnected).
* @param failIfWorkDirIsMissing Flag
* @since 3.8
*/
public void setFailIfWorkDirIsMissing(boolean failIfWorkDirIsMissing) { this.failIfWorkDirIsMissing = failIfWorkDirIsMissing; }
/**
* Returns {@code true} if and only if the socket to the controller will have {@link Socket#setKeepAlive(boolean)} set.
*
* @return {@code true} if and only if the socket to the controller will have {@link Socket#setKeepAlive(boolean)} set.
*/
public boolean isKeepAlive() {
return keepAlive;
}
/**
* Sets the {@link Socket#setKeepAlive(boolean)} to use for the connection to the controller.
*
* @param keepAlive the {@link Socket#setKeepAlive(boolean)} to use for the connection to the controller.
*/
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public void setCandidateCertificates(List<X509Certificate> candidateCertificates) {
this.candidateCertificates = candidateCertificates == null
? null
: new ArrayList<>(candidateCertificates);
}
public void addCandidateCertificate(X509Certificate certificate) {
if (candidateCertificates == null) {
candidateCertificates = new ArrayList<>();
}
candidateCertificates.add(certificate);
}
public void addListener(EngineListener el) {
events.add(el);
}
public void removeListener(EngineListener el) {
events.remove(el);
}
@Override
@SuppressFBWarnings(value = "HARD_CODE_PASSWORD", justification = "Password doesn't need to be protected.")
public void run() {
if (webSocket) {
runWebSocket();
return;
}
// Create the engine
try {
try (IOHub hub = IOHub.create(executor)) {
SSLContext context;
// prepare our SSLContext
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for TLS algorithm", e);
}
char[] password = "password".toCharArray();
KeyStore store;
try {
store = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
throw new IllegalStateException("Java runtime specification requires support for JKS key store", e);
}
try {
store.load(null, password);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for JKS key store", e);
} catch (CertificateException e) {
throw new IllegalStateException("Empty keystore", e);
}
KeyManagerFactory kmf;
try {
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for default key manager", e);
}
try {
kmf.init(store, password);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new IllegalStateException(e);
}
try {
context.init(kmf.getKeyManagers(), new TrustManager[]{agentTrustManager}, null);
} catch (KeyManagementException e) {
events.error(e);
return;
}
innerRun(hub, context, executor);
}
} catch (IOException e) {
events.error(e);
}
}
@SuppressFBWarnings(value = {"REC_CATCH_EXCEPTION", "URLCONNECTION_SSRF_FD"}, justification = "checked exceptions were a mistake to begin with; connecting to Jenkins from agent")
private void runWebSocket() {
try {
while (true) {
AtomicReference<Channel> ch = new AtomicReference<>();
String localCap = new Capability().toASCII();
class HeaderHandler extends ClientEndpointConfig.Configurator {
Capability remoteCapability = new Capability();
@Override
public void beforeRequest(Map<String, List<String>> headers) {
headers.put(JnlpConnectionState.CLIENT_NAME_KEY, Collections.singletonList(agentName));
headers.put(JnlpConnectionState.SECRET_KEY, Collections.singletonList(secretKey));
headers.put(Capability.KEY, Collections.singletonList(localCap));
// TODO use JnlpConnectionState.COOKIE_KEY somehow (see EngineJnlpConnectionStateListener.afterChannel)
if (webSocketHeaders != null) {
for (Map.Entry<String, String> entry : webSocketHeaders.entrySet()) {
headers.put(entry.getKey(), Collections.singletonList(entry.getValue()));
}
}
LOGGER.fine(() -> "Sending: " + headers);
}
@Override
public void afterResponse(HandshakeResponse hr) {
LOGGER.fine(() -> "Receiving: " + hr.getHeaders());
List<String> remotingMinimumVersion = hr.getHeaders().get(REMOTING_MINIMUM_VERSION_HEADER);
if (remotingMinimumVersion != null && !remotingMinimumVersion.isEmpty()) {
VersionNumber minimumSupportedVersion = new VersionNumber(remotingMinimumVersion.get(0));
VersionNumber currentVersion = new VersionNumber(Launcher.VERSION);
if (currentVersion.isOlderThan(minimumSupportedVersion)) {
events.error(new IOException("Agent version " + minimumSupportedVersion + " or newer is required."));
}
}
try {
remoteCapability = Capability.fromASCII(hr.getHeaders().get(Capability.KEY).get(0));
LOGGER.fine(() -> "received " + remoteCapability);
} catch (IOException x) {
events.error(x);
}
}
}
HeaderHandler headerHandler = new HeaderHandler();
class AgentEndpoint extends Endpoint {
@SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "just trust me here")
AgentEndpoint.Transport transport;
@Override
public void onOpen(Session session, EndpointConfig config) {
events.status("WebSocket connection open");
session.addMessageHandler(ByteBuffer.class, this::onMessage);
try {
transport = new Transport(session);
ch.set(new ChannelBuilder(agentName, executor).
withJarCacheOrDefault(jarCache). // unless EngineJnlpConnectionStateListener can be used for this purpose
build(transport));
} catch (IOException x) {
events.error(x);
}
}
private void onMessage(ByteBuffer message) {
try {
transport.receive(message);
} catch (IOException x) {
events.error(x);
} catch (InterruptedException x) {
events.error(x);
Thread.currentThread().interrupt();
}
}
@Override
public void onClose(Session session, CloseReason closeReason) {
LOGGER.fine(() -> "onClose: " + closeReason);
transport.terminate(new ChannelClosedException(ch.get(), null));
}
@Override
public void onError(Session session, Throwable x) {
// TODO or would events.error(x) be better?
LOGGER.log(Level.FINE, null, x);
transport.terminate(new ChannelClosedException(ch.get(), x));
}
class Transport extends AbstractByteBufferCommandTransport {
final Session session;
Transport(Session session) {
this.session = session;
}
@Override
protected void write(ByteBuffer header, ByteBuffer data) throws IOException {
LOGGER.finest(() -> "sending message of length + " + ChunkHeader.length(ChunkHeader.peek(header)));
session.getBasicRemote().sendBinary(header, false);
session.getBasicRemote().sendBinary(data, true);
}
@Override
public Capability getRemoteCapability() {
return headerHandler.remoteCapability;
}
@Override
public void closeWrite() throws IOException {
events.status("Write side closed");
session.close();
}
@Override
public void closeRead() throws IOException {
events.status("Read side closed");
session.close();
}
}
}
hudsonUrl = candidateUrls.get(0);
String wsUrl = hudsonUrl.toString().replaceFirst("^http", "ws");
ContainerProvider.getWebSocketContainer().connectToServer(new AgentEndpoint(),
ClientEndpointConfig.Builder.create().configurator(headerHandler).build(), URI.create(wsUrl + "wsagents/"));
while (ch.get() == null) {
Thread.sleep(100);
}
this.protocolName = "WebSocket";
events.status("Connected");
ch.get().join();
events.status("Terminated");
if (noReconnect) {
return;
}
events.onDisconnect();
while (true) {
// Unlike JnlpAgentEndpointResolver, we do not use $jenkins/tcpSlaveAgentListener/, as that will be a 404 if the TCP port is disabled.
URL ping = new URL(hudsonUrl, "login");
try {
HttpURLConnection conn = (HttpURLConnection) ping.openConnection();
int status = conn.getResponseCode();
conn.disconnect();
if (status == 200) {
break;
} else {
events.status(ping + " is not ready: " + status);
}
} catch (IOException x) {
events.status(ping + " is not ready", x);
}
TimeUnit.SECONDS.sleep(10);
}
events.onReconnect();
}
} catch (Exception e) {
events.error(e);
}
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
private void innerRun(IOHub hub, SSLContext context, ExecutorService service) {
// Create the protocols that will be attempted to connect to the controller.
List<JnlpProtocolHandler<? extends JnlpConnectionState>> protocols = new JnlpProtocolHandlerFactory(service)
.withIOHub(hub)
.withSSLContext(context)
.withPreferNonBlockingIO(false) // we only have one connection, prefer blocking I/O
.handlers();
final Map<String,String> headers = new HashMap<>();
headers.put(JnlpConnectionState.CLIENT_NAME_KEY, agentName);
headers.put(JnlpConnectionState.SECRET_KEY, secretKey);
List<String> jenkinsUrls = new ArrayList<>();
for (URL url: candidateUrls) {
jenkinsUrls.add(url.toExternalForm());
}
JnlpEndpointResolver resolver = createEndpointResolver(jenkinsUrls);
try {
boolean first = true;
while(true) {
if(first) {
first = false;
} else {
if(noReconnect)
return; // exit
}
events.status("Locating server among " + candidateUrls);
final JnlpAgentEndpoint endpoint;
try {
endpoint = resolver.resolve();
} catch (Exception e) {
if (Boolean.getBoolean(Engine.class.getName() + ".nonFatalJnlpAgentEndpointResolutionExceptions")) {
events.status("Could not resolve JNLP agent endpoint", e);
} else {
events.error(e);
}
return;
}
if (endpoint == null) {
events.status("Could not resolve server among " + candidateUrls);
return;
}
hudsonUrl = endpoint.getServiceUrl();
events.status(String.format("Agent discovery successful%n"
+ " Agent address: %s%n"
+ " Agent port: %d%n"
+ " Identity: %s",
endpoint.getHost(),
endpoint.getPort(),
KeyUtils.fingerprint(endpoint.getPublicKey()))
);
PublicKeyMatchingX509ExtendedTrustManager delegate = new PublicKeyMatchingX509ExtendedTrustManager();
RSAPublicKey publicKey = endpoint.getPublicKey();
if (publicKey != null) {
// This is so that JNLP4-connect will only connect if the public key matches
// if the public key is not published then JNLP4-connect will refuse to connect
delegate.add(publicKey);
}
agentTrustManager.setDelegate(delegate);
events.status("Handshaking");
Socket jnlpSocket = connectTcp(endpoint);
Channel channel = null;
try {
// Try available protocols.
boolean triedAtLeastOneProtocol = false;
for (JnlpProtocolHandler<? extends JnlpConnectionState> protocol : protocols) {
if (!protocol.isEnabled()) {
events.status("Protocol " + protocol.getName() + " is not enabled, skipping");
continue;
}
if (jnlpSocket == null) {
jnlpSocket = connectTcp(endpoint);
}
if (!endpoint.isProtocolSupported(protocol.getName())) {
events.status("Server reports protocol " + protocol.getName() + " not supported, skipping");
continue;
}
triedAtLeastOneProtocol = true;
events.status("Trying protocol: " + protocol.getName());
try {
channel = protocol.connect(jnlpSocket, headers, new EngineJnlpConnectionStateListener(endpoint.getPublicKey(), headers)).get();
} catch (IOException ioe) {
events.status("Protocol " + protocol.getName() + " failed to establish channel", ioe);
} catch (RuntimeException e) {
events.status("Protocol " + protocol.getName() + " encountered a runtime error", e);
} catch (Error e) {
events.status("Protocol " + protocol.getName() + " could not be completed due to an error",
e);
} catch (Throwable e) {
events.status("Protocol " + protocol.getName() + " encountered an unexpected exception", e);
}
// On success do not try other protocols.
if (channel != null) {
this.protocolName = protocol.getName();
break;
}
// On failure form a new connection.
jnlpSocket.close();
jnlpSocket = null;
}
// If no protocol worked.
if (channel == null) {
if (triedAtLeastOneProtocol) {
onConnectionRejected("None of the protocols were accepted");
} else {
onConnectionRejected("None of the protocols are enabled");
return; // exit
}
continue;
}
events.status("Connected");
channel.join();
events.status("Terminated");
} finally {
if (jnlpSocket != null) {
try {
jnlpSocket.close();
} catch (IOException e) {
events.status("Failed to close socket", e);
}
}
}
if(noReconnect)
return; // exit
events.onDisconnect();
// try to connect back to the server every 10 secs.
resolver.waitForReady();
try {
events.status("Performing onReconnect operation.");
events.onReconnect();
events.status("onReconnect operation completed.");
} catch (NoClassDefFoundError e) {
events.status("onReconnect operation failed.");
LOGGER.log(Level.FINE, "Reconnection error.", e);
}
}
} catch (Throwable e) {
events.error(e);
}
}
private JnlpEndpointResolver createEndpointResolver(List<String> jenkinsUrls) {
JnlpEndpointResolver resolver;
if (directConnection == null) {
SSLSocketFactory sslSocketFactory = null;
try {
sslSocketFactory = getSSLSocketFactory();
} catch (Exception e) {
events.error(e);
}
resolver = new JnlpAgentEndpointResolver(jenkinsUrls, credentials, proxyCredentials, tunnel,
sslSocketFactory, disableHttpsCertValidation);
} else {
resolver = new JnlpAgentEndpointConfigurator(directConnection, instanceIdentity, protocols);
}
return resolver;
}
private void onConnectionRejected(String greeting) throws InterruptedException {
events.status("reconnect rejected, sleeping 10s: ", new Exception("The server rejected the connection: " + greeting));
TimeUnit.SECONDS.sleep(10);
}
/**
* Connects to TCP agent host:port, with a few retries.
* @param endpoint Connection endpoint
* @throws IOException Connection failure or invalid parameter specification
*/
private Socket connectTcp(@NonNull JnlpAgentEndpoint endpoint) throws IOException, InterruptedException {
String msg = "Connecting to " + endpoint.getHost() + ':' + endpoint.getPort();
events.status(msg);
int retry = 1;
while(true) {
try {
final Socket s = endpoint.open(SOCKET_TIMEOUT); // default is 30 mins. See PingThread for the ping interval
s.setKeepAlive(keepAlive);
return s;
} catch (IOException e) {
if(retry++>10) {
throw e;
}
TimeUnit.SECONDS.sleep(10);
events.status(msg+" (retrying:"+retry+")",e);
}
}
}
/**
* When invoked from within remoted {@link Callable} (that is,
* from the thread that carries out the remote requests),
* this method returns the {@link Engine} in which the remote operations
* run.
*/
public static Engine current() {
return CURRENT.get();
}
private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<>();
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName());
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "File path is loaded from system properties.")
static KeyStore getCacertsKeyStore()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException {
Map<String, String> properties = AccessController.doPrivileged(
(PrivilegedExceptionAction<Map<String, String>>) () -> {
Map<String, String> result = new HashMap<>();
result.put("trustStore", System.getProperty("javax.net.ssl.trustStore"));
result.put("javaHome", System.getProperty("java.home"));
result.put("trustStoreType",
System.getProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType()));
result.put("trustStoreProvider", System.getProperty("javax.net.ssl.trustStoreProvider", ""));
result.put("trustStorePasswd", System.getProperty("javax.net.ssl.trustStorePassword", ""));
return result;
});
KeyStore keystore = null;
FileInputStream trustStoreStream = null;
try {
String trustStore = properties.get("trustStore");
if (!"NONE".equals(trustStore)) {
File trustStoreFile;
if (trustStore != null) {
trustStoreFile = new File(trustStore);
trustStoreStream = getFileInputStream(trustStoreFile);
} else {
String javaHome = properties.get("javaHome");
trustStoreFile = new File(
javaHome + File.separator + "lib" + File.separator + "security" + File.separator
+ "jssecacerts");
if ((trustStoreStream = getFileInputStream(trustStoreFile)) == null) {
trustStoreFile = new File(
javaHome + File.separator + "lib" + File.separator + "security" + File.separator
+ "cacerts");
trustStoreStream = getFileInputStream(trustStoreFile);
}
}
if (trustStoreStream != null) {
trustStore = trustStoreFile.getPath();
} else {
trustStore = "No File Available, using empty keystore.";
}
}
String trustStoreType = properties.get("trustStoreType");
String trustStoreProvider = properties.get("trustStoreProvider");
LOGGER.log(Level.FINE, "trustStore is: {0}", trustStore);
LOGGER.log(Level.FINE, "trustStore type is: {0}", trustStoreType);
LOGGER.log(Level.FINE, "trustStore provider is: {0}", trustStoreProvider);
if (trustStoreType.length() != 0) {
LOGGER.log(Level.FINE, "init truststore");
if (trustStoreProvider.length() == 0) {
keystore = KeyStore.getInstance(trustStoreType);
} else {
keystore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
}
char[] trustStorePasswdChars = null;
String trustStorePasswd = properties.get("trustStorePasswd");
if (trustStorePasswd.length() != 0) {
trustStorePasswdChars = trustStorePasswd.toCharArray();
}
keystore.load(trustStoreStream, trustStorePasswdChars);
if (trustStorePasswdChars != null) {
Arrays.fill(trustStorePasswdChars, (char) 0);
}
}
} finally {
if (trustStoreStream != null) {
trustStoreStream.close();
}
}
return keystore;
}
@CheckForNull
private static FileInputStream getFileInputStream(final File file) throws PrivilegedActionException {
return AccessController.doPrivileged((PrivilegedExceptionAction<FileInputStream>) () -> {
try {
return file.exists() ? new FileInputStream(file) : null;
} catch (FileNotFoundException e) {
return null;
}
});
}
private SSLSocketFactory getSSLSocketFactory()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException, KeyManagementException {
SSLSocketFactory sslSocketFactory = null;
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
KeyStore keyStore = getCacertsKeyStore();
// load the keystore
keyStore.load(null, null);
int i = 0;
for (X509Certificate c : candidateCertificates) {
keyStore.setCertificateEntry(String.format("alias-%d", i++), c);
}
// prepare the trust manager
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// prepare the SSL context
SSLContext ctx = SSLContext.getInstance("TLS");
// now we have our custom socket factory
ctx.init(null, trustManagerFactory.getTrustManagers(), null);
sslSocketFactory = ctx.getSocketFactory();
}
return sslSocketFactory;
}
/**
* Socket read timeout.
* A {@link SocketInputStream#read()} call associated with underlying Socket will block for only this amount of time
* @since 2.4
*/
static final int SOCKET_TIMEOUT = Integer.getInteger(Engine.class.getName()+".socketTimeout",30*60*1000);
/**
* Get the agent name associated with this Engine instance.
*
* @return the agent name.
* @since TODO
*/
public String getAgentName() {
// This is used by various external components that need to get the name from the engine.
return agentName;
}
/**
* Get the name of the communication protocol used in this Engine instance.
* When the channel is not established by Engine (that is, {@link Engine#current()}) returns null),
* use {@link Launcher#getCommunicationProtocolName()} instead.
*
* @return the communication protocol name.
* @since 4.8
*/
public String getProtocolName() {
return this.protocolName;
}
private class EngineJnlpConnectionStateListener extends JnlpConnectionStateListener {
private final RSAPublicKey publicKey;
private final Map<String, String> headers;
public EngineJnlpConnectionStateListener(RSAPublicKey publicKey, Map<String, String> headers) {
this.publicKey = publicKey;
this.headers = headers;
}
@Override
public void beforeProperties(@NonNull JnlpConnectionState event) {
if (event instanceof Jnlp4ConnectionState) {
X509Certificate certificate = ((Jnlp4ConnectionState) event).getCertificate();
if (certificate != null) {
String fingerprint = KeyUtils
.fingerprint(certificate.getPublicKey());
if (!KeyUtils.equals(publicKey, certificate.getPublicKey())) {
event.reject(new ConnectionRefusalException(
"Expecting identity " + fingerprint));
}
events.status("Remote identity confirmed: " + fingerprint);
}
}
}
@Override
public void afterProperties(@NonNull JnlpConnectionState event) {
event.approve();
}
@Override
public void beforeChannel(@NonNull JnlpConnectionState event) {
ChannelBuilder bldr = event.getChannelBuilder().withMode(Mode.BINARY);
if (jarCache != null) {
bldr.withJarCache(jarCache);
}
}
@Override
public void afterChannel(@NonNull JnlpConnectionState event) {
// store the new cookie for next connection attempt
String cookie = event.getProperty(JnlpConnectionState.COOKIE_KEY);
if (cookie == null) {
headers.remove(JnlpConnectionState.COOKIE_KEY);
} else {
headers.put(JnlpConnectionState.COOKIE_KEY, cookie);
}
}
}
}
| src/main/java/hudson/remoting/Engine.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.remoting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.remoting.Channel.Mode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.concurrent.NotThreadSafe;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.HandshakeResponse;
import javax.websocket.Session;
import org.jenkinsci.remoting.engine.JnlpEndpointResolver;
import org.jenkinsci.remoting.engine.Jnlp4ConnectionState;
import org.jenkinsci.remoting.engine.JnlpAgentEndpoint;
import org.jenkinsci.remoting.engine.JnlpAgentEndpointConfigurator;
import org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver;
import org.jenkinsci.remoting.engine.JnlpConnectionState;
import org.jenkinsci.remoting.engine.JnlpConnectionStateListener;
import org.jenkinsci.remoting.engine.JnlpProtocolHandler;
import org.jenkinsci.remoting.engine.JnlpProtocolHandlerFactory;
import org.jenkinsci.remoting.engine.WorkDirManager;
import org.jenkinsci.remoting.protocol.IOHub;
import org.jenkinsci.remoting.protocol.cert.BlindTrustX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.cert.DelegatingX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.cert.PublicKeyMatchingX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException;
import org.jenkinsci.remoting.util.KeyUtils;
import org.jenkinsci.remoting.util.VersionNumber;
/**
* Agent engine that proactively connects to Jenkins controller.
*
* @author Kohsuke Kawaguchi
*/
@NotThreadSafe // the fields in this class should not be modified by multiple threads concurrently
public class Engine extends Thread {
/**
* HTTP header sent by Jenkins to indicate the earliest version of Remoting it is prepared to accept connections from.
*/
public static final String REMOTING_MINIMUM_VERSION_HEADER = "X-Remoting-Minimum-Version";
/**
* Thread pool that sets {@link #CURRENT}.
*/
private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(@NonNull final Runnable r) {
Thread thread = defaultFactory.newThread(() -> {
CURRENT.set(Engine.this);
r.run();
});
thread.setDaemon(true);
thread.setUncaughtExceptionHandler((t, e) -> LOGGER.log(Level.SEVERE, e, () -> "Uncaught exception in thread " + t));
return thread;
}
});
/**
* @deprecated
* Use {@link #events}.
*/
@Deprecated
public final EngineListener listener;
private final EngineListenerSplitter events = new EngineListenerSplitter();
/**
* To make Jenkins more graceful against user error,
* JNLP agent can try to connect to multiple possible Jenkins URLs.
* This field specifies those candidate URLs, such as
* "http://foo.bar/jenkins/".
*/
private final List<URL> candidateUrls;
/**
* The list of {@link X509Certificate} instances to trust when connecting to any of the {@link #candidateUrls}
* or {@code null} to use the JVM default trust store.
*/
private List<X509Certificate> candidateCertificates;
/**
* URL that points to Jenkins's tcp agent listener, like <tt>http://myhost/hudson/</tt>
*
* <p>
* This value is determined from {@link #candidateUrls} after a successful connection.
* Note that this URL <b>DOES NOT</b> have "tcpSlaveAgentListener" in it.
*/
@CheckForNull
private URL hudsonUrl;
private final String secretKey;
private final String agentName;
private boolean webSocket;
private Map<String, String> webSocketHeaders;
private String credentials;
private String protocolName;
private String proxyCredentials = System.getProperty("proxyCredentials");
/**
* See {@link hudson.remoting.jnlp.Main#tunnel} for the documentation.
*/
@CheckForNull
private String tunnel;
private boolean disableHttpsCertValidation = false;
private boolean noReconnect = false;
/**
* Determines whether the socket will have {@link Socket#setKeepAlive(boolean)} set or not.
*
* @since 2.62.1
*/
private boolean keepAlive = true;
@CheckForNull
private JarCache jarCache = null;
/**
* Specifies a destination for the agent log.
* If specified, this option overrides the default destination within {@link #workDir}.
* If both this options and {@link #workDir} is not set, the log will not be generated.
* @since 3.8
*/
@CheckForNull
private Path agentLog;
/**
* Specified location of the property file with JUL settings.
* @since 3.8
*/
@CheckForNull
private Path loggingConfigFilePath = null;
/**
* Specifies a default working directory of the remoting instance.
* If specified, this directory will be used to store logs, JAR cache, etc.
* <p>
* In order to retain compatibility, the option is disabled by default.
* <p>
* Jenkins specifics: This working directory is expected to be equal to the agent root specified in Jenkins configuration.
* @since 3.8
*/
@CheckForNull
public Path workDir = null;
/**
* Specifies a directory within {@link #workDir}, which stores all the remoting-internal files.
* <p>
* This option is not expected to be used frequently, but it allows remoting users to specify a custom
* storage directory if the default {@code remoting} directory is consumed by other stuff.
* @since 3.8
*/
@NonNull
public String internalDir = WorkDirManager.DirType.INTERNAL_DIR.getDefaultLocation();
/**
* Fail the initialization if the workDir or internalDir are missing.
* This option presumes that the workspace structure gets initialized previously in order to ensure that we do not start up with a borked instance
* (e.g. if a filesystem mount gets disconnected).
* @since 3.8
*/
public boolean failIfWorkDirIsMissing = WorkDirManager.DEFAULT_FAIL_IF_WORKDIR_IS_MISSING;
private final DelegatingX509ExtendedTrustManager agentTrustManager = new DelegatingX509ExtendedTrustManager(new BlindTrustX509ExtendedTrustManager());
private final String directConnection;
private final String instanceIdentity;
private final Set<String> protocols;
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String agentName) {
this(listener, hudsonUrls, secretKey, agentName, null, null, null);
}
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String agentName, String directConnection, String instanceIdentity,
Set<String> protocols) {
this.listener = listener;
this.directConnection = directConnection;
this.events.add(listener);
this.candidateUrls = hudsonUrls.stream().map(Engine::ensureTrailingSlash).collect(Collectors.toList());
this.secretKey = secretKey;
this.agentName = agentName;
this.instanceIdentity = instanceIdentity;
this.protocols = protocols;
if(candidateUrls.isEmpty() && instanceIdentity == null) {
throw new IllegalArgumentException("No URLs given");
}
setUncaughtExceptionHandler((t, e) -> {
LOGGER.log(Level.SEVERE, e, () -> "Uncaught exception in Engine thread " + t);
interrupt();
});
}
private static URL ensureTrailingSlash(URL u) {
if (u.toString().endsWith("/")) {
return u;
} else {
try {
return new URL(u + "/");
} catch (MalformedURLException x) {
throw new IllegalArgumentException(x);
}
}
}
/**
* Starts the engine.
* The procedure initializes the working directory and all the required environment
* @throws IOException Initialization error
* @since 3.9
*/
public synchronized void startEngine() throws IOException {
startEngine(false);
}
/**
* Starts engine.
* @param dryRun If {@code true}, do not actually start the engine.
* This method can be used for testing startup logic.
*/
/*package*/ void startEngine(boolean dryRun) throws IOException {
LOGGER.log(Level.INFO, "Using Remoting version: {0}", Launcher.VERSION);
@CheckForNull File jarCacheDirectory = null;
// Prepare the working directory if required
if (workDir != null) {
final WorkDirManager workDirManager = WorkDirManager.getInstance();
if (jarCache != null) {
// Somebody has already specificed Jar Cache, hence we do not need it in the workspace.
workDirManager.disable(WorkDirManager.DirType.JAR_CACHE_DIR);
}
if (loggingConfigFilePath != null) {
workDirManager.setLoggingConfig(loggingConfigFilePath.toFile());
}
final Path path = workDirManager.initializeWorkDir(workDir.toFile(), internalDir, failIfWorkDirIsMissing);
jarCacheDirectory = workDirManager.getLocation(WorkDirManager.DirType.JAR_CACHE_DIR);
workDirManager.setupLogging(path, agentLog);
} else if (jarCache == null) {
LOGGER.log(Level.WARNING, "No Working Directory. Using the legacy JAR Cache location: {0}", JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION);
jarCacheDirectory = JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION;
}
if (jarCache == null){
if (jarCacheDirectory == null) {
// Should never happen in the current code
throw new IOException("Cannot find the JAR Cache location");
}
LOGGER.log(Level.FINE, "Using standard File System JAR Cache. Root Directory is {0}", jarCacheDirectory);
try {
jarCache = new FileSystemJarCache(jarCacheDirectory, true);
} catch (IllegalArgumentException ex) {
throw new IOException("Failed to initialize FileSystem JAR Cache in " + jarCacheDirectory, ex);
}
} else {
LOGGER.log(Level.INFO, "Using custom JAR Cache: {0}", jarCache);
}
// Start the engine thread
if (!dryRun) {
this.start();
}
}
/**
* Configures custom JAR Cache location.
* This option disables JAR Caching in the working directory.
* @param jarCache JAR Cache to be used
* @since 2.24
*/
public void setJarCache(@NonNull JarCache jarCache) {
this.jarCache = jarCache;
}
/**
* Sets path to the property file with JUL settings.
* @param filePath JAR Cache to be used
* @since 3.8
*/
public void setLoggingConfigFile(@NonNull Path filePath) {
this.loggingConfigFilePath = filePath;
}
/**
* Provides Jenkins URL if available.
* @return Jenkins URL. May return {@code null} if the connection is not established or if the URL cannot be determined
* in the {@link JnlpAgentEndpointResolver}.
*/
@CheckForNull
public URL getHudsonUrl() {
return hudsonUrl;
}
public void setWebSocket(boolean webSocket) {
this.webSocket = webSocket;
}
/**
* Sets map of custom websocket headers. These headers will be applied to the websocket connection to Jenkins.
*
* @param webSocketHeaders a map of the headers to apply to the websocket connection
*/
public void setWebSocketHeaders(@NonNull Map<String, String> webSocketHeaders) {
this.webSocketHeaders = webSocketHeaders;
}
/**
* If set, connect to the specified host and port instead of connecting directly to Jenkins.
* @param tunnel Value. {@code null} to disable tunneling
*/
public void setTunnel(@CheckForNull String tunnel) {
this.tunnel = tunnel;
}
public void setCredentials(String creds) {
this.credentials = creds;
}
public void setProxyCredentials(String proxyCredentials) {
this.proxyCredentials = proxyCredentials;
}
public void setNoReconnect(boolean noReconnect) {
this.noReconnect = noReconnect;
}
/**
* Determines if JNLPAgentEndpointResolver will not perform certificate validation in the HTTPs mode.
*
* @return {@code true} if the certificate validation is disabled.
*/
public boolean isDisableHttpsCertValidation() {
return disableHttpsCertValidation;
}
/**
* Sets if JNLPAgentEndpointResolver will not perform certificate validation in the HTTPs mode.
*
* @param disableHttpsCertValidation {@code true} if the certificate validation is disabled.
*/
public void setDisableHttpsCertValidation(boolean disableHttpsCertValidation) {
this.disableHttpsCertValidation = disableHttpsCertValidation;
}
/**
* Sets the destination for agent logs.
* @param agentLog Path to the agent log.
* If {@code null}, the engine will pick the default behavior depending on the {@link #workDir} value
* @since 3.8
*/
public void setAgentLog(@CheckForNull Path agentLog) {
this.agentLog = agentLog;
}
/**
* Specified a path to the work directory.
* @param workDir Path to the working directory of the remoting instance.
* {@code null} Disables the working directory.
* @since 3.8
*/
public void setWorkDir(@CheckForNull Path workDir) {
this.workDir = workDir;
}
/**
* Specifies name of the internal data directory within {@link #workDir}.
* @param internalDir Directory name
* @since 3.8
*/
public void setInternalDir(@NonNull String internalDir) {
this.internalDir = internalDir;
}
/**
* Sets up behavior if the workDir or internalDir are missing during the startup.
* This option presumes that the workspace structure gets initialized previously in order to ensure that we do not start up with a borked instance
* (e.g. if a filesystem mount gets disconnected).
* @param failIfWorkDirIsMissing Flag
* @since 3.8
*/
public void setFailIfWorkDirIsMissing(boolean failIfWorkDirIsMissing) { this.failIfWorkDirIsMissing = failIfWorkDirIsMissing; }
/**
* Returns {@code true} if and only if the socket to the controller will have {@link Socket#setKeepAlive(boolean)} set.
*
* @return {@code true} if and only if the socket to the controller will have {@link Socket#setKeepAlive(boolean)} set.
*/
public boolean isKeepAlive() {
return keepAlive;
}
/**
* Sets the {@link Socket#setKeepAlive(boolean)} to use for the connection to the controller.
*
* @param keepAlive the {@link Socket#setKeepAlive(boolean)} to use for the connection to the controller.
*/
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public void setCandidateCertificates(List<X509Certificate> candidateCertificates) {
this.candidateCertificates = candidateCertificates == null
? null
: new ArrayList<>(candidateCertificates);
}
public void addCandidateCertificate(X509Certificate certificate) {
if (candidateCertificates == null) {
candidateCertificates = new ArrayList<>();
}
candidateCertificates.add(certificate);
}
public void addListener(EngineListener el) {
events.add(el);
}
public void removeListener(EngineListener el) {
events.remove(el);
}
@Override
@SuppressFBWarnings(value = "HARD_CODE_PASSWORD", justification = "Password doesn't need to be protected.")
public void run() {
if (webSocket) {
runWebSocket();
return;
}
// Create the engine
try {
try (IOHub hub = IOHub.create(executor)) {
SSLContext context;
// prepare our SSLContext
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for TLS algorithm", e);
}
char[] password = "password".toCharArray();
KeyStore store;
try {
store = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
throw new IllegalStateException("Java runtime specification requires support for JKS key store", e);
}
try {
store.load(null, password);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for JKS key store", e);
} catch (CertificateException e) {
throw new IllegalStateException("Empty keystore", e);
}
KeyManagerFactory kmf;
try {
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for default key manager", e);
}
try {
kmf.init(store, password);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new IllegalStateException(e);
}
try {
context.init(kmf.getKeyManagers(), new TrustManager[]{agentTrustManager}, null);
} catch (KeyManagementException e) {
events.error(e);
return;
}
innerRun(hub, context, executor);
}
} catch (IOException e) {
events.error(e);
}
}
@SuppressFBWarnings(value = {"REC_CATCH_EXCEPTION", "URLCONNECTION_SSRF_FD"}, justification = "checked exceptions were a mistake to begin with; connecting to Jenkins from agent")
private void runWebSocket() {
try {
while (true) {
AtomicReference<Channel> ch = new AtomicReference<>();
String localCap = new Capability().toASCII();
class HeaderHandler extends ClientEndpointConfig.Configurator {
Capability remoteCapability = new Capability();
@Override
public void beforeRequest(Map<String, List<String>> headers) {
headers.put(JnlpConnectionState.CLIENT_NAME_KEY, Collections.singletonList(agentName));
headers.put(JnlpConnectionState.SECRET_KEY, Collections.singletonList(secretKey));
headers.put(Capability.KEY, Collections.singletonList(localCap));
// TODO use JnlpConnectionState.COOKIE_KEY somehow (see EngineJnlpConnectionStateListener.afterChannel)
if (webSocketHeaders != null) {
for (Map.Entry<String, String> entry : webSocketHeaders.entrySet()) {
headers.put(entry.getKey(), Collections.singletonList(entry.getValue()));
}
}
LOGGER.fine(() -> "Sending: " + headers);
}
@Override
public void afterResponse(HandshakeResponse hr) {
LOGGER.fine(() -> "Receiving: " + hr.getHeaders());
List<String> remotingMinimumVersion = hr.getHeaders().get(REMOTING_MINIMUM_VERSION_HEADER);
if (remotingMinimumVersion != null && !remotingMinimumVersion.isEmpty()) {
VersionNumber minimumSupportedVersion = new VersionNumber(remotingMinimumVersion.get(0));
VersionNumber currentVersion = new VersionNumber(Launcher.VERSION);
if (currentVersion.isOlderThan(minimumSupportedVersion)) {
events.error(new IOException("Agent version " + minimumSupportedVersion + " or newer is required."));
}
}
try {
remoteCapability = Capability.fromASCII(hr.getHeaders().get(Capability.KEY).get(0));
LOGGER.fine(() -> "received " + remoteCapability);
} catch (IOException x) {
events.error(x);
}
}
}
HeaderHandler headerHandler = new HeaderHandler();
class AgentEndpoint extends Endpoint {
@SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "just trust me here")
AgentEndpoint.Transport transport;
@Override
public void onOpen(Session session, EndpointConfig config) {
events.status("WebSocket connection open");
session.addMessageHandler(ByteBuffer.class, this::onMessage);
try {
transport = new Transport(session);
ch.set(new ChannelBuilder(agentName, executor).
withJarCacheOrDefault(jarCache). // unless EngineJnlpConnectionStateListener can be used for this purpose
build(transport));
} catch (IOException x) {
events.error(x);
}
}
private void onMessage(ByteBuffer message) {
try {
transport.receive(message);
} catch (IOException x) {
events.error(x);
} catch (InterruptedException x) {
events.error(x);
Thread.currentThread().interrupt();
}
}
@Override
public void onClose(Session session, CloseReason closeReason) {
LOGGER.fine(() -> "onClose: " + closeReason);
transport.terminate(new ChannelClosedException(ch.get(), null));
}
@Override
public void onError(Session session, Throwable x) {
// TODO or would events.error(x) be better?
LOGGER.log(Level.FINE, null, x);
transport.terminate(new ChannelClosedException(ch.get(), x));
}
class Transport extends AbstractByteBufferCommandTransport {
final Session session;
Transport(Session session) {
this.session = session;
}
@Override
protected void write(ByteBuffer header, ByteBuffer data) throws IOException {
LOGGER.finest(() -> "sending message of length + " + ChunkHeader.length(ChunkHeader.peek(header)));
session.getBasicRemote().sendBinary(header, false);
session.getBasicRemote().sendBinary(data, true);
}
@Override
public Capability getRemoteCapability() {
return headerHandler.remoteCapability;
}
@Override
public void closeWrite() throws IOException {
events.status("Write side closed");
session.close();
}
@Override
public void closeRead() throws IOException {
events.status("Read side closed");
session.close();
}
}
}
hudsonUrl = candidateUrls.get(0);
String wsUrl = hudsonUrl.toString().replaceFirst("^http", "ws");
ContainerProvider.getWebSocketContainer().connectToServer(new AgentEndpoint(),
ClientEndpointConfig.Builder.create().configurator(headerHandler).build(), URI.create(wsUrl + "wsagents/"));
while (ch.get() == null) {
Thread.sleep(100);
}
this.protocolName = "WebSocket";
events.status("Connected");
ch.get().join();
events.status("Terminated");
if (noReconnect) {
return;
}
events.onDisconnect();
while (true) {
// Unlike JnlpAgentEndpointResolver, we do not use $jenkins/tcpSlaveAgentListener/, as that will be a 404 if the TCP port is disabled.
URL ping = new URL(hudsonUrl, "login");
try {
HttpURLConnection conn = (HttpURLConnection) ping.openConnection();
int status = conn.getResponseCode();
conn.disconnect();
if (status == 200) {
break;
} else {
events.status(ping + " is not ready: " + status);
}
} catch (IOException x) {
events.status(ping + " is not ready", x);
}
TimeUnit.SECONDS.sleep(10);
}
events.onReconnect();
}
} catch (Exception e) {
events.error(e);
}
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
private void innerRun(IOHub hub, SSLContext context, ExecutorService service) {
// Create the protocols that will be attempted to connect to the controller.
List<JnlpProtocolHandler<? extends JnlpConnectionState>> protocols = new JnlpProtocolHandlerFactory(service)
.withIOHub(hub)
.withSSLContext(context)
.withPreferNonBlockingIO(false) // we only have one connection, prefer blocking I/O
.handlers();
final Map<String,String> headers = new HashMap<>();
headers.put(JnlpConnectionState.CLIENT_NAME_KEY, agentName);
headers.put(JnlpConnectionState.SECRET_KEY, secretKey);
List<String> jenkinsUrls = new ArrayList<>();
for (URL url: candidateUrls) {
jenkinsUrls.add(url.toExternalForm());
}
JnlpEndpointResolver resolver = createEndpointResolver(jenkinsUrls);
try {
boolean first = true;
while(true) {
if(first) {
first = false;
} else {
if(noReconnect)
return; // exit
}
events.status("Locating server among " + candidateUrls);
final JnlpAgentEndpoint endpoint;
try {
endpoint = resolver.resolve();
} catch (Exception e) {
if (Boolean.getBoolean(Engine.class.getName() + ".nonFatalJnlpAgentEndpointResolutionExceptions")) {
events.status("Could not resolve JNLP agent endpoint", e);
} else {
events.error(e);
}
return;
}
if (endpoint == null) {
events.status("Could not resolve server among " + candidateUrls);
return;
}
hudsonUrl = endpoint.getServiceUrl();
events.status(String.format("Agent discovery successful%n"
+ " Agent address: %s%n"
+ " Agent port: %d%n"
+ " Identity: %s",
endpoint.getHost(),
endpoint.getPort(),
KeyUtils.fingerprint(endpoint.getPublicKey()))
);
PublicKeyMatchingX509ExtendedTrustManager delegate = new PublicKeyMatchingX509ExtendedTrustManager();
RSAPublicKey publicKey = endpoint.getPublicKey();
if (publicKey != null) {
// This is so that JNLP4-connect will only connect if the public key matches
// if the public key is not published then JNLP4-connect will refuse to connect
delegate.add(publicKey);
}
agentTrustManager.setDelegate(delegate);
events.status("Handshaking");
Socket jnlpSocket = connectTcp(endpoint);
Channel channel = null;
try {
// Try available protocols.
boolean triedAtLeastOneProtocol = false;
for (JnlpProtocolHandler<? extends JnlpConnectionState> protocol : protocols) {
if (!protocol.isEnabled()) {
events.status("Protocol " + protocol.getName() + " is not enabled, skipping");
continue;
}
if (jnlpSocket == null) {
jnlpSocket = connectTcp(endpoint);
}
if (!endpoint.isProtocolSupported(protocol.getName())) {
events.status("Server reports protocol " + protocol.getName() + " not supported, skipping");
continue;
}
triedAtLeastOneProtocol = true;
events.status("Trying protocol: " + protocol.getName());
try {
channel = protocol.connect(jnlpSocket, headers, new EngineJnlpConnectionStateListener(endpoint.getPublicKey(), headers)).get();
} catch (IOException ioe) {
events.status("Protocol " + protocol.getName() + " failed to establish channel", ioe);
} catch (RuntimeException e) {
events.status("Protocol " + protocol.getName() + " encountered a runtime error", e);
} catch (Error e) {
events.status("Protocol " + protocol.getName() + " could not be completed due to an error",
e);
} catch (Throwable e) {
events.status("Protocol " + protocol.getName() + " encountered an unexpected exception", e);
}
// On success do not try other protocols.
if (channel != null) {
this.protocolName = protocol.getName();
break;
}
// On failure form a new connection.
jnlpSocket.close();
jnlpSocket = null;
}
// If no protocol worked.
if (channel == null) {
if (triedAtLeastOneProtocol) {
onConnectionRejected("None of the protocols were accepted");
} else {
onConnectionRejected("None of the protocols are enabled");
return; // exit
}
continue;
}
events.status("Connected");
channel.join();
events.status("Terminated");
} finally {
if (jnlpSocket != null) {
try {
jnlpSocket.close();
} catch (IOException e) {
events.status("Failed to close socket", e);
}
}
}
if(noReconnect)
return; // exit
events.onDisconnect();
// try to connect back to the server every 10 secs.
resolver.waitForReady();
try {
events.status("Performing onReconnect operation.");
events.onReconnect();
events.status("onReconnect operation completed.");
} catch (NoClassDefFoundError e) {
events.status("onReconnect operation failed.");
LOGGER.log(Level.FINE, "Reconnection error.", e);
}
}
} catch (Throwable e) {
events.error(e);
}
}
private JnlpEndpointResolver createEndpointResolver(List<String> jenkinsUrls) {
JnlpEndpointResolver resolver;
if (directConnection == null) {
SSLSocketFactory sslSocketFactory = null;
try {
sslSocketFactory = getSSLSocketFactory();
} catch (Exception e) {
events.error(e);
}
resolver = new JnlpAgentEndpointResolver(jenkinsUrls, credentials, proxyCredentials, tunnel,
sslSocketFactory, disableHttpsCertValidation);
} else {
resolver = new JnlpAgentEndpointConfigurator(directConnection, instanceIdentity, protocols);
}
return resolver;
}
private void onConnectionRejected(String greeting) throws InterruptedException {
events.error(new Exception("The server rejected the connection: " + greeting));
TimeUnit.SECONDS.sleep(10);
}
/**
* Connects to TCP agent host:port, with a few retries.
* @param endpoint Connection endpoint
* @throws IOException Connection failure or invalid parameter specification
*/
private Socket connectTcp(@NonNull JnlpAgentEndpoint endpoint) throws IOException, InterruptedException {
String msg = "Connecting to " + endpoint.getHost() + ':' + endpoint.getPort();
events.status(msg);
int retry = 1;
while(true) {
try {
final Socket s = endpoint.open(SOCKET_TIMEOUT); // default is 30 mins. See PingThread for the ping interval
s.setKeepAlive(keepAlive);
return s;
} catch (IOException e) {
if(retry++>10) {
throw e;
}
TimeUnit.SECONDS.sleep(10);
events.status(msg+" (retrying:"+retry+")",e);
}
}
}
/**
* When invoked from within remoted {@link Callable} (that is,
* from the thread that carries out the remote requests),
* this method returns the {@link Engine} in which the remote operations
* run.
*/
public static Engine current() {
return CURRENT.get();
}
private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<>();
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName());
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "File path is loaded from system properties.")
static KeyStore getCacertsKeyStore()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException {
Map<String, String> properties = AccessController.doPrivileged(
(PrivilegedExceptionAction<Map<String, String>>) () -> {
Map<String, String> result = new HashMap<>();
result.put("trustStore", System.getProperty("javax.net.ssl.trustStore"));
result.put("javaHome", System.getProperty("java.home"));
result.put("trustStoreType",
System.getProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType()));
result.put("trustStoreProvider", System.getProperty("javax.net.ssl.trustStoreProvider", ""));
result.put("trustStorePasswd", System.getProperty("javax.net.ssl.trustStorePassword", ""));
return result;
});
KeyStore keystore = null;
FileInputStream trustStoreStream = null;
try {
String trustStore = properties.get("trustStore");
if (!"NONE".equals(trustStore)) {
File trustStoreFile;
if (trustStore != null) {
trustStoreFile = new File(trustStore);
trustStoreStream = getFileInputStream(trustStoreFile);
} else {
String javaHome = properties.get("javaHome");
trustStoreFile = new File(
javaHome + File.separator + "lib" + File.separator + "security" + File.separator
+ "jssecacerts");
if ((trustStoreStream = getFileInputStream(trustStoreFile)) == null) {
trustStoreFile = new File(
javaHome + File.separator + "lib" + File.separator + "security" + File.separator
+ "cacerts");
trustStoreStream = getFileInputStream(trustStoreFile);
}
}
if (trustStoreStream != null) {
trustStore = trustStoreFile.getPath();
} else {
trustStore = "No File Available, using empty keystore.";
}
}
String trustStoreType = properties.get("trustStoreType");
String trustStoreProvider = properties.get("trustStoreProvider");
LOGGER.log(Level.FINE, "trustStore is: {0}", trustStore);
LOGGER.log(Level.FINE, "trustStore type is: {0}", trustStoreType);
LOGGER.log(Level.FINE, "trustStore provider is: {0}", trustStoreProvider);
if (trustStoreType.length() != 0) {
LOGGER.log(Level.FINE, "init truststore");
if (trustStoreProvider.length() == 0) {
keystore = KeyStore.getInstance(trustStoreType);
} else {
keystore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
}
char[] trustStorePasswdChars = null;
String trustStorePasswd = properties.get("trustStorePasswd");
if (trustStorePasswd.length() != 0) {
trustStorePasswdChars = trustStorePasswd.toCharArray();
}
keystore.load(trustStoreStream, trustStorePasswdChars);
if (trustStorePasswdChars != null) {
Arrays.fill(trustStorePasswdChars, (char) 0);
}
}
} finally {
if (trustStoreStream != null) {
trustStoreStream.close();
}
}
return keystore;
}
@CheckForNull
private static FileInputStream getFileInputStream(final File file) throws PrivilegedActionException {
return AccessController.doPrivileged((PrivilegedExceptionAction<FileInputStream>) () -> {
try {
return file.exists() ? new FileInputStream(file) : null;
} catch (FileNotFoundException e) {
return null;
}
});
}
private SSLSocketFactory getSSLSocketFactory()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException, KeyManagementException {
SSLSocketFactory sslSocketFactory = null;
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
KeyStore keyStore = getCacertsKeyStore();
// load the keystore
keyStore.load(null, null);
int i = 0;
for (X509Certificate c : candidateCertificates) {
keyStore.setCertificateEntry(String.format("alias-%d", i++), c);
}
// prepare the trust manager
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// prepare the SSL context
SSLContext ctx = SSLContext.getInstance("TLS");
// now we have our custom socket factory
ctx.init(null, trustManagerFactory.getTrustManagers(), null);
sslSocketFactory = ctx.getSocketFactory();
}
return sslSocketFactory;
}
/**
* Socket read timeout.
* A {@link SocketInputStream#read()} call associated with underlying Socket will block for only this amount of time
* @since 2.4
*/
static final int SOCKET_TIMEOUT = Integer.getInteger(Engine.class.getName()+".socketTimeout",30*60*1000);
/**
* Get the agent name associated with this Engine instance.
*
* @return the agent name.
* @since TODO
*/
public String getAgentName() {
// This is used by various external components that need to get the name from the engine.
return agentName;
}
/**
* Get the name of the communication protocol used in this Engine instance.
* When the channel is not established by Engine (that is, {@link Engine#current()}) returns null),
* use {@link Launcher#getCommunicationProtocolName()} instead.
*
* @return the communication protocol name.
* @since 4.8
*/
public String getProtocolName() {
return this.protocolName;
}
private class EngineJnlpConnectionStateListener extends JnlpConnectionStateListener {
private final RSAPublicKey publicKey;
private final Map<String, String> headers;
public EngineJnlpConnectionStateListener(RSAPublicKey publicKey, Map<String, String> headers) {
this.publicKey = publicKey;
this.headers = headers;
}
@Override
public void beforeProperties(@NonNull JnlpConnectionState event) {
if (event instanceof Jnlp4ConnectionState) {
X509Certificate certificate = ((Jnlp4ConnectionState) event).getCertificate();
if (certificate != null) {
String fingerprint = KeyUtils
.fingerprint(certificate.getPublicKey());
if (!KeyUtils.equals(publicKey, certificate.getPublicKey())) {
event.reject(new ConnectionRefusalException(
"Expecting identity " + fingerprint));
}
events.status("Remote identity confirmed: " + fingerprint);
}
}
}
@Override
public void afterProperties(@NonNull JnlpConnectionState event) {
event.approve();
}
@Override
public void beforeChannel(@NonNull JnlpConnectionState event) {
ChannelBuilder bldr = event.getChannelBuilder().withMode(Mode.BINARY);
if (jarCache != null) {
bldr.withJarCache(jarCache);
}
}
@Override
public void afterChannel(@NonNull JnlpConnectionState event) {
// store the new cookie for next connection attempt
String cookie = event.getProperty(JnlpConnectionState.COOKIE_KEY);
if (cookie == null) {
headers.remove(JnlpConnectionState.COOKIE_KEY);
} else {
headers.put(JnlpConnectionState.COOKIE_KEY, cookie);
}
}
}
}
| JENKINS-66915: Don't die when reconnect fails. (#488)
Instead do the 10s sleep as intentionally written.
Co-authored-by: Lars Berntzon <[email protected]> | src/main/java/hudson/remoting/Engine.java | JENKINS-66915: Don't die when reconnect fails. (#488) | <ide><path>rc/main/java/hudson/remoting/Engine.java
<ide> }
<ide>
<ide> private void onConnectionRejected(String greeting) throws InterruptedException {
<del> events.error(new Exception("The server rejected the connection: " + greeting));
<add> events.status("reconnect rejected, sleeping 10s: ", new Exception("The server rejected the connection: " + greeting));
<ide> TimeUnit.SECONDS.sleep(10);
<ide> }
<ide> |
|
Java | apache-2.0 | 8e7a2ba9587072c549b72189fa8aa115201a3d5a | 0 | stari4ek/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,stari4ek/ExoPlayer,superbderrick/ExoPlayer,androidx/media,saki4510t/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,superbderrick/ExoPlayer,saki4510t/ExoPlayer,superbderrick/ExoPlayer,ened/ExoPlayer,ened/ExoPlayer,androidx/media,google/ExoPlayer,androidx/media,ened/ExoPlayer,amzn/exoplayer-amazon-port,stari4ek/ExoPlayer,saki4510t/ExoPlayer | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.Nullable;
import android.util.Pair;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectorResult;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** An {@link ExoPlayer} implementation. Instances can be obtained from {@link ExoPlayerFactory}. */
/* package */ final class ExoPlayerImpl extends BasePlayer implements ExoPlayer {
private static final String TAG = "ExoPlayerImpl";
/**
* This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult}
* when the player does not have any track selection made (such as when player is reset, or when
* player seeks to an unprepared period). It will not be used as result of any {@link
* TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)}
* operation.
*/
/* package */ final TrackSelectorResult emptyTrackSelectorResult;
private final Renderer[] renderers;
private final TrackSelector trackSelector;
private final Handler eventHandler;
private final ExoPlayerImplInternal internalPlayer;
private final Handler internalPlayerHandler;
private final CopyOnWriteArrayList<ListenerHolder> listeners;
private final Timeline.Period period;
private final ArrayDeque<Runnable> pendingListenerNotifications;
private MediaSource mediaSource;
private boolean playWhenReady;
private boolean internalPlayWhenReady;
private @RepeatMode int repeatMode;
private boolean shuffleModeEnabled;
private int pendingOperationAcks;
private boolean hasPendingPrepare;
private boolean hasPendingSeek;
private boolean foregroundMode;
private PlaybackParameters playbackParameters;
private SeekParameters seekParameters;
private @Nullable ExoPlaybackException playbackError;
// Playback information when there is no pending seek/set source operation.
private PlaybackInfo playbackInfo;
// Playback information when there is a pending seek/set source operation.
private int maskingWindowIndex;
private int maskingPeriodIndex;
private long maskingWindowPositionMs;
/**
* Constructs an instance. Must be called from a thread that has an associated {@link Looper}.
*
* @param renderers The {@link Renderer}s that will be used by the instance.
* @param trackSelector The {@link TrackSelector} that will be used by the instance.
* @param loadControl The {@link LoadControl} that will be used by the instance.
* @param bandwidthMeter The {@link BandwidthMeter} that will be used by the instance.
* @param clock The {@link Clock} that will be used by the instance.
* @param looper The {@link Looper} which must be used for all calls to the player and which is
* used to call listeners on.
*/
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(
Renderer[] renderers,
TrackSelector trackSelector,
LoadControl loadControl,
BandwidthMeter bandwidthMeter,
Clock clock,
Looper looper) {
Log.i(TAG, "Init " + Integer.toHexString(System.identityHashCode(this)) + " ["
+ ExoPlayerLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "]");
Assertions.checkState(renderers.length > 0);
this.renderers = Assertions.checkNotNull(renderers);
this.trackSelector = Assertions.checkNotNull(trackSelector);
this.playWhenReady = false;
this.repeatMode = Player.REPEAT_MODE_OFF;
this.shuffleModeEnabled = false;
this.listeners = new CopyOnWriteArrayList<>();
emptyTrackSelectorResult =
new TrackSelectorResult(
new RendererConfiguration[renderers.length],
new TrackSelection[renderers.length],
null);
period = new Timeline.Period();
playbackParameters = PlaybackParameters.DEFAULT;
seekParameters = SeekParameters.DEFAULT;
eventHandler =
new Handler(looper) {
@Override
public void handleMessage(Message msg) {
ExoPlayerImpl.this.handleEvent(msg);
}
};
playbackInfo = PlaybackInfo.createDummy(/* startPositionUs= */ 0, emptyTrackSelectorResult);
pendingListenerNotifications = new ArrayDeque<>();
internalPlayer =
new ExoPlayerImplInternal(
renderers,
trackSelector,
emptyTrackSelectorResult,
loadControl,
bandwidthMeter,
playWhenReady,
repeatMode,
shuffleModeEnabled,
eventHandler,
clock);
internalPlayerHandler = new Handler(internalPlayer.getPlaybackLooper());
}
@Override
@Nullable
public AudioComponent getAudioComponent() {
return null;
}
@Override
@Nullable
public VideoComponent getVideoComponent() {
return null;
}
@Override
@Nullable
public TextComponent getTextComponent() {
return null;
}
@Override
@Nullable
public MetadataComponent getMetadataComponent() {
return null;
}
@Override
public Looper getPlaybackLooper() {
return internalPlayer.getPlaybackLooper();
}
@Override
public Looper getApplicationLooper() {
return eventHandler.getLooper();
}
@Override
public void addListener(Player.EventListener listener) {
listeners.addIfAbsent(new ListenerHolder(listener));
}
@Override
public void removeListener(Player.EventListener listener) {
for (ListenerHolder listenerHolder : listeners) {
if (listenerHolder.listener.equals(listener)) {
listenerHolder.release();
listeners.remove(listenerHolder);
}
}
}
@Override
public int getPlaybackState() {
return playbackInfo.playbackState;
}
@Override
public @Nullable ExoPlaybackException getPlaybackError() {
return playbackError;
}
@Override
public void retry() {
if (mediaSource != null
&& (playbackError != null || playbackInfo.playbackState == Player.STATE_IDLE)) {
prepare(mediaSource, /* resetPosition= */ false, /* resetState= */ false);
}
}
@Override
public void prepare(MediaSource mediaSource) {
prepare(mediaSource, /* resetPosition= */ true, /* resetState= */ true);
}
@Override
public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) {
playbackError = null;
this.mediaSource = mediaSource;
PlaybackInfo playbackInfo =
getResetPlaybackInfo(
resetPosition, resetState, /* playbackState= */ Player.STATE_BUFFERING);
// Trigger internal prepare first before updating the playback info and notifying external
// listeners to ensure that new operations issued in the listener notifications reach the
// player after this prepare. The internal player can't change the playback info immediately
// because it uses a callback.
hasPendingPrepare = true;
pendingOperationAcks++;
internalPlayer.prepare(mediaSource, resetPosition, resetState);
updatePlaybackInfo(
playbackInfo,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
TIMELINE_CHANGE_REASON_RESET,
/* seekProcessed= */ false);
}
@Override
public void setPlayWhenReady(boolean playWhenReady) {
setPlayWhenReady(playWhenReady, /* suppressPlayback= */ false);
}
public void setPlayWhenReady(boolean playWhenReady, boolean suppressPlayback) {
boolean internalPlayWhenReady = playWhenReady && !suppressPlayback;
if (this.internalPlayWhenReady != internalPlayWhenReady) {
this.internalPlayWhenReady = internalPlayWhenReady;
internalPlayer.setPlayWhenReady(internalPlayWhenReady);
}
if (this.playWhenReady != playWhenReady) {
this.playWhenReady = playWhenReady;
int playbackState = playbackInfo.playbackState;
notifyListeners(listener -> listener.onPlayerStateChanged(playWhenReady, playbackState));
}
}
@Override
public boolean getPlayWhenReady() {
return playWhenReady;
}
@Override
public void setRepeatMode(@RepeatMode int repeatMode) {
if (this.repeatMode != repeatMode) {
this.repeatMode = repeatMode;
internalPlayer.setRepeatMode(repeatMode);
notifyListeners(listener -> listener.onRepeatModeChanged(repeatMode));
}
}
@Override
public @RepeatMode int getRepeatMode() {
return repeatMode;
}
@Override
public void setShuffleModeEnabled(boolean shuffleModeEnabled) {
if (this.shuffleModeEnabled != shuffleModeEnabled) {
this.shuffleModeEnabled = shuffleModeEnabled;
internalPlayer.setShuffleModeEnabled(shuffleModeEnabled);
notifyListeners(listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled));
}
}
@Override
public boolean getShuffleModeEnabled() {
return shuffleModeEnabled;
}
@Override
public boolean isLoading() {
return playbackInfo.isLoading;
}
@Override
public void seekTo(int windowIndex, long positionMs) {
Timeline timeline = playbackInfo.timeline;
if (windowIndex < 0 || (!timeline.isEmpty() && windowIndex >= timeline.getWindowCount())) {
throw new IllegalSeekPositionException(timeline, windowIndex, positionMs);
}
hasPendingSeek = true;
pendingOperationAcks++;
if (isPlayingAd()) {
// TODO: Investigate adding support for seeking during ads. This is complicated to do in
// general because the midroll ad preceding the seek destination must be played before the
// content position can be played, if a different ad is playing at the moment.
Log.w(TAG, "seekTo ignored because an ad is playing");
eventHandler
.obtainMessage(
ExoPlayerImplInternal.MSG_PLAYBACK_INFO_CHANGED,
/* operationAcks */ 1,
/* positionDiscontinuityReason */ C.INDEX_UNSET,
playbackInfo)
.sendToTarget();
return;
}
maskingWindowIndex = windowIndex;
if (timeline.isEmpty()) {
maskingWindowPositionMs = positionMs == C.TIME_UNSET ? 0 : positionMs;
maskingPeriodIndex = 0;
} else {
long windowPositionUs = positionMs == C.TIME_UNSET
? timeline.getWindow(windowIndex, window).getDefaultPositionUs() : C.msToUs(positionMs);
Pair<Object, Long> periodUidAndPosition =
timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs);
maskingWindowPositionMs = C.usToMs(windowPositionUs);
maskingPeriodIndex = timeline.getIndexOfPeriod(periodUidAndPosition.first);
}
internalPlayer.seekTo(timeline, windowIndex, C.msToUs(positionMs));
notifyListeners(listener -> listener.onPositionDiscontinuity(DISCONTINUITY_REASON_SEEK));
}
@Override
public void setPlaybackParameters(@Nullable PlaybackParameters playbackParameters) {
if (playbackParameters == null) {
playbackParameters = PlaybackParameters.DEFAULT;
}
internalPlayer.setPlaybackParameters(playbackParameters);
}
@Override
public PlaybackParameters getPlaybackParameters() {
return playbackParameters;
}
@Override
public void setSeekParameters(@Nullable SeekParameters seekParameters) {
if (seekParameters == null) {
seekParameters = SeekParameters.DEFAULT;
}
if (!this.seekParameters.equals(seekParameters)) {
this.seekParameters = seekParameters;
internalPlayer.setSeekParameters(seekParameters);
}
}
@Override
public SeekParameters getSeekParameters() {
return seekParameters;
}
@Override
public void setForegroundMode(boolean foregroundMode) {
if (this.foregroundMode != foregroundMode) {
this.foregroundMode = foregroundMode;
internalPlayer.setForegroundMode(foregroundMode);
}
}
@Override
public void stop(boolean reset) {
if (reset) {
playbackError = null;
mediaSource = null;
}
PlaybackInfo playbackInfo =
getResetPlaybackInfo(
/* resetPosition= */ reset,
/* resetState= */ reset,
/* playbackState= */ Player.STATE_IDLE);
// Trigger internal stop first before updating the playback info and notifying external
// listeners to ensure that new operations issued in the listener notifications reach the
// player after this stop. The internal player can't change the playback info immediately
// because it uses a callback.
pendingOperationAcks++;
internalPlayer.stop(reset);
updatePlaybackInfo(
playbackInfo,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
TIMELINE_CHANGE_REASON_RESET,
/* seekProcessed= */ false);
}
@Override
public void release() {
Log.i(TAG, "Release " + Integer.toHexString(System.identityHashCode(this)) + " ["
+ ExoPlayerLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "] ["
+ ExoPlayerLibraryInfo.registeredModules() + "]");
mediaSource = null;
internalPlayer.release();
eventHandler.removeCallbacksAndMessages(null);
playbackInfo =
getResetPlaybackInfo(
/* resetPosition= */ true,
/* resetState= */ true,
/* playbackState= */ Player.STATE_IDLE);
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public void sendMessages(ExoPlayerMessage... messages) {
for (ExoPlayerMessage message : messages) {
createMessage(message.target).setType(message.messageType).setPayload(message.message).send();
}
}
@Override
public PlayerMessage createMessage(Target target) {
return new PlayerMessage(
internalPlayer,
target,
playbackInfo.timeline,
getCurrentWindowIndex(),
internalPlayerHandler);
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public void blockingSendMessages(ExoPlayerMessage... messages) {
List<PlayerMessage> playerMessages = new ArrayList<>();
for (ExoPlayerMessage message : messages) {
playerMessages.add(
createMessage(message.target)
.setType(message.messageType)
.setPayload(message.message)
.send());
}
boolean wasInterrupted = false;
for (PlayerMessage message : playerMessages) {
boolean blockMessage = true;
while (blockMessage) {
try {
message.blockUntilDelivered();
blockMessage = false;
} catch (InterruptedException e) {
wasInterrupted = true;
}
}
}
if (wasInterrupted) {
// Restore the interrupted status.
Thread.currentThread().interrupt();
}
}
@Override
public int getCurrentPeriodIndex() {
if (shouldMaskPosition()) {
return maskingPeriodIndex;
} else {
return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid);
}
}
@Override
public int getCurrentWindowIndex() {
if (shouldMaskPosition()) {
return maskingWindowIndex;
} else {
return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period)
.windowIndex;
}
}
@Override
public long getDuration() {
if (isPlayingAd()) {
MediaPeriodId periodId = playbackInfo.periodId;
playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);
long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup);
return C.usToMs(adDurationUs);
}
return getContentDuration();
}
@Override
public long getCurrentPosition() {
if (shouldMaskPosition()) {
return maskingWindowPositionMs;
} else if (playbackInfo.periodId.isAd()) {
return C.usToMs(playbackInfo.positionUs);
} else {
return periodPositionUsToWindowPositionMs(playbackInfo.periodId, playbackInfo.positionUs);
}
}
@Override
public long getBufferedPosition() {
if (isPlayingAd()) {
return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)
? C.usToMs(playbackInfo.bufferedPositionUs)
: getDuration();
}
return getContentBufferedPosition();
}
@Override
public long getTotalBufferedDuration() {
return Math.max(0, C.usToMs(playbackInfo.totalBufferedDurationUs));
}
@Override
public boolean isPlayingAd() {
return !shouldMaskPosition() && playbackInfo.periodId.isAd();
}
@Override
public int getCurrentAdGroupIndex() {
return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET;
}
@Override
public int getCurrentAdIndexInAdGroup() {
return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET;
}
@Override
public long getContentPosition() {
if (isPlayingAd()) {
playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);
return period.getPositionInWindowMs() + C.usToMs(playbackInfo.contentPositionUs);
} else {
return getCurrentPosition();
}
}
@Override
public long getContentBufferedPosition() {
if (shouldMaskPosition()) {
return maskingWindowPositionMs;
}
if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber
!= playbackInfo.periodId.windowSequenceNumber) {
return playbackInfo.timeline.getWindow(getCurrentWindowIndex(), window).getDurationMs();
}
long contentBufferedPositionUs = playbackInfo.bufferedPositionUs;
if (playbackInfo.loadingMediaPeriodId.isAd()) {
Timeline.Period loadingPeriod =
playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period);
contentBufferedPositionUs =
loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex);
if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) {
contentBufferedPositionUs = loadingPeriod.durationUs;
}
}
return periodPositionUsToWindowPositionMs(
playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs);
}
@Override
public int getRendererCount() {
return renderers.length;
}
@Override
public int getRendererType(int index) {
return renderers[index].getTrackType();
}
@Override
public TrackGroupArray getCurrentTrackGroups() {
return playbackInfo.trackGroups;
}
@Override
public TrackSelectionArray getCurrentTrackSelections() {
return playbackInfo.trackSelectorResult.selections;
}
@Override
public Timeline getCurrentTimeline() {
return playbackInfo.timeline;
}
@Override
public Object getCurrentManifest() {
return playbackInfo.manifest;
}
// Not private so it can be called from an inner class without going through a thunk method.
/* package */ void handleEvent(Message msg) {
switch (msg.what) {
case ExoPlayerImplInternal.MSG_PLAYBACK_INFO_CHANGED:
handlePlaybackInfo(
(PlaybackInfo) msg.obj,
/* operationAcks= */ msg.arg1,
/* positionDiscontinuity= */ msg.arg2 != C.INDEX_UNSET,
/* positionDiscontinuityReason= */ msg.arg2);
break;
case ExoPlayerImplInternal.MSG_PLAYBACK_PARAMETERS_CHANGED:
PlaybackParameters playbackParameters = (PlaybackParameters) msg.obj;
if (!this.playbackParameters.equals(playbackParameters)) {
this.playbackParameters = playbackParameters;
notifyListeners(listener -> listener.onPlaybackParametersChanged(playbackParameters));
}
break;
case ExoPlayerImplInternal.MSG_ERROR:
ExoPlaybackException playbackError = (ExoPlaybackException) msg.obj;
this.playbackError = playbackError;
notifyListeners(listener -> listener.onPlayerError(playbackError));
break;
default:
throw new IllegalStateException();
}
}
private void handlePlaybackInfo(
PlaybackInfo playbackInfo,
int operationAcks,
boolean positionDiscontinuity,
@DiscontinuityReason int positionDiscontinuityReason) {
pendingOperationAcks -= operationAcks;
if (pendingOperationAcks == 0) {
if (playbackInfo.startPositionUs == C.TIME_UNSET) {
// Replace internal unset start position with externally visible start position of zero.
playbackInfo =
playbackInfo.resetToNewPosition(
playbackInfo.periodId, /* startPositionUs= */ 0, playbackInfo.contentPositionUs);
}
if (!this.playbackInfo.timeline.isEmpty() && playbackInfo.timeline.isEmpty()) {
// Update the masking variables, which are used when the timeline becomes empty.
maskingPeriodIndex = 0;
maskingWindowIndex = 0;
maskingWindowPositionMs = 0;
}
@Player.TimelineChangeReason
int timelineChangeReason =
hasPendingPrepare
? Player.TIMELINE_CHANGE_REASON_PREPARED
: Player.TIMELINE_CHANGE_REASON_DYNAMIC;
boolean seekProcessed = hasPendingSeek;
hasPendingPrepare = false;
hasPendingSeek = false;
updatePlaybackInfo(
playbackInfo,
positionDiscontinuity,
positionDiscontinuityReason,
timelineChangeReason,
seekProcessed);
}
}
private PlaybackInfo getResetPlaybackInfo(
boolean resetPosition, boolean resetState, int playbackState) {
if (resetPosition) {
maskingWindowIndex = 0;
maskingPeriodIndex = 0;
maskingWindowPositionMs = 0;
} else {
maskingWindowIndex = getCurrentWindowIndex();
maskingPeriodIndex = getCurrentPeriodIndex();
maskingWindowPositionMs = getCurrentPosition();
}
// Also reset period-based PlaybackInfo positions if resetting the state.
resetPosition = resetPosition || resetState;
MediaPeriodId mediaPeriodId =
resetPosition
? playbackInfo.getDummyFirstMediaPeriodId(shuffleModeEnabled, window)
: playbackInfo.periodId;
long startPositionUs = resetPosition ? 0 : playbackInfo.positionUs;
long contentPositionUs = resetPosition ? C.TIME_UNSET : playbackInfo.contentPositionUs;
return new PlaybackInfo(
resetState ? Timeline.EMPTY : playbackInfo.timeline,
resetState ? null : playbackInfo.manifest,
mediaPeriodId,
startPositionUs,
contentPositionUs,
playbackState,
/* isLoading= */ false,
resetState ? TrackGroupArray.EMPTY : playbackInfo.trackGroups,
resetState ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult,
mediaPeriodId,
startPositionUs,
/* totalBufferedDurationUs= */ 0,
startPositionUs);
}
private void updatePlaybackInfo(
PlaybackInfo playbackInfo,
boolean positionDiscontinuity,
@Player.DiscontinuityReason int positionDiscontinuityReason,
@Player.TimelineChangeReason int timelineChangeReason,
boolean seekProcessed) {
// Assign playback info immediately such that all getters return the right values.
PlaybackInfo previousPlaybackInfo = this.playbackInfo;
this.playbackInfo = playbackInfo;
notifyListeners(
new PlaybackInfoUpdate(
playbackInfo,
previousPlaybackInfo,
listeners,
trackSelector,
positionDiscontinuity,
positionDiscontinuityReason,
timelineChangeReason,
seekProcessed,
playWhenReady));
}
private void notifyListeners(ListenerInvocation listenerInvocation) {
CopyOnWriteArrayList<ListenerHolder> listenerSnapshot = new CopyOnWriteArrayList<>(listeners);
notifyListeners(() -> invokeAll(listenerSnapshot, listenerInvocation));
}
private void notifyListeners(Runnable listenerNotificationRunnable) {
boolean isRunningRecursiveListenerNotification = !pendingListenerNotifications.isEmpty();
pendingListenerNotifications.addLast(listenerNotificationRunnable);
if (isRunningRecursiveListenerNotification) {
return;
}
while (!pendingListenerNotifications.isEmpty()) {
pendingListenerNotifications.peekFirst().run();
pendingListenerNotifications.removeFirst();
}
}
private long periodPositionUsToWindowPositionMs(MediaPeriodId periodId, long positionUs) {
long positionMs = C.usToMs(positionUs);
playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);
positionMs += period.getPositionInWindowMs();
return positionMs;
}
private boolean shouldMaskPosition() {
return playbackInfo.timeline.isEmpty() || pendingOperationAcks > 0;
}
private static final class PlaybackInfoUpdate implements Runnable {
private final PlaybackInfo playbackInfo;
private final CopyOnWriteArrayList<ListenerHolder> listenerSnapshot;
private final TrackSelector trackSelector;
private final boolean positionDiscontinuity;
private final @Player.DiscontinuityReason int positionDiscontinuityReason;
private final @Player.TimelineChangeReason int timelineChangeReason;
private final boolean seekProcessed;
private final boolean playbackStateChanged;
private final boolean timelineOrManifestChanged;
private final boolean isLoadingChanged;
private final boolean trackSelectorResultChanged;
private final boolean playWhenReady;
public PlaybackInfoUpdate(
PlaybackInfo playbackInfo,
PlaybackInfo previousPlaybackInfo,
CopyOnWriteArrayList<ListenerHolder> listeners,
TrackSelector trackSelector,
boolean positionDiscontinuity,
@Player.DiscontinuityReason int positionDiscontinuityReason,
@Player.TimelineChangeReason int timelineChangeReason,
boolean seekProcessed,
boolean playWhenReady) {
this.playbackInfo = playbackInfo;
this.listenerSnapshot = new CopyOnWriteArrayList<>(listeners);
this.trackSelector = trackSelector;
this.positionDiscontinuity = positionDiscontinuity;
this.positionDiscontinuityReason = positionDiscontinuityReason;
this.timelineChangeReason = timelineChangeReason;
this.seekProcessed = seekProcessed;
this.playWhenReady = playWhenReady;
playbackStateChanged = previousPlaybackInfo.playbackState != playbackInfo.playbackState;
timelineOrManifestChanged =
previousPlaybackInfo.timeline != playbackInfo.timeline
|| previousPlaybackInfo.manifest != playbackInfo.manifest;
isLoadingChanged = previousPlaybackInfo.isLoading != playbackInfo.isLoading;
trackSelectorResultChanged =
previousPlaybackInfo.trackSelectorResult != playbackInfo.trackSelectorResult;
}
@Override
public void run() {
if (timelineOrManifestChanged || timelineChangeReason == TIMELINE_CHANGE_REASON_PREPARED) {
invokeAll(
listenerSnapshot,
listener ->
listener.onTimelineChanged(
playbackInfo.timeline, playbackInfo.manifest, timelineChangeReason));
}
if (positionDiscontinuity) {
invokeAll(
listenerSnapshot,
listener -> listener.onPositionDiscontinuity(positionDiscontinuityReason));
}
if (trackSelectorResultChanged) {
trackSelector.onSelectionActivated(playbackInfo.trackSelectorResult.info);
invokeAll(
listenerSnapshot,
listener ->
listener.onTracksChanged(
playbackInfo.trackGroups, playbackInfo.trackSelectorResult.selections));
}
if (isLoadingChanged) {
invokeAll(listenerSnapshot, listener -> listener.onLoadingChanged(playbackInfo.isLoading));
}
if (playbackStateChanged) {
invokeAll(
listenerSnapshot,
listener -> listener.onPlayerStateChanged(playWhenReady, playbackInfo.playbackState));
}
if (seekProcessed) {
invokeAll(listenerSnapshot, EventListener::onSeekProcessed);
}
}
}
private static void invokeAll(
CopyOnWriteArrayList<ListenerHolder> listeners, ListenerInvocation listenerInvocation) {
for (ListenerHolder listenerHolder : listeners) {
listenerHolder.invoke(listenerInvocation);
}
}
}
| library/core/src/main/java/com/google/android/exoplayer2/ExoPlayerImpl.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.Nullable;
import android.util.Pair;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectorResult;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** An {@link ExoPlayer} implementation. Instances can be obtained from {@link ExoPlayerFactory}. */
/* package */ final class ExoPlayerImpl extends BasePlayer implements ExoPlayer {
private static final String TAG = "ExoPlayerImpl";
/**
* This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult}
* when the player does not have any track selection made (such as when player is reset, or when
* player seeks to an unprepared period). It will not be used as result of any {@link
* TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)}
* operation.
*/
/* package */ final TrackSelectorResult emptyTrackSelectorResult;
private final Renderer[] renderers;
private final TrackSelector trackSelector;
private final Handler eventHandler;
private final ExoPlayerImplInternal internalPlayer;
private final Handler internalPlayerHandler;
private final CopyOnWriteArrayList<ListenerHolder> listeners;
private final Timeline.Period period;
private final ArrayDeque<Runnable> pendingListenerNotifications;
private MediaSource mediaSource;
private boolean playWhenReady;
private boolean internalPlayWhenReady;
private @RepeatMode int repeatMode;
private boolean shuffleModeEnabled;
private int pendingOperationAcks;
private boolean hasPendingPrepare;
private boolean hasPendingSeek;
private boolean foregroundMode;
private PlaybackParameters playbackParameters;
private SeekParameters seekParameters;
private @Nullable ExoPlaybackException playbackError;
// Playback information when there is no pending seek/set source operation.
private PlaybackInfo playbackInfo;
// Playback information when there is a pending seek/set source operation.
private int maskingWindowIndex;
private int maskingPeriodIndex;
private long maskingWindowPositionMs;
/**
* Constructs an instance. Must be called from a thread that has an associated {@link Looper}.
*
* @param renderers The {@link Renderer}s that will be used by the instance.
* @param trackSelector The {@link TrackSelector} that will be used by the instance.
* @param loadControl The {@link LoadControl} that will be used by the instance.
* @param bandwidthMeter The {@link BandwidthMeter} that will be used by the instance.
* @param clock The {@link Clock} that will be used by the instance.
* @param looper The {@link Looper} which must be used for all calls to the player and which is
* used to call listeners on.
*/
@SuppressLint("HandlerLeak")
public ExoPlayerImpl(
Renderer[] renderers,
TrackSelector trackSelector,
LoadControl loadControl,
BandwidthMeter bandwidthMeter,
Clock clock,
Looper looper) {
Log.i(TAG, "Init " + Integer.toHexString(System.identityHashCode(this)) + " ["
+ ExoPlayerLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "]");
Assertions.checkState(renderers.length > 0);
this.renderers = Assertions.checkNotNull(renderers);
this.trackSelector = Assertions.checkNotNull(trackSelector);
this.playWhenReady = false;
this.repeatMode = Player.REPEAT_MODE_OFF;
this.shuffleModeEnabled = false;
this.listeners = new CopyOnWriteArrayList<>();
emptyTrackSelectorResult =
new TrackSelectorResult(
new RendererConfiguration[renderers.length],
new TrackSelection[renderers.length],
null);
period = new Timeline.Period();
playbackParameters = PlaybackParameters.DEFAULT;
seekParameters = SeekParameters.DEFAULT;
eventHandler =
new Handler(looper) {
@Override
public void handleMessage(Message msg) {
ExoPlayerImpl.this.handleEvent(msg);
}
};
playbackInfo = PlaybackInfo.createDummy(/* startPositionUs= */ 0, emptyTrackSelectorResult);
pendingListenerNotifications = new ArrayDeque<>();
internalPlayer =
new ExoPlayerImplInternal(
renderers,
trackSelector,
emptyTrackSelectorResult,
loadControl,
bandwidthMeter,
playWhenReady,
repeatMode,
shuffleModeEnabled,
eventHandler,
clock);
internalPlayerHandler = new Handler(internalPlayer.getPlaybackLooper());
}
@Override
@Nullable
public AudioComponent getAudioComponent() {
return null;
}
@Override
@Nullable
public VideoComponent getVideoComponent() {
return null;
}
@Override
@Nullable
public TextComponent getTextComponent() {
return null;
}
@Override
@Nullable
public MetadataComponent getMetadataComponent() {
return null;
}
@Override
public Looper getPlaybackLooper() {
return internalPlayer.getPlaybackLooper();
}
@Override
public Looper getApplicationLooper() {
return eventHandler.getLooper();
}
@Override
public void addListener(Player.EventListener listener) {
listeners.addIfAbsent(new ListenerHolder(listener));
}
@Override
public void removeListener(Player.EventListener listener) {
for (ListenerHolder listenerHolder : listeners) {
if (listenerHolder.listener.equals(listener)) {
listenerHolder.release();
listeners.remove(listenerHolder);
}
}
}
@Override
public int getPlaybackState() {
return playbackInfo.playbackState;
}
@Override
public @Nullable ExoPlaybackException getPlaybackError() {
return playbackError;
}
@Override
public void retry() {
if (mediaSource != null
&& (playbackError != null || playbackInfo.playbackState == Player.STATE_IDLE)) {
prepare(mediaSource, /* resetPosition= */ false, /* resetState= */ false);
}
}
@Override
public void prepare(MediaSource mediaSource) {
prepare(mediaSource, /* resetPosition= */ true, /* resetState= */ true);
}
@Override
public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) {
playbackError = null;
this.mediaSource = mediaSource;
PlaybackInfo playbackInfo =
getResetPlaybackInfo(
resetPosition, resetState, /* playbackState= */ Player.STATE_BUFFERING);
// Trigger internal prepare first before updating the playback info and notifying external
// listeners to ensure that new operations issued in the listener notifications reach the
// player after this prepare. The internal player can't change the playback info immediately
// because it uses a callback.
hasPendingPrepare = true;
pendingOperationAcks++;
internalPlayer.prepare(mediaSource, resetPosition, resetState);
updatePlaybackInfo(
playbackInfo,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
TIMELINE_CHANGE_REASON_RESET,
/* seekProcessed= */ false);
}
@Override
public void setPlayWhenReady(boolean playWhenReady) {
setPlayWhenReady(playWhenReady, /* suppressPlayback= */ false);
}
public void setPlayWhenReady(boolean playWhenReady, boolean suppressPlayback) {
boolean internalPlayWhenReady = playWhenReady && !suppressPlayback;
if (this.internalPlayWhenReady != internalPlayWhenReady) {
this.internalPlayWhenReady = internalPlayWhenReady;
internalPlayer.setPlayWhenReady(internalPlayWhenReady);
}
if (this.playWhenReady != playWhenReady) {
this.playWhenReady = playWhenReady;
int playbackState = playbackInfo.playbackState;
notifyListeners(listener -> listener.onPlayerStateChanged(playWhenReady, playbackState));
}
}
@Override
public boolean getPlayWhenReady() {
return playWhenReady;
}
@Override
public void setRepeatMode(@RepeatMode int repeatMode) {
if (this.repeatMode != repeatMode) {
this.repeatMode = repeatMode;
internalPlayer.setRepeatMode(repeatMode);
notifyListeners(listener -> listener.onRepeatModeChanged(repeatMode));
}
}
@Override
public @RepeatMode int getRepeatMode() {
return repeatMode;
}
@Override
public void setShuffleModeEnabled(boolean shuffleModeEnabled) {
if (this.shuffleModeEnabled != shuffleModeEnabled) {
this.shuffleModeEnabled = shuffleModeEnabled;
internalPlayer.setShuffleModeEnabled(shuffleModeEnabled);
notifyListeners(listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled));
}
}
@Override
public boolean getShuffleModeEnabled() {
return shuffleModeEnabled;
}
@Override
public boolean isLoading() {
return playbackInfo.isLoading;
}
@Override
public void seekTo(int windowIndex, long positionMs) {
Timeline timeline = playbackInfo.timeline;
if (windowIndex < 0 || (!timeline.isEmpty() && windowIndex >= timeline.getWindowCount())) {
throw new IllegalSeekPositionException(timeline, windowIndex, positionMs);
}
hasPendingSeek = true;
pendingOperationAcks++;
if (isPlayingAd()) {
// TODO: Investigate adding support for seeking during ads. This is complicated to do in
// general because the midroll ad preceding the seek destination must be played before the
// content position can be played, if a different ad is playing at the moment.
Log.w(TAG, "seekTo ignored because an ad is playing");
eventHandler
.obtainMessage(
ExoPlayerImplInternal.MSG_PLAYBACK_INFO_CHANGED,
/* operationAcks */ 1,
/* positionDiscontinuityReason */ C.INDEX_UNSET,
playbackInfo)
.sendToTarget();
return;
}
maskingWindowIndex = windowIndex;
if (timeline.isEmpty()) {
maskingWindowPositionMs = positionMs == C.TIME_UNSET ? 0 : positionMs;
maskingPeriodIndex = 0;
} else {
long windowPositionUs = positionMs == C.TIME_UNSET
? timeline.getWindow(windowIndex, window).getDefaultPositionUs() : C.msToUs(positionMs);
Pair<Object, Long> periodUidAndPosition =
timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs);
maskingWindowPositionMs = C.usToMs(windowPositionUs);
maskingPeriodIndex = timeline.getIndexOfPeriod(periodUidAndPosition.first);
}
internalPlayer.seekTo(timeline, windowIndex, C.msToUs(positionMs));
notifyListeners(listener -> listener.onPositionDiscontinuity(DISCONTINUITY_REASON_SEEK));
}
@Override
public void setPlaybackParameters(@Nullable PlaybackParameters playbackParameters) {
if (playbackParameters == null) {
playbackParameters = PlaybackParameters.DEFAULT;
}
internalPlayer.setPlaybackParameters(playbackParameters);
}
@Override
public PlaybackParameters getPlaybackParameters() {
return playbackParameters;
}
@Override
public void setSeekParameters(@Nullable SeekParameters seekParameters) {
if (seekParameters == null) {
seekParameters = SeekParameters.DEFAULT;
}
if (!this.seekParameters.equals(seekParameters)) {
this.seekParameters = seekParameters;
internalPlayer.setSeekParameters(seekParameters);
}
}
@Override
public SeekParameters getSeekParameters() {
return seekParameters;
}
@Override
public void setForegroundMode(boolean foregroundMode) {
if (this.foregroundMode != foregroundMode) {
this.foregroundMode = foregroundMode;
internalPlayer.setForegroundMode(foregroundMode);
}
}
@Override
public void stop(boolean reset) {
if (reset) {
playbackError = null;
mediaSource = null;
}
PlaybackInfo playbackInfo =
getResetPlaybackInfo(
/* resetPosition= */ reset,
/* resetState= */ reset,
/* playbackState= */ Player.STATE_IDLE);
// Trigger internal stop first before updating the playback info and notifying external
// listeners to ensure that new operations issued in the listener notifications reach the
// player after this stop. The internal player can't change the playback info immediately
// because it uses a callback.
pendingOperationAcks++;
internalPlayer.stop(reset);
updatePlaybackInfo(
playbackInfo,
/* positionDiscontinuity= */ false,
/* ignored */ DISCONTINUITY_REASON_INTERNAL,
TIMELINE_CHANGE_REASON_RESET,
/* seekProcessed= */ false);
}
@Override
public void release() {
Log.i(TAG, "Release " + Integer.toHexString(System.identityHashCode(this)) + " ["
+ ExoPlayerLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "] ["
+ ExoPlayerLibraryInfo.registeredModules() + "]");
mediaSource = null;
internalPlayer.release();
eventHandler.removeCallbacksAndMessages(null);
playbackInfo =
getResetPlaybackInfo(
/* resetPosition= */ true,
/* resetState= */ true,
/* playbackState= */ Player.STATE_IDLE);
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public void sendMessages(ExoPlayerMessage... messages) {
for (ExoPlayerMessage message : messages) {
createMessage(message.target).setType(message.messageType).setPayload(message.message).send();
}
}
@Override
public PlayerMessage createMessage(Target target) {
return new PlayerMessage(
internalPlayer,
target,
playbackInfo.timeline,
getCurrentWindowIndex(),
internalPlayerHandler);
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public void blockingSendMessages(ExoPlayerMessage... messages) {
List<PlayerMessage> playerMessages = new ArrayList<>();
for (ExoPlayerMessage message : messages) {
playerMessages.add(
createMessage(message.target)
.setType(message.messageType)
.setPayload(message.message)
.send());
}
boolean wasInterrupted = false;
for (PlayerMessage message : playerMessages) {
boolean blockMessage = true;
while (blockMessage) {
try {
message.blockUntilDelivered();
blockMessage = false;
} catch (InterruptedException e) {
wasInterrupted = true;
}
}
}
if (wasInterrupted) {
// Restore the interrupted status.
Thread.currentThread().interrupt();
}
}
@Override
public int getCurrentPeriodIndex() {
if (shouldMaskPosition()) {
return maskingPeriodIndex;
} else {
return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid);
}
}
@Override
public int getCurrentWindowIndex() {
if (shouldMaskPosition()) {
return maskingWindowIndex;
} else {
return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period)
.windowIndex;
}
}
@Override
public long getDuration() {
if (isPlayingAd()) {
MediaPeriodId periodId = playbackInfo.periodId;
playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);
long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup);
return C.usToMs(adDurationUs);
}
return getContentDuration();
}
@Override
public long getCurrentPosition() {
if (shouldMaskPosition()) {
return maskingWindowPositionMs;
} else if (playbackInfo.periodId.isAd()) {
return C.usToMs(playbackInfo.positionUs);
} else {
return periodPositionUsToWindowPositionMs(playbackInfo.periodId, playbackInfo.positionUs);
}
}
@Override
public long getBufferedPosition() {
if (isPlayingAd()) {
return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)
? C.usToMs(playbackInfo.bufferedPositionUs)
: getDuration();
}
return getContentBufferedPosition();
}
@Override
public long getTotalBufferedDuration() {
return Math.max(0, C.usToMs(playbackInfo.totalBufferedDurationUs));
}
@Override
public boolean isPlayingAd() {
return !shouldMaskPosition() && playbackInfo.periodId.isAd();
}
@Override
public int getCurrentAdGroupIndex() {
return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET;
}
@Override
public int getCurrentAdIndexInAdGroup() {
return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET;
}
@Override
public long getContentPosition() {
if (isPlayingAd()) {
playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period);
return period.getPositionInWindowMs() + C.usToMs(playbackInfo.contentPositionUs);
} else {
return getCurrentPosition();
}
}
@Override
public long getContentBufferedPosition() {
if (shouldMaskPosition()) {
return maskingWindowPositionMs;
}
if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber
!= playbackInfo.periodId.windowSequenceNumber) {
return playbackInfo.timeline.getWindow(getCurrentWindowIndex(), window).getDurationMs();
}
long contentBufferedPositionUs = playbackInfo.bufferedPositionUs;
if (playbackInfo.loadingMediaPeriodId.isAd()) {
Timeline.Period loadingPeriod =
playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period);
contentBufferedPositionUs =
loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex);
if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) {
contentBufferedPositionUs = loadingPeriod.durationUs;
}
}
return periodPositionUsToWindowPositionMs(
playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs);
}
@Override
public int getRendererCount() {
return renderers.length;
}
@Override
public int getRendererType(int index) {
return renderers[index].getTrackType();
}
@Override
public TrackGroupArray getCurrentTrackGroups() {
return playbackInfo.trackGroups;
}
@Override
public TrackSelectionArray getCurrentTrackSelections() {
return playbackInfo.trackSelectorResult.selections;
}
@Override
public Timeline getCurrentTimeline() {
return playbackInfo.timeline;
}
@Override
public Object getCurrentManifest() {
return playbackInfo.manifest;
}
// Not private so it can be called from an inner class without going through a thunk method.
/* package */ void handleEvent(Message msg) {
switch (msg.what) {
case ExoPlayerImplInternal.MSG_PLAYBACK_INFO_CHANGED:
handlePlaybackInfo(
(PlaybackInfo) msg.obj,
/* operationAcks= */ msg.arg1,
/* positionDiscontinuity= */ msg.arg2 != C.INDEX_UNSET,
/* positionDiscontinuityReason= */ msg.arg2);
break;
case ExoPlayerImplInternal.MSG_PLAYBACK_PARAMETERS_CHANGED:
PlaybackParameters playbackParameters = (PlaybackParameters) msg.obj;
if (!this.playbackParameters.equals(playbackParameters)) {
this.playbackParameters = playbackParameters;
notifyListeners(listener -> listener.onPlaybackParametersChanged(playbackParameters));
}
break;
case ExoPlayerImplInternal.MSG_ERROR:
ExoPlaybackException playbackError = (ExoPlaybackException) msg.obj;
this.playbackError = playbackError;
notifyListeners(listener -> listener.onPlayerError(playbackError));
break;
default:
throw new IllegalStateException();
}
}
private void handlePlaybackInfo(
PlaybackInfo playbackInfo,
int operationAcks,
boolean positionDiscontinuity,
@DiscontinuityReason int positionDiscontinuityReason) {
pendingOperationAcks -= operationAcks;
if (pendingOperationAcks == 0) {
if (playbackInfo.startPositionUs == C.TIME_UNSET) {
// Replace internal unset start position with externally visible start position of zero.
playbackInfo =
playbackInfo.resetToNewPosition(
playbackInfo.periodId, /* startPositionUs= */ 0, playbackInfo.contentPositionUs);
}
if ((!this.playbackInfo.timeline.isEmpty() || hasPendingPrepare)
&& playbackInfo.timeline.isEmpty()) {
// Update the masking variables, which are used when the timeline becomes empty.
maskingPeriodIndex = 0;
maskingWindowIndex = 0;
maskingWindowPositionMs = 0;
}
@Player.TimelineChangeReason
int timelineChangeReason =
hasPendingPrepare
? Player.TIMELINE_CHANGE_REASON_PREPARED
: Player.TIMELINE_CHANGE_REASON_DYNAMIC;
boolean seekProcessed = hasPendingSeek;
hasPendingPrepare = false;
hasPendingSeek = false;
updatePlaybackInfo(
playbackInfo,
positionDiscontinuity,
positionDiscontinuityReason,
timelineChangeReason,
seekProcessed);
}
}
private PlaybackInfo getResetPlaybackInfo(
boolean resetPosition, boolean resetState, int playbackState) {
if (resetPosition) {
maskingWindowIndex = 0;
maskingPeriodIndex = 0;
maskingWindowPositionMs = 0;
} else {
maskingWindowIndex = getCurrentWindowIndex();
maskingPeriodIndex = getCurrentPeriodIndex();
maskingWindowPositionMs = getCurrentPosition();
}
// Also reset period-based PlaybackInfo positions if resetting the state.
resetPosition = resetPosition || resetState;
MediaPeriodId mediaPeriodId =
resetPosition
? playbackInfo.getDummyFirstMediaPeriodId(shuffleModeEnabled, window)
: playbackInfo.periodId;
long startPositionUs = resetPosition ? 0 : playbackInfo.positionUs;
long contentPositionUs = resetPosition ? C.TIME_UNSET : playbackInfo.contentPositionUs;
return new PlaybackInfo(
resetState ? Timeline.EMPTY : playbackInfo.timeline,
resetState ? null : playbackInfo.manifest,
mediaPeriodId,
startPositionUs,
contentPositionUs,
playbackState,
/* isLoading= */ false,
resetState ? TrackGroupArray.EMPTY : playbackInfo.trackGroups,
resetState ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult,
mediaPeriodId,
startPositionUs,
/* totalBufferedDurationUs= */ 0,
startPositionUs);
}
private void updatePlaybackInfo(
PlaybackInfo playbackInfo,
boolean positionDiscontinuity,
@Player.DiscontinuityReason int positionDiscontinuityReason,
@Player.TimelineChangeReason int timelineChangeReason,
boolean seekProcessed) {
// Assign playback info immediately such that all getters return the right values.
PlaybackInfo previousPlaybackInfo = this.playbackInfo;
this.playbackInfo = playbackInfo;
notifyListeners(
new PlaybackInfoUpdate(
playbackInfo,
previousPlaybackInfo,
listeners,
trackSelector,
positionDiscontinuity,
positionDiscontinuityReason,
timelineChangeReason,
seekProcessed,
playWhenReady));
}
private void notifyListeners(ListenerInvocation listenerInvocation) {
CopyOnWriteArrayList<ListenerHolder> listenerSnapshot = new CopyOnWriteArrayList<>(listeners);
notifyListeners(() -> invokeAll(listenerSnapshot, listenerInvocation));
}
private void notifyListeners(Runnable listenerNotificationRunnable) {
boolean isRunningRecursiveListenerNotification = !pendingListenerNotifications.isEmpty();
pendingListenerNotifications.addLast(listenerNotificationRunnable);
if (isRunningRecursiveListenerNotification) {
return;
}
while (!pendingListenerNotifications.isEmpty()) {
pendingListenerNotifications.peekFirst().run();
pendingListenerNotifications.removeFirst();
}
}
private long periodPositionUsToWindowPositionMs(MediaPeriodId periodId, long positionUs) {
long positionMs = C.usToMs(positionUs);
playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period);
positionMs += period.getPositionInWindowMs();
return positionMs;
}
private boolean shouldMaskPosition() {
return playbackInfo.timeline.isEmpty() || pendingOperationAcks > 0;
}
private static final class PlaybackInfoUpdate implements Runnable {
private final PlaybackInfo playbackInfo;
private final CopyOnWriteArrayList<ListenerHolder> listenerSnapshot;
private final TrackSelector trackSelector;
private final boolean positionDiscontinuity;
private final @Player.DiscontinuityReason int positionDiscontinuityReason;
private final @Player.TimelineChangeReason int timelineChangeReason;
private final boolean seekProcessed;
private final boolean playbackStateChanged;
private final boolean timelineOrManifestChanged;
private final boolean isLoadingChanged;
private final boolean trackSelectorResultChanged;
private final boolean playWhenReady;
public PlaybackInfoUpdate(
PlaybackInfo playbackInfo,
PlaybackInfo previousPlaybackInfo,
CopyOnWriteArrayList<ListenerHolder> listeners,
TrackSelector trackSelector,
boolean positionDiscontinuity,
@Player.DiscontinuityReason int positionDiscontinuityReason,
@Player.TimelineChangeReason int timelineChangeReason,
boolean seekProcessed,
boolean playWhenReady) {
this.playbackInfo = playbackInfo;
this.listenerSnapshot = new CopyOnWriteArrayList<>(listeners);
this.trackSelector = trackSelector;
this.positionDiscontinuity = positionDiscontinuity;
this.positionDiscontinuityReason = positionDiscontinuityReason;
this.timelineChangeReason = timelineChangeReason;
this.seekProcessed = seekProcessed;
this.playWhenReady = playWhenReady;
playbackStateChanged = previousPlaybackInfo.playbackState != playbackInfo.playbackState;
timelineOrManifestChanged =
previousPlaybackInfo.timeline != playbackInfo.timeline
|| previousPlaybackInfo.manifest != playbackInfo.manifest;
isLoadingChanged = previousPlaybackInfo.isLoading != playbackInfo.isLoading;
trackSelectorResultChanged =
previousPlaybackInfo.trackSelectorResult != playbackInfo.trackSelectorResult;
}
@Override
public void run() {
if (timelineOrManifestChanged || timelineChangeReason == TIMELINE_CHANGE_REASON_PREPARED) {
invokeAll(
listenerSnapshot,
listener ->
listener.onTimelineChanged(
playbackInfo.timeline, playbackInfo.manifest, timelineChangeReason));
}
if (positionDiscontinuity) {
invokeAll(
listenerSnapshot,
listener -> listener.onPositionDiscontinuity(positionDiscontinuityReason));
}
if (trackSelectorResultChanged) {
trackSelector.onSelectionActivated(playbackInfo.trackSelectorResult.info);
invokeAll(
listenerSnapshot,
listener ->
listener.onTracksChanged(
playbackInfo.trackGroups, playbackInfo.trackSelectorResult.selections));
}
if (isLoadingChanged) {
invokeAll(listenerSnapshot, listener -> listener.onLoadingChanged(playbackInfo.isLoading));
}
if (playbackStateChanged) {
invokeAll(
listenerSnapshot,
listener -> listener.onPlayerStateChanged(playWhenReady, playbackInfo.playbackState));
}
if (seekProcessed) {
invokeAll(listenerSnapshot, EventListener::onSeekProcessed);
}
}
}
private static void invokeAll(
CopyOnWriteArrayList<ListenerHolder> listeners, ListenerInvocation listenerInvocation) {
for (ListenerHolder listenerHolder : listeners) {
listenerHolder.invoke(listenerInvocation);
}
}
}
| Don't reset masking position when prepare fails.
The removed condition only applies when prepare fails and no timeline was or
is known. We should keep a pending seek position in such a case. The internal
player does the same thing already.
PiperOrigin-RevId: 243819466
| library/core/src/main/java/com/google/android/exoplayer2/ExoPlayerImpl.java | Don't reset masking position when prepare fails. | <ide><path>ibrary/core/src/main/java/com/google/android/exoplayer2/ExoPlayerImpl.java
<ide> playbackInfo.resetToNewPosition(
<ide> playbackInfo.periodId, /* startPositionUs= */ 0, playbackInfo.contentPositionUs);
<ide> }
<del> if ((!this.playbackInfo.timeline.isEmpty() || hasPendingPrepare)
<del> && playbackInfo.timeline.isEmpty()) {
<add> if (!this.playbackInfo.timeline.isEmpty() && playbackInfo.timeline.isEmpty()) {
<ide> // Update the masking variables, which are used when the timeline becomes empty.
<ide> maskingPeriodIndex = 0;
<ide> maskingWindowIndex = 0; |
|
Java | apache-2.0 | b72cd0e9dc221a186702643e4b7cc526544efae1 | 0 | opensingular/singular-server,opensingular/singular-server,opensingular/singular-server | package org.opensingular.app.commons.mail.schedule;
import org.opensingular.lib.commons.base.SingularException;
import org.opensingular.lib.commons.base.SingularProperties;
import org.opensingular.lib.commons.util.Loggable;
import org.opensingular.schedule.quartz.QuartzJobFactory;
import org.opensingular.schedule.quartz.SingularSchedulerAccessor;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.RemoteScheduler;
import org.quartz.impl.SchedulerRepository;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.simpl.SimpleThreadPool;
import org.quartz.spi.JobFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.scheduling.SchedulingException;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.LocalTaskExecutorThreadPool;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.Executor;
import static org.opensingular.lib.commons.base.SingularProperties.SINGULAR_QUARTZ_JOBSTORE_ENABLED;
public class SingularSchedulerBean extends SingularSchedulerAccessor implements FactoryBean<Scheduler>,
BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean, SmartLifecycle, Loggable {
public static final String PROP_THREAD_COUNT = "org.quartz.threadPool.threadCount";
public static final int DEFAULT_THREAD_COUNT = 10;
private static final ThreadLocal<Executor> configTimeTaskExecutorHolder =
new ThreadLocal<Executor>();
private static final ThreadLocal<DataSource> configTimeDataSourceHolder =
new ThreadLocal<DataSource>();
private static final ThreadLocal<DataSource> configTimeNonTransactionalDataSourceHolder =
new ThreadLocal<DataSource>();
public SingularSchedulerBean(DataSource dataSource) {
Properties quartzProperties = new Properties();
quartzProperties.setProperty("org.quartz.scheduler.instanceName", "SINGULARID");
quartzProperties.setProperty("org.quartz.scheduler.instanceId", "AUTO");
if (SingularProperties.get().isTrue(SINGULAR_QUARTZ_JOBSTORE_ENABLED)) {
quartzProperties.put("org.quartz.jobStore.useProperties", "false");
quartzProperties.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
quartzProperties.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.MSSQLDelegate");
quartzProperties.put("org.quartz.jobStore.tablePrefix", "DBSINGULAR.qrtz_");
quartzProperties.put("org.quartz.jobStore.isClustered", "true");
setQuartzProperties(quartzProperties);
setDataSource(dataSource);
setOverwriteExistingJobs(true);
} else {
quartzProperties.put("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
}
}
/**
* Return the TaskExecutor for the currently configured Quartz Scheduler,
* to be used by LocalTaskExecutorThreadPool.
* <p>This instance will be set before initialization of the corresponding
* Scheduler, and reset immediately afterwards. It is thus only available
* during configuration.
*
* @see #setTaskExecutor
* @see LocalTaskExecutorThreadPool
*/
public static Executor getConfigTimeTaskExecutor() {
return configTimeTaskExecutorHolder.get();
}
/**
* Return the DataSource for the currently configured Quartz Scheduler,
* to be used by SingularLocalDataSourceJobStore.
* <p>This instance will be set before initialization of the corresponding
* Scheduler, and reset immediately afterwards. It is thus only available
* during configuration.
*
* @see #setDataSource
* @see SingularLocalDataSourceJobStore
*/
public static DataSource getConfigTimeDataSource() {
return configTimeDataSourceHolder.get();
}
/**
* Return the non-transactional DataSource for the currently configured
* Quartz Scheduler, to be used by SingularLocalDataSourceJobStore.
* <p>This instance will be set before initialization of the corresponding
* Scheduler, and reset immediately afterwards. It is thus only available
* during configuration.
*
* @see #setNonTransactionalDataSource
* @see SingularLocalDataSourceJobStore
*/
public static DataSource getConfigTimeNonTransactionalDataSource() {
return configTimeNonTransactionalDataSourceHolder.get();
}
private Class<? extends SchedulerFactory> schedulerFactoryClass = StdSchedulerFactory.class;
private String schedulerName;
private Resource configLocation;
private Properties quartzProperties;
private Executor taskExecutor;
private DataSource dataSource;
private DataSource nonTransactionalDataSource;
private Map<String, ?> schedulerContextMap;
private ApplicationContext applicationContext;
private String applicationContextSchedulerContextKey;
private JobFactory jobFactory;
private boolean jobFactorySet = false;
private int startupDelay = 0;
private int phase = Integer.MAX_VALUE;
private boolean exposeSchedulerInRepository = false;
private boolean waitForJobsToCompleteOnShutdown = false;
private Scheduler scheduler;
/**
* Set the Quartz SchedulerFactory implementation to use.
* <p>Default is {@link StdSchedulerFactory}, reading in the standard
* {@code quartz.properties} from {@code quartz.jar}.
* To use custom Quartz properties, specify the "configLocation"
* or "quartzProperties" bean property on this FactoryBean.
*
* @see org.quartz.impl.StdSchedulerFactory
* @see #setConfigLocation
* @see #setQuartzProperties
*/
public void setSchedulerFactoryClass(Class<? extends SchedulerFactory> schedulerFactoryClass) {
Assert.isAssignable(SchedulerFactory.class, schedulerFactoryClass);
this.schedulerFactoryClass = schedulerFactoryClass;
}
/**
* Set the name of the Scheduler to create via the SchedulerFactory.
* <p>If not specified, the bean name will be used as default scheduler name.
*
* @see org.quartz.SchedulerFactory#getScheduler()
* @see org.quartz.SchedulerFactory#getScheduler(String)
*/
public void setSchedulerName(String schedulerName) {
this.schedulerName = schedulerName;
}
@Override
public void setConfigLocation(ResourceBundle configLocation) {
}
/**
* Set the location of the Quartz properties config file, for example
* as classpath resource "classpath:quartz.properties".
* <p>Note: Can be omitted when all necessary properties are specified
* locally via this bean, or when relying on Quartz' default configuration.
*
* @see #setQuartzProperties
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set Quartz properties, like "org.quartz.threadPool.class".
* <p>Can be used to override values in a Quartz properties config file,
* or to specify all necessary properties locally.
*
* @see #setConfigLocation
*/
public void setQuartzProperties(Properties quartzProperties) {
this.quartzProperties = quartzProperties;
}
/**
* Set the Spring TaskExecutor to use as Quartz backend.
* Exposed as thread pool through the Quartz SPI.
* <p>Can be used to assign a JDK 1.5 ThreadPoolExecutor or a CommonJ
* WorkManager as Quartz backend, to avoid Quartz's manual thread creation.
* <p>By default, a Quartz SimpleThreadPool will be used, configured through
* the corresponding Quartz properties.
*
* @see #setQuartzProperties
* @see LocalTaskExecutorThreadPool
* @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
* @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
*/
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Set the default DataSource to be used by the Scheduler. If set,
* this will override corresponding settings in Quartz properties.
* <p>Note: If this is set, the Quartz settings should not define
* a job store "dataSource" to avoid meaningless double configuration.
* <p>A Spring-specific subclass of Quartz' JobStoreCMT will be used.
* It is therefore strongly recommended to perform all operations on
* the Scheduler within Spring-managed (or plain JTA) transactions.
* Else, database locking will not properly work and might even break
* (e.g. if trying to obtain a lock on Oracle without a transaction).
* <p>Supports both transactional and non-transactional DataSource access.
* With a non-XA DataSource and local Spring transactions, a single DataSource
* argument is sufficient. In case of an XA DataSource and global JTA transactions,
* SchedulerFactoryBean's "nonTransactionalDataSource" property should be set,
* passing in a non-XA DataSource that will not participate in global transactions.
*
* @see #setNonTransactionalDataSource
* @see #setQuartzProperties
* @see SingularLocalDataSourceJobStore
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Set the DataSource to be used by the Scheduler <i>for non-transactional access</i>.
* <p>This is only necessary if the default DataSource is an XA DataSource that will
* always participate in transactions: A non-XA version of that DataSource should
* be specified as "nonTransactionalDataSource" in such a scenario.
* <p>This is not relevant with a local DataSource instance and Spring transactions.
* Specifying a single default DataSource as "dataSource" is sufficient there.
*
* @see #setDataSource
* @see SingularLocalDataSourceJobStore
*/
public void setNonTransactionalDataSource(DataSource nonTransactionalDataSource) {
this.nonTransactionalDataSource = nonTransactionalDataSource;
}
/**
* Register objects in the Scheduler context via a given Map.
* These objects will be available to any Job that runs in this Scheduler.
* <p>Note: When using persistent Jobs whose JobDetail will be kept in the
* database, do not put Spring-managed beans or an ApplicationContext
* reference into the JobDataMap but rather into the SchedulerContext.
*
* @param schedulerContextAsMap Map with String keys and any objects as
* values (for example Spring-managed beans)
* @see JobDetailFactoryBean#setJobDataAsMap
*/
public void setSchedulerContextAsMap(Map<String, ?> schedulerContextAsMap) {
this.schedulerContextMap = schedulerContextAsMap;
}
/**
* Set the key of an ApplicationContext reference to expose in the
* SchedulerContext, for example "applicationContext". Default is none.
* Only applicable when running in a Spring ApplicationContext.
* <p>Note: When using persistent Jobs whose JobDetail will be kept in the
* database, do not put an ApplicationContext reference into the JobDataMap
* but rather into the SchedulerContext.
* <p>In case of a QuartzJobBean, the reference will be applied to the Job
* instance as bean property. An "applicationContext" attribute will
* correspond to a "setApplicationContext" method in that scenario.
* <p>Note that BeanFactory callback interfaces like ApplicationContextAware
* are not automatically applied to Quartz Job instances, because Quartz
* itself is responsible for the lifecycle of its Jobs.
*
* @see JobDetailFactoryBean#setApplicationContextJobDataKey
* @see org.springframework.context.ApplicationContext
*/
public void setApplicationContextSchedulerContextKey(String applicationContextSchedulerContextKey) {
this.applicationContextSchedulerContextKey = applicationContextSchedulerContextKey;
}
/**
* Set the Quartz JobFactory to use for this Scheduler.
* <p>Default is Spring's {@link AdaptableJobFactory}, which supports
* {@link java.lang.Runnable} objects as well as standard Quartz
* {@link org.quartz.Job} instances. Note that this default only applies
* to a <i>local</i> Scheduler, not to a RemoteScheduler (where setting
* a custom JobFactory is not supported by Quartz).
* <p>Specify an instance of Spring's {@link SpringBeanJobFactory} here
* (typically as an inner bean definition) to automatically populate a job's
* bean properties from the specified job data map and scheduler context.
*
* @see AdaptableJobFactory
* @see SpringBeanJobFactory
*/
public void setJobFactory(JobFactory jobFactory) {
this.jobFactory = jobFactory;
this.jobFactorySet = true;
}
/**
* Set whether to automatically start the scheduler after initialization.
* <p>Default is "true"; set this to "false" to allow for manual startup.
*/
public void setAutoStartup(boolean autoStartup) {}
/**
* Specify the phase in which this scheduler should be started and
* stopped. The startup order proceeds from lowest to highest, and
* the shutdown order is the reverse of that. By default this value
* is Integer.MAX_VALUE meaning that this scheduler starts as late
* as possible and stops as soon as possible.
*/
public void setPhase(int phase) {
this.phase = phase;
}
/**
* Set the number of seconds to wait after initialization before
* starting the scheduler asynchronously. Default is 0, meaning
* immediate synchronous startup on initialization of this bean.
* <p>Setting this to 10 or 20 seconds makes sense if no jobs
* should be run before the entire application has started up.
*/
public void setStartupDelay(int startupDelay) {
this.startupDelay = startupDelay;
}
/**
* Set whether to expose the Spring-managed {@link Scheduler} instance in the
* Quartz {@link SchedulerRepository}. Default is "false", since the Spring-managed
* Scheduler is usually exclusively intended for access within the Spring context.
* <p>Switch this flag to "true" in order to expose the Scheduler globally.
* This is not recommended unless you have an existing Spring application that
* relies on this behavior. Note that such global exposure was the accidental
* default in earlier Spring versions; this has been fixed as of Spring 2.5.6.
*/
public void setExposeSchedulerInRepository(boolean exposeSchedulerInRepository) {
this.exposeSchedulerInRepository = exposeSchedulerInRepository;
}
/**
* Set whether to wait for running jobs to complete on shutdown.
* <p>Default is "false". Switch this to "true" if you prefer
* fully completed jobs at the expense of a longer shutdown phase.
*
* @see org.quartz.Scheduler#shutdown(boolean)
*/
public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
}
public void initialize() throws SingularException {
try {
afterPropertiesSet();
} catch (Exception e) {
throw SingularException.rethrow(e.getMessage(), e);
}
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
//---------------------------------------------------------------------
// Implementation of InitializingBean interface
//---------------------------------------------------------------------
@SuppressWarnings("squid:MethodCyclomaticComplexity")
public void afterPropertiesSet() throws Exception {
if (this.dataSource == null && this.nonTransactionalDataSource != null) {
this.dataSource = this.nonTransactionalDataSource;
}
// Create SchedulerFactory instance...
SchedulerFactory schedulerFactory = BeanUtils.instantiateClass(this.schedulerFactoryClass);
initSchedulerFactory(schedulerFactory);
if (this.taskExecutor != null) {
// Make given TaskExecutor available for SchedulerFactory configuration.
configTimeTaskExecutorHolder.set(this.taskExecutor);
}
if (this.dataSource != null) {
// Make given DataSource available for SchedulerFactory configuration.
configTimeDataSourceHolder.set(this.dataSource);
}
if (this.nonTransactionalDataSource != null) {
// Make given non-transactional DataSource available for SchedulerFactory configuration.
configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
}
// Get Scheduler instance from SchedulerFactory.
try {
this.scheduler = createScheduler(schedulerFactory, this.schedulerName);
populateSchedulerContext();
if (!this.jobFactorySet && !(this.scheduler instanceof RemoteScheduler)) {
/* Use QuartzJobFactory as default for a local Scheduler, unless when
* explicitly given a null value through the "jobFactory" property.
*/
this.jobFactory = new QuartzJobFactory();
}
if (this.jobFactory != null) {
this.scheduler.setJobFactory(this.jobFactory);
}
} finally {
if (this.taskExecutor != null) {
configTimeTaskExecutorHolder.remove();
}
if (this.dataSource != null) {
configTimeDataSourceHolder.remove();
}
if (this.nonTransactionalDataSource != null) {
configTimeNonTransactionalDataSourceHolder.remove();
}
}
registerListeners();
registerJobsAndTriggers();
}
/**
* Load and/or apply Quartz properties to the given SchedulerFactory.
*
* @param schedulerFactory the SchedulerFactory to initialize
*/
private void initSchedulerFactory(SchedulerFactory schedulerFactory) throws SchedulerException, IOException {
if (!(schedulerFactory instanceof StdSchedulerFactory)) {
if (this.configLocation != null || this.quartzProperties != null ||
this.taskExecutor != null || this.dataSource != null) {
throw new IllegalArgumentException(
"StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
}
// Otherwise assume that no initialization is necessary...
return;
}
Properties mergedProps = new Properties();
if (this.taskExecutor != null) {
mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS,
LocalTaskExecutorThreadPool.class.getName());
} else {
// Set necessary default properties here, as Quartz will not apply
// its default configuration when explicitly given properties.
mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName());
mergedProps.setProperty(PROP_THREAD_COUNT, Integer.toString(DEFAULT_THREAD_COUNT));
}
if (this.configLocation != null) {
if (logger.isInfoEnabled()) {
logger.info("Loading Quartz config from [" + this.configLocation + "]");
}
PropertiesLoaderUtils.fillProperties(mergedProps, this.configLocation);
}
CollectionUtils.mergePropertiesIntoMap(this.quartzProperties, mergedProps);
if (this.dataSource != null) {
mergedProps.put(StdSchedulerFactory.PROP_JOB_STORE_CLASS, SingularLocalDataSourceJobStore.class.getName());
}
// Make sure to set the scheduler name as configured in the Spring configuration.
if (this.schedulerName != null) {
mergedProps.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, this.schedulerName);
}
((StdSchedulerFactory) schedulerFactory).initialize(mergedProps);
}
/**
* Create the Scheduler instance for the given factory and scheduler name.
* Called by {@link #afterPropertiesSet}.
* <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
* method. Can be overridden for custom Scheduler creation.
*
* @param schedulerFactory the factory to create the Scheduler with
* @param schedulerName the name of the scheduler to create
* @return the Scheduler instance
* @throws SchedulerException if thrown by Quartz methods
* @see #afterPropertiesSet
* @see org.quartz.SchedulerFactory#getScheduler
*/
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)
throws SchedulerException {
try {
SchedulerRepository repository = SchedulerRepository.getInstance();
synchronized (repository) {
Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
Scheduler newScheduler = schedulerFactory.getScheduler();
if (newScheduler == existingScheduler) {
throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " +
"in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
}
if (!this.exposeSchedulerInRepository) {
// Need to remove it in this case, since Quartz shares the Scheduler instance by default!
SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
}
return newScheduler;
}
} catch (Exception e) {
getLogger().debug(e.getMessage(), e);
throw new SchedulerException(e);
}
}
/**
* Expose the specified context attributes and/or the current
* ApplicationContext in the Quartz SchedulerContext.
*/
private void populateSchedulerContext() throws SchedulerException {
// Put specified objects into Scheduler context.
if (this.schedulerContextMap != null) {
this.scheduler.getContext().putAll(this.schedulerContextMap);
}
// Register ApplicationContext in Scheduler context.
if (this.applicationContextSchedulerContextKey != null) {
if (this.applicationContext == null) {
throw new IllegalStateException(
"SchedulerFactoryBean needs to be set up in an ApplicationContext " +
"to be able to handle an 'applicationContextSchedulerContextKey'");
}
this.scheduler.getContext().put(this.applicationContextSchedulerContextKey, this.applicationContext);
}
}
/**
* Start the Quartz Scheduler, respecting the "startupDelay" setting.
*
* @param scheduler the Scheduler to start
* @param startupDelay the number of seconds to wait before starting
* the Scheduler asynchronously
*/
protected void startScheduler(final Scheduler scheduler, final int startupDelay) throws SchedulerException {
if (startupDelay <= 0) {
logger.info("Starting Quartz Scheduler now");
scheduler.start();
} else {
if (logger.isInfoEnabled()) {
logger.info("Will start Quartz Scheduler [" + scheduler.getSchedulerName() +
"] in " + startupDelay + " seconds");
}
Thread schedulerThread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(startupDelay * 1000L);
} catch (InterruptedException ex) {
getLogger().trace(ex.getMessage(), ex);
}
if (logger.isInfoEnabled()) {
logger.info("Starting Quartz Scheduler now, after delay of " + startupDelay + " seconds");
}
try {
scheduler.start();
} catch (SchedulerException ex) {
throw new SchedulingException("Could not start Quartz Scheduler after delay", ex);
}
}
};
schedulerThread.setName("Quartz Scheduler [" + scheduler.getSchedulerName() + "]");
schedulerThread.setDaemon(true);
schedulerThread.start();
}
}
//---------------------------------------------------------------------
// Implementation of FactoryBean interface
//---------------------------------------------------------------------
@Override
public Scheduler getScheduler() {
return this.scheduler;
}
//---------------------------------------------------------------------
// Implementation of SmartLifecycle interface
//---------------------------------------------------------------------
@Override
public void start() throws SchedulingException {
if (this.scheduler != null) {
try {
startScheduler(this.scheduler, this.startupDelay);
} catch (SchedulerException ex) {
throw new SchedulingException("Could not start Quartz Scheduler", ex);
}
}
}
@Override
public void start(int startupDelay) throws SchedulerException {
}
@Override
public void stop() throws SchedulingException {
if (this.scheduler != null) {
try {
this.scheduler.standby();
} catch (SchedulerException ex) {
throw new SchedulingException("Could not stop Quartz Scheduler", ex);
}
}
}
@Override
public boolean isAutoStartup() {
return false;
}
@Override
public void stop(Runnable callback) throws SchedulingException {
stop();
callback.run();
}
@Override
public boolean isRunning() throws SchedulingException {
if (this.scheduler != null) {
try {
return !this.scheduler.isInStandbyMode();
} catch (SchedulerException ex) {
getLogger().trace(ex.getMessage(), ex);
return false;
}
}
return false;
}
//---------------------------------------------------------------------
// Implementation of DisposableBean interface
//---------------------------------------------------------------------
/**
* Shut down the Quartz scheduler on bean factory shutdown,
* stopping all scheduled jobs.
*/
@Override
public void destroy() throws SchedulerException {
logger.info("Shutting down Quartz Scheduler");
this.scheduler.shutdown(this.waitForJobsToCompleteOnShutdown);
}
// ############ SPRING CONFIGURATION ############
@Override
public void setBeanName(String name) {
if (this.schedulerName == null) {
this.schedulerName = name;
}
}
@Override
public Scheduler getObject() throws Exception {
return this.scheduler;
}
@Override
public Class<?> getObjectType() {
return (this.scheduler != null) ? this.scheduler.getClass() : Scheduler.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public int getPhase() {
return this.phase;
}
// ############ SINGULAR JOB CONFIGURATION ############
@Override
public void addJob(JobDetail jobDetail) throws SchedulerException {
addJobToScheduler(jobDetail);
}
@Override
public void addTrigger(Trigger trigger, JobDetail jobDetail) throws SchedulerException {
trigger.getJobDataMap().put(SINGULAR_JOB_DETAIL_KEY, jobDetail);
addTriggerToScheduler(trigger);
}
/**
* Add trigger and the trigger's job detail.
*
* @param trigger the trigger.
* @throws SchedulerException if could not start Quartz Scheduler.
*/
@Override
public void addTrigger(Trigger trigger) throws SchedulerException {
addJobToScheduler((JobDetail) trigger.getJobDataMap().get(SINGULAR_JOB_DETAIL_KEY));
addTriggerToScheduler(trigger);
}
/**
* Trigger the identified {@link org.quartz.JobDetail} (execute it now).
*
* @param jobKey
* @throws SchedulerException
*/
@Override
public void triggerJob(JobKey jobKey) throws SchedulerException {
getScheduler().triggerJob(jobKey);
}
@Override
public Set<JobKey> getAllJobKeys() throws SchedulerException {
return getScheduler().getJobKeys(GroupMatcher.anyGroup());
}
}
| lib/app-commons/src/main/java/org/opensingular/app/commons/mail/schedule/SingularSchedulerBean.java | package org.opensingular.app.commons.mail.schedule;
import org.opensingular.lib.commons.base.SingularException;
import org.opensingular.lib.commons.base.SingularProperties;
import org.opensingular.lib.commons.util.Loggable;
import org.opensingular.schedule.quartz.QuartzJobFactory;
import org.opensingular.schedule.quartz.SingularSchedulerAccessor;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.RemoteScheduler;
import org.quartz.impl.SchedulerRepository;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.simpl.SimpleThreadPool;
import org.quartz.spi.JobFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.scheduling.SchedulingException;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.LocalTaskExecutorThreadPool;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.Executor;
import static org.opensingular.lib.commons.base.SingularProperties.SINGULAR_QUARTZ_JOBSTORE_ENABLED;
public class SingularSchedulerBean extends SingularSchedulerAccessor implements FactoryBean<Scheduler>,
BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean, SmartLifecycle, Loggable {
public static final String PROP_THREAD_COUNT = "org.quartz.threadPool.threadCount";
public static final int DEFAULT_THREAD_COUNT = 10;
private static final ThreadLocal<Executor> configTimeTaskExecutorHolder =
new ThreadLocal<Executor>();
private static final ThreadLocal<DataSource> configTimeDataSourceHolder =
new ThreadLocal<DataSource>();
private static final ThreadLocal<DataSource> configTimeNonTransactionalDataSourceHolder =
new ThreadLocal<DataSource>();
public SingularSchedulerBean(DataSource dataSource) {
Properties quartzProperties = new Properties();
quartzProperties.setProperty("org.quartz.scheduler.instanceName", "SINGULARID");
quartzProperties.setProperty("org.quartz.scheduler.instanceId", "AUTO");
if (SingularProperties.get().isTrue(SINGULAR_QUARTZ_JOBSTORE_ENABLED)) {
quartzProperties.put("org.quartz.jobStore.useProperties", "false");
quartzProperties.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
quartzProperties.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.MSSQLDelegate");
quartzProperties.put("org.quartz.jobStore.tablePrefix", "DBSINGULAR.qrtz_");
quartzProperties.put("org.quartz.jobStore.isClustered", "true");
setQuartzProperties(quartzProperties);
setDataSource(dataSource);
setOverwriteExistingJobs(true);
} else {
quartzProperties.put("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
}
}
/**
* Return the TaskExecutor for the currently configured Quartz Scheduler,
* to be used by LocalTaskExecutorThreadPool.
* <p>This instance will be set before initialization of the corresponding
* Scheduler, and reset immediately afterwards. It is thus only available
* during configuration.
*
* @see #setTaskExecutor
* @see LocalTaskExecutorThreadPool
*/
public static Executor getConfigTimeTaskExecutor() {
return configTimeTaskExecutorHolder.get();
}
/**
* Return the DataSource for the currently configured Quartz Scheduler,
* to be used by SingularLocalDataSourceJobStore.
* <p>This instance will be set before initialization of the corresponding
* Scheduler, and reset immediately afterwards. It is thus only available
* during configuration.
*
* @see #setDataSource
* @see SingularLocalDataSourceJobStore
*/
public static DataSource getConfigTimeDataSource() {
return configTimeDataSourceHolder.get();
}
/**
* Return the non-transactional DataSource for the currently configured
* Quartz Scheduler, to be used by SingularLocalDataSourceJobStore.
* <p>This instance will be set before initialization of the corresponding
* Scheduler, and reset immediately afterwards. It is thus only available
* during configuration.
*
* @see #setNonTransactionalDataSource
* @see SingularLocalDataSourceJobStore
*/
public static DataSource getConfigTimeNonTransactionalDataSource() {
return configTimeNonTransactionalDataSourceHolder.get();
}
private Class<? extends SchedulerFactory> schedulerFactoryClass = StdSchedulerFactory.class;
private String schedulerName;
private Resource configLocation;
private Properties quartzProperties;
private Executor taskExecutor;
private DataSource dataSource;
private DataSource nonTransactionalDataSource;
private Map<String, ?> schedulerContextMap;
private ApplicationContext applicationContext;
private String applicationContextSchedulerContextKey;
private JobFactory jobFactory;
private boolean jobFactorySet = false;
private int startupDelay = 0;
private int phase = Integer.MAX_VALUE;
private boolean exposeSchedulerInRepository = false;
private boolean waitForJobsToCompleteOnShutdown = false;
private Scheduler scheduler;
/**
* Set the Quartz SchedulerFactory implementation to use.
* <p>Default is {@link StdSchedulerFactory}, reading in the standard
* {@code quartz.properties} from {@code quartz.jar}.
* To use custom Quartz properties, specify the "configLocation"
* or "quartzProperties" bean property on this FactoryBean.
*
* @see org.quartz.impl.StdSchedulerFactory
* @see #setConfigLocation
* @see #setQuartzProperties
*/
public void setSchedulerFactoryClass(Class<? extends SchedulerFactory> schedulerFactoryClass) {
Assert.isAssignable(SchedulerFactory.class, schedulerFactoryClass);
this.schedulerFactoryClass = schedulerFactoryClass;
}
/**
* Set the name of the Scheduler to create via the SchedulerFactory.
* <p>If not specified, the bean name will be used as default scheduler name.
*
* @see org.quartz.SchedulerFactory#getScheduler()
* @see org.quartz.SchedulerFactory#getScheduler(String)
*/
public void setSchedulerName(String schedulerName) {
this.schedulerName = schedulerName;
}
@Override
public void setConfigLocation(ResourceBundle configLocation) {
}
/**
* Set the location of the Quartz properties config file, for example
* as classpath resource "classpath:quartz.properties".
* <p>Note: Can be omitted when all necessary properties are specified
* locally via this bean, or when relying on Quartz' default configuration.
*
* @see #setQuartzProperties
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set Quartz properties, like "org.quartz.threadPool.class".
* <p>Can be used to override values in a Quartz properties config file,
* or to specify all necessary properties locally.
*
* @see #setConfigLocation
*/
public void setQuartzProperties(Properties quartzProperties) {
this.quartzProperties = quartzProperties;
}
/**
* Set the Spring TaskExecutor to use as Quartz backend.
* Exposed as thread pool through the Quartz SPI.
* <p>Can be used to assign a JDK 1.5 ThreadPoolExecutor or a CommonJ
* WorkManager as Quartz backend, to avoid Quartz's manual thread creation.
* <p>By default, a Quartz SimpleThreadPool will be used, configured through
* the corresponding Quartz properties.
*
* @see #setQuartzProperties
* @see LocalTaskExecutorThreadPool
* @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
* @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor
*/
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Set the default DataSource to be used by the Scheduler. If set,
* this will override corresponding settings in Quartz properties.
* <p>Note: If this is set, the Quartz settings should not define
* a job store "dataSource" to avoid meaningless double configuration.
* <p>A Spring-specific subclass of Quartz' JobStoreCMT will be used.
* It is therefore strongly recommended to perform all operations on
* the Scheduler within Spring-managed (or plain JTA) transactions.
* Else, database locking will not properly work and might even break
* (e.g. if trying to obtain a lock on Oracle without a transaction).
* <p>Supports both transactional and non-transactional DataSource access.
* With a non-XA DataSource and local Spring transactions, a single DataSource
* argument is sufficient. In case of an XA DataSource and global JTA transactions,
* SchedulerFactoryBean's "nonTransactionalDataSource" property should be set,
* passing in a non-XA DataSource that will not participate in global transactions.
*
* @see #setNonTransactionalDataSource
* @see #setQuartzProperties
* @see SingularLocalDataSourceJobStore
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Set the DataSource to be used by the Scheduler <i>for non-transactional access</i>.
* <p>This is only necessary if the default DataSource is an XA DataSource that will
* always participate in transactions: A non-XA version of that DataSource should
* be specified as "nonTransactionalDataSource" in such a scenario.
* <p>This is not relevant with a local DataSource instance and Spring transactions.
* Specifying a single default DataSource as "dataSource" is sufficient there.
*
* @see #setDataSource
* @see SingularLocalDataSourceJobStore
*/
public void setNonTransactionalDataSource(DataSource nonTransactionalDataSource) {
this.nonTransactionalDataSource = nonTransactionalDataSource;
}
/**
* Register objects in the Scheduler context via a given Map.
* These objects will be available to any Job that runs in this Scheduler.
* <p>Note: When using persistent Jobs whose JobDetail will be kept in the
* database, do not put Spring-managed beans or an ApplicationContext
* reference into the JobDataMap but rather into the SchedulerContext.
*
* @param schedulerContextAsMap Map with String keys and any objects as
* values (for example Spring-managed beans)
* @see JobDetailFactoryBean#setJobDataAsMap
*/
public void setSchedulerContextAsMap(Map<String, ?> schedulerContextAsMap) {
this.schedulerContextMap = schedulerContextAsMap;
}
/**
* Set the key of an ApplicationContext reference to expose in the
* SchedulerContext, for example "applicationContext". Default is none.
* Only applicable when running in a Spring ApplicationContext.
* <p>Note: When using persistent Jobs whose JobDetail will be kept in the
* database, do not put an ApplicationContext reference into the JobDataMap
* but rather into the SchedulerContext.
* <p>In case of a QuartzJobBean, the reference will be applied to the Job
* instance as bean property. An "applicationContext" attribute will
* correspond to a "setApplicationContext" method in that scenario.
* <p>Note that BeanFactory callback interfaces like ApplicationContextAware
* are not automatically applied to Quartz Job instances, because Quartz
* itself is responsible for the lifecycle of its Jobs.
*
* @see JobDetailFactoryBean#setApplicationContextJobDataKey
* @see org.springframework.context.ApplicationContext
*/
public void setApplicationContextSchedulerContextKey(String applicationContextSchedulerContextKey) {
this.applicationContextSchedulerContextKey = applicationContextSchedulerContextKey;
}
/**
* Set the Quartz JobFactory to use for this Scheduler.
* <p>Default is Spring's {@link AdaptableJobFactory}, which supports
* {@link java.lang.Runnable} objects as well as standard Quartz
* {@link org.quartz.Job} instances. Note that this default only applies
* to a <i>local</i> Scheduler, not to a RemoteScheduler (where setting
* a custom JobFactory is not supported by Quartz).
* <p>Specify an instance of Spring's {@link SpringBeanJobFactory} here
* (typically as an inner bean definition) to automatically populate a job's
* bean properties from the specified job data map and scheduler context.
*
* @see AdaptableJobFactory
* @see SpringBeanJobFactory
*/
public void setJobFactory(JobFactory jobFactory) {
this.jobFactory = jobFactory;
this.jobFactorySet = true;
}
/**
* Set whether to automatically start the scheduler after initialization.
* <p>Default is "true"; set this to "false" to allow for manual startup.
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
/**
* Specify the phase in which this scheduler should be started and
* stopped. The startup order proceeds from lowest to highest, and
* the shutdown order is the reverse of that. By default this value
* is Integer.MAX_VALUE meaning that this scheduler starts as late
* as possible and stops as soon as possible.
*/
public void setPhase(int phase) {
this.phase = phase;
}
/**
* Set the number of seconds to wait after initialization before
* starting the scheduler asynchronously. Default is 0, meaning
* immediate synchronous startup on initialization of this bean.
* <p>Setting this to 10 or 20 seconds makes sense if no jobs
* should be run before the entire application has started up.
*/
public void setStartupDelay(int startupDelay) {
this.startupDelay = startupDelay;
}
/**
* Set whether to expose the Spring-managed {@link Scheduler} instance in the
* Quartz {@link SchedulerRepository}. Default is "false", since the Spring-managed
* Scheduler is usually exclusively intended for access within the Spring context.
* <p>Switch this flag to "true" in order to expose the Scheduler globally.
* This is not recommended unless you have an existing Spring application that
* relies on this behavior. Note that such global exposure was the accidental
* default in earlier Spring versions; this has been fixed as of Spring 2.5.6.
*/
public void setExposeSchedulerInRepository(boolean exposeSchedulerInRepository) {
this.exposeSchedulerInRepository = exposeSchedulerInRepository;
}
/**
* Set whether to wait for running jobs to complete on shutdown.
* <p>Default is "false". Switch this to "true" if you prefer
* fully completed jobs at the expense of a longer shutdown phase.
*
* @see org.quartz.Scheduler#shutdown(boolean)
*/
public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
}
public void initialize() throws SingularException {
try {
afterPropertiesSet();
} catch (Exception e) {
throw SingularException.rethrow(e.getMessage(), e);
}
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
//---------------------------------------------------------------------
// Implementation of InitializingBean interface
//---------------------------------------------------------------------
@SuppressWarnings("squid:MethodCyclomaticComplexity")
public void afterPropertiesSet() throws Exception {
if (this.dataSource == null && this.nonTransactionalDataSource != null) {
this.dataSource = this.nonTransactionalDataSource;
}
// Create SchedulerFactory instance...
SchedulerFactory schedulerFactory = BeanUtils.instantiateClass(this.schedulerFactoryClass);
initSchedulerFactory(schedulerFactory);
if (this.taskExecutor != null) {
// Make given TaskExecutor available for SchedulerFactory configuration.
configTimeTaskExecutorHolder.set(this.taskExecutor);
}
if (this.dataSource != null) {
// Make given DataSource available for SchedulerFactory configuration.
configTimeDataSourceHolder.set(this.dataSource);
}
if (this.nonTransactionalDataSource != null) {
// Make given non-transactional DataSource available for SchedulerFactory configuration.
configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
}
// Get Scheduler instance from SchedulerFactory.
try {
this.scheduler = createScheduler(schedulerFactory, this.schedulerName);
populateSchedulerContext();
if (!this.jobFactorySet && !(this.scheduler instanceof RemoteScheduler)) {
/* Use QuartzJobFactory as default for a local Scheduler, unless when
* explicitly given a null value through the "jobFactory" property.
*/
this.jobFactory = new QuartzJobFactory();
}
if (this.jobFactory != null) {
this.scheduler.setJobFactory(this.jobFactory);
}
} finally {
if (this.taskExecutor != null) {
configTimeTaskExecutorHolder.remove();
}
if (this.dataSource != null) {
configTimeDataSourceHolder.remove();
}
if (this.nonTransactionalDataSource != null) {
configTimeNonTransactionalDataSourceHolder.remove();
}
}
registerListeners();
registerJobsAndTriggers();
}
/**
* Load and/or apply Quartz properties to the given SchedulerFactory.
*
* @param schedulerFactory the SchedulerFactory to initialize
*/
private void initSchedulerFactory(SchedulerFactory schedulerFactory) throws SchedulerException, IOException {
if (!(schedulerFactory instanceof StdSchedulerFactory)) {
if (this.configLocation != null || this.quartzProperties != null ||
this.taskExecutor != null || this.dataSource != null) {
throw new IllegalArgumentException(
"StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
}
// Otherwise assume that no initialization is necessary...
return;
}
Properties mergedProps = new Properties();
if (this.taskExecutor != null) {
mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS,
LocalTaskExecutorThreadPool.class.getName());
} else {
// Set necessary default properties here, as Quartz will not apply
// its default configuration when explicitly given properties.
mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName());
mergedProps.setProperty(PROP_THREAD_COUNT, Integer.toString(DEFAULT_THREAD_COUNT));
}
if (this.configLocation != null) {
if (logger.isInfoEnabled()) {
logger.info("Loading Quartz config from [" + this.configLocation + "]");
}
PropertiesLoaderUtils.fillProperties(mergedProps, this.configLocation);
}
CollectionUtils.mergePropertiesIntoMap(this.quartzProperties, mergedProps);
if (this.dataSource != null) {
mergedProps.put(StdSchedulerFactory.PROP_JOB_STORE_CLASS, SingularLocalDataSourceJobStore.class.getName());
}
// Make sure to set the scheduler name as configured in the Spring configuration.
if (this.schedulerName != null) {
mergedProps.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, this.schedulerName);
}
((StdSchedulerFactory) schedulerFactory).initialize(mergedProps);
}
/**
* Create the Scheduler instance for the given factory and scheduler name.
* Called by {@link #afterPropertiesSet}.
* <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
* method. Can be overridden for custom Scheduler creation.
*
* @param schedulerFactory the factory to create the Scheduler with
* @param schedulerName the name of the scheduler to create
* @return the Scheduler instance
* @throws SchedulerException if thrown by Quartz methods
* @see #afterPropertiesSet
* @see org.quartz.SchedulerFactory#getScheduler
*/
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)
throws SchedulerException {
try {
SchedulerRepository repository = SchedulerRepository.getInstance();
synchronized (repository) {
Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
Scheduler newScheduler = schedulerFactory.getScheduler();
if (newScheduler == existingScheduler) {
throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " +
"in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
}
if (!this.exposeSchedulerInRepository) {
// Need to remove it in this case, since Quartz shares the Scheduler instance by default!
SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
}
return newScheduler;
}
} catch (Exception e) {
getLogger().debug(e.getMessage(), e);
throw new SchedulerException(e);
}
}
/**
* Expose the specified context attributes and/or the current
* ApplicationContext in the Quartz SchedulerContext.
*/
private void populateSchedulerContext() throws SchedulerException {
// Put specified objects into Scheduler context.
if (this.schedulerContextMap != null) {
this.scheduler.getContext().putAll(this.schedulerContextMap);
}
// Register ApplicationContext in Scheduler context.
if (this.applicationContextSchedulerContextKey != null) {
if (this.applicationContext == null) {
throw new IllegalStateException(
"SchedulerFactoryBean needs to be set up in an ApplicationContext " +
"to be able to handle an 'applicationContextSchedulerContextKey'");
}
this.scheduler.getContext().put(this.applicationContextSchedulerContextKey, this.applicationContext);
}
}
/**
* Start the Quartz Scheduler, respecting the "startupDelay" setting.
*
* @param scheduler the Scheduler to start
* @param startupDelay the number of seconds to wait before starting
* the Scheduler asynchronously
*/
protected void startScheduler(final Scheduler scheduler, final int startupDelay) throws SchedulerException {
if (startupDelay <= 0) {
logger.info("Starting Quartz Scheduler now");
scheduler.start();
} else {
if (logger.isInfoEnabled()) {
logger.info("Will start Quartz Scheduler [" + scheduler.getSchedulerName() +
"] in " + startupDelay + " seconds");
}
Thread schedulerThread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(startupDelay * 1000L);
} catch (InterruptedException ex) {
getLogger().trace(ex.getMessage(), ex);
}
if (logger.isInfoEnabled()) {
logger.info("Starting Quartz Scheduler now, after delay of " + startupDelay + " seconds");
}
try {
scheduler.start();
} catch (SchedulerException ex) {
throw new SchedulingException("Could not start Quartz Scheduler after delay", ex);
}
}
};
schedulerThread.setName("Quartz Scheduler [" + scheduler.getSchedulerName() + "]");
schedulerThread.setDaemon(true);
schedulerThread.start();
}
}
//---------------------------------------------------------------------
// Implementation of FactoryBean interface
//---------------------------------------------------------------------
@Override
public Scheduler getScheduler() {
return this.scheduler;
}
//---------------------------------------------------------------------
// Implementation of SmartLifecycle interface
//---------------------------------------------------------------------
@Override
public void start() throws SchedulingException {
if (this.scheduler != null) {
try {
startScheduler(this.scheduler, this.startupDelay);
} catch (SchedulerException ex) {
throw new SchedulingException("Could not start Quartz Scheduler", ex);
}
}
}
@Override
public void start(int startupDelay) throws SchedulerException {
}
@Override
public void stop() throws SchedulingException {
if (this.scheduler != null) {
try {
this.scheduler.standby();
} catch (SchedulerException ex) {
throw new SchedulingException("Could not stop Quartz Scheduler", ex);
}
}
}
@Override
public boolean isAutoStartup() {
return false;
}
@Override
public void stop(Runnable callback) throws SchedulingException {
stop();
callback.run();
}
@Override
public boolean isRunning() throws SchedulingException {
if (this.scheduler != null) {
try {
return !this.scheduler.isInStandbyMode();
} catch (SchedulerException ex) {
getLogger().trace(ex.getMessage(), ex);
return false;
}
}
return false;
}
//---------------------------------------------------------------------
// Implementation of DisposableBean interface
//---------------------------------------------------------------------
/**
* Shut down the Quartz scheduler on bean factory shutdown,
* stopping all scheduled jobs.
*/
@Override
public void destroy() throws SchedulerException {
logger.info("Shutting down Quartz Scheduler");
this.scheduler.shutdown(this.waitForJobsToCompleteOnShutdown);
}
// ############ SPRING CONFIGURATION ############
@Override
public void setBeanName(String name) {
if (this.schedulerName == null) {
this.schedulerName = name;
}
}
@Override
public Scheduler getObject() throws Exception {
return this.scheduler;
}
@Override
public Class<?> getObjectType() {
return (this.scheduler != null) ? this.scheduler.getClass() : Scheduler.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public int getPhase() {
return this.phase;
}
// ############ SINGULAR JOB CONFIGURATION ############
@Override
public void addJob(JobDetail jobDetail) throws SchedulerException {
addJobToScheduler(jobDetail);
}
@Override
public void addTrigger(Trigger trigger, JobDetail jobDetail) throws SchedulerException {
trigger.getJobDataMap().put(SINGULAR_JOB_DETAIL_KEY, jobDetail);
addTriggerToScheduler(trigger);
}
/**
* Add trigger and the trigger's job detail.
*
* @param trigger the trigger.
* @throws SchedulerException if could not start Quartz Scheduler.
*/
@Override
public void addTrigger(Trigger trigger) throws SchedulerException {
addJobToScheduler((JobDetail) trigger.getJobDataMap().get(SINGULAR_JOB_DETAIL_KEY));
addTriggerToScheduler(trigger);
}
/**
* Trigger the identified {@link org.quartz.JobDetail} (execute it now).
*
* @param jobKey
* @throws SchedulerException
*/
@Override
public void triggerJob(JobKey jobKey) throws SchedulerException {
getScheduler().triggerJob(jobKey);
}
@Override
public Set<JobKey> getAllJobKeys() throws SchedulerException {
return getScheduler().getJobKeys(GroupMatcher.anyGroup());
}
}
| [SGL-613] fixing compilation error
| lib/app-commons/src/main/java/org/opensingular/app/commons/mail/schedule/SingularSchedulerBean.java | [SGL-613] fixing compilation error | <ide><path>ib/app-commons/src/main/java/org/opensingular/app/commons/mail/schedule/SingularSchedulerBean.java
<ide> * Set whether to automatically start the scheduler after initialization.
<ide> * <p>Default is "true"; set this to "false" to allow for manual startup.
<ide> */
<del> public void setAutoStartup(boolean autoStartup) {
<del> this.autoStartup = autoStartup;
<del> }
<add> public void setAutoStartup(boolean autoStartup) {}
<ide>
<ide> /**
<ide> * Specify the phase in which this scheduler should be started and |
|
Java | apache-2.0 | d0188f3fc32198c165f178d6aaabab39467b54e6 | 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.config.provision;
import java.util.Set;
/**
* A deployment may have a list of tags associated with it. Config files may have variants for these tags similar
* to how they may have variants for instance and zone.
*
* @author bratseth
*/
public class Tags {
private final Set<String> tags;
public Tags(Set<String> tags) {
this.tags = Set.copyOf(tags);
}
public boolean contains(String tag) {
return tags.contains(tag);
}
public boolean intersects(Tags other) {
return this.tags.stream().anyMatch(other::contains);
}
public boolean isEmpty() { return tags.isEmpty(); }
public boolean containsAll(Tags other) { return tags.containsAll(other.tags); }
/** Returns this as a space-separated string which can be used to recreate this by calling fromString(). */
public String asString() { return String.join(" ", tags); }
@Override
public String toString() {
return asString();
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null || other.getClass() != getClass()) return false;
return tags.equals(((Tags)other).tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
public static Tags empty() { return new Tags(Set.of()); }
/**
* Creates this from a space-separated string or null. */
public static Tags fromString(String tagsString) {
if (tagsString == null || tagsString.isBlank()) return empty();
return new Tags(Set.of(tagsString.trim().split(" +")));
}
}
| config-provisioning/src/main/java/com/yahoo/config/provision/Tags.java | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
import java.util.Set;
/**
* A deployment may have a list of tags associated with it. Config files may have variants for these tags similar
* to how they may have variants for instance and zone.
*
* @author bratseth
*/
public class Tags {
private final Set<String> tags;
public Tags(Set<String> tags) {
this.tags = Set.copyOf(tags);
}
public boolean contains(String tag) {
return tags.contains(tag);
}
public boolean intersects(Tags other) {
return this.tags.stream().anyMatch(other::contains);
}
public boolean isEmpty() { return tags.isEmpty(); }
public boolean containsAll(Tags other) { return tags.containsAll(other.tags); }
/** Returns this as a space-separated string which can be used to recreate this by calling fromString(). */
public String asString() { return String.join(" ", tags); }
@Override
public String toString() {
return asString();
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null || other.getClass() != getClass()) return false;
return tags.equals(((Tags)other).tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
public static Tags empty() { return new Tags(Set.of()); }
/**
* Creates this from a space-separated string or null. */
public static Tags fromString(String tagsString) {
if (tagsString == null || tagsString.isBlank()) return empty();
return new Tags(Set.of(tagsString.trim().split(" ")));
}
}
| Update config-provisioning/src/main/java/com/yahoo/config/provision/Tags.java
Co-authored-by: Jon Marius Venstad <95e427ff401b3e1a275fa458c33470a86d910bc8@users.noreply.github.com> | config-provisioning/src/main/java/com/yahoo/config/provision/Tags.java | Update config-provisioning/src/main/java/com/yahoo/config/provision/Tags.java | <ide><path>onfig-provisioning/src/main/java/com/yahoo/config/provision/Tags.java
<ide> * Creates this from a space-separated string or null. */
<ide> public static Tags fromString(String tagsString) {
<ide> if (tagsString == null || tagsString.isBlank()) return empty();
<del> return new Tags(Set.of(tagsString.trim().split(" ")));
<add> return new Tags(Set.of(tagsString.trim().split(" +")));
<ide> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | 6b4ffc15fc164110cd3d26038e514d03949726bf | 0 | harvard-lts/fits,harvard-lts/fits | package edu.harvard.hul.ois.fits.tools.tika;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import edu.harvard.hul.ois.fits.exceptions.FitsToolException;
import edu.harvard.hul.ois.fits.tools.ToolBase;
import edu.harvard.hul.ois.fits.tools.ToolOutput;
import edu.harvard.hul.ois.fits.Fits;
import edu.harvard.hul.ois.fits.exceptions.FitsException;
import edu.harvard.hul.ois.fits.exceptions.FitsToolException;
import edu.harvard.hul.ois.fits.tools.ToolInfo;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class Tika extends ToolBase {
private final static String TOOL_NAME = "Tika";
private boolean enabled = true;
public Tika() throws FitsToolException {
info = new ToolInfo(TOOL_NAME,"1.3","");
}
public ToolOutput extractInfo(File file) throws FitsToolException {
Parser parser = new AutoDetectParser();
ContentHandler handler = null;
Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext();
FileInputStream instrm;
try {
instrm = new FileInputStream (file);
}
catch (FileNotFoundException e) {
throw new FitsToolException ("Can't open file", e);
}
try {
}
finally {
try {
instrm.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
parser.parse (instrm, handler, metadata, parseContext);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
// TODO convert the information in metadata to FITS output.
String [] propertyNames = metadata.names();
// TODO look through these values to better understand what Tika returns.
return null;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean value) {
enabled = value;
}
}
| src/edu/harvard/hul/ois/fits/tools/tika/Tika.java | package edu.harvard.hul.ois.fits.tools.tika;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import edu.harvard.hul.ois.fits.exceptions.FitsToolException;
import edu.harvard.hul.ois.fits.tools.ToolBase;
import edu.harvard.hul.ois.fits.tools.ToolOutput;
import edu.harvard.hul.ois.fits.Fits;
import edu.harvard.hul.ois.fits.exceptions.FitsException;
import edu.harvard.hul.ois.fits.exceptions.FitsToolException;
import edu.harvard.hul.ois.fits.tools.ToolInfo;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class Tika extends ToolBase {
private final static String TOOL_NAME = "Tika";
public Tika() throws FitsToolException {
// TODO Auto-generated constructor stub
info = new ToolInfo();
info.setName(TOOL_NAME);
}
public ToolOutput extractInfo(File file) throws FitsToolException {
// TODO Auto-generated method stub
Parser parser = new AutoDetectParser();
ContentHandler handler = null;
Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext();
FileInputStream instrm;
try {
instrm = new FileInputStream (file);
}
catch (FileNotFoundException e) {
throw new FitsToolException ("Can't open file", e);
}
try {
}
finally {
try {
instrm.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
parser.parse (instrm, handler, metadata, parseContext);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
// TODO convert the information in metadata to FITS output.
String [] propertyNames = metadata.names();
// TODO look through these values to better understand what Tika returns.
return null;
}
public boolean isEnabled() {
// TODO Auto-generated method stub
return false;
}
public void setEnabled(boolean value) {
// TODO Auto-generated method stub
}
}
| init tika | src/edu/harvard/hul/ois/fits/tools/tika/Tika.java | init tika | <ide><path>rc/edu/harvard/hul/ois/fits/tools/tika/Tika.java
<ide> public class Tika extends ToolBase {
<ide>
<ide> private final static String TOOL_NAME = "Tika";
<add> private boolean enabled = true;
<ide>
<ide> public Tika() throws FitsToolException {
<del> // TODO Auto-generated constructor stub
<del> info = new ToolInfo();
<del> info.setName(TOOL_NAME);
<add> info = new ToolInfo(TOOL_NAME,"1.3","");
<ide> }
<ide>
<ide> public ToolOutput extractInfo(File file) throws FitsToolException {
<del> // TODO Auto-generated method stub
<ide> Parser parser = new AutoDetectParser();
<ide> ContentHandler handler = null;
<ide> Metadata metadata = new Metadata();
<ide> return null;
<ide> }
<ide>
<del> public boolean isEnabled() {
<del> // TODO Auto-generated method stub
<del> return false;
<del> }
<add> public boolean isEnabled() {
<add> return enabled;
<add> }
<ide>
<del> public void setEnabled(boolean value) {
<del> // TODO Auto-generated method stub
<del>
<del> }
<add> public void setEnabled(boolean value) {
<add> enabled = value;
<add> }
<ide>
<ide> } |
|
Java | mit | 5877bcf47ed8adce0f10f395ba4401c1090af537 | 0 | McJty/DeepResonance,VictiniX888/DeepResonance | package mcjty.deepresonance.radiation;
import com.google.common.collect.Sets;
import elec332.core.world.WorldHelper;
import mcjty.deepresonance.blocks.ModBlocks;
import mcjty.deepresonance.items.armor.ItemRadiationSuit;
import mcjty.deepresonance.varia.QuadTree;
import mcjty.lib.varia.GlobalCoordinate;
import mcjty.lib.varia.Logging;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class RadiationTickEvent {
public static final int MAXTICKS = 10;
private int counter = MAXTICKS;
private static Random random = new Random();
private static final int EFFECTS_MAX = 18;
private int counterEffects = EFFECTS_MAX;
public static Potion harm;
public static Potion hunger;
public static Potion moveSlowdown;
public static Potion weakness;
public static Potion poison;
public static Potion wither;
@SubscribeEvent
public void onTick(TickEvent.WorldTickEvent evt) {
if (evt.phase == TickEvent.Phase.START) {
return;
}
if (evt.world.provider.getDimension() != 0) {
return;
}
counter--;
if (counter <= 0) {
counter = MAXTICKS;
counterEffects--;
boolean doEffects = false;
if (counterEffects <= 0) {
counterEffects = EFFECTS_MAX;
doEffects = true;
}
serverTick(evt.world, doEffects);
}
}
// @SubscribeEvent
// public void onServerTick(TickEvent.ServerTickEvent evt) {
// if (evt.phase == TickEvent.Phase.START) {
// return;
// }
// counter--;
// if (counter <= 0) {
// counter = MAXTICKS;
//
// counterEffects--;
// boolean doEffects = false;
// if (counterEffects <= 0) {
// counterEffects = EFFECTS_MAX;
// doEffects = true;
// }
// serverTick(doEffects);
// }
// }
private void serverTick(World entityWorld, boolean doEffects) {
// // @todo improve
// MinecraftServer server = FMLServerHandler.instance().getServer();
// if (server == null) {
// return;
// }
// World entityWorld = server.getEntityWorld();
DRRadiationManager radiationManager = DRRadiationManager.getManager(entityWorld);
Set<GlobalCoordinate> toRemove = Sets.newHashSet();
boolean dirty = false;
for (Map.Entry<GlobalCoordinate, DRRadiationManager.RadiationSource> source : radiationManager.getRadiationSources().entrySet()) {
GlobalCoordinate coordinate = source.getKey();
World world = DimensionManager.getWorld(coordinate.getDimension());
if (world != null) {
if (WorldHelper.chunkLoaded(world, coordinate.getCoordinate())) {
// The world is loaded and the chunk containing the radiation source is also loaded.
DRRadiationManager.RadiationSource radiationSource = source.getValue();
float strength = radiationSource.getStrength();
strength -= RadiationConfiguration.strengthDecreasePerTick * MAXTICKS;
dirty = true;
if (strength <= 0) {
toRemove.add(coordinate);
} else {
radiationSource.setStrength(strength);
if (doEffects) {
handleRadiationEffects(world, coordinate, radiationSource);
}
if (strength > RadiationConfiguration.radiationDestructionEventLevel && random.nextFloat() < RadiationConfiguration.destructionEventChance) {
handleDestructionEvent(world, coordinate, radiationSource);
}
}
}
}
}
if (dirty) {
for (GlobalCoordinate coordinate : toRemove) {
radiationManager.deleteRadiationSource(coordinate);
Logging.logDebug("Removed radiation source at: " + coordinate.getCoordinate().toString() + " (" + coordinate.getDimension() + ")");
}
radiationManager.save(entityWorld);
}
}
private void handleDestructionEvent(World world, GlobalCoordinate coordinate, DRRadiationManager.RadiationSource radiationSource) {
int cx = coordinate.getCoordinate().getX();
int cy = coordinate.getCoordinate().getY();
int cz = coordinate.getCoordinate().getZ();
double centerx = cx;
double centery = cy;
double centerz = cz;
double radius = radiationSource.getRadius();
double theta = random.nextDouble() * Math.PI * 2.0;
double phi = random.nextDouble() * Math.PI - Math.PI / 2.0;
double dist = random.nextDouble() * radius;
double cosphi = Math.cos(phi);
double destx = centerx + dist * Math.cos(theta) * cosphi;
double destz = centerz + dist * Math.sin(theta) * cosphi;
double desty;
if (random.nextFloat() > 0.5f) {
desty = world.getTopSolidOrLiquidBlock(new BlockPos((int) destx, world.getActualHeight(),(int) destz)).getY();
} else {
desty = centery + dist * Math.sin(phi);
}
Logging.logDebug("Destruction event at: " + destx + "," + desty + "," + destz);
float baseStrength = radiationSource.getStrength();
double distanceSq = (centerx-destx) * (centerx-destx) + (centery-desty) * (centery-desty) + (centerz-destz) * (centerz-destz);
double distance = Math.sqrt(distanceSq);
float strength = (float) (baseStrength * (radius-distance) / radius);
QuadTree radiationTree = radiationSource.getRadiationTree(world, cx, cy, cz);
strength = strength * (float) radiationTree.factor(cx, cy, cz, (int) destx, (int) desty, (int) destz);
int eventradius = 8;
int damage;
float poisonBlockChance;
float removeLeafChance;
float setOnFireChance;
if (strength > RadiationConfiguration.radiationDestructionEventLevel/2) {
// Worst destruction event
damage = 30;
poisonBlockChance = 0.9f;
removeLeafChance = 9.0f;
setOnFireChance = 0.03f;
} else if (strength > RadiationConfiguration.radiationDestructionEventLevel/3) {
// Moderate
damage = 5;
poisonBlockChance = 0.6f;
removeLeafChance = 4.0f;
setOnFireChance = 0.001f;
} else if (strength > RadiationConfiguration.radiationDestructionEventLevel/4) {
// Minor
damage = 1;
poisonBlockChance = 0.3f;
removeLeafChance = 1.2f;
setOnFireChance = 0.0f;
} else {
return;
}
List<EntityLivingBase> list = world.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(destx - eventradius, desty - eventradius, destz - eventradius, destx + eventradius, desty + eventradius, destz + eventradius), null);
for (EntityLivingBase entityLivingBase : list) {
getPotions();
entityLivingBase.addPotionEffect(new PotionEffect(harm, 10, damage));
}
BlockPos.MutableBlockPos currentPos = new BlockPos.MutableBlockPos();
for (int x = (int) (destx-eventradius); x <= destx+eventradius ; x++) {
for (int y = (int) (desty-eventradius); y <= desty+eventradius ; y++) {
for (int z = (int) (destz-eventradius); z <= destz+eventradius ; z++) {
double dSq = (x-destx) * (x-destx) + (y-desty) * (y-desty) + (z-destz) * (z-destz);
double d = Math.sqrt(dSq);
double str = (eventradius-d) / eventradius;
currentPos = currentPos.set(x, y, z);
Block block = WorldHelper.getBlockAt(world, currentPos);
if (block == Blocks.dirt || block == Blocks.farmland || block == Blocks.grass) {
if (random.nextFloat() < poisonBlockChance * str) {
WorldHelper.setBlockState(world, currentPos, ModBlocks.poisonedDirtBlock.getDefaultState(), 2);
}
} else if (block.isLeaves(world.getBlockState(currentPos), world, currentPos) || block instanceof IPlantable) {
if (random.nextFloat() < removeLeafChance * str) {
world.setBlockToAir(currentPos);
}
}
if (random.nextFloat() < setOnFireChance * str) {
// @todo temporarily disabled fire because it causes 'TickNextTick list out of synch' for some reason
// if ((!world.isAirBlock(currentPos))){
// currentPos.set(x, y+1, z);
// if(world.isAirBlock(currentPos)) {
// Logging.logDebug("Set fire at: " + x + "," + y + "," + z);
// System.out.println("RadiationTickEvent.handleDestructionEvent: FIRE");
// System.out.flush();
// WorldHelper.setBlockState(world, currentPos, Blocks.fire.getDefaultState(), 2);
// }
// }
}
}
}
}
}
private static void getPotions() {
if (harm == null) {
harm = Potion.potionRegistry.getObject(new ResourceLocation("instant_damage"));
hunger = Potion.potionRegistry.getObject(new ResourceLocation("hunger"));
moveSlowdown = Potion.potionRegistry.getObject(new ResourceLocation("slowness"));
weakness = Potion.potionRegistry.getObject(new ResourceLocation("weakness"));
poison = Potion.potionRegistry.getObject(new ResourceLocation("poison"));
wither = Potion.potionRegistry.getObject(new ResourceLocation("wither"));
}
}
private void handleRadiationEffects(World world, GlobalCoordinate coordinate, DRRadiationManager.RadiationSource radiationSource) {
int cx = coordinate.getCoordinate().getX();
int cy = coordinate.getCoordinate().getY();
int cz = coordinate.getCoordinate().getZ();
double centerx = cx;
double centery = cy;
double centerz = cz;
double radius = radiationSource.getRadius();
double radiusSq = radius * radius;
float baseStrength = radiationSource.getStrength();
List<EntityLivingBase> list = world.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(centerx - radius, centery - radius, centerz - radius, centerx + radius, centery + radius, centerz + radius), null);
for (EntityLivingBase entityLivingBase : list) {
float protection = ItemRadiationSuit.getRadiationProtection(entityLivingBase);
double distanceSq = entityLivingBase.getDistanceSq(centerx, centery, centerz);
if (distanceSq < radiusSq) {
double distance = Math.sqrt(distanceSq);
QuadTree radiationTree = radiationSource.getRadiationTree(world, cx, cy, cz);
float strength = (float) (baseStrength * (radius-distance) / radius);
strength = strength * (1.0f-protection);
strength = strength * (float) radiationTree.factor2(cx, cy, cz, (int) entityLivingBase.posX, (int) entityLivingBase.posY+1, (int) entityLivingBase.posZ);
if (strength < RadiationConfiguration.radiationEffectLevelNone) {
} else if (strength < RadiationConfiguration.radiationEffectLevel0) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 0, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel1) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel2) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel3) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel4) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(poison, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel5) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 3, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(poison, EFFECTS_MAX * MAXTICKS, 2, true, true));
} else {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 3, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(poison, EFFECTS_MAX * MAXTICKS, 3, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(wither, EFFECTS_MAX * MAXTICKS, 2, true, true));
}
}
}
}
}
| src/main/java/mcjty/deepresonance/radiation/RadiationTickEvent.java | package mcjty.deepresonance.radiation;
import com.google.common.collect.Sets;
import elec332.core.world.WorldHelper;
import mcjty.deepresonance.blocks.ModBlocks;
import mcjty.deepresonance.items.armor.ItemRadiationSuit;
import mcjty.deepresonance.varia.QuadTree;
import mcjty.lib.varia.GlobalCoordinate;
import mcjty.lib.varia.Logging;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.server.FMLServerHandler;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class RadiationTickEvent {
public static final int MAXTICKS = 10;
private int counter = MAXTICKS;
private static Random random = new Random();
private static final int EFFECTS_MAX = 18;
private int counterEffects = EFFECTS_MAX;
public static Potion harm;
public static Potion hunger;
public static Potion moveSlowdown;
public static Potion weakness;
public static Potion poison;
public static Potion wither;
@SubscribeEvent
public void onServerTick(TickEvent.ServerTickEvent evt) {
if (evt.phase == TickEvent.Phase.START) {
return;
}
counter--;
if (counter <= 0) {
counter = MAXTICKS;
counterEffects--;
boolean doEffects = false;
if (counterEffects <= 0) {
counterEffects = EFFECTS_MAX;
doEffects = true;
}
serverTick(doEffects);
}
}
private void serverTick(boolean doEffects) {
// @todo improve
MinecraftServer server = FMLServerHandler.instance().getServer();
if (server == null) {
return;
}
World entityWorld = server.getEntityWorld();
DRRadiationManager radiationManager = DRRadiationManager.getManager(entityWorld);
Set<GlobalCoordinate> toRemove = Sets.newHashSet();
boolean dirty = false;
for (Map.Entry<GlobalCoordinate, DRRadiationManager.RadiationSource> source : radiationManager.getRadiationSources().entrySet()) {
GlobalCoordinate coordinate = source.getKey();
World world = DimensionManager.getWorld(coordinate.getDimension());
if (world != null) {
if (WorldHelper.chunkLoaded(world, coordinate.getCoordinate())) {
// The world is loaded and the chunk containing the radiation source is also loaded.
DRRadiationManager.RadiationSource radiationSource = source.getValue();
float strength = radiationSource.getStrength();
strength -= RadiationConfiguration.strengthDecreasePerTick * MAXTICKS;
dirty = true;
if (strength <= 0) {
toRemove.add(coordinate);
} else {
radiationSource.setStrength(strength);
if (doEffects) {
handleRadiationEffects(world, coordinate, radiationSource);
}
if (strength > RadiationConfiguration.radiationDestructionEventLevel && random.nextFloat() < RadiationConfiguration.destructionEventChance) {
handleDestructionEvent(world, coordinate, radiationSource);
}
}
}
}
}
if (dirty) {
for (GlobalCoordinate coordinate : toRemove) {
radiationManager.deleteRadiationSource(coordinate);
Logging.logDebug("Removed radiation source at: " + coordinate.getCoordinate().toString() + " (" + coordinate.getDimension() + ")");
}
radiationManager.save(entityWorld);
}
}
private void handleDestructionEvent(World world, GlobalCoordinate coordinate, DRRadiationManager.RadiationSource radiationSource) {
int cx = coordinate.getCoordinate().getX();
int cy = coordinate.getCoordinate().getY();
int cz = coordinate.getCoordinate().getZ();
double centerx = cx;
double centery = cy;
double centerz = cz;
double radius = radiationSource.getRadius();
double theta = random.nextDouble() * Math.PI * 2.0;
double phi = random.nextDouble() * Math.PI - Math.PI / 2.0;
double dist = random.nextDouble() * radius;
double cosphi = Math.cos(phi);
double destx = centerx + dist * Math.cos(theta) * cosphi;
double destz = centerz + dist * Math.sin(theta) * cosphi;
double desty;
if (random.nextFloat() > 0.5f) {
desty = world.getTopSolidOrLiquidBlock(new BlockPos((int) destx, world.getActualHeight(),(int) destz)).getY();
} else {
desty = centery + dist * Math.sin(phi);
}
Logging.logDebug("Destruction event at: " + destx + "," + desty + "," + destz);
float baseStrength = radiationSource.getStrength();
double distanceSq = (centerx-destx) * (centerx-destx) + (centery-desty) * (centery-desty) + (centerz-destz) * (centerz-destz);
double distance = Math.sqrt(distanceSq);
float strength = (float) (baseStrength * (radius-distance) / radius);
QuadTree radiationTree = radiationSource.getRadiationTree(world, cx, cy, cz);
strength = strength * (float) radiationTree.factor(cx, cy, cz, (int) destx, (int) desty, (int) destz);
int eventradius = 8;
int damage;
float poisonBlockChance;
float removeLeafChance;
float setOnFireChance;
if (strength > RadiationConfiguration.radiationDestructionEventLevel/2) {
// Worst destruction event
damage = 30;
poisonBlockChance = 0.9f;
removeLeafChance = 9.0f;
setOnFireChance = 0.03f;
} else if (strength > RadiationConfiguration.radiationDestructionEventLevel/3) {
// Moderate
damage = 5;
poisonBlockChance = 0.6f;
removeLeafChance = 4.0f;
setOnFireChance = 0.001f;
} else if (strength > RadiationConfiguration.radiationDestructionEventLevel/4) {
// Minor
damage = 1;
poisonBlockChance = 0.3f;
removeLeafChance = 1.2f;
setOnFireChance = 0.0f;
} else {
return;
}
List<EntityLivingBase> list = world.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(destx - eventradius, desty - eventradius, destz - eventradius, destx + eventradius, desty + eventradius, destz + eventradius), null);
for (EntityLivingBase entityLivingBase : list) {
getPotions();
entityLivingBase.addPotionEffect(new PotionEffect(harm, 10, damage));
}
BlockPos.MutableBlockPos currentPos = new BlockPos.MutableBlockPos();
for (int x = (int) (destx-eventradius); x <= destx+eventradius ; x++) {
for (int y = (int) (desty-eventradius); y <= desty+eventradius ; y++) {
for (int z = (int) (destz-eventradius); z <= destz+eventradius ; z++) {
double dSq = (x-destx) * (x-destx) + (y-desty) * (y-desty) + (z-destz) * (z-destz);
double d = Math.sqrt(dSq);
double str = (eventradius-d) / eventradius;
currentPos = currentPos.set(x, y, z);
Block block = WorldHelper.getBlockAt(world, currentPos);
if (block == Blocks.dirt || block == Blocks.farmland || block == Blocks.grass) {
if (random.nextFloat() < poisonBlockChance * str) {
WorldHelper.setBlockState(world, currentPos, ModBlocks.poisonedDirtBlock.getDefaultState(), 2);
}
} else if (block.isLeaves(world.getBlockState(currentPos), world, currentPos) || block instanceof IPlantable) {
if (random.nextFloat() < removeLeafChance * str) {
world.setBlockToAir(currentPos);
}
}
if (random.nextFloat() < setOnFireChance * str) {
// @todo temporarily disabled fire because it causes 'TickNextTick list out of synch' for some reason
// if ((!world.isAirBlock(currentPos))){
// currentPos.set(x, y+1, z);
// if(world.isAirBlock(currentPos)) {
// Logging.logDebug("Set fire at: " + x + "," + y + "," + z);
// System.out.println("RadiationTickEvent.handleDestructionEvent: FIRE");
// System.out.flush();
// WorldHelper.setBlockState(world, currentPos, Blocks.fire.getDefaultState(), 2);
// }
// }
}
}
}
}
}
private static void getPotions() {
if (harm == null) {
harm = Potion.potionRegistry.getObject(new ResourceLocation("instant_damage"));
hunger = Potion.potionRegistry.getObject(new ResourceLocation("hunger"));
moveSlowdown = Potion.potionRegistry.getObject(new ResourceLocation("slowness"));
weakness = Potion.potionRegistry.getObject(new ResourceLocation("weakness"));
poison = Potion.potionRegistry.getObject(new ResourceLocation("poison"));
wither = Potion.potionRegistry.getObject(new ResourceLocation("wither"));
}
}
private void handleRadiationEffects(World world, GlobalCoordinate coordinate, DRRadiationManager.RadiationSource radiationSource) {
int cx = coordinate.getCoordinate().getX();
int cy = coordinate.getCoordinate().getY();
int cz = coordinate.getCoordinate().getZ();
double centerx = cx;
double centery = cy;
double centerz = cz;
double radius = radiationSource.getRadius();
double radiusSq = radius * radius;
float baseStrength = radiationSource.getStrength();
List<EntityLivingBase> list = world.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(centerx - radius, centery - radius, centerz - radius, centerx + radius, centery + radius, centerz + radius), null);
for (EntityLivingBase entityLivingBase : list) {
float protection = ItemRadiationSuit.getRadiationProtection(entityLivingBase);
double distanceSq = entityLivingBase.getDistanceSq(centerx, centery, centerz);
if (distanceSq < radiusSq) {
double distance = Math.sqrt(distanceSq);
QuadTree radiationTree = radiationSource.getRadiationTree(world, cx, cy, cz);
float strength = (float) (baseStrength * (radius-distance) / radius);
strength = strength * (1.0f-protection);
strength = strength * (float) radiationTree.factor2(cx, cy, cz, (int) entityLivingBase.posX, (int) entityLivingBase.posY+1, (int) entityLivingBase.posZ);
if (strength < RadiationConfiguration.radiationEffectLevelNone) {
} else if (strength < RadiationConfiguration.radiationEffectLevel0) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 0, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel1) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel2) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel3) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel4) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(poison, EFFECTS_MAX * MAXTICKS, 1, true, true));
} else if (strength < RadiationConfiguration.radiationEffectLevel5) {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 3, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(poison, EFFECTS_MAX * MAXTICKS, 2, true, true));
} else {
entityLivingBase.addPotionEffect(new PotionEffect(hunger, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(moveSlowdown, EFFECTS_MAX * MAXTICKS, 2, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(weakness, EFFECTS_MAX * MAXTICKS, 3, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(poison, EFFECTS_MAX * MAXTICKS, 3, true, true));
entityLivingBase.addPotionEffect(new PotionEffect(wither, EFFECTS_MAX * MAXTICKS, 2, true, true));
}
}
}
}
}
| Fixed the radiation tick event temporarily
| src/main/java/mcjty/deepresonance/radiation/RadiationTickEvent.java | Fixed the radiation tick event temporarily | <ide><path>rc/main/java/mcjty/deepresonance/radiation/RadiationTickEvent.java
<ide> import net.minecraft.init.Blocks;
<ide> import net.minecraft.potion.Potion;
<ide> import net.minecraft.potion.PotionEffect;
<del>import net.minecraft.server.MinecraftServer;
<ide> import net.minecraft.util.ResourceLocation;
<ide> import net.minecraft.util.math.AxisAlignedBB;
<ide> import net.minecraft.util.math.BlockPos;
<ide> import net.minecraftforge.common.IPlantable;
<ide> import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
<ide> import net.minecraftforge.fml.common.gameevent.TickEvent;
<del>import net.minecraftforge.fml.server.FMLServerHandler;
<ide>
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> public static Potion wither;
<ide>
<ide> @SubscribeEvent
<del> public void onServerTick(TickEvent.ServerTickEvent evt) {
<add> public void onTick(TickEvent.WorldTickEvent evt) {
<ide> if (evt.phase == TickEvent.Phase.START) {
<add> return;
<add> }
<add> if (evt.world.provider.getDimension() != 0) {
<ide> return;
<ide> }
<ide> counter--;
<ide> counterEffects = EFFECTS_MAX;
<ide> doEffects = true;
<ide> }
<del> serverTick(doEffects);
<del> }
<del> }
<del>
<del> private void serverTick(boolean doEffects) {
<del> // @todo improve
<del> MinecraftServer server = FMLServerHandler.instance().getServer();
<del> if (server == null) {
<del> return;
<del> }
<del> World entityWorld = server.getEntityWorld();
<add> serverTick(evt.world, doEffects);
<add> }
<add> }
<add>
<add>
<add>// @SubscribeEvent
<add>// public void onServerTick(TickEvent.ServerTickEvent evt) {
<add>// if (evt.phase == TickEvent.Phase.START) {
<add>// return;
<add>// }
<add>// counter--;
<add>// if (counter <= 0) {
<add>// counter = MAXTICKS;
<add>//
<add>// counterEffects--;
<add>// boolean doEffects = false;
<add>// if (counterEffects <= 0) {
<add>// counterEffects = EFFECTS_MAX;
<add>// doEffects = true;
<add>// }
<add>// serverTick(doEffects);
<add>// }
<add>// }
<add>
<add> private void serverTick(World entityWorld, boolean doEffects) {
<add>// // @todo improve
<add>// MinecraftServer server = FMLServerHandler.instance().getServer();
<add>// if (server == null) {
<add>// return;
<add>// }
<add>// World entityWorld = server.getEntityWorld();
<ide> DRRadiationManager radiationManager = DRRadiationManager.getManager(entityWorld);
<ide>
<ide> Set<GlobalCoordinate> toRemove = Sets.newHashSet(); |
|
Java | apache-2.0 | 7b6801ff2546f2ff10ba253971ebab98fd746166 | 0 | knowhowlab/openkeepass,cternes/openkeepass | package de.slackspace.openkeepass.domain;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.slackspace.openkeepass.parser.UUIDXmlAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Entry implements KeePassFileElement {
private static final String USER_NAME = "UserName";
private static final String NOTES = "Notes";
private static final String URL = "URL";
private static final String PASSWORD = "Password";
private static final String TITLE = "Title";
@XmlTransient
private KeePassFileElement parent;
@XmlElement(name = "UUID")
@XmlJavaTypeAdapter(UUIDXmlAdapter.class)
private String uuid;
@XmlElement(name = "String")
private List<Property> properties = new ArrayList<Property>();
@XmlElement(name = "History")
private History history;
Entry() {
}
public Entry(String uuid) {
setUuid(uuid);
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public String getTitle() {
return getValueFromProperty(TITLE);
}
public void setTitle(String title) {
setValue(false, TITLE, title);
}
public String getPassword() {
return getValueFromProperty(PASSWORD);
}
public void setPassword(String password) {
setValue(true, PASSWORD, password);
}
public String getUrl() {
return getValueFromProperty(URL);
}
public void setUrl(String url) {
setValue(false, URL, url);
}
public String getNotes() {
return getValueFromProperty(NOTES);
}
public void setNotes(String notes) {
setValue(false, NOTES, notes);
}
public String getUsername() {
return getValueFromProperty(USER_NAME);
}
public void setUsername(String username) {
setValue(false, USER_NAME, username);
}
public boolean isTitleProtected() {
return getPropertyByName(TITLE).isProtected();
}
public boolean isPasswordProtected() {
return getPropertyByName(PASSWORD).isProtected();
}
public void setParent(KeePassFileElement element) {
this.parent = element;
for (Property property : properties) {
property.setParent(this);
}
}
private void setValue(boolean isProtected, String propertyName, String propertyValue) {
Property property = getPropertyByName(propertyName);
if (property == null) {
property = new Property(propertyName, propertyValue, isProtected);
properties.add(property);
} else {
property.setValue(new PropertyValue(isProtected, propertyValue));
}
}
private String getValueFromProperty(String name) {
Property property = getPropertyByName(name);
if (property != null) {
return property.getValue();
}
return null;
}
/**
* Retrieves a property by it's name (ignores case)
*
* @param name the name of the property to find
* @return the property if found, null otherwise
*/
public Property getPropertyByName(String name) {
for (Property property : properties) {
if (property.getKey().equalsIgnoreCase(name)) {
return property;
}
}
return null;
}
public History getHistory() {
return history;
}
public void setHistory(History history) {
this.history = history;
}
@Override
public String toString() {
return "Entry [uuid=" + uuid + ", getTitle()=" + getTitle() + ", getPassword()=" + getPassword()
+ ", getUsername()=" + getUsername() + "]";
}
}
| src/main/java/de/slackspace/openkeepass/domain/Entry.java | package de.slackspace.openkeepass.domain;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.slackspace.openkeepass.parser.UUIDXmlAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Entry implements KeePassFileElement {
private static final String USER_NAME = "UserName";
private static final String NOTES = "Notes";
private static final String URL = "URL";
private static final String PASSWORD = "Password";
private static final String TITLE = "Title";
@XmlTransient
private KeePassFileElement parent;
@XmlElement(name = "UUID")
@XmlJavaTypeAdapter(UUIDXmlAdapter.class)
private String uuid;
@XmlElement(name = "String")
private List<Property> properties = new ArrayList<Property>();
@XmlElement(name = "History")
private History history;
Entry() {
}
public Entry(String uuid) {
setUuid(uuid);
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public String getTitle() {
return getValueFromProperty(TITLE);
}
public void setTitle(String title) {
setValue(TITLE, title);
}
public String getPassword() {
return getValueFromProperty(PASSWORD);
}
public void setPassword(String password) {
setValue(PASSWORD, password);
}
public String getUrl() {
return getValueFromProperty(URL);
}
public void setUrl(String url) {
setValue(URL, url);
}
public String getNotes() {
return getValueFromProperty(NOTES);
}
public void setNotes(String notes) {
setValue(NOTES, notes);
}
public String getUsername() {
return getValueFromProperty(USER_NAME);
}
public void setUsername(String username) {
setValue(USER_NAME, username);
}
public boolean isTitleProtected() {
return getPropertyByName(TITLE).isProtected();
}
public boolean isPasswordProtected() {
return getPropertyByName(PASSWORD).isProtected();
}
public void setParent(KeePassFileElement element) {
this.parent = element;
for (Property property : properties) {
property.setParent(this);
}
}
private void setValue(String propertyName, String propertyValue) {
Property property = getPropertyByName(propertyName);
if (property == null) {
property = new Property(propertyName, propertyValue, false);
properties.add(property);
} else {
property.setValue(new PropertyValue(false, propertyValue));
}
}
private String getValueFromProperty(String name) {
Property property = getPropertyByName(name);
if (property != null) {
return property.getValue();
}
return null;
}
/**
* Retrieves a property by it's name (ignores case)
*
* @param name the name of the property to find
* @return the property if found, null otherwise
*/
public Property getPropertyByName(String name) {
for (Property property : properties) {
if (property.getKey().equalsIgnoreCase(name)) {
return property;
}
}
return null;
}
public History getHistory() {
return history;
}
public void setHistory(History history) {
this.history = history;
}
@Override
public String toString() {
return "Entry [uuid=" + uuid + ", getTitle()=" + getTitle() + ", getPassword()=" + getPassword()
+ ", getUsername()=" + getUsername() + "]";
}
}
| Set protection correctly in domain entry | src/main/java/de/slackspace/openkeepass/domain/Entry.java | Set protection correctly in domain entry | <ide><path>rc/main/java/de/slackspace/openkeepass/domain/Entry.java
<ide> }
<ide>
<ide> public void setTitle(String title) {
<del> setValue(TITLE, title);
<add> setValue(false, TITLE, title);
<ide> }
<ide>
<ide> public String getPassword() {
<ide> }
<ide>
<ide> public void setPassword(String password) {
<del> setValue(PASSWORD, password);
<add> setValue(true, PASSWORD, password);
<ide> }
<ide>
<ide> public String getUrl() {
<ide> }
<ide>
<ide> public void setUrl(String url) {
<del> setValue(URL, url);
<add> setValue(false, URL, url);
<ide> }
<ide>
<ide> public String getNotes() {
<ide> }
<ide>
<ide> public void setNotes(String notes) {
<del> setValue(NOTES, notes);
<add> setValue(false, NOTES, notes);
<ide> }
<ide>
<ide> public String getUsername() {
<ide> }
<ide>
<ide> public void setUsername(String username) {
<del> setValue(USER_NAME, username);
<add> setValue(false, USER_NAME, username);
<ide> }
<ide>
<ide> public boolean isTitleProtected() {
<ide> }
<ide> }
<ide>
<del> private void setValue(String propertyName, String propertyValue) {
<add> private void setValue(boolean isProtected, String propertyName, String propertyValue) {
<ide> Property property = getPropertyByName(propertyName);
<ide> if (property == null) {
<del> property = new Property(propertyName, propertyValue, false);
<add> property = new Property(propertyName, propertyValue, isProtected);
<ide> properties.add(property);
<ide> } else {
<del> property.setValue(new PropertyValue(false, propertyValue));
<add> property.setValue(new PropertyValue(isProtected, propertyValue));
<ide> }
<ide> }
<ide> |
|
JavaScript | agpl-3.0 | f8dde0131bd0c76869972d8ad9a43526d86d42e5 | 0 | mwwscott0/WoWAnalyzer,ronaldpereira/WoWAnalyzer,FaideWW/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,FaideWW/WoWAnalyzer,mwwscott0/WoWAnalyzer,hasseboulen/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,FaideWW/WoWAnalyzer,sMteX/WoWAnalyzer,hasseboulen/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,fyruna/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,fyruna/WoWAnalyzer,ronaldpereira/WoWAnalyzer,hasseboulen/WoWAnalyzer,enragednuke/WoWAnalyzer,fyruna/WoWAnalyzer,ronaldpereira/WoWAnalyzer,enragednuke/WoWAnalyzer,enragednuke/WoWAnalyzer,yajinni/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,Juko8/WoWAnalyzer | export default `
29-08-2017 - Shadow Priest: Added Insanity Resource on the Voidform graphs. Fixed pet damage. (by hassebewlen)
26-08-2017 - Shadow Priest: Initial implementation. (by hassebewlen)
`;
| src/CHANGELOG_SHADOW_PRIEST.js | export default `
26-08-2017 - Shadow Priest: Shadow priest - Initial implementation. (by hassebewlen)
`;
| Shadow priest changelog updated.
| src/CHANGELOG_SHADOW_PRIEST.js | Shadow priest changelog updated. | <ide><path>rc/CHANGELOG_SHADOW_PRIEST.js
<ide> export default `
<del>26-08-2017 - Shadow Priest: Shadow priest - Initial implementation. (by hassebewlen)
<add>29-08-2017 - Shadow Priest: Added Insanity Resource on the Voidform graphs. Fixed pet damage. (by hassebewlen)
<add>26-08-2017 - Shadow Priest: Initial implementation. (by hassebewlen)
<ide> `;
<ide> |
|
Java | epl-1.0 | 644e3727a11635e90e153b46a535e153e885b613 | 0 | spring-projects/eclipse-integration-commons,spring-projects/eclipse-integration-commons,spring-projects/eclipse-integration-commons | // COPIED from spring-ide org.springframework.ide.eclipse.core.SpringCoreUtils
/*******************************************************************************
* Copyright (c) 2012, 2013 VMware, 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:
* VMware, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IPathVariableManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Some helper methods.
* @author Torsten Juergeleit
* @author Christian Dupuis
* @author Martin Lippert
*/
public final class SpringCoreUtils {
/**
* File name of OSGi bundle manifests
* @since 2.0.5
*/
public static String BUNDLE_MANIFEST_FILE = "MANIFEST.MF";
/**
* Folder name of OSGi bundle manifests directories
* @since 2.0.5
*/
public static String BUNDLE_MANIFEST_FOLDER = "META-INF";
/** New placeholder string for Spring 3 EL support */
public static final String EL_PLACEHOLDER_PREFIX = "#{";
/** URL file schema */
public static final String FILE_SCHEME = "file";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String PLACEHOLDER_PREFIX = "${";
public static final String PLACEHOLDER_SUFFIX = "}";
public static final String SOURCE_CONTROL_SCHEME = "sourcecontrol";
private static final String DEPLOY_PATH = "deploy-path";
private static boolean DOCUMENT_BUILDER_ERROR = false;
private static final Object DOCUMENT_BUILDER_LOCK = new Object();
private static XPathExpression EXPRESSION;
private static boolean SAX_PARSER_ERROR = false;
private static final Object SAX_PARSER_LOCK = new Object();
private static final String SOURCE_PATH = "source-path";
private static final String XPATH_EXPRESSION = "//project-modules/wb-module/wb-resource";
private static final String SPRING_BUILDER_ID = "org.springframework.ide.eclipse.core.springbuilder";
private static final String MARKER_ID = "org.springframework.ide.eclipse.core.problemmarker";
private static final String NATURE_ID = "org.springframework.ide.eclipse.core.springnature";
static {
try {
XPathFactory newInstance = XPathFactory.newInstance();
XPath xpath = newInstance.newXPath();
EXPRESSION = xpath.compile(XPATH_EXPRESSION);
}
catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
/**
* Adds given builder to specified project.
*/
public static void addProjectBuilder(IProject project, String builderID, IProgressMonitor monitor)
throws CoreException {
IProjectDescription desc = project.getDescription();
ICommand builderCommand = getProjectBuilderCommand(desc, builderID);
if (builderCommand == null) {
// Add a new build spec
ICommand command = desc.newCommand();
command.setBuilderName(builderID);
// Commit the spec change into the project
addProjectBuilderCommand(desc, command);
project.setDescription(desc, monitor);
}
}
/**
* Adds (or updates) a builder in given project description.
*/
public static void addProjectBuilderCommand(IProjectDescription description, ICommand command) throws CoreException {
ICommand[] oldCommands = description.getBuildSpec();
ICommand oldBuilderCommand = getProjectBuilderCommand(description, command.getBuilderName());
ICommand[] newCommands;
if (oldBuilderCommand == null) {
// Add given builder to the end of the builder list
newCommands = new ICommand[oldCommands.length + 1];
System.arraycopy(oldCommands, 0, newCommands, 0, oldCommands.length);
newCommands[oldCommands.length] = command;
}
else {
// Replace old builder with given new one
for (int i = 0, max = oldCommands.length; i < max; i++) {
if (oldCommands[i] == oldBuilderCommand) {
oldCommands[i] = command;
break;
}
}
newCommands = oldCommands;
}
description.setBuildSpec(newCommands);
}
/**
* Adds given nature as first nature to specified project.
*/
public static void addProjectNature(IProject project, String nature, IProgressMonitor monitor) throws CoreException {
if (project != null && nature != null) {
if (!project.hasNature(nature)) {
IProjectDescription desc = project.getDescription();
String[] oldNatures = desc.getNatureIds();
String[] newNatures = new String[oldNatures.length + 1];
newNatures[0] = nature;
if (oldNatures.length > 0) {
System.arraycopy(oldNatures, 0, newNatures, 1, oldNatures.length);
}
desc.setNatureIds(newNatures);
project.setDescription(desc, monitor);
}
}
}
/**
* Triggers a build of the given {@link IProject} instance, but only the
* Spring builder
* @param project the project to build
*/
public static void buildProject(IProject project) {
buildProject(project, SPRING_BUILDER_ID);
}
/**
* Triggers a build of the given {@link IProject} instance with a full build
* and all builders
* @param project the project to build
*/
public static void buildFullProject(IProject project) {
buildProject(project, null);
}
/**
* Triggers a build of the given {@link IProject} instance, but only the
* Spring builder
* @param project the project to build
* @param builderID the ID of the specific builder that should be executed
* on the project
* @since 3.2.0
*/
public static void buildProject(IProject project, String builderID) {
if (ResourcesPlugin.getWorkspace().isAutoBuilding()) {
scheduleBuildInBackground(project, ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(),
new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, builderID);
}
}
/**
* Creates given folder and (if necessary) all of it's parents.
*/
public static void createFolder(IFolder folder, IProgressMonitor monitor) throws CoreException {
if (!folder.exists()) {
IContainer parent = folder.getParent();
if (parent instanceof IFolder) {
createFolder((IFolder) parent, monitor);
}
folder.create(true, true, monitor);
}
}
/**
* Creates specified simple project.
*/
public static IProject createProject(String projectName, IProjectDescription description, IProgressMonitor monitor)
throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(projectName);
if (!project.exists()) {
if (description == null) {
project.create(monitor);
}
else {
project.create(description, monitor);
}
}
else {
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (!project.isOpen()) {
project.open(monitor);
}
return project;
}
/**
* Finds the first line separator used by the given text.
* @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
* or <code>null</code> if none found
* @since 2.2.2
*/
public static String findLineSeparator(char[] text) {
// find the first line separator
int length = text.length;
if (length > 0) {
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length - 1 ? text[i + 1] : ' ';
switch (currentChar) {
case '\n':
return "\n"; //$NON-NLS-1$
case '\r':
return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
// not found
return null;
}
/**
* Returns the specified adapter for the given object or <code>null</code>
* if adapter is not supported.
*/
@SuppressWarnings("unchecked")
public static <T> T getAdapter(Object object, Class<T> adapter) {
if (object != null && adapter != null) {
if (adapter.isAssignableFrom(object.getClass())) {
return (T) object;
}
if (object instanceof IAdaptable) {
return (T) ((IAdaptable) object).getAdapter(adapter);
}
}
return null;
}
public static IFile getDeploymentDescriptor(IProject project) {
if (SpringCoreUtils.hasProjectFacet(project, "jst.web")) {
IFile settingsFile = project.getFile(".settings/org.eclipse.wst.common.component");
if (settingsFile.exists()) {
try {
NodeList nodes = (NodeList) EXPRESSION
.evaluate(parseDocument(settingsFile), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
if ("/".equals(element.getAttribute(DEPLOY_PATH))) {
String path = element.getAttribute(SOURCE_PATH);
if (path != null) {
IFile deploymentDescriptor = project.getFile(new Path(path).append("WEB-INF").append(
"web.xml"));
if (deploymentDescriptor.exists()) {
return deploymentDescriptor;
}
}
}
}
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.WARNING, CorePlugin.PLUGIN_ID, 1, e.getMessage(), e));
}
}
}
return null;
}
public static DocumentBuilder getDocumentBuilder() {
try {
return getDocumentBuilderFactory().newDocumentBuilder();
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating DocumentBuilder", e));
}
return null;
}
public static DocumentBuilderFactory getDocumentBuilderFactory() {
if (!DOCUMENT_BUILDER_ERROR) {
try {
// this might fail on IBM J9; therefore trying only once and
// then falling back to
// OSGi service reference as it should be
return DocumentBuilderFactory.newInstance();
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
"Error creating DocumentBuilderFactory. Switching to OSGi service reference."));
DOCUMENT_BUILDER_ERROR = true;
}
}
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference reference = bundleContext.getServiceReference(DocumentBuilderFactory.class.getName());
if (reference != null) {
try {
synchronized (DOCUMENT_BUILDER_LOCK) {
return (DocumentBuilderFactory) bundleContext.getService(reference);
}
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"Error creating DocumentBuilderFactory", e));
}
finally {
bundleContext.ungetService(reference);
}
}
return null;
}
/**
* Returns the line separator found in the given text. If it is null, or not
* found return the line delimiter for the given project. If the project is
* null, returns the line separator for the workspace. If still null, return
* the system line separator.
* @since 2.2.2
*/
public static String getLineSeparator(String text, IProject project) {
String lineSeparator = null;
// line delimiter in given text
if (text != null && text.length() != 0) {
lineSeparator = findLineSeparator(text.toCharArray());
if (lineSeparator != null) {
return lineSeparator;
}
}
// line delimiter in project preference
IScopeContext[] scopeContext;
if (project != null) {
scopeContext = new IScopeContext[] { new ProjectScope(project) };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME,
Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null) {
return lineSeparator;
}
}
// line delimiter in workspace preference
scopeContext = new IScopeContext[] { new InstanceScope() };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR,
null, scopeContext);
if (lineSeparator != null) {
return lineSeparator;
}
// system line delimiter
return LINE_SEPARATOR;
}
/**
* Returns specified builder from given project description.
*/
public static ICommand getProjectBuilderCommand(IProjectDescription description, String builderID)
throws CoreException {
ICommand[] commands = description.getBuildSpec();
for (int i = commands.length - 1; i >= 0; i--) {
if (commands[i].getBuilderName().equals(builderID)) {
return commands[i];
}
}
return null;
}
public static IPath getProjectLocation(IProject project) {
return (project.getRawLocation() != null ? project.getRawLocation() : project.getLocation());
}
public static URI getResourceURI(IResource resource) {
if (resource != null) {
URI uri = resource.getRawLocationURI();
if (uri == null) {
uri = resource.getLocationURI();
}
if (uri != null) {
String scheme = uri.getScheme();
if (FILE_SCHEME.equalsIgnoreCase(scheme)) {
return uri;
}
else if (SOURCE_CONTROL_SCHEME.equals(scheme)) {
// special case of Rational Team Concert
IPath path = resource.getLocation();
File file = path.toFile();
if (file.exists()) {
return file.toURI();
}
}
else {
IPathVariableManager variableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
return variableManager.resolveURI(uri);
}
}
}
return null;
}
public static SAXParser getSaxParser() {
if (!SAX_PARSER_ERROR) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
return parser;
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
"Error creating SaxParserFactory. Switching to OSGI service reference."));
SAX_PARSER_ERROR = true;
}
}
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference reference = bundleContext.getServiceReference(SAXParserFactory.class.getName());
if (reference != null) {
try {
synchronized (SAX_PARSER_LOCK) {
SAXParserFactory factory = (SAXParserFactory) bundleContext.getService(reference);
return factory.newSAXParser();
}
}
catch (Exception e) {
StatusHandler
.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory", e));
}
finally {
bundleContext.ungetService(reference);
}
}
return null;
}
/**
* Returns a list of all projects with the Spring project nature.
*/
public static Set<IProject> getSpringProjects() {
Set<IProject> projects = new LinkedHashSet<IProject>();
for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
if (isSpringProject(project)) {
projects.add(project);
}
}
return projects;
}
/**
* Returns true if given resource's project has the given nature.
*/
public static boolean hasNature(IResource resource, String natureId) {
if (resource != null && resource.isAccessible()) {
IProject project = resource.getProject();
if (project != null) {
try {
return project.hasNature(natureId);
}
catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"An error occurred inspecting project nature", e));
}
}
}
return false;
}
/**
* Returns <code>true</code> if given text contains a placeholder, e.g.
* <code>${beansRef}</code> .
*/
public static boolean hasPlaceHolder(String text) {
if (text == null || StringUtils.isBlank(text)) {
return false;
}
int pos = text.indexOf(PLACEHOLDER_PREFIX);
int elPos = text.indexOf(EL_PLACEHOLDER_PREFIX);
return ((pos != -1 || elPos != -1) && text.indexOf(PLACEHOLDER_SUFFIX, pos) != -1);
}
public static boolean hasProjectFacet(IResource resource, String facetId) {
if (resource != null && resource.isAccessible()) {
try {
return JdtUtils.isJavaProject(resource)
&& FacetedProjectFramework.hasProjectFacet(resource.getProject(), facetId);
}
catch (CoreException e) {
// TODO CD handle exception
}
}
return false;
}
/**
* Returns true if Eclipse's runtime bundle has the same or a newer than
* given version.
*/
public static boolean isEclipseSameOrNewer(int majorVersion, int minorVersion) {
Bundle bundle = Platform.getBundle(Platform.PI_RUNTIME);
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION);
try {
Version version = new Version(versionString);
int major = version.getMajor();
if (major > majorVersion) {
return true;
}
if (major == majorVersion) {
int minor = version.getMinor();
if (minor >= minorVersion) {
return true;
}
}
}
catch (IllegalArgumentException e) {
// ignore this exception as this can't occur in pratice
}
}
return false;
}
/**
* Checks if the given {@link IResource} is a OSGi bundle manifest.
* <p>
* Note: only the name and last segment of the folder name are checked.
* @since 2.0.5
*/
public static boolean isManifest(IResource resource) {
// check if it is a MANIFEST.MF file in META-INF
if (resource != null
// && resource.isAccessible()
&& resource.getType() == IResource.FILE && resource.getName().equals(BUNDLE_MANIFEST_FILE)
&& resource.getParent() != null && resource.getParent().getProjectRelativePath() != null
&& resource.getParent().getProjectRelativePath().lastSegment() != null
&& resource.getParent().getProjectRelativePath().lastSegment().equals(BUNDLE_MANIFEST_FOLDER)) {
// check if the manifest is not in an output folder
IPath filePath = resource.getFullPath();
IJavaProject javaProject = JdtUtils.getJavaProject(resource);
if (javaProject != null) {
try {
IPath defaultOutputLocation = javaProject.getOutputLocation();
if (defaultOutputLocation != null && defaultOutputLocation.isPrefixOf(filePath)) {
return false;
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath outputLocation = entry.getOutputLocation();
if (outputLocation != null && outputLocation.isPrefixOf(filePath)) {
return false;
}
}
}
}
catch (JavaModelException e) {
// don't care here
}
return true;
}
else {
// if the project is not a java project -> it is the manifest
return true;
}
}
return false;
}
/**
* Returns true if given resource's project is a Spring project.
*/
public static boolean isSpringProject(IResource resource) {
return hasNature(resource, NATURE_ID);
}
/**
* Returns true if Eclipse's runtime bundle has the same or a newer than
* given version.
*/
public static boolean isVersionSameOrNewer(String versionString, int majorVersion, int minorVersion,
int microVersion) {
return new Version(versionString).compareTo(new Version(majorVersion, minorVersion, microVersion)) >= 0;
}
public static Document parseDocument(IFile deploymentDescriptor) {
try {
if (getResourceURI(deploymentDescriptor) != null) {
return parseDocument(getResourceURI(deploymentDescriptor));
}
return getDocumentBuilder().parse(new InputSource(deploymentDescriptor.getContents()));
}
catch (SAXException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
catch (CoreException e) {
throw new RuntimeException(e);
}
}
public static Document parseDocument(URI deploymentDescriptor) {
try {
return getDocumentBuilder().parse(deploymentDescriptor.toString());
}
catch (SAXException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Removes given builder from specified project.
*/
public static void removeProjectBuilder(IProject project, String builderID, IProgressMonitor monitor)
throws CoreException {
if (project != null && builderID != null) {
IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
for (int i = commands.length - 1; i >= 0; i--) {
if (commands[i].getBuilderName().equals(builderID)) {
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy(commands, 0, newCommands, 0, i);
System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
// Commit the spec change into the project
desc.setBuildSpec(newCommands);
project.setDescription(desc, monitor);
break;
}
}
}
}
/**
* Removes given nature from specified project.
*/
public static void removeProjectNature(IProject project, String nature, IProgressMonitor monitor)
throws CoreException {
if (project != null && nature != null) {
if (project.exists() && project.hasNature(nature)) {
// first remove all problem markers (including the
// inherited ones) from Spring beans project
if (nature.equals(NATURE_ID)) {
project.deleteMarkers(MARKER_ID, true, IResource.DEPTH_INFINITE);
}
// now remove project nature
IProjectDescription desc = project.getDescription();
String[] oldNatures = desc.getNatureIds();
String[] newNatures = new String[oldNatures.length - 1];
int newIndex = oldNatures.length - 2;
for (int i = oldNatures.length - 1; i >= 0; i--) {
if (!oldNatures[i].equals(nature)) {
newNatures[newIndex--] = oldNatures[i];
}
}
desc.setNatureIds(newNatures);
project.setDescription(desc, monitor);
}
}
}
/**
* Verify that file can safely be modified; eventually checkout the file
* from source code control.
* @return <code>true</code> if resource can be modified
* @since 2.2.9
*/
public static boolean validateEdit(IFile... files) {
for (IFile file : files) {
if (!file.exists()) {
return false;
}
}
IStatus status = ResourcesPlugin.getWorkspace().validateEdit(files, IWorkspace.VALIDATE_PROMPT);
if (status.isOK()) {
return true;
}
return false;
}
private static void scheduleBuildInBackground(final IProject project, ISchedulingRule rule,
final Object[] jobFamilies, final String builderID) {
Job job = new Job("Building workspace") {
@Override
public boolean belongsTo(Object family) {
if (jobFamilies == null || family == null) {
return false;
}
for (Object jobFamilie : jobFamilies) {
if (family.equals(jobFamilie)) {
return true;
}
}
return false;
}
@Override
public IStatus run(IProgressMonitor monitor) {
try {
if (builderID != null) {
project.build(IncrementalProjectBuilder.FULL_BUILD, builderID, null, monitor);
}
else {
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
}
return Status.OK_STATUS;
}
catch (CoreException e) {
return new Status(Status.ERROR, CorePlugin.PLUGIN_ID, 1, "Error during build of project ["
+ project.getName() + "]", e);
}
}
};
if (rule != null) {
job.setRule(rule);
}
job.setPriority(Job.BUILD);
job.schedule();
}
}
| org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/SpringCoreUtils.java | // COPIED from spring-ide org.springframework.ide.eclipse.core.SpringCoreUtils
/*******************************************************************************
* Copyright (c) 2012 VMware, 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:
* VMware, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IPathVariableManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Some helper methods.
* @author Torsten Juergeleit
* @author Christian Dupuis
* @author Martin Lippert
*/
public final class SpringCoreUtils {
/**
* File name of OSGi bundle manifests
* @since 2.0.5
*/
public static String BUNDLE_MANIFEST_FILE = "MANIFEST.MF";
/**
* Folder name of OSGi bundle manifests directories
* @since 2.0.5
*/
public static String BUNDLE_MANIFEST_FOLDER = "META-INF";
/** New placeholder string for Spring 3 EL support */
public static final String EL_PLACEHOLDER_PREFIX = "#{";
/** URL file schema */
public static final String FILE_SCHEME = "file";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String PLACEHOLDER_PREFIX = "${";
public static final String PLACEHOLDER_SUFFIX = "}";
public static final String SOURCE_CONTROL_SCHEME = "sourcecontrol";
private static final String DEPLOY_PATH = "deploy-path";
private static boolean DOCUMENT_BUILDER_ERROR = false;
private static final Object DOCUMENT_BUILDER_LOCK = new Object();
private static XPathExpression EXPRESSION;
private static boolean SAX_PARSER_ERROR = false;
private static final Object SAX_PARSER_LOCK = new Object();
private static final String SOURCE_PATH = "source-path";
private static final String XPATH_EXPRESSION = "//project-modules/wb-module/wb-resource";
private static final String BUILDER_ID = "org.springframework.ide.eclipse.core.springbuilder";
private static final String MARKER_ID = "org.springframework.ide.eclipse.core.problemmarker";
private static final String NATURE_ID = "org.springframework.ide.eclipse.core.springnature";
static {
try {
XPathFactory newInstance = XPathFactory.newInstance();
XPath xpath = newInstance.newXPath();
EXPRESSION = xpath.compile(XPATH_EXPRESSION);
}
catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
/**
* Adds given builder to specified project.
*/
public static void addProjectBuilder(IProject project, String builderID, IProgressMonitor monitor)
throws CoreException {
IProjectDescription desc = project.getDescription();
ICommand builderCommand = getProjectBuilderCommand(desc, builderID);
if (builderCommand == null) {
// Add a new build spec
ICommand command = desc.newCommand();
command.setBuilderName(builderID);
// Commit the spec change into the project
addProjectBuilderCommand(desc, command);
project.setDescription(desc, monitor);
}
}
/**
* Adds (or updates) a builder in given project description.
*/
public static void addProjectBuilderCommand(IProjectDescription description, ICommand command) throws CoreException {
ICommand[] oldCommands = description.getBuildSpec();
ICommand oldBuilderCommand = getProjectBuilderCommand(description, command.getBuilderName());
ICommand[] newCommands;
if (oldBuilderCommand == null) {
// Add given builder to the end of the builder list
newCommands = new ICommand[oldCommands.length + 1];
System.arraycopy(oldCommands, 0, newCommands, 0, oldCommands.length);
newCommands[oldCommands.length] = command;
}
else {
// Replace old builder with given new one
for (int i = 0, max = oldCommands.length; i < max; i++) {
if (oldCommands[i] == oldBuilderCommand) {
oldCommands[i] = command;
break;
}
}
newCommands = oldCommands;
}
description.setBuildSpec(newCommands);
}
/**
* Adds given nature as first nature to specified project.
*/
public static void addProjectNature(IProject project, String nature, IProgressMonitor monitor) throws CoreException {
if (project != null && nature != null) {
if (!project.hasNature(nature)) {
IProjectDescription desc = project.getDescription();
String[] oldNatures = desc.getNatureIds();
String[] newNatures = new String[oldNatures.length + 1];
newNatures[0] = nature;
if (oldNatures.length > 0) {
System.arraycopy(oldNatures, 0, newNatures, 1, oldNatures.length);
}
desc.setNatureIds(newNatures);
project.setDescription(desc, monitor);
}
}
}
/**
* Triggers a build of the given {@link IProject} instance, but only the
* Spring builder
* @param project the project to build
*/
public static void buildProject(IProject project) {
if (ResourcesPlugin.getWorkspace().isAutoBuilding()) {
scheduleBuildInBackground(project, ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(),
new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, true);
}
}
/**
* Triggers a build of the given {@link IProject} instance with a full build
* and all builders
* @param project the project to build
*/
public static void buildFullProject(IProject project) {
if (ResourcesPlugin.getWorkspace().isAutoBuilding()) {
scheduleBuildInBackground(project, ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(),
new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, false);
}
}
/**
* Creates given folder and (if necessary) all of it's parents.
*/
public static void createFolder(IFolder folder, IProgressMonitor monitor) throws CoreException {
if (!folder.exists()) {
IContainer parent = folder.getParent();
if (parent instanceof IFolder) {
createFolder((IFolder) parent, monitor);
}
folder.create(true, true, monitor);
}
}
/**
* Creates specified simple project.
*/
public static IProject createProject(String projectName, IProjectDescription description, IProgressMonitor monitor)
throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(projectName);
if (!project.exists()) {
if (description == null) {
project.create(monitor);
}
else {
project.create(description, monitor);
}
}
else {
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (!project.isOpen()) {
project.open(monitor);
}
return project;
}
/**
* Finds the first line separator used by the given text.
* @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
* or <code>null</code> if none found
* @since 2.2.2
*/
public static String findLineSeparator(char[] text) {
// find the first line separator
int length = text.length;
if (length > 0) {
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length - 1 ? text[i + 1] : ' ';
switch (currentChar) {
case '\n':
return "\n"; //$NON-NLS-1$
case '\r':
return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
// not found
return null;
}
/**
* Returns the specified adapter for the given object or <code>null</code>
* if adapter is not supported.
*/
@SuppressWarnings("unchecked")
public static <T> T getAdapter(Object object, Class<T> adapter) {
if (object != null && adapter != null) {
if (adapter.isAssignableFrom(object.getClass())) {
return (T) object;
}
if (object instanceof IAdaptable) {
return (T) ((IAdaptable) object).getAdapter(adapter);
}
}
return null;
}
public static IFile getDeploymentDescriptor(IProject project) {
if (SpringCoreUtils.hasProjectFacet(project, "jst.web")) {
IFile settingsFile = project.getFile(".settings/org.eclipse.wst.common.component");
if (settingsFile.exists()) {
try {
NodeList nodes = (NodeList) EXPRESSION
.evaluate(parseDocument(settingsFile), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
if ("/".equals(element.getAttribute(DEPLOY_PATH))) {
String path = element.getAttribute(SOURCE_PATH);
if (path != null) {
IFile deploymentDescriptor = project.getFile(new Path(path).append("WEB-INF").append(
"web.xml"));
if (deploymentDescriptor.exists()) {
return deploymentDescriptor;
}
}
}
}
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.WARNING, CorePlugin.PLUGIN_ID, 1, e.getMessage(), e));
}
}
}
return null;
}
public static DocumentBuilder getDocumentBuilder() {
try {
return getDocumentBuilderFactory().newDocumentBuilder();
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating DocumentBuilder", e));
}
return null;
}
public static DocumentBuilderFactory getDocumentBuilderFactory() {
if (!DOCUMENT_BUILDER_ERROR) {
try {
// this might fail on IBM J9; therefore trying only once and
// then falling back to
// OSGi service reference as it should be
return DocumentBuilderFactory.newInstance();
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
"Error creating DocumentBuilderFactory. Switching to OSGi service reference."));
DOCUMENT_BUILDER_ERROR = true;
}
}
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference reference = bundleContext.getServiceReference(DocumentBuilderFactory.class.getName());
if (reference != null) {
try {
synchronized (DOCUMENT_BUILDER_LOCK) {
return (DocumentBuilderFactory) bundleContext.getService(reference);
}
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"Error creating DocumentBuilderFactory", e));
}
finally {
bundleContext.ungetService(reference);
}
}
return null;
}
/**
* Returns the line separator found in the given text. If it is null, or not
* found return the line delimiter for the given project. If the project is
* null, returns the line separator for the workspace. If still null, return
* the system line separator.
* @since 2.2.2
*/
public static String getLineSeparator(String text, IProject project) {
String lineSeparator = null;
// line delimiter in given text
if (text != null && text.length() != 0) {
lineSeparator = findLineSeparator(text.toCharArray());
if (lineSeparator != null) {
return lineSeparator;
}
}
// line delimiter in project preference
IScopeContext[] scopeContext;
if (project != null) {
scopeContext = new IScopeContext[] { new ProjectScope(project) };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME,
Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null) {
return lineSeparator;
}
}
// line delimiter in workspace preference
scopeContext = new IScopeContext[] { new InstanceScope() };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR,
null, scopeContext);
if (lineSeparator != null) {
return lineSeparator;
}
// system line delimiter
return LINE_SEPARATOR;
}
/**
* Returns specified builder from given project description.
*/
public static ICommand getProjectBuilderCommand(IProjectDescription description, String builderID)
throws CoreException {
ICommand[] commands = description.getBuildSpec();
for (int i = commands.length - 1; i >= 0; i--) {
if (commands[i].getBuilderName().equals(builderID)) {
return commands[i];
}
}
return null;
}
public static IPath getProjectLocation(IProject project) {
return (project.getRawLocation() != null ? project.getRawLocation() : project.getLocation());
}
public static URI getResourceURI(IResource resource) {
if (resource != null) {
URI uri = resource.getRawLocationURI();
if (uri == null) {
uri = resource.getLocationURI();
}
if (uri != null) {
String scheme = uri.getScheme();
if (FILE_SCHEME.equalsIgnoreCase(scheme)) {
return uri;
}
else if (SOURCE_CONTROL_SCHEME.equals(scheme)) {
// special case of Rational Team Concert
IPath path = resource.getLocation();
File file = path.toFile();
if (file.exists()) {
return file.toURI();
}
}
else {
IPathVariableManager variableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
return variableManager.resolveURI(uri);
}
}
}
return null;
}
public static SAXParser getSaxParser() {
if (!SAX_PARSER_ERROR) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
return parser;
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
"Error creating SaxParserFactory. Switching to OSGI service reference."));
SAX_PARSER_ERROR = true;
}
}
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference reference = bundleContext.getServiceReference(SAXParserFactory.class.getName());
if (reference != null) {
try {
synchronized (SAX_PARSER_LOCK) {
SAXParserFactory factory = (SAXParserFactory) bundleContext.getService(reference);
return factory.newSAXParser();
}
}
catch (Exception e) {
StatusHandler
.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory", e));
}
finally {
bundleContext.ungetService(reference);
}
}
return null;
}
/**
* Returns a list of all projects with the Spring project nature.
*/
public static Set<IProject> getSpringProjects() {
Set<IProject> projects = new LinkedHashSet<IProject>();
for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
if (isSpringProject(project)) {
projects.add(project);
}
}
return projects;
}
/**
* Returns true if given resource's project has the given nature.
*/
public static boolean hasNature(IResource resource, String natureId) {
if (resource != null && resource.isAccessible()) {
IProject project = resource.getProject();
if (project != null) {
try {
return project.hasNature(natureId);
}
catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"An error occurred inspecting project nature", e));
}
}
}
return false;
}
/**
* Returns <code>true</code> if given text contains a placeholder, e.g.
* <code>${beansRef}</code> .
*/
public static boolean hasPlaceHolder(String text) {
if (text == null || StringUtils.isBlank(text)) {
return false;
}
int pos = text.indexOf(PLACEHOLDER_PREFIX);
int elPos = text.indexOf(EL_PLACEHOLDER_PREFIX);
return ((pos != -1 || elPos != -1) && text.indexOf(PLACEHOLDER_SUFFIX, pos) != -1);
}
public static boolean hasProjectFacet(IResource resource, String facetId) {
if (resource != null && resource.isAccessible()) {
try {
return JdtUtils.isJavaProject(resource)
&& FacetedProjectFramework.hasProjectFacet(resource.getProject(), facetId);
}
catch (CoreException e) {
// TODO CD handle exception
}
}
return false;
}
/**
* Returns true if Eclipse's runtime bundle has the same or a newer than
* given version.
*/
public static boolean isEclipseSameOrNewer(int majorVersion, int minorVersion) {
Bundle bundle = Platform.getBundle(Platform.PI_RUNTIME);
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION);
try {
Version version = new Version(versionString);
int major = version.getMajor();
if (major > majorVersion) {
return true;
}
if (major == majorVersion) {
int minor = version.getMinor();
if (minor >= minorVersion) {
return true;
}
}
}
catch (IllegalArgumentException e) {
// ignore this exception as this can't occur in pratice
}
}
return false;
}
/**
* Checks if the given {@link IResource} is a OSGi bundle manifest.
* <p>
* Note: only the name and last segment of the folder name are checked.
* @since 2.0.5
*/
public static boolean isManifest(IResource resource) {
// check if it is a MANIFEST.MF file in META-INF
if (resource != null
// && resource.isAccessible()
&& resource.getType() == IResource.FILE && resource.getName().equals(BUNDLE_MANIFEST_FILE)
&& resource.getParent() != null && resource.getParent().getProjectRelativePath() != null
&& resource.getParent().getProjectRelativePath().lastSegment() != null
&& resource.getParent().getProjectRelativePath().lastSegment().equals(BUNDLE_MANIFEST_FOLDER)) {
// check if the manifest is not in an output folder
IPath filePath = resource.getFullPath();
IJavaProject javaProject = JdtUtils.getJavaProject(resource);
if (javaProject != null) {
try {
IPath defaultOutputLocation = javaProject.getOutputLocation();
if (defaultOutputLocation != null && defaultOutputLocation.isPrefixOf(filePath)) {
return false;
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath outputLocation = entry.getOutputLocation();
if (outputLocation != null && outputLocation.isPrefixOf(filePath)) {
return false;
}
}
}
}
catch (JavaModelException e) {
// don't care here
}
return true;
}
else {
// if the project is not a java project -> it is the manifest
return true;
}
}
return false;
}
/**
* Returns true if given resource's project is a Spring project.
*/
public static boolean isSpringProject(IResource resource) {
return hasNature(resource, NATURE_ID);
}
/**
* Returns true if Eclipse's runtime bundle has the same or a newer than
* given version.
*/
public static boolean isVersionSameOrNewer(String versionString, int majorVersion, int minorVersion,
int microVersion) {
return new Version(versionString).compareTo(new Version(majorVersion, minorVersion, microVersion)) >= 0;
}
public static Document parseDocument(IFile deploymentDescriptor) {
try {
if (getResourceURI(deploymentDescriptor) != null) {
return parseDocument(getResourceURI(deploymentDescriptor));
}
return getDocumentBuilder().parse(new InputSource(deploymentDescriptor.getContents()));
}
catch (SAXException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
catch (CoreException e) {
throw new RuntimeException(e);
}
}
public static Document parseDocument(URI deploymentDescriptor) {
try {
return getDocumentBuilder().parse(deploymentDescriptor.toString());
}
catch (SAXException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Removes given builder from specified project.
*/
public static void removeProjectBuilder(IProject project, String builderID, IProgressMonitor monitor)
throws CoreException {
if (project != null && builderID != null) {
IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
for (int i = commands.length - 1; i >= 0; i--) {
if (commands[i].getBuilderName().equals(builderID)) {
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy(commands, 0, newCommands, 0, i);
System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
// Commit the spec change into the project
desc.setBuildSpec(newCommands);
project.setDescription(desc, monitor);
break;
}
}
}
}
/**
* Removes given nature from specified project.
*/
public static void removeProjectNature(IProject project, String nature, IProgressMonitor monitor)
throws CoreException {
if (project != null && nature != null) {
if (project.exists() && project.hasNature(nature)) {
// first remove all problem markers (including the
// inherited ones) from Spring beans project
if (nature.equals(NATURE_ID)) {
project.deleteMarkers(MARKER_ID, true, IResource.DEPTH_INFINITE);
}
// now remove project nature
IProjectDescription desc = project.getDescription();
String[] oldNatures = desc.getNatureIds();
String[] newNatures = new String[oldNatures.length - 1];
int newIndex = oldNatures.length - 2;
for (int i = oldNatures.length - 1; i >= 0; i--) {
if (!oldNatures[i].equals(nature)) {
newNatures[newIndex--] = oldNatures[i];
}
}
desc.setNatureIds(newNatures);
project.setDescription(desc, monitor);
}
}
}
/**
* Verify that file can safely be modified; eventually checkout the file
* from source code control.
* @return <code>true</code> if resource can be modified
* @since 2.2.9
*/
public static boolean validateEdit(IFile... files) {
for (IFile file : files) {
if (!file.exists()) {
return false;
}
}
IStatus status = ResourcesPlugin.getWorkspace().validateEdit(files, IWorkspace.VALIDATE_PROMPT);
if (status.isOK()) {
return true;
}
return false;
}
private static void scheduleBuildInBackground(final IProject project, ISchedulingRule rule,
final Object[] jobFamilies, final boolean springBuilderOnly) {
Job job = new Job("Building workspace") {
@Override
public boolean belongsTo(Object family) {
if (jobFamilies == null || family == null) {
return false;
}
for (Object jobFamilie : jobFamilies) {
if (family.equals(jobFamilie)) {
return true;
}
}
return false;
}
@Override
public IStatus run(IProgressMonitor monitor) {
try {
if (springBuilderOnly) {
project.build(IncrementalProjectBuilder.FULL_BUILD, BUILDER_ID, null, monitor);
}
else {
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
}
return Status.OK_STATUS;
}
catch (CoreException e) {
return new Status(Status.ERROR, CorePlugin.PLUGIN_ID, 1, "Error during build of project ["
+ project.getName() + "]", e);
}
}
};
if (rule != null) {
job.setRule(rule);
}
job.setPriority(Job.BUILD);
job.schedule();
}
}
| STS-2502: fixed the way additional validation builds are triggered in case of a change on the project classpath (these are the required changes that are used inside spring-ide)
| org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/SpringCoreUtils.java | STS-2502: fixed the way additional validation builds are triggered in case of a change on the project classpath (these are the required changes that are used inside spring-ide) | <ide><path>rg.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/SpringCoreUtils.java
<ide> // COPIED from spring-ide org.springframework.ide.eclipse.core.SpringCoreUtils
<ide> /*******************************************************************************
<del> * Copyright (c) 2012 VMware, Inc.
<add> * Copyright (c) 2012, 2013 VMware, Inc.
<ide> * All rights reserved. This program and the accompanying materials
<ide> * are made available under the terms of the Eclipse Public License v1.0
<ide> * which accompanies this distribution, and is available at
<ide> import org.xml.sax.InputSource;
<ide> import org.xml.sax.SAXException;
<ide>
<del>
<ide> /**
<ide> * Some helper methods.
<ide> * @author Torsten Juergeleit
<ide>
<ide> private static final String XPATH_EXPRESSION = "//project-modules/wb-module/wb-resource";
<ide>
<del> private static final String BUILDER_ID = "org.springframework.ide.eclipse.core.springbuilder";
<add> private static final String SPRING_BUILDER_ID = "org.springframework.ide.eclipse.core.springbuilder";
<ide>
<ide> private static final String MARKER_ID = "org.springframework.ide.eclipse.core.problemmarker";
<ide>
<ide> * @param project the project to build
<ide> */
<ide> public static void buildProject(IProject project) {
<del> if (ResourcesPlugin.getWorkspace().isAutoBuilding()) {
<del> scheduleBuildInBackground(project, ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(),
<del> new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, true);
<del> }
<add> buildProject(project, SPRING_BUILDER_ID);
<ide> }
<ide>
<ide> /**
<ide> * @param project the project to build
<ide> */
<ide> public static void buildFullProject(IProject project) {
<add> buildProject(project, null);
<add> }
<add>
<add> /**
<add> * Triggers a build of the given {@link IProject} instance, but only the
<add> * Spring builder
<add> * @param project the project to build
<add> * @param builderID the ID of the specific builder that should be executed
<add> * on the project
<add> * @since 3.2.0
<add> */
<add> public static void buildProject(IProject project, String builderID) {
<ide> if (ResourcesPlugin.getWorkspace().isAutoBuilding()) {
<ide> scheduleBuildInBackground(project, ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(),
<del> new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, false);
<add> new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, builderID);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> private static void scheduleBuildInBackground(final IProject project, ISchedulingRule rule,
<del> final Object[] jobFamilies, final boolean springBuilderOnly) {
<add> final Object[] jobFamilies, final String builderID) {
<ide> Job job = new Job("Building workspace") {
<ide>
<ide> @Override
<ide> @Override
<ide> public IStatus run(IProgressMonitor monitor) {
<ide> try {
<del> if (springBuilderOnly) {
<del> project.build(IncrementalProjectBuilder.FULL_BUILD, BUILDER_ID, null, monitor);
<add> if (builderID != null) {
<add> project.build(IncrementalProjectBuilder.FULL_BUILD, builderID, null, monitor);
<ide> }
<ide> else {
<ide> project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); |
|
Java | apache-2.0 | 9915508b9c054dbedd16b5a66930d7f8b643b2e2 | 0 | ymn/lorsource,bodqhrohro/lorsource,kloun/lorsource,maxcom/lorsource,hizel/lorsource,maxcom/lorsource,hizel/lorsource,fat0troll/lorsource,ymn/lorsource,fat0troll/lorsource,hizel/lorsource,maxcom/lorsource,ymn/lorsource,hizel/lorsource,kloun/lorsource,kloun/lorsource,bodqhrohro/lorsource,fat0troll/lorsource,maxcom/lorsource,kloun/lorsource,ymn/lorsource,bodqhrohro/lorsource,fat0troll/lorsource | package ru.org.linux.group;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.org.linux.section.Section;
import ru.org.linux.section.SectionService;
import ru.org.linux.topic.PreparedTopic;
import ru.org.linux.topic.Topic;
import ru.org.linux.topic.TopicPermissionService;
import ru.org.linux.user.User;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
@Service
public class GroupPermissionService {
private static final int EDIT_SELF_ALWAYS_SCORE = 300;
private static final int EDIT_PERIOD = 2 * 60 * 60 * 1000; // milliseconds
private SectionService sectionService;
@Autowired
public void setSectionService(SectionService sectionService) {
this.sectionService = sectionService;
}
private int getEffectivePostscore(@Nonnull Group group) {
Section section = sectionService.getSection(group.getSectionId());
return Math.max(group.getTopicRestriction(), section.getTopicsRestriction());
}
public boolean isTopicPostingAllowed(@Nonnull Group group, @Nullable User currentUser) {
int restriction = getEffectivePostscore(group);
if (restriction == TopicPermissionService.POSTSCORE_UNRESTRICTED) {
return true;
}
if (currentUser==null || currentUser.isAnonymous()) {
return false;
}
if (currentUser.isBlocked()) {
return false;
}
if (restriction==TopicPermissionService.POSTSCORE_MODERATORS_ONLY) {
return currentUser.isModerator();
} else {
return currentUser.getScore() >= restriction;
}
}
public boolean isImagePostingAllowed(@Nonnull Section section, @Nullable User currentUser) {
if (section.isImagepost()) {
return true;
}
if (currentUser!=null && currentUser.isAdministrator()) {
return section.isImageAllowed();
}
return false;
}
public String getPostScoreInfo(Group group) {
int postscore = getEffectivePostscore(group);
switch (postscore) {
case TopicPermissionService.POSTSCORE_UNRESTRICTED:
return "";
case 100:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(100, 100);
case 200:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(200, 200);
case 300:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(300, 300);
case 400:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(400, 400);
case 500:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(500, 500);
case TopicPermissionService.POSTSCORE_MODERATORS_ONLY:
return "<b>Ограничение на добавление сообщений</b>: только для модераторов";
case TopicPermissionService.POSTSCORE_REGISTERED_ONLY:
return "<b>Ограничение на добавление сообщений</b>: только для зарегистрированных пользователей";
default:
return "<b>Ограничение на добавление сообщений</b>: только для зарегистрированных пользователей, score>=" + postscore;
}
}
public boolean isDeletable(Topic topic, User user) {
boolean perm = isDeletableByUser(topic, user);
if (!perm && user.isModerator()) {
perm = isDeletableByModerator(topic, user);
}
if (!perm) {
return user.isAdministrator();
}
return perm;
}
/**
* Проверка может ли пользователь удалить топик
* @param user пользователь удаляющий сообщение
* @return признак возможности удаления
*/
private static boolean isDeletableByUser(Topic topic, User user) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.HOUR_OF_DAY, -1);
Timestamp hourDeltaTime = new Timestamp(calendar.getTimeInMillis());
return (topic.getPostdate().compareTo(hourDeltaTime) >= 0 && topic.getUid() == user.getId());
}
/**
* Проверка, может ли модератор удалить топик
* @param user пользователь удаляющий сообщение
* @return признак возможности удаления
*/
private boolean isDeletableByModerator(Topic topic, User user) {
if(!user.isModerator()) {
return false;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, -1);
Timestamp monthDeltaTime = new Timestamp(calendar.getTimeInMillis());
boolean ret = false;
Section section = sectionService.getSection(topic.getSectionId());
// Если раздел премодерируемый и топик не подтвержден удалять можно
if(section.isPremoderated() && !topic.isCommited()) {
ret = true;
}
// Если раздел премодерируемый, топик подтвержден и прошло меньше месяца с подтверждения удалять можно
if(section.isPremoderated() && topic.isCommited() && topic.getPostdate().compareTo(monthDeltaTime) >= 0) {
ret = true;
}
// Если раздел не премодерируем, удалять можно
if(!section.isPremoderated()) {
ret = true;
}
return ret;
}
/**
* Можно ли редактировать сообщения полностью
*
* @param topic тема
* @param by редактор
* @return true если можно, false если нет
*/
public boolean isEditable(@Nonnull PreparedTopic topic, @Nullable User by) {
Topic message = topic.getMessage();
Section section = topic.getSection();
User author = topic.getAuthor();
if (message.isDeleted()) {
return false;
}
if (by==null || by.isAnonymous() || by.isBlocked()) {
return false;
}
if (message.isExpired()) {
return false;
}
if (by.isAdministrator()) {
return true;
}
if (!topic.isLorcode()) {
return false;
}
if (by.isModerator()) {
return true;
}
if (by.canCorrect() && section.isPremoderated()) {
return true;
}
if (by.getId()==author.getId() && !message.isCommited()) {
if (message.isSticky()) {
return true;
}
if (section.isPremoderated()) {
return true;
}
if (author.getScore()>=EDIT_SELF_ALWAYS_SCORE) {
return !message.isExpired();
}
return (System.currentTimeMillis() - message.getPostdate().getTime()) < EDIT_PERIOD;
}
return false;
}
/**
* Можно ли редактировать теги сообщения
*
* @param topic тема
* @param by редактор
* @return true если можно, false если нет
*/
public boolean isTagsEditable(@Nonnull PreparedTopic topic, @Nullable User by) {
Topic message = topic.getMessage();
Section section = topic.getSection();
User author = topic.getAuthor();
if (message.isDeleted()) {
return false;
}
if (by==null || by.isAnonymous() || by.isBlocked()) {
return false;
}
if (by.isAdministrator()) {
return true;
}
if (by.isModerator()) {
return true;
}
if (by.canCorrect() && section.isPremoderated()) {
return true;
}
if (by.getId()==author.getId() && !message.isCommited()) {
if (message.isSticky()) {
return true;
}
if (section.isPremoderated()) {
return true;
}
if (author.getScore()>=EDIT_SELF_ALWAYS_SCORE) {
return !message.isExpired();
}
return (System.currentTimeMillis() - message.getPostdate().getTime()) < EDIT_PERIOD;
}
return false;
}
}
| src/main/java/ru/org/linux/group/GroupPermissionService.java | package ru.org.linux.group;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.org.linux.section.Section;
import ru.org.linux.section.SectionService;
import ru.org.linux.topic.PreparedTopic;
import ru.org.linux.topic.Topic;
import ru.org.linux.topic.TopicPermissionService;
import ru.org.linux.user.User;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
@Service
public class GroupPermissionService {
private static final int EDIT_SELF_ALWAYS_SCORE = 300;
private static final int EDIT_PERIOD = 2 * 60 * 60 * 1000; // milliseconds
private SectionService sectionService;
@Autowired
public void setSectionService(SectionService sectionService) {
this.sectionService = sectionService;
}
private int getEffectivePostscore(@Nonnull Group group) {
Section section = sectionService.getSection(group.getSectionId());
return Math.max(group.getTopicRestriction(), section.getTopicsRestriction());
}
public boolean isTopicPostingAllowed(@Nonnull Group group, @Nullable User currentUser) {
int restriction = getEffectivePostscore(group);
if (restriction == TopicPermissionService.POSTSCORE_UNRESTRICTED) {
return true;
}
if (currentUser==null || currentUser.isAnonymous()) {
return false;
}
if (currentUser.isBlocked()) {
return false;
}
if (restriction==TopicPermissionService.POSTSCORE_MODERATORS_ONLY) {
return currentUser.isModerator();
} else {
return currentUser.getScore() >= restriction;
}
}
public boolean isImagePostingAllowed(@Nonnull Section section, @Nullable User currentUser) {
if (section.isImagepost()) {
return true;
}
if (currentUser!=null && currentUser.isAdministrator()) {
return section.isImageAllowed();
}
return false;
}
public String getPostScoreInfo(Group group) {
int postscore = getEffectivePostscore(group);
switch (postscore) {
case TopicPermissionService.POSTSCORE_UNRESTRICTED:
return "";
case 100:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(100, 100);
case 200:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(200, 200);
case 300:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(300, 300);
case 400:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(400, 400);
case 500:
return "<b>Ограничение на добавление сообщений</b>: " + User.getStars(500, 500);
case TopicPermissionService.POSTSCORE_MODERATORS_ONLY:
return "<b>Ограничение на добавление сообщений</b>: только для модераторов";
case TopicPermissionService.POSTSCORE_REGISTERED_ONLY:
return "<b>Ограничение на добавление сообщений</b>: только для зарегистрированных пользователей";
default:
return "<b>Ограничение на добавление сообщений</b>: только для зарегистрированных пользователей, score>=" + postscore;
}
}
public boolean isDeletable(Topic topic, User user) {
boolean perm = isDeletableByUser(topic, user);
if (!perm && user.isModerator()) {
perm = isDeletableByModerator(topic, user);
}
if (!perm) {
return user.isAdministrator();
}
return perm;
}
/**
* Проверка может ли пользователь удалить топик
* @param user пользователь удаляющий сообщение
* @return признак возможности удаления
*/
private static boolean isDeletableByUser(Topic topic, User user) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.HOUR_OF_DAY, -1);
Timestamp hourDeltaTime = new Timestamp(calendar.getTimeInMillis());
return (topic.getPostdate().compareTo(hourDeltaTime) >= 0 && topic.getUid() == user.getId());
}
/**
* Проверка, может ли модератор удалить топик
* @param user пользователь удаляющий сообщение
* @return признак возможности удаления
*/
private boolean isDeletableByModerator(Topic topic, User user) {
if(!user.isModerator()) {
return false;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, -1);
Timestamp monthDeltaTime = new Timestamp(calendar.getTimeInMillis());
boolean ret = false;
Section section = sectionService.getSection(topic.getSectionId());
// Если раздел премодерируемый и топик не подтвержден удалять можно
if(section.isPremoderated() && !topic.isCommited()) {
ret = true;
}
// Если раздел премодерируемый, топик подтвержден и прошло меньше месяца с подтверждения удалять можно
if(section.isPremoderated() && topic.isCommited() && topic.getPostdate().compareTo(monthDeltaTime) >= 0) {
ret = true;
}
// Если раздел не премодерируем, удалять можно
if(!section.isPremoderated()) {
ret = true;
}
return ret;
}
/**
* Можно ли редактировать сообщения полностью
*
* @param topic тема
* @param by редактор
* @return true если можно, false если нет
*/
public boolean isEditable(@Nonnull PreparedTopic topic, @Nullable User by) {
Topic message = topic.getMessage();
Section section = topic.getSection();
User author = topic.getAuthor();
if (message.isDeleted()) {
return false;
}
if (by==null || by.isAnonymous() || by.isBlocked()) {
return false;
}
if (message.isExpired()) {
return false;
}
if (by.isModerator()) {
if (author.isModerator()) {
return true;
}
return section.isPremoderated();
}
if (!topic.isLorcode()) {
return false;
}
if (by.canCorrect() && section.isPremoderated()) {
return true;
}
if (by.getId()==author.getId() && !message.isCommited()) {
if (message.isSticky()) {
return true;
}
if (section.isPremoderated()) {
return true;
}
if (author.getScore()>=EDIT_SELF_ALWAYS_SCORE) {
return !message.isExpired();
}
return (System.currentTimeMillis() - message.getPostdate().getTime()) < EDIT_PERIOD;
}
return false;
}
/**
* Можно ли редактировать теги сообщения
*
* @param topic тема
* @param by редактор
* @return true если можно, false если нет
*/
public boolean isTagsEditable(@Nonnull PreparedTopic topic, @Nullable User by) {
Topic message = topic.getMessage();
Section section = topic.getSection();
User author = topic.getAuthor();
if (message.isDeleted()) {
return false;
}
if (by==null || by.isAnonymous() || by.isBlocked()) {
return false;
}
if (by.isAdministrator()) {
return true;
}
if (by.isModerator()) {
return true;
}
if (by.canCorrect() && section.isPremoderated()) {
return true;
}
if (by.getId()==author.getId() && !message.isCommited()) {
if (message.isSticky()) {
return true;
}
if (section.isPremoderated()) {
return true;
}
if (author.getScore()>=EDIT_SELF_ALWAYS_SCORE) {
return !message.isExpired();
}
return (System.currentTimeMillis() - message.getPostdate().getTime()) < EDIT_PERIOD;
}
return false;
}
}
| редактирование топиков модераторами
| src/main/java/ru/org/linux/group/GroupPermissionService.java | редактирование топиков модераторами | <ide><path>rc/main/java/ru/org/linux/group/GroupPermissionService.java
<ide> return false;
<ide> }
<ide>
<add> if (by.isAdministrator()) {
<add> return true;
<add> }
<add>
<add> if (!topic.isLorcode()) {
<add> return false;
<add> }
<add>
<ide> if (by.isModerator()) {
<del> if (author.isModerator()) {
<del> return true;
<del> }
<del>
<del> return section.isPremoderated();
<del> }
<del>
<del> if (!topic.isLorcode()) {
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> if (by.canCorrect() && section.isPremoderated()) { |
|
Java | artistic-2.0 | 58f9aefe59b233ad9b472273a0bdd2e42bb53058 | 0 | probablytom/assessed,probablytom/assessed,probablytom/assessed,probablytom/assessed,probablytom/assessed,probablytom/assessed | /**
* We are given n guests to be allocated to m equally sized tables (where n % m = 0) at a banquest.
* There are constraint of the form together(i,j) and apart(i,j) where
* together(i,j) means that guests i and j must sit at the same table and
* apart(i,j) means that guests i and j must sit at different tables.
* By default, guests can sit at any table with any other guest
*/
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.stream.IntStream;
import org.chocosolver.solver.*;
import org.chocosolver.solver.variables.*;
import org.chocosolver.solver.search.strategy.*;
import org.chocosolver.solver.constraints.*;
public class BanquetPlanner {
Solver solver;
int nGuests;
int mTables;
int tableSize;
int[] guestsAtTables; // An array of table allocation for each guest
HashMap<Integer, IntVar> constrainedGuests;
//TODO: Write report
/*
* As an optimisation, we'll only create IntVars for constrained guests.
* To identify which guests we've made constraints for, and which IntVars correspond to which guests,
* we keep them in a hashmap where the keys are guest IDs and the values are the guests' IntVars.
* Each guest's IntVar contains that guest's table number.
* If two guests are to be placed together, they should have an equal table number. Guests to be kept
* apart are to have nonequal table numbers.
* We enforce this via arithmetic constraints.
*
* We can then enforce table size simits by specifying that an array of the created IntVars (table numbers)
* can have at least 0 and at most tableSize occurrences of each table number.
*
* When we come to print our output, we know that if we have no entry in our hashmap for the guest,
* that guest had no constraints and can be placed at any table.
* They are therefore given the next available table.
*
*/
BanquetPlanner(String fname) throws IOException {
try (Scanner sc = new Scanner(new File(fname))) {
nGuests = sc.nextInt(); // number of guests
mTables = sc.nextInt(); // number of tables
tableSize = nGuests / mTables;
solver = new Solver("banquet planner");
constrainedGuests = new HashMap<Integer, IntVar>();
while (sc.hasNext()) {
String s = sc.next();
int i = sc.nextInt();
int j = sc.nextInt();
// Create variables for the constrained guests if they don't yet exist
if (!constrainedGuests.containsKey(i)) {
constrainedGuests.put(i, VF.integer("guest" + Integer.toString(i), 0, mTables-1, solver));
}
if (!constrainedGuests.containsKey(j)) {
constrainedGuests.put(j, VF.integer("guest" + Integer.toString(j), 0, mTables-1, solver));
}
// guarantee that two "together" guests have the same table number, and not equal for "apart"
// ICF.arithm requires that the last argument be an int, so we couldn't simply use i != j.
if (s.equals("together")) {
solver.post(IntConstraintFactory.arithm((IntVar)constrainedGuests.get(i), "-", (IntVar)constrainedGuests.get(j), "=", 0));
} else { // s.equals("apart")
solver.post(IntConstraintFactory.arithm((IntVar)constrainedGuests.get(i), "-", (IntVar)constrainedGuests.get(j), "!=", 0));
}
}
}
// Set a constraint so the solution can have 0->tableSize occurrences of each table number.
IntVar[] tableArray = createArrayFromHashMap(constrainedGuests); // An array of the intvars
int[] values = IntStream.rangeClosed(0,mTables-1).toArray(); // The values the intVars can take
IntVar[] OCC = VF.enumeratedArray("occurences", mTables,
0, tableSize, solver); // The range of allowable occurences of any value in `values`
solver.post(ICF.global_cardinality(tableArray, values, OCC, false)); // Constrain the table sizes
// set a custom variable ordering to process the least constrained first
solver.set(ISF.custom(ISF.minDomainSize_var_selector(), ISF.min_value_selector(), tableArray));
}
boolean solve() {
return solver.findSolution();
}
// print out solution in specified format (see readme.txt)
// so that results can be verified
void result() {
StringBuffer[] outputLines = new StringBuffer[mTables]; // Places to put lines of output
guestsAtTables = new int[mTables]; // Count how many guests are at each table so far
int currentTable = 0; // So we add unconstrained guests to the right tables
Integer guestID; // for readability later
int tableNumber; // for readability later
// Create our string buffers for output, begin them with their respective tablenumbers
for (int table = 0; table < mTables; table++) {
outputLines[table] = new StringBuffer(Integer.toString(table) + " ");
}
// Allocate the constrained guests to their tables
for (Entry<Integer, IntVar> guestDetails : constrainedGuests.entrySet()) {
// for readability, convert entry to variables
guestID = guestDetails.getKey();
tableNumber = guestDetails.getValue().getValue();
outputLines[tableNumber].append(guestID.toString() + " ");
guestsAtTables[tableNumber]++;
}
// Add in the unconstrained guests to the tables that aren't yet full
for (Integer guestIndex = 0; guestIndex < nGuests; guestIndex++) {
// Make sure we don't process a guest twice
if (!constrainedGuests.containsKey(guestIndex)) {
currentTable = correctCurrentTable(guestsAtTables, currentTable); // Maybe the table we're at is now full?
outputLines[currentTable].append(guestIndex.toString() + " ");
guestsAtTables[currentTable]++;
}
}
// We've constructed output with each guest, regardless of constraints. We can print now.
for (StringBuffer line : outputLines) {
System.out.println(line.toString());
}
}
void stats() {
System.out.println("nodes: " + solver.getMeasures().getNodeCount() + " cpu: " + solver.getMeasures().getTimeCount());
}
public static void main(String[] args) throws IOException {
BanquetPlanner bp = new BanquetPlanner(args[0]);
if (bp.solve()) {
bp.result();
} else {
System.out.println(false);
}
bp.stats();
}
// --------------------------------------------------------
// --- Helper functions to clean up the above code a little
// --------------------------------------------------------
// Turn a constrained guests hashmap into an array of the guests' IntVars, which contain table numbers.
public IntVar[] createArrayFromHashMap(HashMap<Integer, IntVar> originalHashmap) {
return originalHashmap.values().toArray(VF.integerArray("constrained guests array", constrainedGuests.size(), 0, mTables-1, solver));
}
// Helper function to make sure we're on the right table to add a guest to in the result() function
public int correctCurrentTable(int[] guestsAtTables, int currentTable) {
// If we've reached our capacity, move to the next table and make sure that isn't full too.
if (guestsAtTables[currentTable] == tableSize) {
currentTable++;
return correctCurrentTable(guestsAtTables, currentTable); // Check the next table isn't full
}
return currentTable;
}
}
| Level4/CPM/exercise1/BanquetPlanner.java | /**
* We are given n guests to be allocated to m equally sized tables (where n % m = 0) at a banquest.
* There are constraint of the form together(i,j) and apart(i,j) where
* together(i,j) means that guests i and j must sit at the same table and
* apart(i,j) means that guests i and j must sit at different tables.
* By default, guests can sit at any table with any other guest
*/
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.stream.IntStream;
import org.chocosolver.solver.*;
import org.chocosolver.solver.variables.*;
import org.chocosolver.solver.search.strategy.*;
import org.chocosolver.solver.constraints.*;
public class BanquetPlanner {
Solver solver;
int nGuests;
int mTables;
int tableSize;
int tableCapacity;
int[] guestsAtTables; // An array of table allocation for each guest
IntVar[] count; // An array of the counts of guests at each table
HashMap<Integer, IntVar> constrainedGuests;
//TODO: Clean up code and delete unnecesary variables
//TODO: Write report
/*
* As an optimisation, we'll only create IntVars for constrained guests.
* To identify which guests we've made constraints for, and which IntVars correspond to which guests,
* we keep them in a hashmap where the keys are guest IDs and the values are the guests' IntVars.
* Each guest's IntVar contains that guest's table number.
* If two guests are to be placed together, they should have an equal table number. Guests to be kept
* apart are to have nonequal table numbers.
* We enforce this via arithmetic constraints.
*
* We can then enforce table size simits by specifying that an array of the created IntVars (table numbers)
* can have at least 0 and at most tableSize occurrences of each table number.
*
* When we come to print our output, we know that if we have no entry in our hashmap for the guest,
* that guest had no constraints and can be placed at any table.
* They are therefore given the next available table.
*
*/
BanquetPlanner(String fname) throws IOException {
try (Scanner sc = new Scanner(new File(fname))) {
nGuests = sc.nextInt(); // number of guests
mTables = sc.nextInt(); // number of tables
tableSize = nGuests / mTables;
solver = new Solver("banquet planner");
constrainedGuests = new HashMap<Integer, IntVar>();
while (sc.hasNext()) {
String s = sc.next();
int i = sc.nextInt();
int j = sc.nextInt();
// Create variables for the constrained guests if they don't yet exist
if (!constrainedGuests.containsKey(i)) {
constrainedGuests.put(i, VF.integer("guest" + Integer.toString(i), 0, mTables-1, solver));
}
if (!constrainedGuests.containsKey(j)) {
constrainedGuests.put(j, VF.integer("guest" + Integer.toString(j), 0, mTables-1, solver));
}
// guarantee that two "together" guests have the same table number, and not equal for "apart"
// ICF.arithm requires that the last argument be an int, so we couldn't simply use i != j.
if (s.equals("together")) {
solver.post(IntConstraintFactory.arithm((IntVar)constrainedGuests.get(i), "-", (IntVar)constrainedGuests.get(j), "=", 0));
} else { // s.equals("apart")
solver.post(IntConstraintFactory.arithm((IntVar)constrainedGuests.get(i), "-", (IntVar)constrainedGuests.get(j), "!=", 0));
}
}
}
// Set a constraint so the solution can have 0->tableSize occurrences of each table number.
IntVar[] tableArray = createArrayFromHashMap(constrainedGuests); // An array of the intvars
int[] values = IntStream.rangeClosed(0,mTables-1).toArray(); // The values the intVars can take
IntVar[] OCC = VF.enumeratedArray("occurences", mTables,
0, tableSize, solver); // The range of allowable occurences of any value in `values`
solver.post(ICF.global_cardinality(tableArray, values, OCC, false)); // Constrain the table sizes
// set a custom variable ordering to process the least constrained first
solver.set(ISF.custom(ISF.minDomainSize_var_selector(), ISF.min_value_selector(), tableArray));
}
boolean solve() {
return solver.findSolution();
}
// print out solution in specified format (see readme.txt)
// so that results can be verified
void result() {
StringBuffer[] outputLines = new StringBuffer[mTables]; // Places to put lines of output
guestsAtTables = new int[mTables]; // Count how many guests are at each table so far
Integer guestID; // for readability later
int tableNumber; // for readability later
int currentTable = 0; // So we add unconstrained guests to the right tables
// Create our string buffers for output, begin them with their respective tablenumbers
for (int table = 0; table < mTables; table++) {
outputLines[table] = new StringBuffer(Integer.toString(table) + " ");
}
// Allocate the constrained guests to their tables
for (Entry<Integer, IntVar> guestDetails : constrainedGuests.entrySet()) {
// for readability, convert entry to variables
guestID = guestDetails.getKey();
tableNumber = guestDetails.getValue().getValue();
outputLines[tableNumber].append(guestID.toString() + " ");
guestsAtTables[tableNumber]++;
}
// Add in the unconstrained guests to the tables that aren't yet full
for (Integer guestIndex = 0; guestIndex < nGuests; guestIndex++) {
// Make sure we don't process a guest twice
if (!constrainedGuests.containsKey(guestIndex)) {
currentTable = correctCurrentTable(guestsAtTables, currentTable); // Maybe the table we're at is now full?
outputLines[currentTable].append(guestIndex.toString() + " ");
guestsAtTables[currentTable]++;
}
}
// We've constructed output with each guest, regardless of constraints. We can print now.
for (StringBuffer line : outputLines) {
System.out.println(line.toString());
}
}
void stats() {
System.out.println("nodes: " + solver.getMeasures().getNodeCount() + " cpu: " + solver.getMeasures().getTimeCount());
}
public static void main(String[] args) throws IOException {
BanquetPlanner bp = new BanquetPlanner(args[0]);
if (bp.solve()) {
bp.result();
} else {
System.out.println(false);
}
bp.stats();
}
// --------------------------------------------------------
// --- Helper functions to clean up the above code a little
// --------------------------------------------------------
// Turn a constrained guests hashmap into an array of the guests' IntVars, which contain table numbers.
public IntVar[] createArrayFromHashMap(HashMap<Integer, IntVar> originalHashmap) {
return originalHashmap.values().toArray(VF.integerArray("constrained guests array", constrainedGuests.size(), 0, mTables-1, solver));
}
// Helper function to make sure we're on the right table to add a guest to in the result() function
public int correctCurrentTable(int[] guestsAtTables, int currentTable) {
// If we've reached our capacity, move to the next table and make sure that isn't full too (hence the recursion).
if (guestsAtTables[currentTable] == tableSize) {
currentTable++;
return correctCurrentTable(guestsAtTables, currentTable);
}
return currentTable;
}
}
| Cleaned up code | Level4/CPM/exercise1/BanquetPlanner.java | Cleaned up code | <ide><path>evel4/CPM/exercise1/BanquetPlanner.java
<ide> int nGuests;
<ide> int mTables;
<ide> int tableSize;
<del> int tableCapacity;
<del>
<ide> int[] guestsAtTables; // An array of table allocation for each guest
<del> IntVar[] count; // An array of the counts of guests at each table
<ide> HashMap<Integer, IntVar> constrainedGuests;
<ide>
<ide>
<del> //TODO: Clean up code and delete unnecesary variables
<ide> //TODO: Write report
<ide> /*
<ide> * As an optimisation, we'll only create IntVars for constrained guests.
<ide> constrainedGuests.put(j, VF.integer("guest" + Integer.toString(j), 0, mTables-1, solver));
<ide> }
<ide>
<del>
<ide> // guarantee that two "together" guests have the same table number, and not equal for "apart"
<ide> // ICF.arithm requires that the last argument be an int, so we couldn't simply use i != j.
<ide> if (s.equals("together")) {
<ide> solver.post(ICF.global_cardinality(tableArray, values, OCC, false)); // Constrain the table sizes
<ide>
<ide>
<del>
<ide> // set a custom variable ordering to process the least constrained first
<ide> solver.set(ISF.custom(ISF.minDomainSize_var_selector(), ISF.min_value_selector(), tableArray));
<ide>
<ide>
<ide> StringBuffer[] outputLines = new StringBuffer[mTables]; // Places to put lines of output
<ide> guestsAtTables = new int[mTables]; // Count how many guests are at each table so far
<add> int currentTable = 0; // So we add unconstrained guests to the right tables
<ide> Integer guestID; // for readability later
<ide> int tableNumber; // for readability later
<del>
<del> int currentTable = 0; // So we add unconstrained guests to the right tables
<ide>
<ide> // Create our string buffers for output, begin them with their respective tablenumbers
<ide> for (int table = 0; table < mTables; table++) {
<ide> // Helper function to make sure we're on the right table to add a guest to in the result() function
<ide> public int correctCurrentTable(int[] guestsAtTables, int currentTable) {
<ide>
<del> // If we've reached our capacity, move to the next table and make sure that isn't full too (hence the recursion).
<add> // If we've reached our capacity, move to the next table and make sure that isn't full too.
<ide> if (guestsAtTables[currentTable] == tableSize) {
<ide> currentTable++;
<del> return correctCurrentTable(guestsAtTables, currentTable);
<add> return correctCurrentTable(guestsAtTables, currentTable); // Check the next table isn't full
<ide> }
<ide> return currentTable;
<ide> } |
|
Java | apache-2.0 | 72c4e23fe5400b3bc961cb38d7f43b3426aac14b | 0 | allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,allotria/intellij-community,fitermay/intellij-community,ibinti/intellij-community,apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,allotria/intellij-community,semonte/intellij-community,xfournet/intellij-community,fitermay/intellij-community,allotria/intellij-community,da1z/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,da1z/intellij-community,apixandru/intellij-community,signed/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,FHannes/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,signed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,signed/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,signed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,da1z/intellij-community,semonte/intellij-community,asedunov/intellij-community,asedunov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,da1z/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,xfournet/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,signed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,vvv1559/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,fitermay/intellij-community,fitermay/intellij-community,signed/intellij-community,xfournet/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ibinti/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,semonte/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community | /*
* Copyright 2000-2016 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.vcs.impl;
import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.impl.projectlevelman.NewMappings;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.project.ProjectKt;
import com.intellij.util.PathUtilRt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author yole
*/
public abstract class DefaultVcsRootPolicy {
public static DefaultVcsRootPolicy getInstance(Project project) {
return PeriodicalTasksCloser.getInstance().safeGetService(project, DefaultVcsRootPolicy.class);
}
public abstract void addDefaultVcsRoots(final NewMappings mappingList, @NotNull String vcsName, List<VirtualFile> result);
public abstract boolean matchesDefaultMapping(final VirtualFile file, final Object matchContext);
@Nullable
public abstract Object getMatchContext(final VirtualFile file);
@Nullable
public abstract VirtualFile getVcsRootFor(final VirtualFile file);
@NotNull
public abstract Collection<VirtualFile> getDirtyRoots();
public String getProjectConfigurationMessage(@NotNull Project project) {
boolean isDirectoryBased = ProjectKt.isDirectoryBased(project);
String[] parts = new String[]{"Content roots of all modules", "all immediate descendants of project base directory",
PathUtilRt.getFileName(ProjectKt.getStateStore(project).getDirectoryStorePath(true)) + " directory contents"};
final StringBuilder sb = new StringBuilder(parts[0]);
if (isDirectoryBased) {
sb.append(", ");
}
else {
sb.append(", and ");
}
sb.append(parts[1]);
if (isDirectoryBased) {
sb.append(", and ");
sb.append(parts[2]);
}
return sb.toString();
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/impl/DefaultVcsRootPolicy.java | /*
* Copyright 2000-2016 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.vcs.impl;
import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.impl.projectlevelman.NewMappings;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.project.ProjectKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author yole
*/
public abstract class DefaultVcsRootPolicy {
public static DefaultVcsRootPolicy getInstance(Project project) {
return PeriodicalTasksCloser.getInstance().safeGetService(project, DefaultVcsRootPolicy.class);
}
public abstract void addDefaultVcsRoots(final NewMappings mappingList, @NotNull String vcsName, List<VirtualFile> result);
public abstract boolean matchesDefaultMapping(final VirtualFile file, final Object matchContext);
@Nullable
public abstract Object getMatchContext(final VirtualFile file);
@Nullable
public abstract VirtualFile getVcsRootFor(final VirtualFile file);
@NotNull
public abstract Collection<VirtualFile> getDirtyRoots();
public String getProjectConfigurationMessage(final Project project) {
boolean isDirectoryBased = ProjectKt.isDirectoryBased(project);
final String[] parts = new String[] {"Content roots of all modules", "all immediate descendants of project base directory",
Project.DIRECTORY_STORE_FOLDER + " directory contents"};
final StringBuilder sb = new StringBuilder(parts[0]);
if (isDirectoryBased) {
sb.append(", ");
} else {
sb.append(", and ");
}
sb.append(parts[1]);
if (isDirectoryBased) {
sb.append(", and ");
sb.append(parts[2]);
}
return sb.toString();
}
}
| DefaultVcsRootPolicy — do not use Project.DIRECTORY_STORE_FOLDER
| platform/vcs-impl/src/com/intellij/openapi/vcs/impl/DefaultVcsRootPolicy.java | DefaultVcsRootPolicy — do not use Project.DIRECTORY_STORE_FOLDER | <ide><path>latform/vcs-impl/src/com/intellij/openapi/vcs/impl/DefaultVcsRootPolicy.java
<ide> import com.intellij.openapi.vcs.impl.projectlevelman.NewMappings;
<ide> import com.intellij.openapi.vfs.VirtualFile;
<ide> import com.intellij.project.ProjectKt;
<add>import com.intellij.util.PathUtilRt;
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<ide> @NotNull
<ide> public abstract Collection<VirtualFile> getDirtyRoots();
<ide>
<del> public String getProjectConfigurationMessage(final Project project) {
<add> public String getProjectConfigurationMessage(@NotNull Project project) {
<ide> boolean isDirectoryBased = ProjectKt.isDirectoryBased(project);
<del> final String[] parts = new String[] {"Content roots of all modules", "all immediate descendants of project base directory",
<del> Project.DIRECTORY_STORE_FOLDER + " directory contents"};
<add> String[] parts = new String[]{"Content roots of all modules", "all immediate descendants of project base directory",
<add> PathUtilRt.getFileName(ProjectKt.getStateStore(project).getDirectoryStorePath(true)) + " directory contents"};
<ide> final StringBuilder sb = new StringBuilder(parts[0]);
<ide> if (isDirectoryBased) {
<ide> sb.append(", ");
<del> } else {
<add> }
<add> else {
<ide> sb.append(", and ");
<ide> }
<ide> sb.append(parts[1]); |
|
Java | lgpl-2.1 | 8c5587c1c9f06d55fb507f5ff620037710a83df8 | 0 | ggiudetti/opencms-core,gallardo/opencms-core,gallardo/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,alkacon/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,victos/opencms-core,serrapos/opencms-core,alkacon/opencms-core,victos/opencms-core,MenZil/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,serrapos/opencms-core,alkacon/opencms-core,gallardo/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,victos/opencms-core,victos/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,it-tavis/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsStringUtil.java,v $
* Date : $Date: 2008/06/20 15:38:03 $
* Version: $Revision: 1.49 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 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.49 $
*
* @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) {
int keyValLen = keyValDelim.length();
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 + keyValLen < param.length()) {
value = param.substring(pos + keyValLen);
}
}
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: 2008/02/27 12:05:36 $
* Version: $Revision: 1.48 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 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.48 $
*
* @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;
}
} | fixed bug in map parsing
| src/org/opencms/util/CmsStringUtil.java | fixed bug in map parsing | <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: 2008/02/27 12:05:36 $
<del> * Version: $Revision: 1.48 $
<add> * Date : $Date: 2008/06/20 15:38:03 $
<add> * Version: $Revision: 1.49 $
<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.48 $
<add> * @version $Revision: 1.49 $
<ide> *
<ide> * @since 6.0.0
<ide> */
<ide> */
<ide> public static Map splitAsMap(String source, String paramDelim, String keyValDelim) {
<ide>
<add> int keyValLen = keyValDelim.length();
<ide> Map params = new HashMap();
<ide> Iterator itParams = CmsStringUtil.splitAsList(source, paramDelim, true).iterator();
<ide> while (itParams.hasNext()) {
<ide> String value = "";
<ide> if (pos > 0) {
<ide> key = param.substring(0, pos);
<del> if (pos + keyValDelim.length() < param.length()) {
<del> value = param.substring(pos + 1);
<add> if (pos + keyValLen < param.length()) {
<add> value = param.substring(pos + keyValLen);
<ide> }
<ide> }
<ide> params.put(key, value); |
|
Java | apache-2.0 | d94612ec0df0f08a2735ca99b2ccea6c32a32311 | 0 | jahlborn/jackcess | /*
Copyright (c) 2008 Health Market Science, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
You can contact Health Market Science at [email protected]
or at the following address:
Health Market Science
2700 Horizon Drive
Suite 200
King of Prussia, PA 19406
*/
package com.healthmarketscience.jackcess;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
import static com.healthmarketscience.jackcess.Index.*;
/**
* Manager of the index pages for a BigIndex.
* @author James Ahlborn
*/
public class IndexPageCache
{
private enum UpdateType {
ADD, REMOVE, REPLACE;
}
/** the index whose pages this cache is managing */
private final BigIndex _index;
/** the root page for the index */
private DataPageMain _rootPage;
/** the currently loaded pages for this index, pageNumber -> page */
private final Map<Integer, DataPageMain> _dataPages =
new HashMap<Integer, DataPageMain>();
/** the currently modified index pages */
private final List<CacheDataPage> _modifiedPages =
new ArrayList<CacheDataPage>();
public IndexPageCache(BigIndex index) {
_index = index;
}
public BigIndex getIndex() {
return _index;
}
public PageChannel getPageChannel() {
return getIndex().getPageChannel();
}
/**
* Sets the root page for this index, must be called before normal usage.
*
* @param pageNumber the root page number
*/
public void setRootPageNumber(int pageNumber) throws IOException {
_rootPage = getDataPage(pageNumber);
// root page has no parent
_rootPage.initParentPage(INVALID_INDEX_PAGE_NUMBER, false);
}
/**
* Writes any outstanding changes for this index to the file.
*/
public void write()
throws IOException
{
// first discard any empty pages
handleEmptyPages();
// next, handle any necessary page splitting
preparePagesForWriting();
// finally, write all the modified pages (which are not being deleted)
writeDataPages();
}
/**
* Handles any modified pages which are empty as the first pass during a
* {@link #write} call. All empty pages are removed from the _modifiedPages
* collection by this method.
*/
private void handleEmptyPages() throws IOException
{
for(Iterator<CacheDataPage> iter = _modifiedPages.iterator();
iter.hasNext(); ) {
CacheDataPage cacheDataPage = iter.next();
if(cacheDataPage._extra._entryView.isEmpty()) {
if(!cacheDataPage._main.isRoot()) {
deleteDataPage(cacheDataPage);
} else {
writeDataPage(cacheDataPage);
}
iter.remove();
}
}
}
/**
* Prepares any non-empty modified pages for writing as the second pass
* during a {@link #write} call. Updates entry prefixes, promotes/demotes
* tail pages, and splits pages as needed.
*/
private void preparePagesForWriting() throws IOException
{
boolean splitPages = false;
int maxPageEntrySize = getIndex().getMaxPageEntrySize();
// we need to continue looping through all the pages until we do not split
// any pages (because a split may cascade up the tree)
do {
splitPages = false;
// we might be adding to this list while iterating, so we can't use an
// iterator
for(int i = 0; i < _modifiedPages.size(); ++i) {
CacheDataPage cacheDataPage = _modifiedPages.get(i);
if(!cacheDataPage.isLeaf()) {
// see if we need to update any child tail status
DataPageMain dpMain = cacheDataPage._main;
int size = cacheDataPage._extra._entryView.size();
if(dpMain.hasChildTail()) {
if(size == 1) {
demoteTail(cacheDataPage);
}
} else {
if(size > 1) {
promoteTail(cacheDataPage);
}
}
}
// look for pages with more entries than can fit on a page
if(cacheDataPage.getTotalEntrySize() > maxPageEntrySize) {
// make sure the prefix is up-to-date (this may have gotten
// discarded by one of the update entry methods)
cacheDataPage._extra.updateEntryPrefix();
// now, see if the page will fit when compressed
if(cacheDataPage.getCompressedEntrySize() > maxPageEntrySize) {
// need to split this page
splitPages = true;
splitDataPage(cacheDataPage);
}
}
}
} while(splitPages);
}
/**
* Writes any non-empty modified pages as the last pass during a
* {@link #write} call. Clears the _modifiedPages collection when finised.
*/
private void writeDataPages() throws IOException
{
for(CacheDataPage cacheDataPage : _modifiedPages) {
if(cacheDataPage._extra._entryView.isEmpty()) {
throw new IllegalStateException("Unexpected empty page " +
cacheDataPage);
}
writeDataPage(cacheDataPage);
}
_modifiedPages.clear();
}
/**
* Returns a CacheDataPage for the given page number, may be {@code null} if
* the given page number is invalid. Loads the given page if necessary.
*/
public CacheDataPage getCacheDataPage(Integer pageNumber)
throws IOException
{
DataPageMain main = getDataPage(pageNumber);
return((main != null) ? new CacheDataPage(main) : null);
}
/**
* Returns a DataPageMain for the given page number, may be {@code null} if
* the given page number is invalid. Loads the given page if necessary.
*/
private DataPageMain getDataPage(Integer pageNumber)
throws IOException
{
DataPageMain dataPage = _dataPages.get(pageNumber);
if((dataPage == null) && (pageNumber > INVALID_INDEX_PAGE_NUMBER)) {
dataPage = readDataPage(pageNumber)._main;
_dataPages.put(pageNumber, dataPage);
}
return dataPage;
}
/**
* Writes the given index page to the file.
*/
private void writeDataPage(CacheDataPage cacheDataPage)
throws IOException
{
getIndex().writeDataPage(cacheDataPage);
// lastly, mark the page as no longer modified
cacheDataPage._extra._modified = false;
}
/**
* Deletes the given index page from the file (clears the page).
*/
private void deleteDataPage(CacheDataPage cacheDataPage)
throws IOException
{
// free this database page
getPageChannel().deallocatePage(cacheDataPage._main._pageNumber);
// discard from our cache
_dataPages.remove(cacheDataPage._main._pageNumber);
// lastly, mark the page as no longer modified
cacheDataPage._extra._modified = false;
}
/**
* Reads the given index page from the file.
*/
private CacheDataPage readDataPage(Integer pageNumber)
throws IOException
{
DataPageMain dataPage = new DataPageMain(pageNumber);
DataPageExtra extra = new DataPageExtra();
CacheDataPage cacheDataPage = new CacheDataPage(dataPage, extra);
getIndex().readDataPage(cacheDataPage);
// associate the extra info with the main data page
dataPage.setExtra(extra);
return cacheDataPage;
}
/**
* Removes the entry with the given index from the given page.
*
* @param cacheDataPage the page from which to remove the entry
* @param entryIdx the index of the entry to remove
*/
private void removeEntry(CacheDataPage cacheDataPage, int entryIdx)
throws IOException
{
updateEntry(cacheDataPage, entryIdx, null, UpdateType.REMOVE);
}
/**
* Adds the entry to the given page at the given index.
*
* @param cacheDataPage the page to which to add the entry
* @param entryIdx the index at which to add the entry
* @param newEntry the entry to add
*/
private void addEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry)
throws IOException
{
updateEntry(cacheDataPage, entryIdx, newEntry, UpdateType.ADD);
}
/**
* Updates the entries on the given page according to the given updateType.
*
* @param cacheDataPage the page to update
* @param entryIdx the index at which to add/remove/replace the entry
* @param newEntry the entry to add/replace
* @param upType the type of update to make
*/
private void updateEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry,
UpdateType upType)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
if(newEntry != null) {
validateEntryForPage(dpMain, newEntry);
}
// note, it's slightly ucky, but we need to load the parent page before we
// start mucking with our entries because our parent may use our entries.
CacheDataPage parentDataPage = (!dpMain.isRoot() ?
new CacheDataPage(dpMain.getParentPage()) :
null);
Entry oldLastEntry = dpExtra._entryView.getLast();
Entry oldEntry = null;
int entrySizeDiff = 0;
switch(upType) {
case ADD:
dpExtra._entryView.add(entryIdx, newEntry);
entrySizeDiff += newEntry.size();
break;
case REPLACE:
oldEntry = dpExtra._entryView.set(entryIdx, newEntry);
entrySizeDiff += newEntry.size() - oldEntry.size();
break;
case REMOVE: {
oldEntry = dpExtra._entryView.remove(entryIdx);
entrySizeDiff -= oldEntry.size();
break;
}
default:
throw new RuntimeException("unknown update type " + upType);
}
boolean updateLast = (oldLastEntry != dpExtra._entryView.getLast());
// child tail entry updates do not modify the page
if(!updateLast || !dpMain.hasChildTail()) {
dpExtra._totalEntrySize += entrySizeDiff;
setModified(cacheDataPage);
// for now, just clear the prefix, we'll fix it later
dpExtra._entryPrefix = EMPTY_PREFIX;
}
if(dpExtra._entryView.isEmpty()) {
// this page is dead
removeDataPage(parentDataPage, cacheDataPage, oldLastEntry);
return;
}
// determine if we need to update our parent page
if(!updateLast || dpMain.isRoot()) {
// no parent
return;
}
// the update to the last entry needs to be propagated to our parent
replaceParentEntry(parentDataPage, cacheDataPage, oldLastEntry);
}
/**
* Removes an index page which has become empty. If this page is the root
* page, just clears it.
*
* @param parentDataPage the parent of the removed page
* @param cacheDataPage the page to remove
* @param oldLastEntry the last entry for this page (before it was removed)
*/
private void removeDataPage(CacheDataPage parentDataPage,
CacheDataPage cacheDataPage,
Entry oldLastEntry)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
if(dpMain.hasChildTail()) {
throw new IllegalStateException("Still has child tail?");
}
if(dpExtra._totalEntrySize != 0) {
throw new IllegalStateException("Empty page but size is not 0? " +
dpExtra._totalEntrySize + ", " +
cacheDataPage);
}
if(dpMain.isRoot()) {
// clear out this page (we don't actually remove it)
dpExtra._entryPrefix = EMPTY_PREFIX;
// when the root page becomes empty, it becomes a leaf page again
dpMain._leaf = true;
return;
}
// remove this page from its parent page
updateParentEntry(parentDataPage, cacheDataPage, oldLastEntry, null,
UpdateType.REMOVE);
// remove this page from any next/prev pages
removeFromPeers(cacheDataPage);
}
/**
* Removes a now empty index page from its next and previous peers.
*
* @param cacheDataPage the page to remove
*/
private void removeFromPeers(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
Integer prevPageNumber = dpMain._prevPageNumber;
Integer nextPageNumber = dpMain._nextPageNumber;
DataPageMain prevMain = dpMain.getPrevPage();
if(prevMain != null) {
setModified(new CacheDataPage(prevMain));
prevMain._nextPageNumber = nextPageNumber;
}
DataPageMain nextMain = dpMain.getNextPage();
if(nextMain != null) {
setModified(new CacheDataPage(nextMain));
nextMain._prevPageNumber = prevPageNumber;
}
}
/**
* Adds an entry for the given child page to the given parent page.
*
* @param parentDataPage the parent page to which to add the entry
* @param childDataPage the child from which to get the entry to add
*/
private void addParentEntry(CacheDataPage parentDataPage,
CacheDataPage childDataPage)
throws IOException
{
DataPageExtra childExtra = childDataPage._extra;
updateParentEntry(parentDataPage, childDataPage, null,
childExtra._entryView.getLast(), UpdateType.ADD);
}
/**
* Replaces the entry for the given child page in the given parent page.
*
* @param parentDataPage the parent page in which to replace the entry
* @param childDataPage the child for which the entry is being replaced
* @param oldEntry the old child entry for the child page
*/
private void replaceParentEntry(CacheDataPage parentDataPage,
CacheDataPage childDataPage,
Entry oldEntry)
throws IOException
{
DataPageExtra childExtra = childDataPage._extra;
updateParentEntry(parentDataPage, childDataPage, oldEntry,
childExtra._entryView.getLast(), UpdateType.REPLACE);
}
/**
* Updates the entry for the given child page in the given parent page
* according to the given updateType.
*
* @param parentDataPage the parent page in which to update the entry
* @param childDataPage the child for which the entry is being updated
* @param oldEntry the old child entry to remove/replace
* @param newEntry the new child entry to replace/add
* @param upType the type of update to make
*/
private void updateParentEntry(CacheDataPage parentDataPage,
CacheDataPage childDataPage,
Entry oldEntry, Entry newEntry,
UpdateType upType)
throws IOException
{
DataPageMain childMain = childDataPage._main;
DataPageExtra parentExtra = parentDataPage._extra;
if(childMain.isTail() && (upType != UpdateType.REMOVE)) {
// for add or replace, update the child tail info before updating the
// parent entries
updateParentTail(parentDataPage, childDataPage, upType);
}
if(oldEntry != null) {
oldEntry = oldEntry.asNodeEntry(childMain._pageNumber);
}
if(newEntry != null) {
newEntry = newEntry.asNodeEntry(childMain._pageNumber);
}
boolean expectFound = true;
int idx = 0;
switch(upType) {
case ADD:
expectFound = false;
idx = parentExtra._entryView.find(newEntry);
break;
case REPLACE:
case REMOVE:
idx = parentExtra._entryView.find(oldEntry);
break;
default:
throw new RuntimeException("unknown update type " + upType);
}
if(idx < 0) {
if(expectFound) {
throw new IllegalStateException(
"Could not find child entry in parent; childEntry " + oldEntry +
"; parent " + parentDataPage);
}
idx = missingIndexToInsertionPoint(idx);
} else {
if(!expectFound) {
throw new IllegalStateException(
"Unexpectedly found child entry in parent; childEntry " +
newEntry + "; parent " + parentDataPage);
}
}
updateEntry(parentDataPage, idx, newEntry, upType);
if(childMain.isTail() && (upType == UpdateType.REMOVE)) {
// for remove, update the child tail info after updating the parent
// entries
updateParentTail(parentDataPage, childDataPage, upType);
}
}
/**
* Updates the child tail info in the given parent page according to the
* given updateType.
*
* @param parentDataPage the parent page in which to update the child tail
* @param childDataPage the child to add/replace
* @param upType the type of update to make
*/
private void updateParentTail(CacheDataPage parentDataPage,
CacheDataPage childDataPage,
UpdateType upType)
throws IOException
{
DataPageMain parentMain = parentDataPage._main;
int newChildTailPageNumber =
((upType == UpdateType.REMOVE) ?
INVALID_INDEX_PAGE_NUMBER :
childDataPage._main._pageNumber);
if(!parentMain.isChildTailPageNumber(newChildTailPageNumber)) {
setModified(parentDataPage);
parentMain._childTailPageNumber = newChildTailPageNumber;
}
}
/**
* Verifies that the given entry type (node/leaf) is valid for the given
* page (node/leaf).
*
* @param dpMain the page to which the entry will be added
* @param entry the entry being added
* @throws IllegalStateException if the entry type does not match the page
* type
*/
private void validateEntryForPage(DataPageMain dpMain, Entry entry) {
if(dpMain._leaf != entry.isLeafEntry()) {
throw new IllegalStateException(
"Trying to update page with wrong entry type; pageLeaf " +
dpMain._leaf + ", entryLeaf " + entry.isLeafEntry());
}
}
/**
* Splits an index page which has too many entries on it.
*
* @param origDataPage the page to split
*/
private void splitDataPage(CacheDataPage origDataPage)
throws IOException
{
DataPageMain origMain = origDataPage._main;
DataPageExtra origExtra = origDataPage._extra;
setModified(origDataPage);
int numEntries = origExtra._entries.size();
if(numEntries < 2) {
throw new IllegalStateException(
"Cannot split page with less than 2 entries " + origDataPage);
}
if(origMain.isRoot()) {
// we can't split the root page directly, so we need to put another page
// between the root page and its sub-pages, and then split that page.
CacheDataPage newDataPage = nestRootDataPage(origDataPage);
// now, split this new page instead
origDataPage = newDataPage;
origMain = newDataPage._main;
origExtra = newDataPage._extra;
}
// note, it's slightly ucky, but we need to load the parent page before we
// start mucking with our entries because our parent may use our entries.
DataPageMain parentMain = origMain.getParentPage();
CacheDataPage parentDataPage = new CacheDataPage(parentMain);
// note, there are many, many ways this could be improved/tweaked. for
// now, we just want it to be functional...
// so, we will naively move half the entries from one page to a new page.
CacheDataPage newDataPage = allocateNewCacheDataPage(
parentMain._pageNumber, origMain._leaf);
DataPageMain newMain = newDataPage._main;
DataPageExtra newExtra = newDataPage._extra;
List<Entry> headEntries =
origExtra._entries.subList(0, ((numEntries + 1) / 2));
// move first half of the entries from old page to new page (so we do not
// need to muck with any tail entries)
for(Entry headEntry : headEntries) {
newExtra._totalEntrySize += headEntry.size();
newExtra._entries.add(headEntry);
}
newExtra.setEntryView(newMain);
// remove the moved entries from the old page
headEntries.clear();
origExtra._entryPrefix = EMPTY_PREFIX;
origExtra._totalEntrySize -= newExtra._totalEntrySize;
// insert this new page between the old page and any previous page
addToPeersBefore(newDataPage, origDataPage);
if(!newMain._leaf) {
// reparent the children pages of the new page
reparentChildren(newDataPage);
// if the children of this page are also node pages, then the next/prev
// links should not cross parent boundaries (the leaf pages are linked
// from beginning to end, but child node pages are only linked within
// the same parent)
DataPageMain childMain = newMain.getChildPage(
newExtra._entryView.getLast());
if(!childMain._leaf) {
separateFromNextPeer(new CacheDataPage(childMain));
}
}
// lastly, we need to add the new page to the parent page's entries
addParentEntry(parentDataPage, newDataPage);
}
/**
* Copies the current root page info into a new page and nests this page
* under the root page. This must be done when the root page needs to be
* split.
*
* @param rootDataPage the root data page
*
* @return the newly created page nested under the root page
*/
private CacheDataPage nestRootDataPage(CacheDataPage rootDataPage)
throws IOException
{
DataPageMain rootMain = rootDataPage._main;
DataPageExtra rootExtra = rootDataPage._extra;
if(!rootMain.isRoot()) {
throw new IllegalArgumentException("should be called with root, duh");
}
CacheDataPage newDataPage =
allocateNewCacheDataPage(rootMain._pageNumber, rootMain._leaf);
DataPageMain newMain = newDataPage._main;
DataPageExtra newExtra = newDataPage._extra;
// move entries to new page
newMain._childTailPageNumber = rootMain._childTailPageNumber;
newExtra._entries = rootExtra._entries;
newExtra._entryPrefix = rootExtra._entryPrefix;
newExtra._totalEntrySize = rootExtra._totalEntrySize;
newExtra.setEntryView(newMain);
if(!newMain._leaf) {
// we need to re-parent all the child pages
reparentChildren(newDataPage);
}
// clear the root page
rootMain._leaf = false;
rootMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
rootExtra._entries = new ArrayList<Entry>();
rootExtra._entryPrefix = EMPTY_PREFIX;
rootExtra._totalEntrySize = 0;
rootExtra.setEntryView(rootMain);
// add the new page as the first child of the root page
addParentEntry(rootDataPage, newDataPage);
return newDataPage;
}
/**
* Allocates a new index page with the given parent page and type.
*
* @param parentPageNumber the parent page for the new page
* @param isLeaf whether or not the new page is a leaf page
*
* @return the newly created page
*/
private CacheDataPage allocateNewCacheDataPage(Integer parentPageNumber,
boolean isLeaf)
throws IOException
{
DataPageMain dpMain = new DataPageMain(getPageChannel().allocateNewPage());
DataPageExtra dpExtra = new DataPageExtra();
dpMain.initParentPage(parentPageNumber, false);
dpMain._leaf = isLeaf;
dpMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpExtra._entries = new ArrayList<Entry>();
dpExtra._entryPrefix = EMPTY_PREFIX;
dpMain.setExtra(dpExtra);
// add to our page cache
_dataPages.put(dpMain._pageNumber, dpMain);
// needs to be written out
CacheDataPage cacheDataPage = new CacheDataPage(dpMain, dpExtra);
setModified(cacheDataPage);
return cacheDataPage;
}
/**
* Inserts the new page as a peer between the given original page and any
* previous peer page.
*
* @param newDataPage the new index page
* @param origDataPage the current index page
*/
private void addToPeersBefore(CacheDataPage newDataPage,
CacheDataPage origDataPage)
throws IOException
{
DataPageMain origMain = origDataPage._main;
DataPageMain newMain = newDataPage._main;
DataPageMain prevMain = origMain.getPrevPage();
newMain._nextPageNumber = origMain._pageNumber;
newMain._prevPageNumber = origMain._prevPageNumber;
origMain._prevPageNumber = newMain._pageNumber;
if(prevMain != null) {
setModified(new CacheDataPage(prevMain));
prevMain._nextPageNumber = newMain._pageNumber;
}
}
/**
* Separates the given index page from any next peer page.
*
* @param cacheDataPage the index page to be separated
*/
private void separateFromNextPeer(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
setModified(cacheDataPage);
DataPageMain nextMain = dpMain.getNextPage();
setModified(new CacheDataPage(nextMain));
nextMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
}
/**
* Sets the parent info for the children of the given page to the given
* page.
*
* @param cacheDataPage the page whose children need to be updated
*/
private void reparentChildren(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
// note, the "parent" page number is not actually persisted, so we do not
// need to mark any updated pages as modified. for the same reason, we
// don't need to load the pages if not already loaded
for(Entry entry : dpExtra._entryView) {
Integer childPageNumber = entry.getSubPageNumber();
DataPageMain childMain = _dataPages.get(childPageNumber);
if(childMain != null) {
childMain.setParentPage(dpMain._pageNumber,
dpMain.isChildTailPageNumber(childPageNumber));
}
}
}
/**
* Makes the tail entry of the given page a normal entry on that page, done
* when there is only one entry left on a page, and it is the tail.
*
* @param cacheDataPage the page whose tail must be updated
*/
private void demoteTail(CacheDataPage cacheDataPage)
throws IOException
{
// there's only one entry on the page, and it's the tail. make it a
// normal entry
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
setModified(cacheDataPage);
DataPageMain tailMain = dpMain.getChildTailPage();
CacheDataPage tailDataPage = new CacheDataPage(tailMain);
// move the tail entry to the last normal entry
updateParentTail(cacheDataPage, tailDataPage, UpdateType.REMOVE);
Entry tailEntry = dpExtra._entryView.demoteTail();
dpExtra._totalEntrySize += tailEntry.size();
dpExtra._entryPrefix = EMPTY_PREFIX;
tailMain.setParentPage(dpMain._pageNumber, false);
}
/**
* Makes the last normal entry of the given page the tail entry on that
* page, done when there are multiple entries on a page and no tail entry.
*
* @param cacheDataPage the page whose tail must be updated
*/
private void promoteTail(CacheDataPage cacheDataPage)
throws IOException
{
// there's not tail currently on this page, make last entry a tail
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
setModified(cacheDataPage);
DataPageMain lastMain = dpMain.getChildPage(dpExtra._entryView.getLast());
CacheDataPage lastDataPage = new CacheDataPage(lastMain);
// move the "last" normal entry to the tail entry
updateParentTail(cacheDataPage, lastDataPage, UpdateType.ADD);
Entry lastEntry = dpExtra._entryView.promoteTail();
dpExtra._totalEntrySize -= lastEntry.size();
dpExtra._entryPrefix = EMPTY_PREFIX;
lastMain.setParentPage(dpMain._pageNumber, true);
}
/**
* Finds the index page on which the given entry does or should reside.
*
* @param e the entry to find
*/
public CacheDataPage findCacheDataPage(Entry e)
throws IOException
{
DataPageMain curPage = _rootPage;
while(true) {
if(curPage._leaf) {
// nowhere to go from here
return new CacheDataPage(curPage);
}
DataPageExtra extra = curPage.getExtra();
// need to descend
int idx = extra._entryView.find(e);
if(idx < 0) {
idx = missingIndexToInsertionPoint(idx);
if(idx == extra._entryView.size()) {
// just move to last child page
--idx;
}
}
Entry nodeEntry = extra._entryView.get(idx);
curPage = curPage.getChildPage(nodeEntry);
}
}
/**
* Marks the given index page as modified and saves it for writing, if
* necessary (if the page is already marked, does nothing).
*
* @param cacheDataPage the modified index page
*/
private void setModified(CacheDataPage cacheDataPage)
{
if(!cacheDataPage._extra._modified) {
_modifiedPages.add(cacheDataPage);
cacheDataPage._extra._modified = true;
}
}
/**
* Finds the valid entry prefix given the first/last entries on an index
* page.
*
* @param e1 the first entry on the page
* @param e2 the last entry on the page
*
* @return a valid entry prefix for the page
*/
private static byte[] findCommonPrefix(Entry e1, Entry e2)
{
byte[] b1 = e1.getEntryBytes();
byte[] b2 = e2.getEntryBytes();
int maxLen = b1.length;
byte[] prefix = b1;
if(b1.length > b2.length) {
maxLen = b2.length;
prefix = b2;
}
int len = 0;
while((len < maxLen) && (b1[len] == b2[len])) {
++len;
}
if(len < prefix.length) {
if(len == 0) {
return EMPTY_PREFIX;
}
// need new prefix
byte[] tmpPrefix = new byte[len];
System.arraycopy(prefix, 0, tmpPrefix, 0, len);
prefix = tmpPrefix;
}
return prefix;
}
/**
* Used by unit tests to validate the internal status of the index.
*/
void validate() throws IOException {
for(DataPageMain dpMain : _dataPages.values()) {
DataPageExtra dpExtra = dpMain.getExtra();
validateEntries(dpExtra);
validateChildren(dpMain, dpExtra);
validatePeers(dpMain);
}
}
/**
* Validates the entries for an index page
*
* @param dpExtra the entries to validate
*/
private void validateEntries(DataPageExtra dpExtra) throws IOException {
int entrySize = 0;
Entry prevEntry = Index.FIRST_ENTRY;
for(Entry e : dpExtra._entries) {
entrySize += e.size();
if(prevEntry.compareTo(e) >= 0) {
throw new IOException("Unexpected order in index entries, " +
prevEntry + " >= " + e);
}
prevEntry = e;
}
if(entrySize != dpExtra._totalEntrySize) {
throw new IllegalStateException("Expected size " + entrySize +
" but was " + dpExtra._totalEntrySize);
}
}
/**
* Validates the children for an index page
*
* @param dpMain the index page
* @param dpExtra the child entries to validate
*/
private void validateChildren(DataPageMain dpMain,
DataPageExtra dpExtra) throws IOException {
int childTailPageNumber = dpMain._childTailPageNumber;
if(dpMain._leaf) {
if(childTailPageNumber != INVALID_INDEX_PAGE_NUMBER) {
throw new IllegalStateException("Leaf page has tail " + dpMain);
}
return;
}
if((dpExtra._entryView.size() == 1) && dpMain.hasChildTail()) {
throw new IllegalStateException("Single child is tail " + dpMain);
}
for(Entry e : dpExtra._entryView) {
validateEntryForPage(dpMain, e);
Integer subPageNumber = e.getSubPageNumber();
DataPageMain childMain = _dataPages.get(subPageNumber);
if(childMain != null) {
if(childMain._parentPageNumber != null) {
if((int)childMain._parentPageNumber != dpMain._pageNumber) {
throw new IllegalStateException("Child's parent is incorrect " +
childMain);
}
boolean expectTail = ((int)subPageNumber == childTailPageNumber);
if(expectTail != childMain._tail) {
throw new IllegalStateException("Child tail status incorrect " +
childMain);
}
}
Entry lastEntry = childMain.getExtra()._entryView.getLast();
if(e.compareTo(lastEntry) != 0) {
throw new IllegalStateException("Invalid entry " + e +
" but child is " + lastEntry);
}
}
}
}
/**
* Validates the peer pages for an index page.
*
* @param dpMain the index page
*/
private void validatePeers(DataPageMain dpMain) throws IOException {
DataPageMain prevMain = _dataPages.get(dpMain._prevPageNumber);
if(prevMain != null) {
if((int)prevMain._nextPageNumber != dpMain._pageNumber) {
throw new IllegalStateException("Prev page " + prevMain +
" does not ref " + dpMain);
}
validatePeerStatus(dpMain, prevMain);
}
DataPageMain nextMain = _dataPages.get(dpMain._nextPageNumber);
if(nextMain != null) {
if((int)nextMain._prevPageNumber != dpMain._pageNumber) {
throw new IllegalStateException("Next page " + nextMain +
" does not ref " + dpMain);
}
validatePeerStatus(dpMain, nextMain);
}
}
/**
* Validates the given peer page against the given index page
*
* @param dpMain the index page
* @param peerMain the peer index page
*/
private void validatePeerStatus(DataPageMain dpMain, DataPageMain peerMain)
throws IOException
{
if(dpMain._leaf != peerMain._leaf) {
throw new IllegalStateException("Mismatched peer status " +
dpMain._leaf + " " + peerMain._leaf);
}
if(!dpMain._leaf) {
if((dpMain._parentPageNumber != null) &&
(peerMain._parentPageNumber != null) &&
((int)dpMain._parentPageNumber != (int)peerMain._parentPageNumber)) {
throw new IllegalStateException("Mismatched node parents " +
dpMain._parentPageNumber + " " +
peerMain._parentPageNumber);
}
}
}
/**
* Dumps the given index page to a StringBuilder
*
* @param rtn the StringBuilder to update
* @param dpMain the index page to dump
*/
private void dumpPage(StringBuilder rtn, DataPageMain dpMain) {
try {
CacheDataPage cacheDataPage = new CacheDataPage(dpMain);
rtn.append(cacheDataPage).append("\n");
if(!dpMain._leaf) {
for(Entry e : cacheDataPage._extra._entryView) {
DataPageMain childMain = dpMain.getChildPage(e);
dumpPage(rtn, childMain);
}
}
} catch(IOException e) {
rtn.append("Page[" + dpMain._pageNumber + "]: " + e);
}
}
@Override
public String toString() {
if(_rootPage == null) {
return "Cache: (uninitialized)";
}
StringBuilder rtn = new StringBuilder("Cache: \n");
dumpPage(rtn, _rootPage);
return rtn.toString();
}
/**
* Keeps track of the main info for an index page.
*/
private class DataPageMain
{
public final int _pageNumber;
public Integer _prevPageNumber;
public Integer _nextPageNumber;
public Integer _childTailPageNumber;
public Integer _parentPageNumber;
public boolean _leaf;
public boolean _tail;
private Reference<DataPageExtra> _extra;
private DataPageMain(int pageNumber) {
_pageNumber = pageNumber;
}
public IndexPageCache getCache() {
return IndexPageCache.this;
}
public boolean isRoot() {
return(this == _rootPage);
}
public boolean isTail() throws IOException
{
resolveParent();
return _tail;
}
public boolean hasChildTail() {
return((int)_childTailPageNumber != INVALID_INDEX_PAGE_NUMBER);
}
public boolean isChildTailPageNumber(int pageNumber) {
return((int)_childTailPageNumber == pageNumber);
}
public DataPageMain getParentPage() throws IOException
{
resolveParent();
return IndexPageCache.this.getDataPage(_parentPageNumber);
}
public void initParentPage(Integer parentPageNumber, boolean isTail) {
// only set if not already set
if(_parentPageNumber == null) {
setParentPage(parentPageNumber, isTail);
}
}
public void setParentPage(Integer parentPageNumber, boolean isTail) {
_parentPageNumber = parentPageNumber;
_tail = isTail;
}
public DataPageMain getPrevPage() throws IOException
{
return IndexPageCache.this.getDataPage(_prevPageNumber);
}
public DataPageMain getNextPage() throws IOException
{
return IndexPageCache.this.getDataPage(_nextPageNumber);
}
public DataPageMain getChildPage(Entry e) throws IOException
{
Integer childPageNumber = e.getSubPageNumber();
return getChildPage(childPageNumber,
isChildTailPageNumber(childPageNumber));
}
public DataPageMain getChildTailPage() throws IOException
{
return getChildPage(_childTailPageNumber, true);
}
/**
* Returns a child page for the given page number, updating its parent
* info if necessary.
*/
private DataPageMain getChildPage(Integer childPageNumber, boolean isTail)
throws IOException
{
DataPageMain child = getDataPage(childPageNumber);
if(child != null) {
// set the parent info for this child (if necessary)
child.initParentPage(_pageNumber, isTail);
}
return child;
}
public DataPageExtra getExtra() throws IOException
{
DataPageExtra extra = _extra.get();
if(extra == null) {
extra = readDataPage(_pageNumber)._extra;
setExtra(extra);
}
return extra;
}
public void setExtra(DataPageExtra extra) throws IOException
{
extra.setEntryView(this);
_extra = new SoftReference<DataPageExtra>(extra);
}
private void resolveParent() throws IOException {
if(_parentPageNumber == null) {
// the act of searching for the last entry should resolve any parent
// pages along the path
findCacheDataPage(getExtra()._entryView.getLast());
if(_parentPageNumber == null) {
throw new IllegalStateException("Parent was not resolved");
}
}
}
@Override
public String toString() {
return (_leaf ? "Leaf" : "Node") + "DPMain[" + _pageNumber +
"] " + _prevPageNumber + ", " + _nextPageNumber + ", (" +
_childTailPageNumber + ")";
}
}
/**
* Keeps track of the extra info for an index page. This info (if
* unmodified) may be re-read from disk as necessary.
*/
private static class DataPageExtra
{
/** sorted collection of index entries. this is kept in a list instead of
a SortedSet because the SortedSet has lame traversal utilities */
public List<Entry> _entries;
public EntryListView _entryView;
public byte[] _entryPrefix;
public int _totalEntrySize;
public boolean _modified;
private DataPageExtra()
{
}
public void setEntryView(DataPageMain main) throws IOException {
_entryView = new EntryListView(main, this);
}
public void updateEntryPrefix() {
if(_entryPrefix.length == 0) {
// prefix is only related to *real* entries, tail not included
_entryPrefix = findCommonPrefix(_entries.get(0),
_entries.get(_entries.size() - 1));
}
}
@Override
public String toString() {
return "DPExtra: " + _entryView;
}
}
/**
* IndexPageCache implementation of an {@link Index.DataPage}.
*/
public static final class CacheDataPage
extends Index.DataPage
{
public final DataPageMain _main;
public final DataPageExtra _extra;
private CacheDataPage(DataPageMain dataPage) throws IOException {
this(dataPage, dataPage.getExtra());
}
private CacheDataPage(DataPageMain dataPage, DataPageExtra extra) {
_main = dataPage;
_extra = extra;
}
@Override
public int getPageNumber() {
return _main._pageNumber;
}
@Override
public boolean isLeaf() {
return _main._leaf;
}
@Override
public void setLeaf(boolean isLeaf) {
_main._leaf = isLeaf;
}
@Override
public int getPrevPageNumber() {
return _main._prevPageNumber;
}
@Override
public void setPrevPageNumber(int pageNumber) {
_main._prevPageNumber = pageNumber;
}
@Override
public int getNextPageNumber() {
return _main._nextPageNumber;
}
@Override
public void setNextPageNumber(int pageNumber) {
_main._nextPageNumber = pageNumber;
}
@Override
public int getChildTailPageNumber() {
return _main._childTailPageNumber;
}
@Override
public void setChildTailPageNumber(int pageNumber) {
_main._childTailPageNumber = pageNumber;
}
@Override
public int getTotalEntrySize() {
return _extra._totalEntrySize;
}
@Override
public void setTotalEntrySize(int totalSize) {
_extra._totalEntrySize = totalSize;
}
@Override
public byte[] getEntryPrefix() {
return _extra._entryPrefix;
}
@Override
public void setEntryPrefix(byte[] entryPrefix) {
_extra._entryPrefix = entryPrefix;
}
@Override
public List<Entry> getEntries() {
return _extra._entries;
}
@Override
public void setEntries(List<Entry> entries) {
_extra._entries = entries;
}
@Override
public void addEntry(int idx, Entry entry) throws IOException {
_main.getCache().addEntry(this, idx, entry);
}
@Override
public void removeEntry(int idx) throws IOException {
_main.getCache().removeEntry(this, idx);
}
}
/**
* A view of an index page's entries which combines the normal entries and
* tail entry into one collection.
*/
private static class EntryListView extends AbstractList<Entry>
implements RandomAccess
{
private final DataPageExtra _extra;
private Entry _childTailEntry;
private EntryListView(DataPageMain main, DataPageExtra extra)
throws IOException
{
if(main.hasChildTail()) {
_childTailEntry = main.getChildTailPage().getExtra()._entryView
.getLast().asNodeEntry(main._childTailPageNumber);
}
_extra = extra;
}
private List<Entry> getEntries() {
return _extra._entries;
}
@Override
public int size() {
int size = getEntries().size();
if(hasChildTail()) {
++size;
}
return size;
}
@Override
public Entry get(int idx) {
return (isCurrentChildTailIndex(idx) ?
_childTailEntry :
getEntries().get(idx));
}
@Override
public Entry set(int idx, Entry newEntry) {
return (isCurrentChildTailIndex(idx) ?
setChildTailEntry(newEntry) :
getEntries().set(idx, newEntry));
}
@Override
public void add(int idx, Entry newEntry) {
// note, we will never add to the "tail" entry, that will always be
// handled through promoteTail
getEntries().add(idx, newEntry);
}
@Override
public Entry remove(int idx) {
return (isCurrentChildTailIndex(idx) ?
setChildTailEntry(null) :
getEntries().remove(idx));
}
public Entry setChildTailEntry(Entry newEntry) {
Entry old = _childTailEntry;
_childTailEntry = newEntry;
return old;
}
public Entry getChildTailEntry() {
return _childTailEntry;
}
private boolean hasChildTail() {
return(_childTailEntry != null);
}
private boolean isCurrentChildTailIndex(int idx) {
return(idx == getEntries().size());
}
public Entry getLast() {
return(hasChildTail() ? _childTailEntry :
(!getEntries().isEmpty() ?
getEntries().get(getEntries().size() - 1) : null));
}
public Entry demoteTail() {
Entry tail = _childTailEntry;
_childTailEntry = null;
getEntries().add(tail);
return tail;
}
public Entry promoteTail() {
Entry last = getEntries().remove(getEntries().size() - 1);
_childTailEntry = last;
return last;
}
public int find(Entry e) {
return Collections.binarySearch(this, e);
}
}
}
| src/java/com/healthmarketscience/jackcess/IndexPageCache.java | /*
Copyright (c) 2008 Health Market Science, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
You can contact Health Market Science at [email protected]
or at the following address:
Health Market Science
2700 Horizon Drive
Suite 200
King of Prussia, PA 19406
*/
package com.healthmarketscience.jackcess;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
import static com.healthmarketscience.jackcess.Index.*;
/**
* Manager of the index pages for a BigIndex.
* @author James Ahlborn
*/
public class IndexPageCache
{
private enum UpdateType {
ADD, REMOVE, REPLACE;
}
/** the index whose pages this cache is managing */
private final BigIndex _index;
/** the root page for the index */
private DataPageMain _rootPage;
/** the currently loaded pages for this index, pageNumber -> page */
private final Map<Integer, DataPageMain> _dataPages =
new HashMap<Integer, DataPageMain>();
/** the currently modified index pages */
private final List<CacheDataPage> _modifiedPages =
new ArrayList<CacheDataPage>();
public IndexPageCache(BigIndex index) {
_index = index;
}
public BigIndex getIndex() {
return _index;
}
public PageChannel getPageChannel() {
return getIndex().getPageChannel();
}
public void setRootPageNumber(int pageNumber) throws IOException {
_rootPage = getDataPage(pageNumber);
// root page has no parent
_rootPage.initParentPage(INVALID_INDEX_PAGE_NUMBER, false);
}
public void write()
throws IOException
{
// first discard any empty pages
handleEmptyPages();
// next, handle any necessary page splitting
preparePagesForWriting();
// finally, write all the modified pages (which are not being deleted)
writeDataPages();
}
private void handleEmptyPages() throws IOException
{
for(Iterator<CacheDataPage> iter = _modifiedPages.iterator();
iter.hasNext(); ) {
CacheDataPage cacheDataPage = iter.next();
if(cacheDataPage._extra._entryView.isEmpty()) {
if(!cacheDataPage._main.isRoot()) {
deleteDataPage(cacheDataPage);
} else {
writeDataPage(cacheDataPage);
}
iter.remove();
}
}
}
private void preparePagesForWriting() throws IOException
{
boolean splitPages = false;
int maxPageEntrySize = getIndex().getMaxPageEntrySize();
do {
splitPages = false;
// we might be adding to this list while iterating, so we can't use an
// iterator
for(int i = 0; i < _modifiedPages.size(); ++i) {
CacheDataPage cacheDataPage = _modifiedPages.get(i);
if(!cacheDataPage.isLeaf()) {
// see if we need to update any child tail status
DataPageMain dpMain = cacheDataPage._main;
int size = cacheDataPage._extra._entryView.size();
if(dpMain.hasChildTail()) {
if(size == 1) {
demoteTail(cacheDataPage);
}
} else {
if(size > 1) {
promoteTail(cacheDataPage);
}
}
}
// look for pages with more entries than can fit on a page
if(cacheDataPage.getTotalEntrySize() > maxPageEntrySize) {
// make sure the prefix is up-to-date (this may have gotten
// discarded by one of the update entry methods)
cacheDataPage._extra.updateEntryPrefix();
// now, see if the page will fit when compressed
if(cacheDataPage.getCompressedEntrySize() > maxPageEntrySize) {
// need to split this page
splitPages = true;
splitDataPage(cacheDataPage);
}
}
}
} while(splitPages);
}
private void writeDataPages() throws IOException
{
for(CacheDataPage cacheDataPage : _modifiedPages) {
if(cacheDataPage._extra._entryView.isEmpty()) {
throw new IllegalStateException("Unexpected empty page " +
cacheDataPage);
}
writeDataPage(cacheDataPage);
}
_modifiedPages.clear();
}
public CacheDataPage getCacheDataPage(Integer pageNumber)
throws IOException
{
DataPageMain main = getDataPage(pageNumber);
return((main != null) ? new CacheDataPage(main) : null);
}
private DataPageMain getChildDataPage(Integer childPageNumber,
DataPageMain parent,
boolean isTail)
throws IOException
{
DataPageMain child = getDataPage(childPageNumber);
if(child != null) {
// set the parent info for this child (if necessary)
child.initParentPage(parent._pageNumber, isTail);
}
return child;
}
private DataPageMain getDataPage(Integer pageNumber)
throws IOException
{
DataPageMain dataPage = _dataPages.get(pageNumber);
if((dataPage == null) && (pageNumber > INVALID_INDEX_PAGE_NUMBER)) {
dataPage = readDataPage(pageNumber)._main;
_dataPages.put(pageNumber, dataPage);
}
return dataPage;
}
/**
* Writes the given index page to the file.
*/
private void writeDataPage(CacheDataPage cacheDataPage)
throws IOException
{
getIndex().writeDataPage(cacheDataPage);
// lastly, mark the page as no longer modified
cacheDataPage._extra._modified = false;
}
/**
* Deletes the given index page from the file (clears the page).
*/
private void deleteDataPage(CacheDataPage cacheDataPage)
throws IOException
{
// free this database page
getPageChannel().deallocatePage(cacheDataPage._main._pageNumber);
// discard from our cache
_dataPages.remove(cacheDataPage._main._pageNumber);
// lastly, mark the page as no longer modified
cacheDataPage._extra._modified = false;
}
/**
* Reads the given index page from the file.
*/
private CacheDataPage readDataPage(Integer pageNumber)
throws IOException
{
DataPageMain dataPage = new DataPageMain(pageNumber);
DataPageExtra extra = new DataPageExtra();
CacheDataPage cacheDataPage = new CacheDataPage(dataPage, extra);
getIndex().readDataPage(cacheDataPage);
// associate the extra info with the main data page
dataPage.setExtra(extra);
return cacheDataPage;
}
private void removeEntry(CacheDataPage cacheDataPage, int entryIdx)
throws IOException
{
updateEntry(cacheDataPage, entryIdx, null, UpdateType.REMOVE);
}
private void addEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry)
throws IOException
{
updateEntry(cacheDataPage, entryIdx, newEntry, UpdateType.ADD);
}
private void updateEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry,
UpdateType upType)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
if(newEntry != null) {
validateEntryForPage(dpMain, newEntry);
}
// note, it's slightly ucky, but we need to load the parent page before we
// start mucking with our entries because our parent may use our entries.
CacheDataPage parentDataPage = (!dpMain.isRoot() ?
new CacheDataPage(dpMain.getParentPage()) :
null);
Entry oldLastEntry = dpExtra._entryView.getLast();
Entry oldEntry = null;
int entrySizeDiff = 0;
switch(upType) {
case ADD:
dpExtra._entryView.add(entryIdx, newEntry);
entrySizeDiff += newEntry.size();
break;
case REPLACE:
oldEntry = dpExtra._entryView.set(entryIdx, newEntry);
entrySizeDiff += newEntry.size() - oldEntry.size();
break;
case REMOVE: {
oldEntry = dpExtra._entryView.remove(entryIdx);
entrySizeDiff -= oldEntry.size();
break;
}
default:
throw new RuntimeException("unknown update type " + upType);
}
boolean updateLast = (oldLastEntry != dpExtra._entryView.getLast());
// child tail entry updates do not modify the page
if(!updateLast || !dpMain.hasChildTail()) {
dpExtra._totalEntrySize += entrySizeDiff;
setModified(cacheDataPage);
// for now, just clear the prefix, we'll fix it later
dpExtra._entryPrefix = EMPTY_PREFIX;
}
if(dpExtra._entryView.isEmpty()) {
// this page is dead
removeDataPage(parentDataPage, cacheDataPage, oldLastEntry);
return;
}
// determine if we need to update our parent page
if(!updateLast || dpMain.isRoot()) {
// no parent
return;
}
// the update to the last entry needs to be propagated to our parent
replaceParentEntry(parentDataPage, cacheDataPage, oldLastEntry);
}
private void removeDataPage(CacheDataPage parentDataPage,
CacheDataPage cacheDataPage,
Entry oldLastEntry)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
if(dpMain.hasChildTail()) {
throw new IllegalStateException("Still has child tail?");
}
if(dpExtra._totalEntrySize != 0) {
throw new IllegalStateException("Empty page but size is not 0? " +
dpExtra._totalEntrySize + ", " +
cacheDataPage);
}
if(dpMain.isRoot()) {
// clear out this page (we don't actually remove it)
dpExtra._entryPrefix = EMPTY_PREFIX;
// when the root page becomes empty, it becomes a leaf page again
dpMain._leaf = true;
return;
}
// remove this page from its parent page
updateParentEntry(parentDataPage, cacheDataPage, oldLastEntry, null,
UpdateType.REMOVE);
// remove this page from any next/prev pages
removeFromPeers(cacheDataPage);
}
private void removeFromPeers(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
Integer prevPageNumber = dpMain._prevPageNumber;
Integer nextPageNumber = dpMain._nextPageNumber;
DataPageMain prevMain = dpMain.getPrevPage();
if(prevMain != null) {
setModified(new CacheDataPage(prevMain));
prevMain._nextPageNumber = nextPageNumber;
}
DataPageMain nextMain = dpMain.getNextPage();
if(nextMain != null) {
setModified(new CacheDataPage(nextMain));
nextMain._prevPageNumber = prevPageNumber;
}
}
private void addParentEntry(CacheDataPage parentDataPage,
CacheDataPage childDataPage)
throws IOException
{
DataPageExtra childExtra = childDataPage._extra;
updateParentEntry(parentDataPage, childDataPage, null,
childExtra._entryView.getLast(), UpdateType.ADD);
}
private void replaceParentEntry(CacheDataPage parentDataPage,
CacheDataPage childDataPage,
Entry oldEntry)
throws IOException
{
DataPageExtra childExtra = childDataPage._extra;
updateParentEntry(parentDataPage, childDataPage, oldEntry,
childExtra._entryView.getLast(), UpdateType.REPLACE);
}
private void updateParentEntry(CacheDataPage parentDataPage,
CacheDataPage childDataPage,
Entry oldEntry, Entry newEntry,
UpdateType upType)
throws IOException
{
DataPageMain childMain = childDataPage._main;
DataPageExtra parentExtra = parentDataPage._extra;
if(childMain.isTail() && (upType != UpdateType.REMOVE)) {
// for add or replace, update the child tail info before updating the
// parent entries
updateParentTail(parentDataPage, childDataPage, upType);
}
if(oldEntry != null) {
oldEntry = oldEntry.asNodeEntry(childMain._pageNumber);
}
if(newEntry != null) {
newEntry = newEntry.asNodeEntry(childMain._pageNumber);
}
boolean expectFound = true;
int idx = 0;
switch(upType) {
case ADD:
expectFound = false;
idx = parentExtra._entryView.find(newEntry);
break;
case REPLACE:
case REMOVE:
idx = parentExtra._entryView.find(oldEntry);
break;
default:
throw new RuntimeException("unknown update type " + upType);
}
if(idx < 0) {
if(expectFound) {
throw new IllegalStateException(
"Could not find child entry in parent; childEntry " + oldEntry +
"; parent " + parentDataPage);
}
idx = missingIndexToInsertionPoint(idx);
} else {
if(!expectFound) {
throw new IllegalStateException(
"Unexpectedly found child entry in parent; childEntry " +
newEntry + "; parent " + parentDataPage);
}
}
updateEntry(parentDataPage, idx, newEntry, upType);
if(childMain.isTail() && (upType == UpdateType.REMOVE)) {
// for remove, update the child tail info after updating the parent
// entries
updateParentTail(parentDataPage, childDataPage, upType);
}
}
private void updateParentTail(CacheDataPage parentDataPage,
CacheDataPage childDataPage,
UpdateType upType)
throws IOException
{
DataPageMain childMain = childDataPage._main;
DataPageMain parentMain = parentDataPage._main;
int newChildTailPageNumber =
((upType == UpdateType.REMOVE) ?
INVALID_INDEX_PAGE_NUMBER :
childMain._pageNumber);
if(!parentMain.isChildTailPageNumber(newChildTailPageNumber)) {
setModified(parentDataPage);
parentMain._childTailPageNumber = newChildTailPageNumber;
}
}
private void validateEntryForPage(DataPageMain dpMain, Entry entry) {
if(dpMain._leaf != entry.isLeafEntry()) {
throw new IllegalStateException(
"Trying to update page with wrong entry type; pageLeaf " +
dpMain._leaf + ", entryLeaf " + entry.isLeafEntry());
}
}
private void splitDataPage(CacheDataPage origDataPage)
throws IOException
{
DataPageMain origMain = origDataPage._main;
DataPageExtra origExtra = origDataPage._extra;
setModified(origDataPage);
int numEntries = origExtra._entries.size();
if(numEntries < 2) {
throw new IllegalStateException(
"Cannot split page with less than 2 entries " + origDataPage);
}
if(origMain.isRoot()) {
// we can't split the root page directly, so we need to put another page
// between the root page and its sub-pages, and then split that page.
CacheDataPage newDataPage = nestRootDataPage(origDataPage);
// now, split this new page instead
origDataPage = newDataPage;
origMain = newDataPage._main;
origExtra = newDataPage._extra;
}
// note, it's slightly ucky, but we need to load the parent page before we
// start mucking with our entries because our parent may use our entries.
DataPageMain parentMain = origMain.getParentPage();
CacheDataPage parentDataPage = new CacheDataPage(parentMain);
// note, there are many, many ways this could be improved/tweaked. for
// now, we just want it to be functional...
// so, we will naively move half the entries from one page to a new page.
CacheDataPage newDataPage = allocateNewCacheDataPage(
parentMain._pageNumber, origMain._leaf);
DataPageMain newMain = newDataPage._main;
DataPageExtra newExtra = newDataPage._extra;
List<Entry> headEntries =
origExtra._entries.subList(0, ((numEntries + 1) / 2));
// move first half of the entries from old page to new page
for(Entry headEntry : headEntries) {
newExtra._totalEntrySize += headEntry.size();
newExtra._entries.add(headEntry);
}
newExtra.setEntryView(newMain);
// remove the moved entries from the old page
headEntries.clear();
origExtra._entryPrefix = EMPTY_PREFIX;
origExtra._totalEntrySize -= newExtra._totalEntrySize;
// insert this new page between the old page and any previous page
addToPeersBefore(newDataPage, origDataPage);
if(!newMain._leaf) {
// reparent the children pages of the new page
reparentChildren(newDataPage);
// if the children of this page are also node pages, then the next/prev
// links should not cross parent boundaries (the leaf pages are linked
// from beginning to end, but child node pages are only linked within
// the same parent)
DataPageMain childMain = newMain.getChildPage(
newExtra._entryView.getLast());
if(!childMain._leaf) {
separateFromNextPeer(new CacheDataPage(childMain));
}
}
// lastly, we need to add the new page to the parent page's entries
addParentEntry(parentDataPage, newDataPage);
}
private CacheDataPage nestRootDataPage(CacheDataPage rootDataPage)
throws IOException
{
DataPageMain rootMain = rootDataPage._main;
DataPageExtra rootExtra = rootDataPage._extra;
if(!rootMain.isRoot()) {
throw new IllegalArgumentException("should be called with root, duh");
}
CacheDataPage newDataPage =
allocateNewCacheDataPage(rootMain._pageNumber, rootMain._leaf);
DataPageMain newMain = newDataPage._main;
DataPageExtra newExtra = newDataPage._extra;
// move entries to new page
newMain._childTailPageNumber = rootMain._childTailPageNumber;
newExtra._entries = rootExtra._entries;
newExtra._entryPrefix = rootExtra._entryPrefix;
newExtra._totalEntrySize = rootExtra._totalEntrySize;
newExtra.setEntryView(newMain);
if(!newMain._leaf) {
// we need to re-parent all the child pages
reparentChildren(newDataPage);
}
// clear the root page
rootMain._leaf = false;
rootMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
rootExtra._entries = new ArrayList<Entry>();
rootExtra._entryPrefix = EMPTY_PREFIX;
rootExtra._totalEntrySize = 0;
rootExtra.setEntryView(rootMain);
// add the new page as the first child of the root page
addParentEntry(rootDataPage, newDataPage);
return newDataPage;
}
private CacheDataPage allocateNewCacheDataPage(Integer parentPageNumber,
boolean isLeaf)
throws IOException
{
DataPageMain dpMain = new DataPageMain(getPageChannel().allocateNewPage());
DataPageExtra dpExtra = new DataPageExtra();
dpMain.initParentPage(parentPageNumber, false);
dpMain._leaf = isLeaf;
dpMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpExtra._entries = new ArrayList<Entry>();
dpExtra._entryPrefix = EMPTY_PREFIX;
dpMain.setExtra(dpExtra);
// add to our page cache
_dataPages.put(dpMain._pageNumber, dpMain);
// needs to be written out
CacheDataPage cacheDataPage = new CacheDataPage(dpMain, dpExtra);
setModified(cacheDataPage);
return cacheDataPage;
}
private void addToPeersBefore(CacheDataPage newDataPage,
CacheDataPage origDataPage)
throws IOException
{
DataPageMain origMain = origDataPage._main;
DataPageMain newMain = newDataPage._main;
DataPageMain prevMain = origMain.getPrevPage();
newMain._nextPageNumber = origMain._pageNumber;
newMain._prevPageNumber = origMain._prevPageNumber;
origMain._prevPageNumber = newMain._pageNumber;
if(prevMain != null) {
setModified(new CacheDataPage(prevMain));
prevMain._nextPageNumber = newMain._pageNumber;
}
}
private void separateFromNextPeer(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
setModified(cacheDataPage);
DataPageMain nextMain = dpMain.getNextPage();
setModified(new CacheDataPage(nextMain));
nextMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
}
private void reparentChildren(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
// note, the "parent" page number is not actually persisted, so we do not
// need to mark any updated pages as modified. for the same reason, we
// don't need to load the pages if not already loaded
for(Entry entry : dpExtra._entryView) {
Integer childPageNumber = entry.getSubPageNumber();
DataPageMain childMain = _dataPages.get(childPageNumber);
if(childMain != null) {
childMain.setParentPage(dpMain._pageNumber,
dpMain.isChildTailPageNumber(childPageNumber));
}
}
}
private void demoteTail(CacheDataPage cacheDataPage)
throws IOException
{
// there's only one entry on the page, and it's the tail. make it a
// normal entry
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
setModified(cacheDataPage);
DataPageMain tailMain = dpMain.getChildTailPage();
CacheDataPage tailDataPage = new CacheDataPage(tailMain);
// move the tail entry to the last normal entry
updateParentTail(cacheDataPage, tailDataPage, UpdateType.REMOVE);
Entry tailEntry = dpExtra._entryView.demoteTail();
dpExtra._totalEntrySize += tailEntry.size();
dpExtra._entryPrefix = EMPTY_PREFIX;
tailMain.setParentPage(dpMain._pageNumber, false);
}
private void promoteTail(CacheDataPage cacheDataPage)
throws IOException
{
// there's not tail currently on this page, make last entry a tail
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
setModified(cacheDataPage);
DataPageMain lastMain = dpMain.getChildPage(dpExtra._entryView.getLast());
CacheDataPage lastDataPage = new CacheDataPage(lastMain);
// move the "last" normal entry to the tail entry
updateParentTail(cacheDataPage, lastDataPage, UpdateType.ADD);
Entry lastEntry = dpExtra._entryView.promoteTail();
dpExtra._totalEntrySize -= lastEntry.size();
dpExtra._entryPrefix = EMPTY_PREFIX;
lastMain.setParentPage(dpMain._pageNumber, true);
}
public CacheDataPage findCacheDataPage(Entry e)
throws IOException
{
DataPageMain curPage = _rootPage;
while(true) {
if(curPage._leaf) {
// nowhere to go from here
return new CacheDataPage(curPage);
}
DataPageExtra extra = curPage.getExtra();
// need to descend
int idx = extra._entryView.find(e);
if(idx < 0) {
idx = missingIndexToInsertionPoint(idx);
if(idx == extra._entryView.size()) {
// just move to last child page
--idx;
}
}
Entry nodeEntry = extra._entryView.get(idx);
curPage = curPage.getChildPage(nodeEntry);
}
}
private void setModified(CacheDataPage cacheDataPage)
{
if(!cacheDataPage._extra._modified) {
_modifiedPages.add(cacheDataPage);
cacheDataPage._extra._modified = true;
}
}
private static byte[] findCommonPrefix(Entry e1, Entry e2)
{
return findCommonPrefix(e1.getEntryBytes(), e2.getEntryBytes());
}
private static byte[] findCommonPrefix(byte[] b1, byte[] b2)
{
int maxLen = b1.length;
byte[] prefix = b1;
if(b1.length > b2.length) {
maxLen = b2.length;
prefix = b2;
}
int len = 0;
while((len < maxLen) && (b1[len] == b2[len])) {
++len;
}
if(len < prefix.length) {
if(len == 0) {
return EMPTY_PREFIX;
}
// need new prefix
byte[] tmpPrefix = new byte[len];
System.arraycopy(prefix, 0, tmpPrefix, 0, len);
prefix = tmpPrefix;
}
return prefix;
}
/**
* Used by unit tests to validate the internal status of the index.
*/
void validate() throws IOException {
for(DataPageMain dpMain : _dataPages.values()) {
DataPageExtra dpExtra = dpMain.getExtra();
validateEntries(dpExtra);
validateChildren(dpMain, dpExtra);
validatePeers(dpMain);
}
}
private void validateEntries(DataPageExtra dpExtra) throws IOException {
int entrySize = 0;
Entry prevEntry = Index.FIRST_ENTRY;
for(Entry e : dpExtra._entries) {
entrySize += e.size();
if(prevEntry.compareTo(e) >= 0) {
throw new IOException("Unexpected order in index entries, " +
prevEntry + " >= " + e);
}
prevEntry = e;
}
if(entrySize != dpExtra._totalEntrySize) {
throw new IllegalStateException("Expected size " + entrySize +
" but was " + dpExtra._totalEntrySize);
}
}
private void validateChildren(DataPageMain dpMain,
DataPageExtra dpExtra) throws IOException {
int childTailPageNumber = dpMain._childTailPageNumber;
if(dpMain._leaf) {
if(childTailPageNumber != INVALID_INDEX_PAGE_NUMBER) {
throw new IllegalStateException("Leaf page has tail " + dpMain);
}
return;
}
if((dpExtra._entryView.size() == 1) && dpMain.hasChildTail()) {
throw new IllegalStateException("Single child is tail " + dpMain);
}
for(Entry e : dpExtra._entryView) {
validateEntryForPage(dpMain, e);
Integer subPageNumber = e.getSubPageNumber();
DataPageMain childMain = _dataPages.get(subPageNumber);
if(childMain != null) {
if(childMain._parentPageNumber != null) {
if((int)childMain._parentPageNumber != dpMain._pageNumber) {
throw new IllegalStateException("Child's parent is incorrect " +
childMain);
}
boolean expectTail = ((int)subPageNumber == childTailPageNumber);
if(expectTail != childMain._tail) {
throw new IllegalStateException("Child tail status incorrect " +
childMain);
}
}
Entry lastEntry = childMain.getExtra()._entryView.getLast();
if(e.compareTo(lastEntry) != 0) {
throw new IllegalStateException("Invalid entry " + e +
" but child is " + lastEntry);
}
}
}
}
private void validatePeers(DataPageMain dpMain) throws IOException {
DataPageMain prevMain = _dataPages.get(dpMain._prevPageNumber);
if(prevMain != null) {
if((int)prevMain._nextPageNumber != dpMain._pageNumber) {
throw new IllegalStateException("Prev page " + prevMain +
" does not ref " + dpMain);
}
validatePeerStatus(dpMain, prevMain);
}
DataPageMain nextMain = _dataPages.get(dpMain._nextPageNumber);
if(nextMain != null) {
if((int)nextMain._prevPageNumber != dpMain._pageNumber) {
throw new IllegalStateException("Next page " + nextMain +
" does not ref " + dpMain);
}
validatePeerStatus(dpMain, nextMain);
}
}
private void validatePeerStatus(DataPageMain dpMain, DataPageMain peerMain)
throws IOException
{
if(dpMain._leaf != peerMain._leaf) {
throw new IllegalStateException("Mismatched peer status " +
dpMain._leaf + " " + peerMain._leaf);
}
if(!dpMain._leaf) {
if((dpMain._parentPageNumber != null) &&
(peerMain._parentPageNumber != null) &&
((int)dpMain._parentPageNumber != (int)peerMain._parentPageNumber)) {
throw new IllegalStateException("Mismatched node parents " +
dpMain._parentPageNumber + " " +
peerMain._parentPageNumber);
}
}
}
private void dumpPage(StringBuilder rtn, DataPageMain dpMain) {
try {
CacheDataPage cacheDataPage = new CacheDataPage(dpMain);
rtn.append(cacheDataPage).append("\n");
if(!dpMain._leaf) {
for(Entry e : cacheDataPage._extra._entryView) {
DataPageMain childMain = dpMain.getChildPage(e);
dumpPage(rtn, childMain);
}
}
} catch(IOException e) {
rtn.append("Page[" + dpMain._pageNumber + "]: " + e);
}
}
@Override
public String toString() {
if(_rootPage == null) {
return "Cache: (uninitialized)";
}
StringBuilder rtn = new StringBuilder("Cache: \n");
dumpPage(rtn, _rootPage);
return rtn.toString();
}
private class DataPageMain
{
public final int _pageNumber;
public Integer _prevPageNumber;
public Integer _nextPageNumber;
public Integer _childTailPageNumber;
public Integer _parentPageNumber;
public boolean _leaf;
public boolean _tail;
private Reference<DataPageExtra> _extra;
private DataPageMain(int pageNumber) {
_pageNumber = pageNumber;
}
public IndexPageCache getCache() {
return IndexPageCache.this;
}
public boolean isRoot() {
return(this == _rootPage);
}
public boolean isTail() throws IOException
{
resolveParent();
return _tail;
}
public boolean hasChildTail() {
return((int)_childTailPageNumber != INVALID_INDEX_PAGE_NUMBER);
}
public boolean isChildTailPageNumber(int pageNumber) {
return((int)_childTailPageNumber == pageNumber);
}
public DataPageMain getParentPage() throws IOException
{
resolveParent();
return IndexPageCache.this.getDataPage(_parentPageNumber);
}
public void initParentPage(Integer parentPageNumber, boolean isTail) {
// only set if not already set
if(_parentPageNumber == null) {
setParentPage(parentPageNumber, isTail);
}
}
public void setParentPage(Integer parentPageNumber, boolean isTail) {
_parentPageNumber = parentPageNumber;
_tail = isTail;
}
public DataPageMain getPrevPage() throws IOException
{
return IndexPageCache.this.getDataPage(_prevPageNumber);
}
public DataPageMain getNextPage() throws IOException
{
return IndexPageCache.this.getDataPage(_nextPageNumber);
}
public DataPageMain getChildPage(Entry e) throws IOException
{
Integer childPageNumber = e.getSubPageNumber();
return IndexPageCache.this.getChildDataPage(
childPageNumber, this, isChildTailPageNumber(childPageNumber));
}
public DataPageMain getChildTailPage() throws IOException
{
return IndexPageCache.this.getChildDataPage(
_childTailPageNumber, this, true);
}
public DataPageExtra getExtra() throws IOException
{
DataPageExtra extra = _extra.get();
if(extra == null) {
extra = readDataPage(_pageNumber)._extra;
setExtra(extra);
}
return extra;
}
public void setExtra(DataPageExtra extra) throws IOException
{
extra.setEntryView(this);
_extra = new SoftReference<DataPageExtra>(extra);
}
private void resolveParent() throws IOException {
if(_parentPageNumber == null) {
// the act of searching for the last entry should resolve any parent
// pages along the path
findCacheDataPage(getExtra()._entryView.getLast());
if(_parentPageNumber == null) {
throw new IllegalStateException("Parent was not resolved");
}
}
}
@Override
public String toString() {
return (_leaf ? "Leaf" : "Node") + "DPMain[" + _pageNumber +
"] " + _prevPageNumber + ", " + _nextPageNumber + ", (" +
_childTailPageNumber + ")";
}
}
private static class DataPageExtra
{
/** sorted collection of index entries. this is kept in a list instead of
a SortedSet because the SortedSet has lame traversal utilities */
public List<Entry> _entries;
public EntryListView _entryView;
public byte[] _entryPrefix;
public int _totalEntrySize;
public boolean _modified;
private DataPageExtra()
{
}
public void setEntryView(DataPageMain main) throws IOException {
_entryView = new EntryListView(main, this);
}
public void updateEntryPrefix() {
if(_entryPrefix.length == 0) {
// prefix is only related to *real* entries, tail not included
_entryPrefix = findCommonPrefix(_entries.get(0),
_entries.get(_entries.size() - 1));
}
}
@Override
public String toString() {
return "DPExtra: " + _entryView;
}
}
public static final class CacheDataPage
extends Index.DataPage
{
public final DataPageMain _main;
public final DataPageExtra _extra;
private CacheDataPage(DataPageMain dataPage) throws IOException {
this(dataPage, dataPage.getExtra());
}
private CacheDataPage(DataPageMain dataPage, DataPageExtra extra) {
_main = dataPage;
_extra = extra;
}
@Override
public int getPageNumber() {
return _main._pageNumber;
}
@Override
public boolean isLeaf() {
return _main._leaf;
}
@Override
public void setLeaf(boolean isLeaf) {
_main._leaf = isLeaf;
}
@Override
public int getPrevPageNumber() {
return _main._prevPageNumber;
}
@Override
public void setPrevPageNumber(int pageNumber) {
_main._prevPageNumber = pageNumber;
}
@Override
public int getNextPageNumber() {
return _main._nextPageNumber;
}
@Override
public void setNextPageNumber(int pageNumber) {
_main._nextPageNumber = pageNumber;
}
@Override
public int getChildTailPageNumber() {
return _main._childTailPageNumber;
}
@Override
public void setChildTailPageNumber(int pageNumber) {
_main._childTailPageNumber = pageNumber;
}
@Override
public int getTotalEntrySize() {
return _extra._totalEntrySize;
}
@Override
public void setTotalEntrySize(int totalSize) {
_extra._totalEntrySize = totalSize;
}
@Override
public byte[] getEntryPrefix() {
return _extra._entryPrefix;
}
@Override
public void setEntryPrefix(byte[] entryPrefix) {
_extra._entryPrefix = entryPrefix;
}
@Override
public List<Entry> getEntries() {
return _extra._entries;
}
@Override
public void setEntries(List<Entry> entries) {
_extra._entries = entries;
}
@Override
public void addEntry(int idx, Entry entry) throws IOException {
_main.getCache().addEntry(this, idx, entry);
}
@Override
public void removeEntry(int idx) throws IOException {
_main.getCache().removeEntry(this, idx);
}
}
private static class EntryListView extends AbstractList<Entry>
implements RandomAccess
{
private final DataPageExtra _extra;
private Entry _childTailEntry;
private EntryListView(DataPageMain main, DataPageExtra extra)
throws IOException
{
if(main.hasChildTail()) {
_childTailEntry = main.getChildTailPage().getExtra()._entryView
.getLast().asNodeEntry(main._childTailPageNumber);
}
_extra = extra;
}
private List<Entry> getEntries() {
return _extra._entries;
}
@Override
public int size() {
int size = getEntries().size();
if(hasChildTail()) {
++size;
}
return size;
}
@Override
public Entry get(int idx) {
return (isCurrentChildTailIndex(idx) ?
_childTailEntry :
getEntries().get(idx));
}
@Override
public Entry set(int idx, Entry newEntry) {
return (isCurrentChildTailIndex(idx) ?
setChildTailEntry(newEntry) :
getEntries().set(idx, newEntry));
}
@Override
public void add(int idx, Entry newEntry) {
// note, we will never add to the "tail" entry, that will always be
// handled through promoteTail
getEntries().add(idx, newEntry);
}
@Override
public Entry remove(int idx) {
return (isCurrentChildTailIndex(idx) ?
setChildTailEntry(null) :
getEntries().remove(idx));
}
public Entry setChildTailEntry(Entry newEntry) {
Entry old = _childTailEntry;
_childTailEntry = newEntry;
return old;
}
public Entry getChildTailEntry() {
return _childTailEntry;
}
private boolean hasChildTail() {
return(_childTailEntry != null);
}
private boolean isCurrentChildTailIndex(int idx) {
return(idx == getEntries().size());
}
public Entry getLast() {
return(hasChildTail() ? _childTailEntry :
(!getEntries().isEmpty() ?
getEntries().get(getEntries().size() - 1) : null));
}
public Entry demoteTail() {
Entry tail = _childTailEntry;
_childTailEntry = null;
getEntries().add(tail);
return tail;
}
public Entry promoteTail() {
Entry last = getEntries().remove(getEntries().size() - 1);
_childTailEntry = last;
return last;
}
public int find(Entry e) {
return Collections.binarySearch(this, e);
}
}
}
| add comments
git-svn-id: 3a2409cd0beef11b2606a17fdc4e1262b30a237e@345 f203690c-595d-4dc9-a70b-905162fa7fd2
| src/java/com/healthmarketscience/jackcess/IndexPageCache.java | add comments | <ide><path>rc/java/com/healthmarketscience/jackcess/IndexPageCache.java
<ide> return getIndex().getPageChannel();
<ide> }
<ide>
<add> /**
<add> * Sets the root page for this index, must be called before normal usage.
<add> *
<add> * @param pageNumber the root page number
<add> */
<ide> public void setRootPageNumber(int pageNumber) throws IOException {
<ide> _rootPage = getDataPage(pageNumber);
<ide> // root page has no parent
<ide> _rootPage.initParentPage(INVALID_INDEX_PAGE_NUMBER, false);
<ide> }
<ide>
<add> /**
<add> * Writes any outstanding changes for this index to the file.
<add> */
<ide> public void write()
<ide> throws IOException
<ide> {
<ide> writeDataPages();
<ide> }
<ide>
<add> /**
<add> * Handles any modified pages which are empty as the first pass during a
<add> * {@link #write} call. All empty pages are removed from the _modifiedPages
<add> * collection by this method.
<add> */
<ide> private void handleEmptyPages() throws IOException
<ide> {
<ide> for(Iterator<CacheDataPage> iter = _modifiedPages.iterator();
<ide> }
<ide> }
<ide>
<add> /**
<add> * Prepares any non-empty modified pages for writing as the second pass
<add> * during a {@link #write} call. Updates entry prefixes, promotes/demotes
<add> * tail pages, and splits pages as needed.
<add> */
<ide> private void preparePagesForWriting() throws IOException
<ide> {
<ide> boolean splitPages = false;
<ide> int maxPageEntrySize = getIndex().getMaxPageEntrySize();
<add>
<add> // we need to continue looping through all the pages until we do not split
<add> // any pages (because a split may cascade up the tree)
<ide> do {
<ide> splitPages = false;
<ide>
<ide> } while(splitPages);
<ide> }
<ide>
<add> /**
<add> * Writes any non-empty modified pages as the last pass during a
<add> * {@link #write} call. Clears the _modifiedPages collection when finised.
<add> */
<ide> private void writeDataPages() throws IOException
<ide> {
<ide> for(CacheDataPage cacheDataPage : _modifiedPages) {
<ide> _modifiedPages.clear();
<ide> }
<ide>
<add> /**
<add> * Returns a CacheDataPage for the given page number, may be {@code null} if
<add> * the given page number is invalid. Loads the given page if necessary.
<add> */
<ide> public CacheDataPage getCacheDataPage(Integer pageNumber)
<ide> throws IOException
<ide> {
<ide> DataPageMain main = getDataPage(pageNumber);
<ide> return((main != null) ? new CacheDataPage(main) : null);
<ide> }
<del>
<del> private DataPageMain getChildDataPage(Integer childPageNumber,
<del> DataPageMain parent,
<del> boolean isTail)
<del> throws IOException
<del> {
<del> DataPageMain child = getDataPage(childPageNumber);
<del> if(child != null) {
<del> // set the parent info for this child (if necessary)
<del> child.initParentPage(parent._pageNumber, isTail);
<del> }
<del> return child;
<del> }
<del>
<add>
<add> /**
<add> * Returns a DataPageMain for the given page number, may be {@code null} if
<add> * the given page number is invalid. Loads the given page if necessary.
<add> */
<ide> private DataPageMain getDataPage(Integer pageNumber)
<ide> throws IOException
<ide> {
<ide> return cacheDataPage;
<ide> }
<ide>
<add> /**
<add> * Removes the entry with the given index from the given page.
<add> *
<add> * @param cacheDataPage the page from which to remove the entry
<add> * @param entryIdx the index of the entry to remove
<add> */
<ide> private void removeEntry(CacheDataPage cacheDataPage, int entryIdx)
<ide> throws IOException
<ide> {
<ide> updateEntry(cacheDataPage, entryIdx, null, UpdateType.REMOVE);
<ide> }
<ide>
<add> /**
<add> * Adds the entry to the given page at the given index.
<add> *
<add> * @param cacheDataPage the page to which to add the entry
<add> * @param entryIdx the index at which to add the entry
<add> * @param newEntry the entry to add
<add> */
<ide> private void addEntry(CacheDataPage cacheDataPage,
<ide> int entryIdx,
<ide> Entry newEntry)
<ide> updateEntry(cacheDataPage, entryIdx, newEntry, UpdateType.ADD);
<ide> }
<ide>
<add> /**
<add> * Updates the entries on the given page according to the given updateType.
<add> *
<add> * @param cacheDataPage the page to update
<add> * @param entryIdx the index at which to add/remove/replace the entry
<add> * @param newEntry the entry to add/replace
<add> * @param upType the type of update to make
<add> */
<ide> private void updateEntry(CacheDataPage cacheDataPage,
<ide> int entryIdx,
<ide> Entry newEntry,
<ide> replaceParentEntry(parentDataPage, cacheDataPage, oldLastEntry);
<ide> }
<ide>
<add> /**
<add> * Removes an index page which has become empty. If this page is the root
<add> * page, just clears it.
<add> *
<add> * @param parentDataPage the parent of the removed page
<add> * @param cacheDataPage the page to remove
<add> * @param oldLastEntry the last entry for this page (before it was removed)
<add> */
<ide> private void removeDataPage(CacheDataPage parentDataPage,
<ide> CacheDataPage cacheDataPage,
<ide> Entry oldLastEntry)
<ide> removeFromPeers(cacheDataPage);
<ide> }
<ide>
<add> /**
<add> * Removes a now empty index page from its next and previous peers.
<add> *
<add> * @param cacheDataPage the page to remove
<add> */
<ide> private void removeFromPeers(CacheDataPage cacheDataPage)
<ide> throws IOException
<ide> {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Adds an entry for the given child page to the given parent page.
<add> *
<add> * @param parentDataPage the parent page to which to add the entry
<add> * @param childDataPage the child from which to get the entry to add
<add> */
<ide> private void addParentEntry(CacheDataPage parentDataPage,
<ide> CacheDataPage childDataPage)
<ide> throws IOException
<ide> childExtra._entryView.getLast(), UpdateType.ADD);
<ide> }
<ide>
<add> /**
<add> * Replaces the entry for the given child page in the given parent page.
<add> *
<add> * @param parentDataPage the parent page in which to replace the entry
<add> * @param childDataPage the child for which the entry is being replaced
<add> * @param oldEntry the old child entry for the child page
<add> */
<ide> private void replaceParentEntry(CacheDataPage parentDataPage,
<ide> CacheDataPage childDataPage,
<ide> Entry oldEntry)
<ide> childExtra._entryView.getLast(), UpdateType.REPLACE);
<ide> }
<ide>
<add> /**
<add> * Updates the entry for the given child page in the given parent page
<add> * according to the given updateType.
<add> *
<add> * @param parentDataPage the parent page in which to update the entry
<add> * @param childDataPage the child for which the entry is being updated
<add> * @param oldEntry the old child entry to remove/replace
<add> * @param newEntry the new child entry to replace/add
<add> * @param upType the type of update to make
<add> */
<ide> private void updateParentEntry(CacheDataPage parentDataPage,
<ide> CacheDataPage childDataPage,
<ide> Entry oldEntry, Entry newEntry,
<ide> }
<ide> }
<ide>
<add> /**
<add> * Updates the child tail info in the given parent page according to the
<add> * given updateType.
<add> *
<add> * @param parentDataPage the parent page in which to update the child tail
<add> * @param childDataPage the child to add/replace
<add> * @param upType the type of update to make
<add> */
<ide> private void updateParentTail(CacheDataPage parentDataPage,
<ide> CacheDataPage childDataPage,
<ide> UpdateType upType)
<ide> throws IOException
<ide> {
<del> DataPageMain childMain = childDataPage._main;
<ide> DataPageMain parentMain = parentDataPage._main;
<ide>
<ide> int newChildTailPageNumber =
<ide> ((upType == UpdateType.REMOVE) ?
<ide> INVALID_INDEX_PAGE_NUMBER :
<del> childMain._pageNumber);
<add> childDataPage._main._pageNumber);
<ide> if(!parentMain.isChildTailPageNumber(newChildTailPageNumber)) {
<ide> setModified(parentDataPage);
<ide> parentMain._childTailPageNumber = newChildTailPageNumber;
<ide> }
<ide> }
<ide>
<add> /**
<add> * Verifies that the given entry type (node/leaf) is valid for the given
<add> * page (node/leaf).
<add> *
<add> * @param dpMain the page to which the entry will be added
<add> * @param entry the entry being added
<add> * @throws IllegalStateException if the entry type does not match the page
<add> * type
<add> */
<ide> private void validateEntryForPage(DataPageMain dpMain, Entry entry) {
<ide> if(dpMain._leaf != entry.isLeafEntry()) {
<ide> throw new IllegalStateException(
<ide> }
<ide> }
<ide>
<add> /**
<add> * Splits an index page which has too many entries on it.
<add> *
<add> * @param origDataPage the page to split
<add> */
<ide> private void splitDataPage(CacheDataPage origDataPage)
<ide> throws IOException
<ide> {
<ide> List<Entry> headEntries =
<ide> origExtra._entries.subList(0, ((numEntries + 1) / 2));
<ide>
<del> // move first half of the entries from old page to new page
<add> // move first half of the entries from old page to new page (so we do not
<add> // need to muck with any tail entries)
<ide> for(Entry headEntry : headEntries) {
<ide> newExtra._totalEntrySize += headEntry.size();
<ide> newExtra._entries.add(headEntry);
<ide> addParentEntry(parentDataPage, newDataPage);
<ide> }
<ide>
<add> /**
<add> * Copies the current root page info into a new page and nests this page
<add> * under the root page. This must be done when the root page needs to be
<add> * split.
<add> *
<add> * @param rootDataPage the root data page
<add> *
<add> * @return the newly created page nested under the root page
<add> */
<ide> private CacheDataPage nestRootDataPage(CacheDataPage rootDataPage)
<ide> throws IOException
<ide> {
<ide> return newDataPage;
<ide> }
<ide>
<add> /**
<add> * Allocates a new index page with the given parent page and type.
<add> *
<add> * @param parentPageNumber the parent page for the new page
<add> * @param isLeaf whether or not the new page is a leaf page
<add> *
<add> * @return the newly created page
<add> */
<ide> private CacheDataPage allocateNewCacheDataPage(Integer parentPageNumber,
<ide> boolean isLeaf)
<ide> throws IOException
<ide> return cacheDataPage;
<ide> }
<ide>
<add> /**
<add> * Inserts the new page as a peer between the given original page and any
<add> * previous peer page.
<add> *
<add> * @param newDataPage the new index page
<add> * @param origDataPage the current index page
<add> */
<ide> private void addToPeersBefore(CacheDataPage newDataPage,
<ide> CacheDataPage origDataPage)
<ide> throws IOException
<ide> }
<ide> }
<ide>
<add> /**
<add> * Separates the given index page from any next peer page.
<add> *
<add> * @param cacheDataPage the index page to be separated
<add> */
<ide> private void separateFromNextPeer(CacheDataPage cacheDataPage)
<ide> throws IOException
<ide> {
<ide> dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
<ide> }
<ide>
<add> /**
<add> * Sets the parent info for the children of the given page to the given
<add> * page.
<add> *
<add> * @param cacheDataPage the page whose children need to be updated
<add> */
<ide> private void reparentChildren(CacheDataPage cacheDataPage)
<ide> throws IOException
<ide> {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Makes the tail entry of the given page a normal entry on that page, done
<add> * when there is only one entry left on a page, and it is the tail.
<add> *
<add> * @param cacheDataPage the page whose tail must be updated
<add> */
<ide> private void demoteTail(CacheDataPage cacheDataPage)
<ide> throws IOException
<ide> {
<ide> tailMain.setParentPage(dpMain._pageNumber, false);
<ide> }
<ide>
<add> /**
<add> * Makes the last normal entry of the given page the tail entry on that
<add> * page, done when there are multiple entries on a page and no tail entry.
<add> *
<add> * @param cacheDataPage the page whose tail must be updated
<add> */
<ide> private void promoteTail(CacheDataPage cacheDataPage)
<ide> throws IOException
<ide> {
<ide> lastMain.setParentPage(dpMain._pageNumber, true);
<ide> }
<ide>
<add> /**
<add> * Finds the index page on which the given entry does or should reside.
<add> *
<add> * @param e the entry to find
<add> */
<ide> public CacheDataPage findCacheDataPage(Entry e)
<ide> throws IOException
<ide> {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Marks the given index page as modified and saves it for writing, if
<add> * necessary (if the page is already marked, does nothing).
<add> *
<add> * @param cacheDataPage the modified index page
<add> */
<ide> private void setModified(CacheDataPage cacheDataPage)
<ide> {
<ide> if(!cacheDataPage._extra._modified) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Finds the valid entry prefix given the first/last entries on an index
<add> * page.
<add> *
<add> * @param e1 the first entry on the page
<add> * @param e2 the last entry on the page
<add> *
<add> * @return a valid entry prefix for the page
<add> */
<ide> private static byte[] findCommonPrefix(Entry e1, Entry e2)
<ide> {
<del> return findCommonPrefix(e1.getEntryBytes(), e2.getEntryBytes());
<del> }
<del>
<del> private static byte[] findCommonPrefix(byte[] b1, byte[] b2)
<del> {
<add> byte[] b1 = e1.getEntryBytes();
<add> byte[] b2 = e2.getEntryBytes();
<add>
<ide> int maxLen = b1.length;
<ide> byte[] prefix = b1;
<ide> if(b1.length > b2.length) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Validates the entries for an index page
<add> *
<add> * @param dpExtra the entries to validate
<add> */
<ide> private void validateEntries(DataPageExtra dpExtra) throws IOException {
<ide> int entrySize = 0;
<ide> Entry prevEntry = Index.FIRST_ENTRY;
<ide> }
<ide> }
<ide>
<add> /**
<add> * Validates the children for an index page
<add> *
<add> * @param dpMain the index page
<add> * @param dpExtra the child entries to validate
<add> */
<ide> private void validateChildren(DataPageMain dpMain,
<ide> DataPageExtra dpExtra) throws IOException {
<ide> int childTailPageNumber = dpMain._childTailPageNumber;
<ide> }
<ide> }
<ide>
<add> /**
<add> * Validates the peer pages for an index page.
<add> *
<add> * @param dpMain the index page
<add> */
<ide> private void validatePeers(DataPageMain dpMain) throws IOException {
<ide> DataPageMain prevMain = _dataPages.get(dpMain._prevPageNumber);
<ide> if(prevMain != null) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Validates the given peer page against the given index page
<add> *
<add> * @param dpMain the index page
<add> * @param peerMain the peer index page
<add> */
<ide> private void validatePeerStatus(DataPageMain dpMain, DataPageMain peerMain)
<ide> throws IOException
<ide> {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Dumps the given index page to a StringBuilder
<add> *
<add> * @param rtn the StringBuilder to update
<add> * @param dpMain the index page to dump
<add> */
<ide> private void dumpPage(StringBuilder rtn, DataPageMain dpMain) {
<ide> try {
<ide> CacheDataPage cacheDataPage = new CacheDataPage(dpMain);
<ide> return rtn.toString();
<ide> }
<ide>
<add> /**
<add> * Keeps track of the main info for an index page.
<add> */
<ide> private class DataPageMain
<ide> {
<ide> public final int _pageNumber;
<ide> public DataPageMain getChildPage(Entry e) throws IOException
<ide> {
<ide> Integer childPageNumber = e.getSubPageNumber();
<del> return IndexPageCache.this.getChildDataPage(
<del> childPageNumber, this, isChildTailPageNumber(childPageNumber));
<add> return getChildPage(childPageNumber,
<add> isChildTailPageNumber(childPageNumber));
<ide> }
<ide>
<ide> public DataPageMain getChildTailPage() throws IOException
<ide> {
<del> return IndexPageCache.this.getChildDataPage(
<del> _childTailPageNumber, this, true);
<add> return getChildPage(_childTailPageNumber, true);
<add> }
<add>
<add> /**
<add> * Returns a child page for the given page number, updating its parent
<add> * info if necessary.
<add> */
<add> private DataPageMain getChildPage(Integer childPageNumber, boolean isTail)
<add> throws IOException
<add> {
<add> DataPageMain child = getDataPage(childPageNumber);
<add> if(child != null) {
<add> // set the parent info for this child (if necessary)
<add> child.initParentPage(_pageNumber, isTail);
<add> }
<add> return child;
<ide> }
<ide>
<ide> public DataPageExtra getExtra() throws IOException
<ide> }
<ide> }
<ide>
<add> /**
<add> * Keeps track of the extra info for an index page. This info (if
<add> * unmodified) may be re-read from disk as necessary.
<add> */
<ide> private static class DataPageExtra
<ide> {
<ide> /** sorted collection of index entries. this is kept in a list instead of
<ide> }
<ide> }
<ide>
<add> /**
<add> * IndexPageCache implementation of an {@link Index.DataPage}.
<add> */
<ide> public static final class CacheDataPage
<ide> extends Index.DataPage
<ide> {
<ide>
<ide> }
<ide>
<add> /**
<add> * A view of an index page's entries which combines the normal entries and
<add> * tail entry into one collection.
<add> */
<ide> private static class EntryListView extends AbstractList<Entry>
<ide> implements RandomAccess
<ide> { |
|
Java | apache-2.0 | 653cc6f6d05bca98422ae89c9046611870c26570 | 0 | tetrapods/core,tetrapods/core,tetrapods/core,tetrapods/core,tetrapods/core | package io.tetrapod.core;
import static io.tetrapod.protocol.core.Core.UNADDRESSED;
import static io.tetrapod.protocol.core.TetrapodContract.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.tetrapod.core.Session.RelayHandler;
import io.tetrapod.core.registry.*;
import io.tetrapod.core.rpc.*;
import io.tetrapod.core.rpc.Error;
import io.tetrapod.core.serialize.StructureAdapter;
import io.tetrapod.core.serialize.datasources.ByteBufDataSource;
import io.tetrapod.core.utils.*;
import io.tetrapod.core.web.*;
import io.tetrapod.protocol.core.*;
import io.tetrapod.protocol.service.ServiceCommand;
import io.tetrapod.protocol.storage.*;
import java.io.*;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.slf4j.*;
/**
* The tetrapod service is the core cluster service which handles message routing, cluster management, service discovery, and load balancing
* of client connections
*/
public class TetrapodService extends DefaultService implements TetrapodContract.API, StorageContract.API, RelayHandler,
io.tetrapod.core.registry.Registry.RegistryBroadcaster {
public static final Logger logger = LoggerFactory.getLogger(TetrapodService.class);
public static final int DEFAULT_PUBLIC_PORT = 9900;
public static final int DEFAULT_SERVICE_PORT = 9901;
public static final int DEFAULT_CLUSTER_PORT = 9902;
public static final int DEFAULT_WS_PORT = 9903;
public static final int DEFAULT_HTTP_PORT = 9904;
public static final int DEFAULT_WSS_PORT = 9905;
public static final int DEFAULT_HTTPS_PORT = 9906;
protected final SecureRandom random = new SecureRandom();
protected final io.tetrapod.core.registry.Registry registry;
private Topic clusterTopic;
private Topic registryTopic;
private Topic servicesTopic;
private final TetrapodCluster cluster;
private final TetrapodWorker worker;
private Storage storage;
private final EventLoopGroup bossGroup = new NioEventLoopGroup();
private final List<Server> servers = new ArrayList<Server>();
private final WebRoutes webRoutes = new WebRoutes();
private long lastStatsLog;
private String webContentRoot;
public TetrapodService() {
registry = new io.tetrapod.core.registry.Registry(this);
worker = new TetrapodWorker(this);
cluster = new TetrapodCluster(this);
setMainContract(new TetrapodContract());
addContracts(new StorageContract());
addSubscriptionHandler(new TetrapodContract.Registry(), registry);
}
@Override
public void startNetwork(ServerAddress address, String token, Map<String, String> otherOpts) throws Exception {
logger.info(" ***** Start Network ***** ");
cluster.startListening();
if (address == null && token == null) {
// we're not connecting anywhere, so bootstrap and self register as the first
registerSelf(io.tetrapod.core.registry.Registry.BOOTSTRAP_ID, random.nextLong());
} else {
// joining existing cluster
this.token = token;
cluster.joinCluster(address);
}
webContentRoot = "./webContent";
if (otherOpts.containsKey("webroot"))
webContentRoot = otherOpts.get("webroot");
}
/**
* Bootstrap a new cluster by claiming the first id and self-registering
*/
protected void registerSelf(int myEntityId, long reclaimToken) {
registry.setParentId(myEntityId);
this.parentId = this.entityId = myEntityId;
this.token = EntityToken.encode(entityId, reclaimToken);
final EntityInfo e = new EntityInfo(entityId, 0, reclaimToken, Util.getHostName(), 0, Core.TYPE_TETRAPOD, getShortName(), 0, 0,
getContractId());
registry.register(e);
logger.info(String.format("SELF-REGISTERED: 0x%08X %s", entityId, e));
clusterTopic = registry.publish(entityId);
registryTopic = registry.publish(entityId);
servicesTopic = registry.publish(entityId);
try {
// Establish a special loopback connection to ourselves
// connects to self on localhost on our clusterport
clusterClient.connect("localhost", getClusterPort(), dispatcher).sync();
} catch (Exception ex) {
fail(ex);
}
}
@Override
public String getServiceIcon() {
return "media/lizard.png";
}
@Override
public ServiceCommand[] getServiceCommands() {
return new ServiceCommand[] { new ServiceCommand("Log Registry Stats", null, LogRegistryStatsRequest.CONTRACT_ID,
LogRegistryStatsRequest.STRUCT_ID) };
}
public byte getEntityType() {
return Core.TYPE_TETRAPOD;
}
public int getServicePort() {
return Util.getProperty("tetrapod.service.port", DEFAULT_SERVICE_PORT);
}
public int getClusterPort() {
return Util.getProperty("tetrapod.cluster.port", DEFAULT_CLUSTER_PORT);
}
public int getPublicPort() {
return Util.getProperty("tetrapod.public.port", DEFAULT_PUBLIC_PORT);
}
public int getWebSocketPort() {
return Util.getProperty("tetrapod.ws.port", DEFAULT_WS_PORT);
}
public int getWebSocketSecurePort() {
return Util.getProperty("tetrapod.wss.port", DEFAULT_WSS_PORT);
}
public int getHTTPPort() {
return Util.getProperty("tetrapod.http.port", DEFAULT_HTTP_PORT);
}
public int getHTTPSPort() {
return Util.getProperty("tetrapod.https.port", DEFAULT_HTTPS_PORT);
}
@Override
public long getCounter() {
long count = cluster.getNumSessions();
for (Server s : servers) {
count += s.getNumSessions();
}
return count;
}
private class TypedSessionFactory implements SessionFactory {
private final byte type;
private TypedSessionFactory(byte type) {
this.type = type;
}
/**
* Session factory for our sessions from clients and services
*/
@Override
public Session makeSession(SocketChannel ch) {
final Session ses = new WireSession(ch, TetrapodService.this);
ses.setMyEntityId(getEntityId());
ses.setMyEntityType(Core.TYPE_TETRAPOD);
ses.setTheirEntityType(type);
ses.setRelayHandler(TetrapodService.this);
ses.addSessionListener(new Session.Listener() {
@Override
public void onSessionStop(Session ses) {
logger.info("Session Stopped: {}", ses);
onEntityDisconnected(ses);
}
@Override
public void onSessionStart(Session ses) {}
});
return ses;
}
}
private class WebSessionFactory implements SessionFactory {
public WebSessionFactory(String contentRoot, boolean webSockets) {
this.contentRoot = contentRoot;
this.webSockets = webSockets;
}
boolean webSockets = false;
String contentRoot;
@Override
public Session makeSession(SocketChannel ch) {
TetrapodService pod = TetrapodService.this;
Session ses = webSockets ? new WebSocketSession(ch, pod, contentRoot) : new WebHttpSession(ch, pod, contentRoot);
ses.setRelayHandler(pod);
ses.setMyEntityId(getEntityId());
ses.setMyEntityType(Core.TYPE_TETRAPOD);
ses.setTheirEntityType(Core.TYPE_CLIENT);
ses.addSessionListener(new Session.Listener() {
@Override
public void onSessionStop(Session ses) {
logger.info("Session Stopped: {}", ses);
onEntityDisconnected(ses);
}
@Override
public void onSessionStart(Session ses) {}
});
return ses;
}
}
protected void onEntityDisconnected(Session ses) {
if (ses.getTheirEntityId() != 0) {
final EntityInfo e = registry.getEntity(ses.getTheirEntityId());
if (e != null) {
registry.setGone(e);
}
}
}
/**
* As a Tetrapod service, we can't start serving as one until we've registered & fully sync'ed with the cluster, or self-registered if we
* are the first one. We call this once this criteria has been reached
*/
@Override
public void onReadyToServe() {
// TODO: wait for confirmed cluster registry sync before calling onReadyToServe
logger.info(" ***** READY TO SERVE ***** ");
try {
storage = new Storage();
registry.setStorage(storage);
AuthToken.setSecret(storage.getSharedSecret());
// create servers
servers.add(new Server(getPublicPort(), new TypedSessionFactory(Core.TYPE_ANONYMOUS), dispatcher));
servers.add(new Server(getServicePort(), new TypedSessionFactory(Core.TYPE_SERVICE), dispatcher));
servers.add(new Server(getHTTPPort(), new WebSessionFactory(webContentRoot, false), dispatcher));
servers.add(new Server(getWebSocketPort(), new WebSessionFactory("/sockets", true), dispatcher));
// create secure port servers, if configured
if (Util.getProperty("tetrapod.tls", true)) {
SSLContext ctx = Util.createSSLContext(new FileInputStream(System.getProperty("tetrapod.jks.file", "cfg/tetrapod.jks")), System
.getProperty("tetrapod.jks.pwd", "4pod.dop4").toCharArray());
servers.add(new Server(getWebSocketSecurePort(), new WebSessionFactory("/sockets", true), dispatcher, ctx, false));
servers.add(new Server(getHTTPSPort(), new WebSessionFactory(webContentRoot, false), dispatcher, ctx, false));
}
// start listening
for (Server s : servers) {
s.start(bossGroup).sync();
}
} catch (Exception e) {
fail(e);
}
scheduleHealthCheck();
}
@Override
public void onShutdown(boolean restarting) {
logger.info("Shutting Down Tetrapod");
if (cluster != null) {
cluster.shutdown();
}
try {
// we have one boss group for all the other servers
bossGroup.shutdownGracefully().sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (storage != null) {
storage.shutdown();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private Session findSession(final EntityInfo entity) {
if (entity.parentId == getEntityId()) {
return entity.getSession();
} else {
if (entity.isTetrapod()) {
return cluster.getSession(entity.entityId);
}
final EntityInfo parent = registry.getEntity(entity.parentId);
assert (parent != null);
return cluster.getSession(parent.entityId);
}
}
@Override
public Session getRelaySession(int entityId, int contractId) {
EntityInfo entity = null;
if (entityId == Core.UNADDRESSED) {
entity = registry.getRandomAvailableService(contractId);
} else {
entity = registry.getEntity(entityId);
if (entity == null) {
logger.warn("Could not find an entity for {}", entityId);
}
}
if (entity != null) {
return findSession(entity);
}
return null;
}
@Override
public void relayMessage(final MessageHeader header, final ByteBuf buf, final boolean isBroadcast) throws IOException {
final EntityInfo sender = registry.getEntity(header.fromId);
if (sender != null) {
buf.retain();
sender.queue(new Runnable() {
public void run() {
try {
if (header.toId == UNADDRESSED) {
if (isBroadcast) {
broadcast(sender, header, buf);
}
} else {
final Session ses = getRelaySession(header.toId, header.contractId);
if (ses != null) {
ses.sendRelayedMessage(header, buf, false);
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
} finally {
// FIXME: This is fragile -- if we delete an entity with queued work, we need to make sure we
// release all the buffers in the queued work items.
buf.release();
}
}
});
worker.kick();
} else {
logger.error("Could not find sender entity {} for {}", header.fromId, header.dump());
}
}
private void broadcast(final EntityInfo publisher, final MessageHeader header, final ByteBuf buf) throws IOException {
final Topic topic = publisher.getTopic(header.topicId);
if (topic != null) {
for (final Subscriber s : topic.getChildSubscribers()) {
broadcast(publisher, s, topic, header, buf);
}
for (final Subscriber s : topic.getProxySubscribers()) {
broadcast(publisher, s, topic, header, buf);
}
} else {
logger.error("Could not find topic {} for entity {}", header.topicId, publisher);
}
}
private void broadcast(final EntityInfo publisher, final Subscriber sub, final Topic topic, final MessageHeader header, final ByteBuf buf)
throws IOException {
final int ri = buf.readerIndex();
final EntityInfo e = registry.getEntity(sub.entityId);
if (e != null) {
if (e.entityId == getEntityId()) {
// dispatch to self
ByteBufDataSource reader = new ByteBufDataSource(buf);
final Message msg = (Message) StructureFactory.make(header.contractId, header.structId);
if (msg != null) {
msg.read(reader);
clusterClient.getSession().dispatchMessage(header, msg);
}
buf.readerIndex(ri);
} else {
if (!e.isGone() && (e.parentId == getEntityId() || e.isTetrapod())) {
final Session session = findSession(e);
if (session != null) {
// rebroadcast this message if it was published by one of our children and we're sending it to another tetrapod
final boolean keepBroadcasting = e.isTetrapod() && publisher.parentId == getEntityId();
session.sendRelayedMessage(header, buf, keepBroadcasting);
buf.readerIndex(ri);
} else {
logger.error("Could not find session for {} {}", e, header.dump());
}
}
}
} else {
logger.error("Could not find subscriber {} for topic {}", sub, topic);
}
}
@Override
public WebRoutes getWebRoutes() {
return webRoutes;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public void broadcastRegistryMessage(Message msg) {
if (registryTopic.getNumScubscribers() > 0) {
broadcast(msg, registryTopic);
}
cluster.broadcast(msg);
}
@Override
public void broadcastServicesMessage(Message msg) {
broadcast(msg, servicesTopic);
}
public void broadcast(Message msg, Topic topic) {
logger.trace("BROADCASTING {} {}", topic, msg.dump());
if (topic != null) {
synchronized (topic) {
// OPTIMIZE: call broadcast() directly instead of through loop-back
clusterClient.getSession().sendBroadcastMessage(msg, topic.topicId);
}
}
}
@Override
public void subscribe(int topicId, int entityId) {
registry.subscribe(registry.getEntity(getEntityId()), topicId, entityId);
}
@Override
public void unsubscribe(int topicId, int entityId) {
registry.unsubscribe(registry.getEntity(getEntityId()), topicId, entityId, false);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void scheduleHealthCheck() {
dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() {
public void run() {
if (dispatcher.isRunning()) {
try {
healthCheck();
cluster.service();
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
scheduleHealthCheck();
}
}
});
}
private void healthCheck() {
if (System.currentTimeMillis() - lastStatsLog > 5 * 60 * 1000) {
registry.logStats();
lastStatsLog = System.currentTimeMillis();
}
for (EntityInfo e : registry.getChildren()) {
if (e.isGone() && System.currentTimeMillis() - e.getGoneSince() > 60 * 1000) {
logger.info("Reaping: {}", e);
registry.unregister(e);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void subscribeToCluster(Session ses, int toEntityId) {
assert (clusterTopic != null);
synchronized (cluster) {
subscribe(clusterTopic.topicId, toEntityId);
cluster.sendClusterDetails(ses, toEntityId, clusterTopic.topicId);
}
}
@Override
public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) {
synchronized (cluster) {
if (cluster.addMember(m.entityId, m.host, m.servicePort, m.clusterPort, null)) {
broadcast(new ClusterMemberMessage(m.entityId, m.host, m.servicePort, m.clusterPort), clusterTopic);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public Response requestKeepAlive(KeepAliveRequest r, RequestContext ctx) {
return Response.SUCCESS;
}
@Override
public Response requestRegister(RegisterRequest r, final RequestContext ctx) {
if (getEntityId() == 0) {
return new Error(ERROR_SERVICE_UNAVAILABLE);
}
EntityInfo info = null;
final EntityToken t = EntityToken.decode(r.token);
if (t != null) {
info = registry.getEntity(t.entityId);
if (info != null) {
if (info.reclaimToken != t.nonce) {
info = null; // return error instead?
}
}
}
if (info == null) {
info = new EntityInfo();
info.version = ctx.header.version;
info.build = r.build;
info.host = ctx.session.getPeerHostname();
info.name = r.name;
info.reclaimToken = random.nextLong();
info.contractId = r.contractId;
}
info.status = r.status &= ~Core.STATUS_GONE;
info.parentId = getEntityId();
info.type = ctx.session.getTheirEntityType();
if (info.type == Core.TYPE_ANONYMOUS) {
info.type = Core.TYPE_CLIENT;
}
// register/reclaim
registry.register(info);
if (info.type == Core.TYPE_TETRAPOD) {
info.parentId = info.entityId;
}
// update & store session
ctx.session.setTheirEntityId(info.entityId);
ctx.session.setTheirEntityType(info.type);
info.setSession(ctx.session);
// deliver them their entityId immediately to avoid some race conditions with the response
ctx.session.sendMessage(new EntityMessage(info.entityId), Core.UNADDRESSED, Core.UNADDRESSED);
if (info.isService() && info.entityId != entityId) {
subscribeToCluster(ctx.session, info.entityId);
}
return new RegisterResponse(info.entityId, getEntityId(), EntityToken.encode(info.entityId, info.reclaimToken));
}
@Override
public Response requestUnregister(UnregisterRequest r, RequestContext ctx) {
if (r.entityId != ctx.header.fromId && ctx.header.fromType != Core.TYPE_ADMIN) {
return new Error(ERROR_INVALID_RIGHTS);
}
final EntityInfo info = registry.getEntity(r.entityId);
if (info == null) {
return new Error(ERROR_INVALID_ENTITY);
}
registry.unregister(info);
return Response.SUCCESS;
}
@Override
public Response requestPublish(PublishRequest r, RequestContext ctx) {
if (ctx.header.fromType == Core.TYPE_TETRAPOD || ctx.header.fromType == Core.TYPE_SERVICE) {
final EntityInfo entity = registry.getEntity(ctx.header.fromId);
if (entity != null) {
if (entity.parentId == getEntityId()) {
final Topic t = registry.publish(ctx.header.fromId);
if (t != null) {
return new PublishResponse(t.topicId);
}
} else {
return new Error(ERROR_NOT_PARENT);
}
} else {
return new Error(ERROR_INVALID_ENTITY);
}
}
return new Error(ERROR_INVALID_RIGHTS);
}
/**
* Lock registryTopic and send our current registry state to the subscriber
*/
protected void registrySubscribe(final Session session, final int toEntityId, boolean clusterMode) {
if (registryTopic != null) {
synchronized (registryTopic) {
// cluster members are not subscribed through this subscription, due to chicken-and-egg issues
// synchronizing registries using topics. Cluster members are implicitly auto-subscribed without
// an entry in the topic.
if (!clusterMode) {
subscribe(registryTopic.topicId, toEntityId);
}
registry.sendRegistryState(session, toEntityId, registryTopic.topicId);
}
}
}
@Override
public Response requestRegistrySubscribe(RegistrySubscribeRequest r, RequestContext ctx) {
if (registryTopic == null) {
return new Error(ERROR_UNKNOWN);
}
registrySubscribe(ctx.session, ctx.header.fromId, false);
return Response.SUCCESS;
}
@Override
public Response requestRegistryUnsubscribe(RegistryUnsubscribeRequest r, RequestContext ctx) {
// TODO: validate
unsubscribe(registryTopic.topicId, ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServicesSubscribe(ServicesSubscribeRequest r, RequestContext ctx) {
if (servicesTopic == null) {
return new Error(ERROR_UNKNOWN);
}
synchronized (servicesTopic) {
subscribe(servicesTopic.topicId, ctx.header.fromId);
// send all current entities
for (EntityInfo e : registry.getServices()) {
ctx.session.sendMessage(new ServiceAddedMessage(e), ctx.header.fromId, servicesTopic.topicId);
}
}
return Response.SUCCESS;
}
@Override
public Response requestServicesUnsubscribe(ServicesUnsubscribeRequest r, RequestContext ctx) {
// TODO: validate
unsubscribe(servicesTopic.topicId, ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServiceStatusUpdate(ServiceStatusUpdateRequest r, RequestContext ctx) {
// TODO: don't allow certain bits to be set from a request
if (ctx.header.fromId != 0) {
final EntityInfo e = registry.getEntity(ctx.header.fromId);
if (e != null) {
registry.updateStatus(e, r.status);
} else {
return new Error(ERROR_INVALID_ENTITY);
}
}
return Response.SUCCESS;
}
@Override
public Response requestAddServiceInformation(AddServiceInformationRequest req, RequestContext ctx) {
for (WebRoute r : req.routes)
webRoutes.setRoute(r.path, r.contractId, r.structId);
for (StructDescription sd : req.structs)
StructureFactory.add(new StructureAdapter(sd));
return Response.SUCCESS;
}
@Override
protected void registerServiceInformation() {
// do nothing, our protocol is known by all tetrapods
}
@Override
public Response requestClusterJoin(ClusterJoinRequest r, RequestContext ctx) {
if (ctx.session.getTheirEntityType() != Core.TYPE_TETRAPOD) {
return new Error(ERROR_INVALID_RIGHTS);
}
ctx.session.setTheirEntityId(r.entityId);
logger.info("JOINING TETRAPOD {} {}", ctx.session);
synchronized (cluster) {
if (cluster.addMember(r.entityId, r.host, r.servicePort, r.clusterPort, ctx.session)) {
broadcast(new ClusterMemberMessage(r.entityId, r.host, r.servicePort, r.clusterPort), clusterTopic);
}
}
registrySubscribe(ctx.session, ctx.session.getTheirEntityId(), true);
return new ClusterJoinResponse(getEntityId());
}
@Override
public Response requestLogRegistryStats(LogRegistryStatsRequest r, RequestContext ctx) {
registry.logStats();
return Response.SUCCESS;
}
@Override
public Response requestStorageGet(StorageGetRequest r, RequestContext ctx) {
return new StorageGetResponse(storage.get(r.key));
}
@Override
public Response requestStorageSet(StorageSetRequest r, RequestContext ctx) {
storage.put(r.key, r.value);
return Response.SUCCESS;
}
@Override
public Response requestStorageDelete(StorageDeleteRequest r, RequestContext ctx) {
storage.delete(r.key);
return Response.SUCCESS;
}
@Override
public Response requestAdminAuthorize(AdminAuthorizeRequest r, RequestContext ctx) {
logger.info("AUTHORIZE WITH {} ...", r.token);
AuthToken.Decoded d = AuthToken.decodeAuthToken1(r.token);
if (d != null) {
logger.info("TOKEN {} time left = {}", r.token, d.timeLeft);
ctx.session.theirType = Core.TYPE_ADMIN;
return Response.SUCCESS;
} else {
logger.info("TOKEN {} NOT VALID", r.token);
}
return new Error(ERROR_INVALID_RIGHTS);
}
@Override
public Response requestAdminLogin(AdminLoginRequest r, RequestContext ctx) {
if (r.email == null) {
return new Error(ERROR_INVALID_RIGHTS);
}
if (r.email.trim().length() < 3) {
return new Error(ERROR_INVALID_RIGHTS);
}
// FIXME: Check password
// mark them as an admin
ctx.session.theirType = Core.TYPE_ADMIN;
final String authtoken = AuthToken.encodeAuthToken1(1, 1, 60 * 24 * 14);
return new AdminLoginResponse(authtoken);
}
}
| Tetrapod-Core/src/io/tetrapod/core/TetrapodService.java | package io.tetrapod.core;
import static io.tetrapod.protocol.core.Core.UNADDRESSED;
import static io.tetrapod.protocol.core.TetrapodContract.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.tetrapod.core.Session.RelayHandler;
import io.tetrapod.core.registry.*;
import io.tetrapod.core.rpc.*;
import io.tetrapod.core.rpc.Error;
import io.tetrapod.core.serialize.StructureAdapter;
import io.tetrapod.core.serialize.datasources.ByteBufDataSource;
import io.tetrapod.core.utils.*;
import io.tetrapod.core.web.*;
import io.tetrapod.protocol.core.*;
import io.tetrapod.protocol.service.ServiceCommand;
import io.tetrapod.protocol.storage.*;
import java.io.*;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.slf4j.*;
/**
* The tetrapod service is the core cluster service which handles message routing, cluster management, service discovery, and load balancing
* of client connections
*/
public class TetrapodService extends DefaultService implements TetrapodContract.API, StorageContract.API, RelayHandler,
io.tetrapod.core.registry.Registry.RegistryBroadcaster {
public static final Logger logger = LoggerFactory.getLogger(TetrapodService.class);
public static final int DEFAULT_PUBLIC_PORT = 9900;
public static final int DEFAULT_SERVICE_PORT = 9901;
public static final int DEFAULT_CLUSTER_PORT = 9902;
public static final int DEFAULT_WS_PORT = 9903;
public static final int DEFAULT_HTTP_PORT = 9904;
public static final int DEFAULT_WSS_PORT = 9905;
public static final int DEFAULT_HTTPS_PORT = 9906;
protected final SecureRandom random = new SecureRandom();
protected final io.tetrapod.core.registry.Registry registry;
private Topic clusterTopic;
private Topic registryTopic;
private Topic servicesTopic;
private final TetrapodCluster cluster;
private final TetrapodWorker worker;
private Storage storage;
private final EventLoopGroup bossGroup = new NioEventLoopGroup();
private final List<Server> servers = new ArrayList<Server>();
private final WebRoutes webRoutes = new WebRoutes();
private long lastStatsLog;
private String webContentRoot;
public TetrapodService() {
registry = new io.tetrapod.core.registry.Registry(this);
worker = new TetrapodWorker(this);
cluster = new TetrapodCluster(this);
setMainContract(new TetrapodContract());
addContracts(new StorageContract());
addSubscriptionHandler(new TetrapodContract.Registry(), registry);
}
@Override
public void startNetwork(ServerAddress address, String token, Map<String, String> otherOpts) throws Exception {
logger.info(" ***** Start Network ***** ");
cluster.startListening();
if (address == null && token == null) {
// we're not connecting anywhere, so bootstrap and self register as the first
registerSelf(io.tetrapod.core.registry.Registry.BOOTSTRAP_ID, random.nextLong());
} else {
// joining existing cluster
this.token = token;
cluster.joinCluster(address);
}
webContentRoot = "./webContent";
if (otherOpts.containsKey("webroot"))
webContentRoot = otherOpts.get("webroot");
}
/**
* Bootstrap a new cluster by claiming the first id and self-registering
*/
protected void registerSelf(int myEntityId, long reclaimToken) {
registry.setParentId(myEntityId);
this.parentId = this.entityId = myEntityId;
this.token = EntityToken.encode(entityId, reclaimToken);
final EntityInfo e = new EntityInfo(entityId, 0, reclaimToken, Util.getHostName(), 0, Core.TYPE_TETRAPOD, getShortName(), 0, 0,
getContractId());
registry.register(e);
logger.info(String.format("SELF-REGISTERED: 0x%08X %s", entityId, e));
clusterTopic = registry.publish(entityId);
registryTopic = registry.publish(entityId);
servicesTopic = registry.publish(entityId);
try {
// Establish a special loopback connection to ourselves
// connects to self on localhost on our clusterport
clusterClient.connect("localhost", getClusterPort(), dispatcher).sync();
} catch (Exception ex) {
fail(ex);
}
}
@Override
public String getServiceIcon() {
return "media/lizard.png";
}
@Override
public ServiceCommand[] getServiceCommands() {
return new ServiceCommand[] { new ServiceCommand("Log Registry Stats", null, LogRegistryStatsRequest.CONTRACT_ID,
LogRegistryStatsRequest.STRUCT_ID) };
}
public byte getEntityType() {
return Core.TYPE_TETRAPOD;
}
public int getServicePort() {
return Util.getProperty("tetrapod.service.port", DEFAULT_SERVICE_PORT);
}
public int getClusterPort() {
return Util.getProperty("tetrapod.cluster.port", DEFAULT_CLUSTER_PORT);
}
public int getPublicPort() {
return Util.getProperty("tetrapod.public.port", DEFAULT_PUBLIC_PORT);
}
public int getWebSocketPort() {
return Util.getProperty("tetrapod.ws.port", DEFAULT_WS_PORT);
}
public int getWebSocketSecurePort() {
return Util.getProperty("tetrapod.wss.port", DEFAULT_WSS_PORT);
}
public int getHTTPPort() {
return Util.getProperty("tetrapod.http.port", DEFAULT_HTTP_PORT);
}
public int getHTTPSPort() {
return Util.getProperty("tetrapod.https.port", DEFAULT_HTTPS_PORT);
}
@Override
public long getCounter() {
long count = cluster.getNumSessions();
for (Server s : servers) {
count += s.getNumSessions();
}
return count;
}
private class TypedSessionFactory implements SessionFactory {
private final byte type;
private TypedSessionFactory(byte type) {
this.type = type;
}
/**
* Session factory for our sessions from clients and services
*/
@Override
public Session makeSession(SocketChannel ch) {
final Session ses = new WireSession(ch, TetrapodService.this);
ses.setMyEntityId(getEntityId());
ses.setMyEntityType(Core.TYPE_TETRAPOD);
ses.setTheirEntityType(type);
ses.setRelayHandler(TetrapodService.this);
ses.addSessionListener(new Session.Listener() {
@Override
public void onSessionStop(Session ses) {
logger.info("Session Stopped: {}", ses);
onEntityDisconnected(ses);
}
@Override
public void onSessionStart(Session ses) {}
});
return ses;
}
}
private class WebSessionFactory implements SessionFactory {
public WebSessionFactory(String contentRoot, boolean webSockets) {
this.contentRoot = contentRoot;
this.webSockets = webSockets;
}
boolean webSockets = false;
String contentRoot;
@Override
public Session makeSession(SocketChannel ch) {
TetrapodService pod = TetrapodService.this;
Session ses = webSockets ? new WebSocketSession(ch, pod, contentRoot) : new WebHttpSession(ch, pod, contentRoot);
ses.setRelayHandler(pod);
ses.setMyEntityId(getEntityId());
ses.setMyEntityType(Core.TYPE_TETRAPOD);
ses.setTheirEntityType(Core.TYPE_CLIENT);
ses.addSessionListener(new Session.Listener() {
@Override
public void onSessionStop(Session ses) {
logger.info("Session Stopped: {}", ses);
onEntityDisconnected(ses);
}
@Override
public void onSessionStart(Session ses) {}
});
return ses;
}
}
protected void onEntityDisconnected(Session ses) {
if (ses.getTheirEntityId() != 0) {
final EntityInfo e = registry.getEntity(ses.getTheirEntityId());
if (e != null) {
registry.setGone(e);
}
}
}
/**
* As a Tetrapod service, we can't start serving as one until we've registered & fully sync'ed with the cluster, or self-registered if we
* are the first one. We call this once this criteria has been reached
*/
@Override
public void onReadyToServe() {
// TODO: wait for confirmed cluster registry sync before calling onReadyToServe
logger.info(" ***** READY TO SERVE ***** ");
try {
storage = new Storage();
registry.setStorage(storage);
AuthToken.setSecret(storage.getSharedSecret());
// create servers
servers.add(new Server(getPublicPort(), new TypedSessionFactory(Core.TYPE_ANONYMOUS), dispatcher));
servers.add(new Server(getServicePort(), new TypedSessionFactory(Core.TYPE_SERVICE), dispatcher));
servers.add(new Server(getHTTPPort(), new WebSessionFactory(webContentRoot, false), dispatcher));
servers.add(new Server(getWebSocketPort(), new WebSessionFactory("/sockets", true), dispatcher));
// create secure port servers, if configured
if (Util.getProperty("tetrapod.tls", false)) {
SSLContext ctx = Util.createSSLContext(new FileInputStream(System.getProperty("tetrapod.jks.file", "cfg/tetrapod.jks")), System
.getProperty("tetrapod.jks.pwd", "4pod.dop4").toCharArray());
servers.add(new Server(getWebSocketSecurePort(), new WebSessionFactory("/sockets", true), dispatcher, ctx, false));
servers.add(new Server(getHTTPSPort(), new WebSessionFactory(webContentRoot, false), dispatcher, ctx, false));
}
// start listening
for (Server s : servers) {
s.start(bossGroup).sync();
}
} catch (Exception e) {
fail(e);
}
scheduleHealthCheck();
}
@Override
public void onShutdown(boolean restarting) {
logger.info("Shutting Down Tetrapod");
if (cluster != null) {
cluster.shutdown();
}
try {
// we have one boss group for all the other servers
bossGroup.shutdownGracefully().sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (storage != null) {
storage.shutdown();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private Session findSession(final EntityInfo entity) {
if (entity.parentId == getEntityId()) {
return entity.getSession();
} else {
if (entity.isTetrapod()) {
return cluster.getSession(entity.entityId);
}
final EntityInfo parent = registry.getEntity(entity.parentId);
assert (parent != null);
return cluster.getSession(parent.entityId);
}
}
@Override
public Session getRelaySession(int entityId, int contractId) {
EntityInfo entity = null;
if (entityId == Core.UNADDRESSED) {
entity = registry.getRandomAvailableService(contractId);
} else {
entity = registry.getEntity(entityId);
if (entity == null) {
logger.warn("Could not find an entity for {}", entityId);
}
}
if (entity != null) {
return findSession(entity);
}
return null;
}
@Override
public void relayMessage(final MessageHeader header, final ByteBuf buf, final boolean isBroadcast) throws IOException {
final EntityInfo sender = registry.getEntity(header.fromId);
if (sender != null) {
buf.retain();
sender.queue(new Runnable() {
public void run() {
try {
if (header.toId == UNADDRESSED) {
if (isBroadcast) {
broadcast(sender, header, buf);
}
} else {
final Session ses = getRelaySession(header.toId, header.contractId);
if (ses != null) {
ses.sendRelayedMessage(header, buf, false);
}
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
} finally {
// FIXME: This is fragile -- if we delete an entity with queued work, we need to make sure we
// release all the buffers in the queued work items.
buf.release();
}
}
});
worker.kick();
} else {
logger.error("Could not find sender entity {} for {}", header.fromId, header.dump());
}
}
private void broadcast(final EntityInfo publisher, final MessageHeader header, final ByteBuf buf) throws IOException {
final Topic topic = publisher.getTopic(header.topicId);
if (topic != null) {
for (final Subscriber s : topic.getChildSubscribers()) {
broadcast(publisher, s, topic, header, buf);
}
for (final Subscriber s : topic.getProxySubscribers()) {
broadcast(publisher, s, topic, header, buf);
}
} else {
logger.error("Could not find topic {} for entity {}", header.topicId, publisher);
}
}
private void broadcast(final EntityInfo publisher, final Subscriber sub, final Topic topic, final MessageHeader header, final ByteBuf buf)
throws IOException {
final int ri = buf.readerIndex();
final EntityInfo e = registry.getEntity(sub.entityId);
if (e != null) {
if (e.entityId == getEntityId()) {
// dispatch to self
ByteBufDataSource reader = new ByteBufDataSource(buf);
final Message msg = (Message) StructureFactory.make(header.contractId, header.structId);
if (msg != null) {
msg.read(reader);
clusterClient.getSession().dispatchMessage(header, msg);
}
buf.readerIndex(ri);
} else {
if (!e.isGone() && (e.parentId == getEntityId() || e.isTetrapod())) {
final Session session = findSession(e);
if (session != null) {
// rebroadcast this message if it was published by one of our children and we're sending it to another tetrapod
final boolean keepBroadcasting = e.isTetrapod() && publisher.parentId == getEntityId();
session.sendRelayedMessage(header, buf, keepBroadcasting);
buf.readerIndex(ri);
} else {
logger.error("Could not find session for {} {}", e, header.dump());
}
}
}
} else {
logger.error("Could not find subscriber {} for topic {}", sub, topic);
}
}
@Override
public WebRoutes getWebRoutes() {
return webRoutes;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public void broadcastRegistryMessage(Message msg) {
if (registryTopic.getNumScubscribers() > 0) {
broadcast(msg, registryTopic);
}
cluster.broadcast(msg);
}
@Override
public void broadcastServicesMessage(Message msg) {
broadcast(msg, servicesTopic);
}
public void broadcast(Message msg, Topic topic) {
logger.trace("BROADCASTING {} {}", topic, msg.dump());
if (topic != null) {
synchronized (topic) {
// OPTIMIZE: call broadcast() directly instead of through loop-back
clusterClient.getSession().sendBroadcastMessage(msg, topic.topicId);
}
}
}
@Override
public void subscribe(int topicId, int entityId) {
registry.subscribe(registry.getEntity(getEntityId()), topicId, entityId);
}
@Override
public void unsubscribe(int topicId, int entityId) {
registry.unsubscribe(registry.getEntity(getEntityId()), topicId, entityId, false);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void scheduleHealthCheck() {
dispatcher.dispatch(1, TimeUnit.SECONDS, new Runnable() {
public void run() {
if (dispatcher.isRunning()) {
try {
healthCheck();
cluster.service();
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
scheduleHealthCheck();
}
}
});
}
private void healthCheck() {
if (System.currentTimeMillis() - lastStatsLog > 5 * 60 * 1000) {
registry.logStats();
lastStatsLog = System.currentTimeMillis();
}
for (EntityInfo e : registry.getChildren()) {
if (e.isGone() && System.currentTimeMillis() - e.getGoneSince() > 60 * 1000) {
logger.info("Reaping: {}", e);
registry.unregister(e);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void subscribeToCluster(Session ses, int toEntityId) {
assert (clusterTopic != null);
synchronized (cluster) {
subscribe(clusterTopic.topicId, toEntityId);
cluster.sendClusterDetails(ses, toEntityId, clusterTopic.topicId);
}
}
@Override
public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) {
synchronized (cluster) {
if (cluster.addMember(m.entityId, m.host, m.servicePort, m.clusterPort, null)) {
broadcast(new ClusterMemberMessage(m.entityId, m.host, m.servicePort, m.clusterPort), clusterTopic);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public Response requestKeepAlive(KeepAliveRequest r, RequestContext ctx) {
return Response.SUCCESS;
}
@Override
public Response requestRegister(RegisterRequest r, final RequestContext ctx) {
if (getEntityId() == 0) {
return new Error(ERROR_SERVICE_UNAVAILABLE);
}
EntityInfo info = null;
final EntityToken t = EntityToken.decode(r.token);
if (t != null) {
info = registry.getEntity(t.entityId);
if (info != null) {
if (info.reclaimToken != t.nonce) {
info = null; // return error instead?
}
}
}
if (info == null) {
info = new EntityInfo();
info.version = ctx.header.version;
info.build = r.build;
info.host = ctx.session.getPeerHostname();
info.name = r.name;
info.reclaimToken = random.nextLong();
info.contractId = r.contractId;
}
info.status = r.status &= ~Core.STATUS_GONE;
info.parentId = getEntityId();
info.type = ctx.session.getTheirEntityType();
if (info.type == Core.TYPE_ANONYMOUS) {
info.type = Core.TYPE_CLIENT;
}
// register/reclaim
registry.register(info);
if (info.type == Core.TYPE_TETRAPOD) {
info.parentId = info.entityId;
}
// update & store session
ctx.session.setTheirEntityId(info.entityId);
ctx.session.setTheirEntityType(info.type);
info.setSession(ctx.session);
// deliver them their entityId immediately to avoid some race conditions with the response
ctx.session.sendMessage(new EntityMessage(info.entityId), Core.UNADDRESSED, Core.UNADDRESSED);
if (info.isService() && info.entityId != entityId) {
subscribeToCluster(ctx.session, info.entityId);
}
return new RegisterResponse(info.entityId, getEntityId(), EntityToken.encode(info.entityId, info.reclaimToken));
}
@Override
public Response requestUnregister(UnregisterRequest r, RequestContext ctx) {
if (r.entityId != ctx.header.fromId && ctx.header.fromType != Core.TYPE_ADMIN) {
return new Error(ERROR_INVALID_RIGHTS);
}
final EntityInfo info = registry.getEntity(r.entityId);
if (info == null) {
return new Error(ERROR_INVALID_ENTITY);
}
registry.unregister(info);
return Response.SUCCESS;
}
@Override
public Response requestPublish(PublishRequest r, RequestContext ctx) {
if (ctx.header.fromType == Core.TYPE_TETRAPOD || ctx.header.fromType == Core.TYPE_SERVICE) {
final EntityInfo entity = registry.getEntity(ctx.header.fromId);
if (entity != null) {
if (entity.parentId == getEntityId()) {
final Topic t = registry.publish(ctx.header.fromId);
if (t != null) {
return new PublishResponse(t.topicId);
}
} else {
return new Error(ERROR_NOT_PARENT);
}
} else {
return new Error(ERROR_INVALID_ENTITY);
}
}
return new Error(ERROR_INVALID_RIGHTS);
}
/**
* Lock registryTopic and send our current registry state to the subscriber
*/
protected void registrySubscribe(final Session session, final int toEntityId, boolean clusterMode) {
if (registryTopic != null) {
synchronized (registryTopic) {
// cluster members are not subscribed through this subscription, due to chicken-and-egg issues
// synchronizing registries using topics. Cluster members are implicitly auto-subscribed without
// an entry in the topic.
if (!clusterMode) {
subscribe(registryTopic.topicId, toEntityId);
}
registry.sendRegistryState(session, toEntityId, registryTopic.topicId);
}
}
}
@Override
public Response requestRegistrySubscribe(RegistrySubscribeRequest r, RequestContext ctx) {
if (registryTopic == null) {
return new Error(ERROR_UNKNOWN);
}
registrySubscribe(ctx.session, ctx.header.fromId, false);
return Response.SUCCESS;
}
@Override
public Response requestRegistryUnsubscribe(RegistryUnsubscribeRequest r, RequestContext ctx) {
// TODO: validate
unsubscribe(registryTopic.topicId, ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServicesSubscribe(ServicesSubscribeRequest r, RequestContext ctx) {
if (servicesTopic == null) {
return new Error(ERROR_UNKNOWN);
}
synchronized (servicesTopic) {
subscribe(servicesTopic.topicId, ctx.header.fromId);
// send all current entities
for (EntityInfo e : registry.getServices()) {
ctx.session.sendMessage(new ServiceAddedMessage(e), ctx.header.fromId, servicesTopic.topicId);
}
}
return Response.SUCCESS;
}
@Override
public Response requestServicesUnsubscribe(ServicesUnsubscribeRequest r, RequestContext ctx) {
// TODO: validate
unsubscribe(servicesTopic.topicId, ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServiceStatusUpdate(ServiceStatusUpdateRequest r, RequestContext ctx) {
// TODO: don't allow certain bits to be set from a request
if (ctx.header.fromId != 0) {
final EntityInfo e = registry.getEntity(ctx.header.fromId);
if (e != null) {
registry.updateStatus(e, r.status);
} else {
return new Error(ERROR_INVALID_ENTITY);
}
}
return Response.SUCCESS;
}
@Override
public Response requestAddServiceInformation(AddServiceInformationRequest req, RequestContext ctx) {
for (WebRoute r : req.routes)
webRoutes.setRoute(r.path, r.contractId, r.structId);
for (StructDescription sd : req.structs)
StructureFactory.add(new StructureAdapter(sd));
return Response.SUCCESS;
}
@Override
protected void registerServiceInformation() {
// do nothing, our protocol is known by all tetrapods
}
@Override
public Response requestClusterJoin(ClusterJoinRequest r, RequestContext ctx) {
if (ctx.session.getTheirEntityType() != Core.TYPE_TETRAPOD) {
return new Error(ERROR_INVALID_RIGHTS);
}
ctx.session.setTheirEntityId(r.entityId);
logger.info("JOINING TETRAPOD {} {}", ctx.session);
synchronized (cluster) {
if (cluster.addMember(r.entityId, r.host, r.servicePort, r.clusterPort, ctx.session)) {
broadcast(new ClusterMemberMessage(r.entityId, r.host, r.servicePort, r.clusterPort), clusterTopic);
}
}
registrySubscribe(ctx.session, ctx.session.getTheirEntityId(), true);
return new ClusterJoinResponse(getEntityId());
}
@Override
public Response requestLogRegistryStats(LogRegistryStatsRequest r, RequestContext ctx) {
registry.logStats();
return Response.SUCCESS;
}
@Override
public Response requestStorageGet(StorageGetRequest r, RequestContext ctx) {
return new StorageGetResponse(storage.get(r.key));
}
@Override
public Response requestStorageSet(StorageSetRequest r, RequestContext ctx) {
storage.put(r.key, r.value);
return Response.SUCCESS;
}
@Override
public Response requestStorageDelete(StorageDeleteRequest r, RequestContext ctx) {
storage.delete(r.key);
return Response.SUCCESS;
}
@Override
public Response requestAdminAuthorize(AdminAuthorizeRequest r, RequestContext ctx) {
logger.info("AUTHORIZE WITH {} ...", r.token);
AuthToken.Decoded d = AuthToken.decodeAuthToken1(r.token);
if (d != null) {
logger.info("TOKEN {} time left = {}", r.token, d.timeLeft);
ctx.session.theirType = Core.TYPE_ADMIN;
return Response.SUCCESS;
} else {
logger.info("TOKEN {} NOT VALID", r.token);
}
return new Error(ERROR_INVALID_RIGHTS);
}
@Override
public Response requestAdminLogin(AdminLoginRequest r, RequestContext ctx) {
if (r.email == null) {
return new Error(ERROR_INVALID_RIGHTS);
}
if (r.email.trim().length() < 3) {
return new Error(ERROR_INVALID_RIGHTS);
}
// FIXME: Check password
// mark them as an admin
ctx.session.theirType = Core.TYPE_ADMIN;
final String authtoken = AuthToken.encodeAuthToken1(1, 1, 60 * 24 * 14);
return new AdminLoginResponse(authtoken);
}
}
| enable tls by default
| Tetrapod-Core/src/io/tetrapod/core/TetrapodService.java | enable tls by default | <ide><path>etrapod-Core/src/io/tetrapod/core/TetrapodService.java
<ide> servers.add(new Server(getWebSocketPort(), new WebSessionFactory("/sockets", true), dispatcher));
<ide>
<ide> // create secure port servers, if configured
<del> if (Util.getProperty("tetrapod.tls", false)) {
<add> if (Util.getProperty("tetrapod.tls", true)) {
<ide> SSLContext ctx = Util.createSSLContext(new FileInputStream(System.getProperty("tetrapod.jks.file", "cfg/tetrapod.jks")), System
<ide> .getProperty("tetrapod.jks.pwd", "4pod.dop4").toCharArray());
<ide> servers.add(new Server(getWebSocketSecurePort(), new WebSessionFactory("/sockets", true), dispatcher, ctx, false)); |
|
JavaScript | agpl-3.0 | b205697f5818fc134833f3a56edb1828c83d85bb | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | /**
* Created by Shadowgun on 17.02.2015.
*/
Imcms.Document = {};
Imcms.Document.API = function () {
};
Imcms.Document.API.prototype = {
path: Imcms.contextPath + "/api/document",
create: function (request, response) {
$.ajax({
url: this.path,
type: "POST",
data: request,
success: response
})
},
read: function (request, response) {
$.ajax({
url: this.path + "/" + (request.id || ""),
type: "GET",
data: request,
success: response
});
},
create2: function (request, response, path) {
$.ajax({
url: this.path + "/" + (path ? path.join("/") : ""),
type: "POST",
contentType: false,
processData: false,
data: request,
success: response
})
},
delete: function (request, response) {
$.ajax({
url: this.path + "/" + request,
type: "DELETE",
success: response
})
}
};
Imcms.Document.Loader = function () {
this.init();
};
Imcms.Document.Loader.prototype = {
_api: new Imcms.Document.API(),
_editor: {},
show: function () {
this._editor.open();
},
init: function () {
this._editor = new Imcms.Document.Editor(this);
},
create: function (name) {
var that = this;
this._api.create({name: name}, function (data) {
if (!data.result) return;
that.redirect(data.id);
})
},
update: function (data, callback) {
this._api.create2(data, callback);
},
documentsList: function (callback) {
this._api.read({}, callback);
},
filteredDocumentList: function (params, callback) {
this._api.read({
filter: params.term || params.filter,
skip: params.skip,
take: params.take,
sort: params.sort,
order: params.order
}, callback);
},
getDocument: function (id, callback) {
this._api.read({id: id}, callback);
},
copyDocument: function (id, callback) {
this._api.create2({}, callback, [id, "copy"])
},
getPrototype: function (id, callback) {
this._api.read({id: id, isPrototype: true}, callback);
},
deleteDocument: function (data) {
this._api.delete(data, function () {
});
},
archiveDocument: function (data) {
this._api.delete(data + "?action=archive", function () {
});
},
unarchiveDocument: function (data) {
this._api.delete(data + "?action=unarchive", function () {
});
},
languagesList: function (callback) {
Imcms.Editors.Language.read(callback);
},
templatesList: function (callback) {
Imcms.Editors.Template.read(callback);
},
rolesList: function (callback) {
Imcms.Editors.Role.read(callback);
},
categoriesList: function (callback) {
Imcms.Editors.Category.read(callback);
},
redirect: function (id) {
location.href = "/imcms/docadmin?meta_id=" + id;
}
};
Imcms.Document.Editor = function (loader) {
this._loader = loader;
this.init();
};
Imcms.Document.Editor.prototype = {
_builder: {},
_loader: {},
_documentListAdapter: {},
init: function () {
return this.buildView().buildDocumentsList();
},
buildView: function () {
this._builder = new JSFormBuilder("<DIV>")
.form()
.div()
.class("imcms-header")
.div()
.html("Document Editor")
.class("imcms-title")
.end()
.button()
.reference("closeButton")
.class("imcms-close-button")
.on("click", $.proxy(this.close, this))
.end()
.end()
.div()
.class("imcms-content")
.table()
.reference("documentsList")
.end()
.end()
.div()
.class("imcms-footer")
.button()
.class("imcms-neutral create-new")
.html("Create new…")
.on("click", $.proxy(this.showDocumentViewer, this))
.end()
.end()
.end();
$(this._builder[0])
.appendTo("body")
.addClass("editor-form editor-document reset");
return this;
},
buildDocumentsList: function () {
this._documentListAdapter =
new Imcms.Document.ListAdapter(
this._builder.ref("documentsList"),
this._loader
);
},
showDocumentViewer: function () {
new Imcms.Document.TypeViewer({
loader: this._loader,
onApply: function (data) {
this._loader.getPrototype(data.parentDocumentId, function (doc) {
new Imcms.Document.Viewer({
data: doc,
type: data.documentType,
parentDocumentId: data.parentDocumentId,
loader: this._loader,
target: $("body"),
onApply: $.proxy(this.onApply, this)
});
}.bind(this));
}.bind(this)
});
},
onApply: function (viewer) {
var data = viewer.serialize();
this._loader.update(data, $.proxy(function () {
this._documentListAdapter.reload();
}, this));
},
open: function () {
$(this._builder[0]).fadeIn("fast").find(".imcms-content").css({height: $(window).height() - 95});
},
close: function () {
$(this._builder[0]).fadeOut("fast");
}
};
Imcms.Document.Viewer = function (options) {
this.init(Imcms.Utils.merge(options, this.defaults));
};
Imcms.Document.Viewer.prototype = {
_loader: {},
_target: {},
_builder: {},
_modal: {},
_options: {},
_title: "",
_activeContent: {},
_contentCollection: {},
_rowsCount: 0,
defaults: {
data: null,
type: 2,
parentDocumentId: 1001,
loader: {},
target: {},
onApply: function () {
},
onCancel: function () {
}
},
init: function (options) {
this._options = options;
this._loader = options.loader;
this._target = options.target;
this._title = options.data ? "DOCUMENT " + options.data.id : "NEW DOCUMENT";
this.buildView();
this.buildValidator();
this.createModal();
this._loader.languagesList($.proxy(this.loadLanguages, this));
this._loader.rolesList($.proxy(this.loadRoles, this));
this._loader.categoriesList($.proxy(this.loadCategories, this));
if (options.type === 2) {
this._loader.templatesList($.proxy(this.loadTemplates, this));
}
if (options.data)
this.deserialize(options.data);
var $builder = $(this._builder[0]);
$builder.fadeIn("fast").css({
left: $(window).width() / 2 - $builder.width() / 2,
top: $(window).height() / 2 - $builder.height() / 2
});
$(this._modal).fadeIn("fast");
},
buildValidator: function () {
$(this._builder[0]).find("form").validate({
rules: {
enabled: {
required: true
},
alias: {
remote: {
url: this._loader._api.path,
type: "GET",
success: function (data) {
var result = true,
validator = $(this._builder[0]).find("form").data("validator"),
element = $(this._builder[0]).find("input[name=alias]"),
currentAlias = element.val(),
previous, errors, message, submitted;
element = element[0];
previous = validator.previousValue(element);
data.forEach(function (it) {
result = !result ? false : it.alias != currentAlias || it.id == this._options.data.id;
}.bind(this));
validator.settings.messages[element.name].remote = previous.originalMessage;
if (result) {
submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
errors = {};
message = validator.defaultMessage(element, "remote");
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
}
previous.valid = result;
validator.stopRequest(element, result);
}.bind(this)
}
}
},
messages: {
alias: {
remote: "This alias has already been taken"
}
},
ignore: ""
});
},
buildView: function () {
this._builder = JSFormBuilder("<div>")
.form()
.div()
.class("imcms-header")
.div()
.class("imcms-title")
.html(this._title)
.hidden()
.name("id")
.end()
.end()
.button()
.reference("closeButton")
.class("imcms-close-button")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.div()
.class("imcms-content with-tabs")
.div()
.class("imcms-tabs")
.reference("tabs")
.end()
.div()
.class("imcms-pages")
.reference("pages")
.end()
.end()
.div()
.class("imcms-footer")
.div()
.class("buttons")
.button()
.class("imcms-positive")
.html("OK")
.on("click", $.proxy(this.apply, this))
.end()
.button()
.class("imcms-neutral")
.html("Cancel")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.end()
.end();
$(this._builder[0]).appendTo($("body")).addClass("document-viewer pop-up-form reset");
this.buildAppearance();
this.buildLifeCycle();
this.buildKeywords();
this.buildCategories();
this.buildAccess();
switch (this._options.type) {
case 2:
{
this.buildPermissions();
this.buildTemplates();
}
break;
case 5:
this.buildLinking();
break;
case 8:
this.buildFile();
break;
}
this.buildDates();
},
buildLifeCycle: function () {
this._builder.ref("tabs")
.div()
.reference("life-cycle-tab")
.class("life-cycle-tab imcms-tab")
.html("Life Cycle")
.end();
this._builder.ref("pages")
.div()
.reference("life-cycle-page")
.class("life-cycle-page imcms-page")
.div()
.class("select field")
.select()
.name("status")
.option("In Process", "0")
.option("Disapproved", "1")
.option("Approved", "2")
//.option("Published", "3")
//.option("Archived", "4")
//.option("Expired", "5")
.end()
.end()
.end();
this._contentCollection["life-cycle"] = {
tab: this._builder.ref("life-cycle-tab"),
page: this._builder.ref("life-cycle-page")
};
this._builder.ref("life-cycle-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["life-cycle"]));
},
buildAppearance: function () {
this._builder.ref("tabs")
.div()
.reference("appearance-tab")
.class("appearance-tab imcms-tab active")
.html("Appearance")
.end();
this._builder.ref("pages")
.div()
.reference("appearance-page")
.class("appearance-page imcms-page active")
.div()
.class("language field")
.reference("languages")
.end()
.div()
.class("link-action field")
.select()
.name("target")
.label("Show in")
.option("Same frame", "_self")
.option("New window", "_blank")
.option("Replace all", "_top")
.end()
.end()
.div()
.class("alias")
.div()
.class("field")
.text()
.name('alias')
.on("focus", function (e) {
if ($(e.target).val()) {
return true;
}
var $languagesArea = $(this._builder.ref("languages").getHTMLElement()),
lang = $languagesArea.find("input[data-node-key=language]:checked").attr("data-node-value"),
title = $languagesArea.find("input[name=title]").filter("[data-node-value=" + lang + "]").val(),
$target = $(e.target);
$target.val(getSlug(title));
}.bind(this))
.label("Document Alias")
.end()
.end()
.end()
.end();
this._contentCollection["appearance"] = {
tab: this._builder.ref("appearance-tab"),
page: this._builder.ref("appearance-page")
};
this._activeContent = this._contentCollection["appearance"];
this._builder.ref("appearance-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["appearance"]));
},
buildTemplates: function () {
this._builder.ref("tabs")
.div()
.reference("templates-tab")
.class("templates-tab imcms-tab")
.html("Templates")
.end();
this._builder.ref("pages")
.div()
.reference("templates-page")
.class("templates-page imcms-page")
.div()
.class("select field")
.select()
.name("template")
.label("Template")
.reference("templates")
.end()
.end()
.div()
.class("select field")
.select()
.name("defaultTemplate")
.label("Default template for child documents")
.reference("defaultTemplates")
.end()
.end()
.end();
this._contentCollection["templates"] = {
tab: this._builder.ref("templates-tab"),
page: this._builder.ref("templates-page")
};
this._builder.ref("templates-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["templates"]));
},
buildPermissions: function () {
this._builder.ref("tabs")
.div()
.reference("permissions-tab")
.class("permissions-tab imcms-tab")
.html("Permissions")
.end();
this._builder.ref("pages")
.div()
.reference("permissions-page")
.class("permissions-page imcms-page")
.div()
.class("imcms-column")
.div()
.class("imcms-label")
.html("Restricted 1")
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditText")
.label("Edit Text")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditMenu")
.label("Edit Menu")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditImage")
.label("Edit Image")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditLoop")
.label("Edit Loop")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditDocumentInformation")
.label("Edit Doc Info")
.end()
.end()
.end()
.div()
.class("imcms-column")
.div()
.class("imcms-label")
.html("Restricted 2")
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditText")
.label("Edit Text")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditMenu")
.label("Edit Menu")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditImage")
.label("Edit Image")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditLoop")
.label("Edit Loop")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditDocumentInformation")
.label("Edit Doc Info")
.end()
.end()
.end()
.end()
.end();
this._contentCollection["permissions"] = {
tab: this._builder.ref("permissions-tab"),
page: this._builder.ref("permissions-page")
};
this._builder.ref("permissions-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["permissions"]));
},
buildLinking: function () {
this._builder.ref("tabs")
.div()
.reference("linking-tab")
.class("linking-tab imcms-tab")
.html("Linking")
.end();
this._builder.ref("pages")
.div()
.reference("linking-page")
.class("linking-page imcms-page")
.div()
.class("field")
.text()
.name("url")
.label("Url")
.reference("linking")
.end()
.end()
.end();
this._contentCollection["linking"] = {
tab: this._builder.ref("linking-tab"),
page: this._builder.ref("linking-page")
};
this._builder.ref("linking-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["linking"]));
},
buildFile: function () {
this._builder.ref("tabs")
.div()
.reference("file-tab")
.class("file-tab imcms-tab")
.html("File")
.end();
this._builder.ref("pages")
.div()
.reference("file-page")
.class("file-page imcms-page")
.div()
.class("select field")
.file()
.name("file")
.label("File")
.reference("file")
.end()
.end()
.div()
.table()
.reference("files")
.column("name")
.column("default")
.column("")
.end()
.end()
.end();
this._contentCollection["file"] = {
tab: this._builder.ref("file-tab"),
page: this._builder.ref("file-page")
};
this._builder.ref("file-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["file"]));
},
buildAccess: function () {
this._builder.ref("tabs")
.div()
.reference("access-tab")
.class("access-tab imcms-tab")
.html("Access")
.end();
this._builder.ref("pages")
.div()
.reference("access-page")
.class("access-page imcms-page")
.table()
.reference("access")
.column("Role")
.column("View")
.column("Edit")
.end()
.div()
.class("field")
.select()
.reference("rolesList")
.end()
.button()
.class("imcms-positive")
.html("Add role")
.on("click", this.addRolePermission.bind(this))
.end()
.end()
.end();
if (this._options.type === 2) {
this._builder.ref("access")
.column("RESTRICTED 1")
.column("RESTRICTED 2")
}
this._builder.ref("access")
.column("");
this._contentCollection["access"] = {
tab: this._builder.ref("access-tab"),
page: this._builder.ref("access-page")
};
this._builder.ref("access-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["access"]));
},
buildKeywords: function () {
this._builder.ref("tabs")
.div()
.reference("keywords-tab")
.class("keywords-tab imcms-tab")
.html("Keywords")
.end();
this._builder.ref("pages")
.div()
.reference("keywords-page")
.class("keywords-page imcms-page")
.div()
.class("field")
.text()
.label("Keyword text")
.placeholder("Input keyword name")
.reference("keywordInput")
.end()
.button()
.class("imcms-positive")
.html("Add")
.on("click", this.addKeyword.bind(this))
.end()
.end()
.div()
.class("field")
.select()
.label("Keywords")
.attr("data-node-key", "keywords")
.name("keywordsList")
.reference("keywordsList")
.multiple()
.end()
.button()
.class("imcms-negative")
.html("Remove")
.on("click", this.removeKeyword.bind(this))
.end()
.end()
.div()
.class("field")
.checkbox()
.name("isSearchDisabled")
.label("Disable Searching")
.end()
.end()
.end();
this._contentCollection["keywords"] = {
tab: this._builder.ref("keywords-tab"),
page: this._builder.ref("keywords-page")
};
this._builder.ref("keywords-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["keywords"]));
},
buildCategories: function () {
this._builder.ref("tabs")
.div()
.reference("categories-tab")
.class("categories-tab imcms-tab")
.html("Categories")
.end();
this._builder.ref("pages")
.div()
.reference("categories-page")
.class("categories-page imcms-page")
.end();
this._contentCollection["categories"] = {
tab: this._builder.ref("categories-tab"),
page: this._builder.ref("categories-page")
};
this._builder.ref("categories-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["categories"]));
},
buildDates: function () {
this._builder.ref("tabs")
.div()
.reference("dates-tab")
.class("dates-tab imcms-tab")
.html("Status")
.end();
this._builder.ref("pages")
.div().reference("dates-page").class("dates-page imcms-page")
.div()
.class("imcms-label")
.html("Created:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("created-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("created-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Modified:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("modified-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("modified-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Archived:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("archived-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("archived-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Published:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("published-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("published-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Publication end:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("publication-end-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("publication-end-time")
.placeholder("Empty")
.end()
.end()
.end();
this._contentCollection["dates"] = {
tab: this._builder.ref("dates-tab"),
page: this._builder.ref("dates-page")
};
this._builder.ref("dates-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["dates"]));
},
createModal: function () {
$(this._modal = document.createElement("div")).addClass("modal")
.click($.proxy(this.cancel, this))
.appendTo($("body"));
},
changeTab: function (collectionItem) {
$(this._activeContent.tab.getHTMLElement()).removeClass("active");
$(this._activeContent.page.getHTMLElement()).removeClass("active");
$(collectionItem.tab.getHTMLElement()).addClass("active");
$(collectionItem.page.getHTMLElement()).addClass("active");
this._activeContent = collectionItem;
this.fillDateTimes();
},
fillDateTimes: function () {
var types = [
"date",
"time"
];
var dates = [
"created",
"modified",
"archived",
"published",
"publication-end"
];
types.forEach(function (type) {
dates.forEach(function (date) {
$("input[name=" + date + "-" + type + "]")
.val($("div.hide-" + type + "s#" + date + "-" + type + "").data(date + ""));
})
});
},
setDateTimeVal: function (type, date) {
$("input[name=" + date + "-" + type + "]").val($("div.hide-" + type + "s#" + date + "-" + type + "").data(date));
},
loadTemplates: function (data) {
$.each(data, $.proxy(this.addTemplate, this));
if (this._options.data)
this.deserialize(this._options.data);
},
addTemplate: function (key, name) {
this._builder.ref("templates").option(key, name);
this._builder.ref("defaultTemplates").option(key, name);
},
loadLanguages: function (id) {
$.each(id, $.proxy(this.addLanguage, this));
if (this._options.data)
this.deserialize(this._options.data);
},
addLanguage: function (language, code) {
this._builder.ref("languages")
.div()
.div()
.class("checkbox")
.checkbox()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.name("enabled")
.end()
.div()
.class("label")
.html(language)
.end()
.end()
.hidden()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.name("code")
.value(code)
.end()
.div()
.class("field")
.text()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.label("Title")
.name("title")
.end()
.end()
.div()
.class("field")
.textarea()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.label("Menu text")
.name("menu-text")
.rows(3)
.end()
.end()
.div()
.class("field")
.text()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.label("Link to image")
.name("image")
.end()
.button()
.class("imcms-neutral")
.on("click", this.chooseImage.bind(this))
.html("…")
.end()
.end()
.end();
},
loadRoles: function (roles) {
$.each(roles, this.addRole.bind(this));
if (this._options.data)
this.deserialize(this._options.data);
},
addRole: function (name, roleId) {
this._builder.ref("rolesList").option(name, roleId);
},
addRolePermission: function (key, value) {
var divWithHidden, removeButton, hiddenRemoveRole, currentRow;
if (typeof value === "undefined") {
value = $(this._builder.ref("rolesList").getHTMLElement()).find("option:selected");
value = {name: value.text(), roleId: value.val()};
key = 3;
}
else {
key = value.permission;
value = value.role;
}
hiddenRemoveRole = $("<input>")
.attr("data-node-key", "access")
.attr("type", "radio")
.attr("name", value.name.toLowerCase() + "-access")
.attr("value", 4).css("display", "none");
divWithHidden = $("<div>").append(value.name)
.append($("<input>")
.attr("type", "hidden")
.attr("data-node-key", "access")
.attr("data-role-name", value.name)
.attr("value", value.roleId)
.attr("name", value.name.toLowerCase() + "-id")
).append(hiddenRemoveRole);
removeButton = $("<button>").attr("type", "button").addClass("imcms-negative");
if (this._options.type === 2) {
this._builder.ref("access")
.row(
divWithHidden[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 3)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 0)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 1)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 2)
.attr("name", value.name.toLowerCase() + "-access")[0],
removeButton[0]
);
}
else {
this._builder.ref("access")
.row(
divWithHidden[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 3)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 0)
.attr("name", value.name.toLowerCase() + "-access")[0],
removeButton[0]
);
key = key == 3 || key == 0 ? key : 3;
}
currentRow = this._builder.ref("access").row(this._rowsCount);
removeButton.on("click", function () {
$(currentRow).hide();
hiddenRemoveRole.prop("checked", true);
}.bind(this));
this._rowsCount++;
$("input[name=" + value.name.toLowerCase() + "-access]").filter("[value=" + key + "]").prop("checked", true);
},
loadCategories: function (categories) {
$.each(categories, this.addCategoryType.bind(this));
if (this._options.data)
this.deserialize(this._options.data);
},
addCategoryType: function (categoryType, options) {
this._builder.ref("categories-page")
.div()
.class("section field")
.select()
.label(categoryType)
.name(categoryType)
.reference(categoryType)
.attr("data-node-key", "categories")
.end()
.end();
if (options.isMultiple) {
this._builder.ref(categoryType).class("pqSelect").multiple();
}
else {
this._builder.ref(categoryType)
.option("none", "");
}
$.each(options.items, this.addCategory.bind(this, categoryType));
},
addCategory: function (categoryType, position, category) {
$(this._builder.ref(categoryType).getHTMLElement()).append(
$("<option>")
.val(category.name).text(category.name).attr("title", category.description)
);
},
addKeyword: function (position, keyword) {
var exist;
if (!keyword) {
keyword = this._builder.ref("keywordInput").value()
}
exist = $(this._builder.ref("keywordsList").getHTMLElement()).find("option").filter(function () {
return $(this).val() === keyword;
}).length > 0;
if (!exist) {
this._builder.ref("keywordsList").option(keyword);
}
},
addFile: function (key, val) {
var radio = $("<input>").attr("type", "radio").attr("name", "defaultFile").val(val);
this._builder.ref("files").row(
val,
radio[0],
$("<button>").attr("type", "button").addClass("imcms-negative").click(this.removeFile.bind(this, radio))[0]
)
},
removeFile: function (radio) {
radio.attr("data-removed", "").parents("tr").hide();
},
removeKeyword: function () {
$(this._builder.ref("keywordsList").getHTMLElement()).find("option:selected").remove();
},
chooseImage: function (e) {
var onFileChosen = function (data) {
if (data) {
$(e.target).parent().children("input[name=image]").val(data.urlPathRelativeToContextPath);
}
$(this._builder[0]).fadeIn();
}.bind(this);
Imcms.Editors.Content.showDialog({
onApply: $.proxy(onFileChosen, this),
onCancel: $.proxy(onFileChosen, this)
});
$(this._builder[0]).fadeOut();
},
setDateTimes: function () {
// var dates = [
// "created",
// "modified",
// "archived",
// "published",
// "publication-end"
// ];
// for (var i = 0; i < dates.length; i++) {
// var type = dates[i];
// this.setDateTimeVal("date", type);
// this.setDateTimeVal("time", type);
// }
////?dateType=created&date=2010-12-23$time=17:55
// $.ajax({
// url: Imcms.contextPath + "/api/document/" + id + "?dateType=archive",
// type: "POST"
// })
},
apply: function () {
if (!$(this._builder[0]).find("form").valid()) {
return false;
}
this.setDateTimes();
this._options.onApply(this);
this.destroy();
},
cancel: function () {
this._options.onCancel(this);
this.destroy();
},
destroy: function () {
$(this._builder[0]).remove();
$(this._modal).remove();
},
serialize: function () {
var result = {languages: {}, access: {}, keywords: [], categories: {}},
$source = $(this._builder[0]),
formData = new FormData();
$source.find("[name]").filter(function () {
return !$(this).attr("data-node-key") && "file" !== $(this).attr("type") && !$(this).attr("ignored");
}).each(function () {
var $this = $(this);
if ($this.is("[type=checkbox]")) {
result[$this.attr("name")] = $this.is(":checked")
} else {
result[$this.attr("name")] = $this.val();
}
});
$source.find("[data-node-key=language]").each(function () {
var $dataElement = $(this);
var language = $dataElement.attr("data-node-value");
if (!Object.prototype.hasOwnProperty.call(result["languages"], language))
result["languages"][language] = {};
result["languages"][language][$dataElement.attr("name")] = $dataElement.attr("name") === "enabled" ?
($dataElement.is(":checked") ? true : false) : $dataElement.val();
});
$source.find("[data-role-name]").each(function () {
var role = {name: $(this).attr("data-role-name"), roleId: $(this).val()},
permission = $source.find("input[name=" + role.name.toLowerCase() + "-access]").filter(function () {
return $(this).prop("checked");
}).val();
result["access"][role.roleId] = {permission: permission, role: role};
});
$source.find("select[name=keywordsList]").children().each(function () {
result.keywords.push($(this).val());
});
$source.find("select[data-node-key=categories]").each(function () {
var $this = $(this);
if ($this.attr("multiple")) {
result.categories[$this.attr("name")] = $this.val() || [];
}
else {
result.categories[$this.attr("name")] = [$this.val() || ""];
}
});
if (this._options.type === 2) {
result.permissions = [{}, {}];
$source.find("input[data-node-key=permissions]").each(function () {
var $this = $(this);
var id = +$this.attr("data-node-value") - 1;
result.permissions[id][$this.attr("name")] = $this.is(":checked");
});
}
if (this._options.type === 8) {
result["removedFiles"] = $source.find("input[type=radio][data-removed]").map(function (pos, item) {
return $(item).val();
}).toArray();
formData.append("file", $source.find("input[name=file]")[0].files[0]);
}
formData.append("data", JSON.stringify(result));
formData.append("type", this._options.type);
formData.append("parent", this._options.parentDocumentId);
return formData;
},
deserialize: function (data) {
var $source = $(this._builder[0]);
$source.find("[name]").filter(function () {
return !$(this).attr("data-node-key") && "file" !== $(this).attr("type");
}).each(function () {
var $this = $(this);
if ($this.is("[type=checkbox]")) {
$this.prop("checked", data[$this.attr("name")]);
} else {
$this.val(data[$this.attr("name")]);
}
});
$source.find("[data-node-key=language]").each(function () {
var $dataElement = $(this);
var language = $dataElement.attr("data-node-value");
if (Object.prototype.hasOwnProperty.call(data.languages, language)) {
if ($dataElement.attr("name") === "enabled")
$dataElement.prop('checked', data.languages[language][$dataElement.attr("name")]);
else
$dataElement.val(data.languages[language][$dataElement.attr("name")]);
}
});
this._builder.ref("access").clear();
this._rowsCount = 0;
$.each(data.access, this.addRolePermission.bind(this));
$(this._builder.ref("keywordsList").getHTMLElement()).empty();
$.each(data.keywords, this.addKeyword.bind(this));
$.each(data.categories, function (categoryType, selectedCategories) {
selectedCategories.forEach(function (selectedCategory) {
$source
.find("select[name='" + categoryType + "']")
.find("option[value='" + selectedCategory + "']")
.attr("selected", "");
});
$($source.find("select[name='" + categoryType + "']")).multiselect();
});
if (this._options.type === 2 && data.permissions) {
$.each(data.permissions, function (index, value) {
var $elements = $source.find("[data-node-key=permissions]").filter("[data-node-value=" + ++index + "]");
$.each(value, function (key, val) {
if (val) {
$elements.filter("input[name=" + key + "]").attr("checked", "")
}
});
});
}
if (this._options.type === 8 && data.files) {
this._builder.ref("files").clear();
$.each(data.files, this.addFile.bind(this));
$(this._builder.ref("files").getHTMLElement())
.find("input[name=defaultFile]")
.filter('[value="' + data.defaultFile + '"]')
.prop('checked', true);
}
}
};
Imcms.Document.TypeViewer = function (options) {
this._options = Imcms.Utils.merge(options, this._options);
this.init();
};
Imcms.Document.TypeViewer.prototype = {
_builder: undefined,
_options: {
loader: undefined,
onApply: function () {
},
onCancel: function () {
}
},
init: function () {
var $builder;
this.buildView();
this.onLoaded();
$builder = $(this._builder[0]);
$builder.fadeIn("fast").css({
left: $(window).width() / 2 - $builder.width() / 2,
top: $(window).height() / 2 - $builder.height() / 2
});
},
buildView: function () {
this._builder = JSFormBuilder("<div>")
.form()
.div()
.class("imcms-header")
.div()
.class("imcms-title")
.html("Document Types")
.hidden()
.name("id")
.end()
.end()
.button()
.reference("closeButton")
.class("imcms-close-button")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.div()
.class("imcms-content")
.div()
.class("field select")
.select()
.label("Document Type")
.name("documentTypes")
.option("Text Document", 2)
.option("Url Document", 5)
.option("File Document", 8)
.end()
.end()
.div()
.class("field select")
.text()
.label("Document Parent")
.reference("parentDocument")
.name("parentDocument")
.disabled()
.end()
.button()
.on("click", this.openSearchDocumentDialog.bind(this))
.class("imcms-neutral browse")
.html("…")
.end()
.end()
.end()
.div()
.class("imcms-footer")
.div()
.class("buttons")
.button()
.class("imcms-positive")
.html("OK")
.on("click", $.proxy(this.apply, this))
.end()
.button()
.class("imcms-neutral")
.html("Cancel")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.end()
.end();
$(this._builder[0]).appendTo($("body")).addClass("document-type-viewer pop-up-form reset");
},
openSearchDocumentDialog: function () {
var documentSearchDialog = new Imcms.Document.DocumentSearchDialog(function (term, callback) {
Imcms.Editors.Document.filteredDocumentList(term, callback)
});
documentSearchDialog.result(function (data) {
$(this._builder.ref("parentDocument").getHTMLElement()).val(data.label).attr("data-id", data.id);
documentSearchDialog.dispose();
}.bind(this));
documentSearchDialog._dialog.parent().css("z-index", "99999999");
documentSearchDialog.open();
},
onLoaded: function (data) {
$(this._builder.ref("parentDocument").getHTMLElement()).val(Imcms.document.label).attr("data-id", Imcms.document.meta);
},
apply: function () {
this._options.onApply({
documentType: +$(this._builder[0]).find("select[name=documentTypes]").val(),
parentDocumentId: +$(this._builder[0]).find("input[name=parentDocument]").attr("data-id")
});
this.destroy();
},
cancel: function () {
this._options.onCancel();
this.destroy();
},
destroy: function () {
$(this._builder[0]).remove();
}
};
Imcms.Document.ListAdapter = function (container, loader) {
this._container = container;
this._loader = loader;
this.init();
};
Imcms.Document.ListAdapter.prototype = {
_container: {},
_ul: {},
_loader: {},
_pagerHandler: undefined,
init: function () {
this._loader.documentsList($.proxy(this.buildList, this));
this.buildPager();
},
buildList: function (data) {
$.each(data, $.proxy(this.addDocumentToList, this));
},
addDocumentToList: function (position, data) {
var deleteButton = $("<button>"),
row;
this._container.row(data.id, data.label, data.alias, data.type, $("<span>")
.append($("<button>")
.click($.proxy(this.copyDocument, this, data.id))
.addClass("imcms-positive")
.text("Copy")
.attr("type", "button"))
.append($("<button>")
.click($.proxy(this.editDocument, this, data.id))
.addClass("imcms-positive")
.text("Edit…")
.attr("type", "button"))
.append(deleteButton
.addClass("imcms-negative")
.attr("type", "button"))[0]
);
row = this._container.row(position);
if (data.isArchived) {
$(row).addClass("archived");
}
$(row).hover(function (e) {
if (e.shiftKey) {
deleteButton.attr("data-remove", true).text("");
}
else {
deleteButton.attr("data-remove", false).text(this.isArchived(row) ? "U" : "A");
}
}.bind(this));
deleteButton
.click($.proxy(this.deleteDocument, this, data.id, row));
},
buildPager: function () {
this._pagerHandler = new Imcms.Document.PagerHandler({
target: $(this._container.getHTMLElement()).parent()[0],
handler: this._loader.filteredDocumentList.bind(this._loader),
itemsPointer: function () {
var $source = $(this._container.getHTMLElement()).parent(),
height = $source.height(),
found = false,
rows = $source.find("table").find('tr'),
pointer = rows.length - 1,
index = rows.filter(function (pos, it) {
var result = false;
if ($(it).position().top > height) {
result = !found;
found = true;
}
return result;
}).index();
return index > -1 ? index : pointer;
}.bind(this),
resultProcessor: function (startIndex, data) {
this.buildList(data);
}.bind(this)
});
},
reload: function () {
this._container.clear();
this._loader.documentsList(function (data) {
this.buildList(data);
this._pagerHandler.reset();
}.bind(this));
},
deleteDocument: function (id, row) {
var deleteButton = $(row).find("button.imcms-negative"),
flag = deleteButton.attr("data-remove");
if (flag && flag.toString().toLowerCase() == "true") {
if (!confirm("Are you sure?")) {
return;
}
this._loader.deleteDocument(id);
$(row).remove();
} else if (this.isArchived(row)) {
this.unarchive(id, row);
}
else {
this.archive(id, row);
}
},
isArchived: function (row) {
return $(row).hasClass("archived");
},
archive: function (id, row) {
this._loader.archiveDocument(id);
$(row).addClass("archived");
},
unarchive: function (id, row) {
this._loader.unarchiveDocument(id);
$(row).removeClass("archived");
},
editDocument: function (id) {
this._loader.getDocument(id, $.proxy(this.showDocumentViewer, this));
},
copyDocument: function (id) {
this._loader.copyDocument(id, this.reload.bind(this));
},
showDocumentViewer: function (data) {
new Imcms.Document.Viewer({
data: data,
type: (+data.type) || undefined,
loader: this._loader,
target: $("body")[0],
onApply: $.proxy(this.saveDocument, this)
});
},
saveDocument: function (viewer) {
this._loader.update(viewer.serialize(), $.proxy(this.reload, this));
}
};
Imcms.Document.DocumentSearchDialog = function (source) {
this._source = source;
this.init();
};
Imcms.Document.DocumentSearchDialog.prototype = {
_source: null,
_currentTerm: "",
_builder: {},
_dialog: {},
_sort: "",
_order: "",
_selectedRow: {},
_pagerHandler: {},
_callback: function () {
},
init: function () {
this.buildContent();
this.buildDialog();
this.buildPager();
this.find();
},
buildContent: function () {
var that = this;
this._builder = JSFormBuilder("<DIV>")
.form()
.class("editor-menu-form")
.div()
.div()
.class("field")
.text()
.on("input", function () {
that.find(this.value());
})
.reference("searchField")
.placeholder("Type to find document")
.end()
.end()
.div()
.class("field")
.div()
.class("field-wrapper")
.table()
.on("click", $.proxy(this._onSelectElement, this))
.column("id")
.column("label")
.column("language")
.column("alias")
.reference("documentsTable")
.end()
.end()
.end()
.end()
.end();
},
sort: function (index) {
//var sortingType = $(this._builder[0]).find("input[name=sorting]:checked").val(),
// i = index,
// comparator = function (row1, row2) {
// return $($(row1).find("td")[i]).text().localeCompare($($(row2).find("td")[i]).text());
// },
// table = $(this._builder.ref("documentsTable").getHTMLElement());
//
//switch (sortingType) {
// default:
// case "id":
// i = 0;
// break;
// case "headline":
// i = 1;
// break;
// case "alias":
// i = 3;
// break;
//}
var oldSort = this._sort;
switch (index) {
default:
case 0:
this._sort = "meta_id";
break;
case 1:
this._sort = "meta_headline";
break;
case 2:
this._sort = "language";
break;
case 3:
this._sort = "alias";
break;
}
if (this._sort === oldSort) {
this._order = this._order === "asc" ? "desc" : "asc";
}
else {
this._order = "asc";
}
//table.find("tr").sort(comparator).detach().appendTo(table);
this.find(this._currentTerm);
},
buildDialog: function () {
this._dialog = $(this._builder[0]).dialog({
autoOpen: false,
height: 500,
width: 700,
modal: true,
buttons: {
"Add selected": $.proxy(this._onApply, this),
Cancel: function () {
$(this).dialog("close");
}
}
});
var dialog = $(this._builder[0]).parents(".ui-dialog").removeClass()
.addClass("pop-up-form menu-viewer reset").css({position: "fixed"}),
header = dialog.children(".ui-dialog-titlebar").removeClass()
.addClass("imcms-header").append($("<div>").addClass("imcms-title").text("DOCUMENT SELECTOR")),
content = dialog.children(".ui-dialog-content").removeClass()
.addClass("imcms-content"),
footer = dialog.children(".ui-dialog-buttonpane").removeClass()
.addClass("imcms-footer"),
buttons = footer.find(".ui-button").removeClass();
header.find(".ui-dialog-title").remove();
header.children("button").empty().removeClass().addClass("imcms-close-button");
$(buttons[0]).addClass("imcms-positive");
$(buttons[1]).addClass("imcms-neutral cancel-button");
},
buildPager: function () {
this._pagerHandler = new Imcms.Document.PagerHandler({
target: $(this._builder[0]).find(".field-wrapper")[0],
handler: this.pagingHandler.bind(this),
itemsPointer: function () {
var $source = $(this._builder[0]).find('.field-wrapper'),
height = $source.height(),
found = false,
rows = $source.find("table").find('tr'),
pointer = rows.length - 1,
index = rows.filter(function (pos, it) {
var result = false;
if ($(it).position().top > height) {
result = !found;
found = true;
}
return result;
}).index();
return index > -1 ? index : pointer;
}.bind(this),
resultProcessor: this.appendDataToTable.bind(this)
});
},
open: function () {
this._dialog.dialog("open");
},
dispose: function () {
this._dialog.remove();
},
find: function (word) {
this._currentTerm = word;
this._pagerHandler.reset();
this._source({term: word || "", sort: this._sort, order: this._order}, $.proxy(this.fillDataToTable, this));
},
pagingHandler: function (params, callback) {
params["term"] = this._currentTerm;
params["sort"] = this._sort;
params["order"] = this._order;
this._source(params, callback);
},
fillDataToTable: function (data) {
this.clearTable();
this.appendDataToTable(0, data);
},
clearTable: function () {
this._builder.ref("documentsTable").clear();
},
appendDataToTable: function (startIndex, data) {
$(this._builder.ref("documentsTable").getHTMLElement()).find("th").each(function (pos, item) {
$(item).find("div").remove();
});
for (var rowId in data) {
if (data.hasOwnProperty(rowId) && data[rowId]) {
this._builder.ref("documentsTable").row(data[rowId]);
}
}
$(this._builder.ref("documentsTable").getHTMLElement()).find("tr")
.filter(function (pos) {
return pos >= startIndex;
}).each(function (pos, item) {
$(item).on("dragstart", function (event) {
$(".ui-widget-overlay").css("display", "none");
event.originalEvent.dataTransfer.setData("data", JSON.stringify(data[pos - 1]));
}).on("dragend", function () {
$(".ui-widget-overlay").css("display", "block");
}).attr("draggable", true);
});
$(this._builder.ref("documentsTable").getHTMLElement()).find("th").each(function (pos, item) {
$("<div>").append($(item).html()).click(this.sort.bind(this, pos)).appendTo(item);
}.bind(this));
},
result: function (callback) {
this._callback = callback;
return this;
},
_onApply: function () {
var resultData = {id: this._selectedRow.children[0].innerHTML, label: this._selectedRow.children[1].innerHTML};
this._callback(resultData);
this._dialog.dialog("close");
},
_onSelectElement: function (e) {
var $table = $(e.currentTarget),
// tableOffset = $table.offset();
element = $table.find("tbody tr").filter(function (index, element) {
/* var offset, farCorner;
element = $(element);
offset = element.position();
//offset = {left: offset.left - tableOffset.left, top: offset.top - tableOffset.top};
farCorner = {right: offset.left + element.width(), bottom: offset.top + element.height()};
return offset.left <= e.offsetX && offset.top <= e.offsetY && e.offsetX <= farCorner.right && e.offsetY <= farCorner.bottom*/
return $.contains(element, e.target);
});
if (!element.length) {
return false;
}
element = element[0];
if (this._selectedRow)
this._selectedRow.className = "";
this._selectedRow = element;
this._selectedRow.className = "clicked";
}
};
Imcms.Document.PagerHandler = function (options) {
this._target = options.target;
this._options = Imcms.Utils.merge(options, this._options);
this.init();
};
Imcms.Document.PagerHandler.prototype = {
_target: undefined,
_waiter: undefined,
_isHandled: false,
_pageNumber: 1,
_options: {
count: 25,
handler: function () {
},
itemsPointer: function () {
return 0;
},
resultProcessor: function (data) {
},
waiterContent: ""
},
init: function () {
$(this._target).scroll(this.scrollHandler.bind(this)).bind('beforeShow', this.scrollHandler.bind(this));
this.scrollHandler();
},
handleRequest: function (skip) {
this._addWaiterToTarget();
this._isHandled = true;
this._options.handler({skip: skip, take: this._options.count}, this.requestCompleted.bind(this));
},
requestCompleted: function (data) {
this._options.resultProcessor(this._pageNumber * this._options.count, data);
this._pageNumber++;
this._removeWaiterFromTarget();
this._isHandled = false;
this.scrollHandler();
},
scrollHandler: function () {
if (this._isHandled) {
return;
}
var pointer = this._options.itemsPointer(),
currentItemsCount = this._pageNumber * this._options.count;
if (pointer >= currentItemsCount - 3) {
this.handleRequest(currentItemsCount)
}
},
_addWaiterToTarget: function () {
this._waiter = $("<div>")
.addClass("waiter")
.append(this._options.waiterContent)
.appendTo(this._target);
},
_removeWaiterFromTarget: function () {
this._waiter.remove();
},
reset: function () {
this._pageNumber = 1;
this.scrollHandler();
}
};
| src/main/web/imcms/lang/scripts/imcms_document.js | /**
* Created by Shadowgun on 17.02.2015.
*/
Imcms.Document = {};
Imcms.Document.API = function () {
};
Imcms.Document.API.prototype = {
path: Imcms.contextPath + "/api/document",
create: function (request, response) {
$.ajax({
url: this.path,
type: "POST",
data: request,
success: response
})
},
read: function (request, response) {
$.ajax({
url: this.path + "/" + (request.id || ""),
type: "GET",
data: request,
success: response
});
},
create2: function (request, response, path) {
$.ajax({
url: this.path + "/" + (path ? path.join("/") : ""),
type: "POST",
contentType: false,
processData: false,
data: request,
success: response
})
},
delete: function (request, response) {
$.ajax({
url: this.path + "/" + request,
type: "DELETE",
success: response
})
}
};
Imcms.Document.Loader = function () {
this.init();
};
Imcms.Document.Loader.prototype = {
_api: new Imcms.Document.API(),
_editor: {},
show: function () {
this._editor.open();
},
init: function () {
this._editor = new Imcms.Document.Editor(this);
},
create: function (name) {
var that = this;
this._api.create({name: name}, function (data) {
if (!data.result) return;
that.redirect(data.id);
})
},
update: function (data, callback) {
this._api.create2(data, callback);
},
documentsList: function (callback) {
this._api.read({}, callback);
},
filteredDocumentList: function (params, callback) {
this._api.read({
filter: params.term || params.filter,
skip: params.skip,
take: params.take,
sort: params.sort,
order: params.order
}, callback);
},
getDocument: function (id, callback) {
this._api.read({id: id}, callback);
},
copyDocument: function (id, callback) {
this._api.create2({}, callback, [id, "copy"])
},
getPrototype: function (id, callback) {
this._api.read({id: id, isPrototype: true}, callback);
},
deleteDocument: function (data) {
this._api.delete(data, function () {
});
},
archiveDocument: function (data) {
this._api.delete(data + "?action=archive", function () {
});
},
unarchiveDocument: function (data) {
this._api.delete(data + "?action=unarchive", function () {
});
},
languagesList: function (callback) {
Imcms.Editors.Language.read(callback);
},
templatesList: function (callback) {
Imcms.Editors.Template.read(callback);
},
rolesList: function (callback) {
Imcms.Editors.Role.read(callback);
},
categoriesList: function (callback) {
Imcms.Editors.Category.read(callback);
},
redirect: function (id) {
location.href = "/imcms/docadmin?meta_id=" + id;
}
};
Imcms.Document.Editor = function (loader) {
this._loader = loader;
this.init();
};
Imcms.Document.Editor.prototype = {
_builder: {},
_loader: {},
_documentListAdapter: {},
init: function () {
return this.buildView().buildDocumentsList();
},
buildView: function () {
this._builder = new JSFormBuilder("<DIV>")
.form()
.div()
.class("imcms-header")
.div()
.html("Document Editor")
.class("imcms-title")
.end()
.button()
.reference("closeButton")
.class("imcms-close-button")
.on("click", $.proxy(this.close, this))
.end()
.end()
.div()
.class("imcms-content")
.table()
.reference("documentsList")
.end()
.end()
.div()
.class("imcms-footer")
.button()
.class("imcms-neutral create-new")
.html("Create new…")
.on("click", $.proxy(this.showDocumentViewer, this))
.end()
.end()
.end();
$(this._builder[0])
.appendTo("body")
.addClass("editor-form editor-document reset");
return this;
},
buildDocumentsList: function () {
this._documentListAdapter =
new Imcms.Document.ListAdapter(
this._builder.ref("documentsList"),
this._loader
);
},
showDocumentViewer: function () {
new Imcms.Document.TypeViewer({
loader: this._loader,
onApply: function (data) {
this._loader.getPrototype(data.parentDocumentId, function (doc) {
new Imcms.Document.Viewer({
data: doc,
type: data.documentType,
parentDocumentId: data.parentDocumentId,
loader: this._loader,
target: $("body"),
onApply: $.proxy(this.onApply, this)
});
}.bind(this));
}.bind(this)
});
},
onApply: function (viewer) {
var data = viewer.serialize();
this._loader.update(data, $.proxy(function () {
this._documentListAdapter.reload();
}, this));
},
open: function () {
$(this._builder[0]).fadeIn("fast").find(".imcms-content").css({height: $(window).height() - 95});
},
close: function () {
$(this._builder[0]).fadeOut("fast");
}
};
Imcms.Document.Viewer = function (options) {
this.init(Imcms.Utils.merge(options, this.defaults));
};
Imcms.Document.Viewer.prototype = {
_loader: {},
_target: {},
_builder: {},
_modal: {},
_options: {},
_title: "",
_activeContent: {},
_contentCollection: {},
_rowsCount: 0,
defaults: {
data: null,
type: 2,
parentDocumentId: 1001,
loader: {},
target: {},
onApply: function () {
},
onCancel: function () {
}
},
init: function (options) {
this._options = options;
this._loader = options.loader;
this._target = options.target;
this._title = options.data ? "DOCUMENT " + options.data.id : "NEW DOCUMENT";
this.buildView();
this.buildValidator();
this.createModal();
this._loader.languagesList($.proxy(this.loadLanguages, this));
this._loader.rolesList($.proxy(this.loadRoles, this));
this._loader.categoriesList($.proxy(this.loadCategories, this));
if (options.type === 2) {
this._loader.templatesList($.proxy(this.loadTemplates, this));
}
if (options.data)
this.deserialize(options.data);
var $builder = $(this._builder[0]);
$builder.fadeIn("fast").css({
left: $(window).width() / 2 - $builder.width() / 2,
top: $(window).height() / 2 - $builder.height() / 2
});
$(this._modal).fadeIn("fast");
},
buildValidator: function () {
$(this._builder[0]).find("form").validate({
rules: {
enabled: {
required: true
},
alias: {
remote: {
url: this._loader._api.path,
type: "GET",
success: function (data) {
var result = true,
validator = $(this._builder[0]).find("form").data("validator"),
element = $(this._builder[0]).find("input[name=alias]"),
currentAlias = element.val(),
previous, errors, message, submitted;
element = element[0];
previous = validator.previousValue(element);
data.forEach(function (it) {
result = !result ? false : it.alias != currentAlias || it.id == this._options.data.id;
}.bind(this));
validator.settings.messages[element.name].remote = previous.originalMessage;
if (result) {
submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
errors = {};
message = validator.defaultMessage(element, "remote");
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
}
previous.valid = result;
validator.stopRequest(element, result);
}.bind(this)
}
}
},
messages: {
alias: {
remote: "This alias has already been taken"
}
},
ignore: ""
});
},
buildView: function () {
this._builder = JSFormBuilder("<div>")
.form()
.div()
.class("imcms-header")
.div()
.class("imcms-title")
.html(this._title)
.hidden()
.name("id")
.end()
.end()
.button()
.reference("closeButton")
.class("imcms-close-button")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.div()
.class("imcms-content with-tabs")
.div()
.class("imcms-tabs")
.reference("tabs")
.end()
.div()
.class("imcms-pages")
.reference("pages")
.end()
.end()
.div()
.class("imcms-footer")
.div()
.class("buttons")
.button()
.class("imcms-positive")
.html("OK")
.on("click", $.proxy(this.apply, this))
.end()
.button()
.class("imcms-neutral")
.html("Cancel")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.end()
.end();
$(this._builder[0]).appendTo($("body")).addClass("document-viewer pop-up-form reset");
this.buildAppearance();
this.buildLifeCycle();
this.buildKeywords();
this.buildCategories();
this.buildAccess();
switch (this._options.type) {
case 2:
{
this.buildPermissions();
this.buildTemplates();
}
break;
case 5:
this.buildLinking();
break;
case 8:
this.buildFile();
break;
}
this.buildDates();
},
buildLifeCycle: function () {
this._builder.ref("tabs")
.div()
.reference("life-cycle-tab")
.class("life-cycle-tab imcms-tab")
.html("Life Cycle")
.end();
this._builder.ref("pages")
.div()
.reference("life-cycle-page")
.class("life-cycle-page imcms-page")
.div()
.class("select field")
.select()
.name("status")
.option("In Process", "0")
.option("Disapproved", "1")
.option("Approved", "2")
//.option("Published", "3")
//.option("Archived", "4")
//.option("Expired", "5")
.end()
.end()
.end();
this._contentCollection["life-cycle"] = {
tab: this._builder.ref("life-cycle-tab"),
page: this._builder.ref("life-cycle-page")
};
this._builder.ref("life-cycle-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["life-cycle"]));
},
buildAppearance: function () {
this._builder.ref("tabs")
.div()
.reference("appearance-tab")
.class("appearance-tab imcms-tab active")
.html("Appearance")
.end();
this._builder.ref("pages")
.div()
.reference("appearance-page")
.class("appearance-page imcms-page active")
.div()
.class("language field")
.reference("languages")
.end()
.div()
.class("link-action field")
.select()
.name("target")
.label("Show in")
.option("Same frame", "_self")
.option("New window", "_blank")
.option("Replace all", "_top")
.end()
.end()
.div()
.class("alias")
.div()
.class("field")
.text()
.name('alias')
.on("focus", function (e) {
if ($(e.target).val()) {
return true;
}
var $languagesArea = $(this._builder.ref("languages").getHTMLElement()),
lang = $languagesArea.find("input[data-node-key=language]:checked").attr("data-node-value"),
title = $languagesArea.find("input[name=title]").filter("[data-node-value=" + lang + "]").val(),
$target = $(e.target);
$target.val(getSlug(title));
}.bind(this))
.label("Document Alias")
.end()
.end()
.end()
.end();
this._contentCollection["appearance"] = {
tab: this._builder.ref("appearance-tab"),
page: this._builder.ref("appearance-page")
};
this._activeContent = this._contentCollection["appearance"];
this._builder.ref("appearance-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["appearance"]));
},
buildTemplates: function () {
this._builder.ref("tabs")
.div()
.reference("templates-tab")
.class("templates-tab imcms-tab")
.html("Templates")
.end();
this._builder.ref("pages")
.div()
.reference("templates-page")
.class("templates-page imcms-page")
.div()
.class("select field")
.select()
.name("template")
.label("Template")
.reference("templates")
.end()
.end()
.div()
.class("select field")
.select()
.name("defaultTemplate")
.label("Default template for child documents")
.reference("defaultTemplates")
.end()
.end()
.end();
this._contentCollection["templates"] = {
tab: this._builder.ref("templates-tab"),
page: this._builder.ref("templates-page")
};
this._builder.ref("templates-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["templates"]));
},
buildPermissions: function () {
this._builder.ref("tabs")
.div()
.reference("permissions-tab")
.class("permissions-tab imcms-tab")
.html("Permissions")
.end();
this._builder.ref("pages")
.div()
.reference("permissions-page")
.class("permissions-page imcms-page")
.div()
.class("imcms-column")
.div()
.class("imcms-label")
.html("Restricted 1")
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditText")
.label("Edit Text")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditMenu")
.label("Edit Menu")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditImage")
.label("Edit Image")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditLoop")
.label("Edit Loop")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 1)
.name("canEditDocumentInformation")
.label("Edit Doc Info")
.end()
.end()
.end()
.div()
.class("imcms-column")
.div()
.class("imcms-label")
.html("Restricted 2")
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditText")
.label("Edit Text")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditMenu")
.label("Edit Menu")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditImage")
.label("Edit Image")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditLoop")
.label("Edit Loop")
.end()
.end()
.div()
.class("field")
.checkbox()
.attr("data-node-key", "permissions")
.attr("data-node-value", 2)
.name("canEditDocumentInformation")
.label("Edit Doc Info")
.end()
.end()
.end()
.end()
.end();
this._contentCollection["permissions"] = {
tab: this._builder.ref("permissions-tab"),
page: this._builder.ref("permissions-page")
};
this._builder.ref("permissions-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["permissions"]));
},
buildLinking: function () {
this._builder.ref("tabs")
.div()
.reference("linking-tab")
.class("linking-tab imcms-tab")
.html("Linking")
.end();
this._builder.ref("pages")
.div()
.reference("linking-page")
.class("linking-page imcms-page")
.div()
.class("field")
.text()
.name("url")
.label("Url")
.reference("linking")
.end()
.end()
.end();
this._contentCollection["linking"] = {
tab: this._builder.ref("linking-tab"),
page: this._builder.ref("linking-page")
};
this._builder.ref("linking-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["linking"]));
},
buildFile: function () {
this._builder.ref("tabs")
.div()
.reference("file-tab")
.class("file-tab imcms-tab")
.html("File")
.end();
this._builder.ref("pages")
.div()
.reference("file-page")
.class("file-page imcms-page")
.div()
.class("select field")
.file()
.name("file")
.label("File")
.reference("file")
.end()
.end()
.div()
.table()
.reference("files")
.column("name")
.column("default")
.column("")
.end()
.end()
.end();
this._contentCollection["file"] = {
tab: this._builder.ref("file-tab"),
page: this._builder.ref("file-page")
};
this._builder.ref("file-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["file"]));
},
buildAccess: function () {
this._builder.ref("tabs")
.div()
.reference("access-tab")
.class("access-tab imcms-tab")
.html("Access")
.end();
this._builder.ref("pages")
.div()
.reference("access-page")
.class("access-page imcms-page")
.table()
.reference("access")
.column("Role")
.column("View")
.column("Edit")
.end()
.div()
.class("field")
.select()
.reference("rolesList")
.end()
.button()
.class("imcms-positive")
.html("Add role")
.on("click", this.addRolePermission.bind(this))
.end()
.end()
.end();
if (this._options.type === 2) {
this._builder.ref("access")
.column("RESTRICTED 1")
.column("RESTRICTED 2")
}
this._builder.ref("access")
.column("");
this._contentCollection["access"] = {
tab: this._builder.ref("access-tab"),
page: this._builder.ref("access-page")
};
this._builder.ref("access-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["access"]));
},
buildKeywords: function () {
this._builder.ref("tabs")
.div()
.reference("keywords-tab")
.class("keywords-tab imcms-tab")
.html("Keywords")
.end();
this._builder.ref("pages")
.div()
.reference("keywords-page")
.class("keywords-page imcms-page")
.div()
.class("field")
.text()
.label("Keyword text")
.placeholder("Input keyword name")
.reference("keywordInput")
.end()
.button()
.class("imcms-positive")
.html("Add")
.on("click", this.addKeyword.bind(this))
.end()
.end()
.div()
.class("field")
.select()
.label("Keywords")
.attr("data-node-key", "keywords")
.name("keywordsList")
.reference("keywordsList")
.multiple()
.end()
.button()
.class("imcms-negative")
.html("Remove")
.on("click", this.removeKeyword.bind(this))
.end()
.end()
.div()
.class("field")
.checkbox()
.name("isSearchDisabled")
.label("Disable Searching")
.end()
.end()
.end();
this._contentCollection["keywords"] = {
tab: this._builder.ref("keywords-tab"),
page: this._builder.ref("keywords-page")
};
this._builder.ref("keywords-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["keywords"]));
},
buildCategories: function () {
this._builder.ref("tabs")
.div()
.reference("categories-tab")
.class("categories-tab imcms-tab")
.html("Categories")
.end();
this._builder.ref("pages")
.div()
.reference("categories-page")
.class("categories-page imcms-page")
.end();
this._contentCollection["categories"] = {
tab: this._builder.ref("categories-tab"),
page: this._builder.ref("categories-page")
};
this._builder.ref("categories-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["categories"]));
},
buildDates: function () {
this._builder.ref("tabs")
.div()
.reference("dates-tab")
.class("dates-tab imcms-tab")
.html("Status")
.end();
this._builder.ref("pages")
.div().reference("dates-page").class("dates-page imcms-page")
.div()
.class("imcms-label")
.html("Created:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("created-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("created-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Modified:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("modified-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("modified-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Archived:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("archived-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("archived-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Published:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("published-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("published-time")
.placeholder("Empty")
.end()
.end()
.div()
.class("imcms-label")
.html("Publication end:")
.end()
.div()
.class("field")
.text()
.class("date-time")
.name("publication-end-date")
.placeholder("Empty")
.end()
.text()
.class("date-time")
.name("publication-end-time")
.placeholder("Empty")
.end()
.end()
.end();
this._contentCollection["dates"] = {
tab: this._builder.ref("dates-tab"),
page: this._builder.ref("dates-page")
};
this._builder.ref("dates-tab").on("click", $.proxy(this.changeTab, this, this._contentCollection["dates"]));
},
createModal: function () {
$(this._modal = document.createElement("div")).addClass("modal")
.click($.proxy(this.cancel, this))
.appendTo($("body"));
},
changeTab: function (collectionItem) {
$(this._activeContent.tab.getHTMLElement()).removeClass("active");
$(this._activeContent.page.getHTMLElement()).removeClass("active");
$(collectionItem.tab.getHTMLElement()).addClass("active");
$(collectionItem.page.getHTMLElement()).addClass("active");
this._activeContent = collectionItem;
this.fillDateTimes();
},
fillDateTimes: function () {
var types = [
"date",
"time"
];
var dates = [
"created",
"modified",
"archived",
"published",
"publication-end"
];
types.forEach(function (type) {
dates.forEach(function (date) {
$("input[name=" + date + "-" + type + "]")
.val($("div.hide-" + type + "s#" + date + "-" + type + "").data(date + ""));
})
});
},
setDateTimeVal: function (type, date) {
$("input[name=" + date + "-" + type + "]").val($("div.hide-" + type + "s#" + date + "-" + type + "").data(date));
},
loadTemplates: function (data) {
$.each(data, $.proxy(this.addTemplate, this));
if (this._options.data)
this.deserialize(this._options.data);
},
addTemplate: function (key, name) {
this._builder.ref("templates").option(key, name);
this._builder.ref("defaultTemplates").option(key, name);
},
loadLanguages: function (id) {
$.each(id, $.proxy(this.addLanguage, this));
if (this._options.data)
this.deserialize(this._options.data);
},
addLanguage: function (language, code) {
this._builder.ref("languages")
.div()
.div()
.class("checkbox")
.checkbox()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.name("enabled")
.end()
.div()
.class("label")
.html(language)
.end()
.end()
.hidden()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.name("code")
.value(code)
.end()
.div()
.class("field")
.text()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.label("Title")
.name("title")
.end()
.end()
.div()
.class("field")
.textarea()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.label("Menu text")
.name("menu-text")
.rows(3)
.end()
.end()
.div()
.class("field")
.text()
.attr("data-node-key", "language")
.attr("data-node-value", language)
.label("Link to image")
.name("image")
.end()
.button()
.class("imcms-neutral")
.on("click", this.chooseImage.bind(this))
.html("…")
.end()
.end()
.end();
},
loadRoles: function (roles) {
$.each(roles, this.addRole.bind(this));
if (this._options.data)
this.deserialize(this._options.data);
},
addRole: function (name, roleId) {
this._builder.ref("rolesList").option(name, roleId);
},
addRolePermission: function (key, value) {
var divWithHidden, removeButton, hiddenRemoveRole, currentRow;
if (typeof value === "undefined") {
value = $(this._builder.ref("rolesList").getHTMLElement()).find("option:selected");
value = {name: value.text(), roleId: value.val()};
key = 3;
}
else {
key = value.permission;
value = value.role;
}
hiddenRemoveRole = $("<input>")
.attr("data-node-key", "access")
.attr("type", "radio")
.attr("name", value.name.toLowerCase() + "-access")
.attr("value", 4).css("display", "none");
divWithHidden = $("<div>").append(value.name)
.append($("<input>")
.attr("type", "hidden")
.attr("data-node-key", "access")
.attr("data-role-name", value.name)
.attr("value", value.roleId)
.attr("name", value.name.toLowerCase() + "-id")
).append(hiddenRemoveRole);
removeButton = $("<button>").attr("type", "button").addClass("imcms-negative");
if (this._options.type === 2) {
this._builder.ref("access")
.row(
divWithHidden[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 3)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 0)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 1)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 2)
.attr("name", value.name.toLowerCase() + "-access")[0],
removeButton[0]
);
}
else {
this._builder.ref("access")
.row(
divWithHidden[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 3)
.attr("name", value.name.toLowerCase() + "-access")[0],
$("<input>")
.attr("type", "radio")
.attr("data-node-key", "access")
.attr("value", 0)
.attr("name", value.name.toLowerCase() + "-access")[0],
removeButton[0]
);
key = key == 3 || key == 0 ? key : 3;
}
currentRow = this._builder.ref("access").row(this._rowsCount);
removeButton.on("click", function () {
$(currentRow).hide();
hiddenRemoveRole.prop("checked", true);
}.bind(this));
this._rowsCount++;
$("input[name=" + value.name.toLowerCase() + "-access]").filter("[value=" + key + "]").prop("checked", true);
},
loadCategories: function (categories) {
$.each(categories, this.addCategoryType.bind(this));
if (this._options.data)
this.deserialize(this._options.data);
},
addCategoryType: function (categoryType, options) {
this._builder.ref("categories-page")
.div()
.class("section field")
.select()
.label(categoryType)
.name(categoryType)
.reference(categoryType)
.attr("data-node-key", "categories")
.end()
.end();
if (options.isMultiple) {
this._builder.ref(categoryType).class("pqSelect").multiple();
}
else {
this._builder.ref(categoryType)
.option("none", "");
}
$.each(options.items, this.addCategory.bind(this, categoryType));
},
addCategory: function (categoryType, position, category) {
$(this._builder.ref(categoryType).getHTMLElement()).append(
$("<option>")
.val(category.name).text(category.name).attr("title", category.description)
);
},
addKeyword: function (position, keyword) {
var exist;
if (!keyword) {
keyword = this._builder.ref("keywordInput").value()
}
exist = $(this._builder.ref("keywordsList").getHTMLElement()).find("option").filter(function () {
return $(this).val() === keyword;
}).length > 0;
if (!exist) {
this._builder.ref("keywordsList").option(keyword);
}
},
addFile: function (key, val) {
var radio = $("<input>").attr("type", "radio").attr("name", "defaultFile").val(val);
this._builder.ref("files").row(
val,
radio[0],
$("<button>").attr("type", "button").addClass("imcms-negative").click(this.removeFile.bind(this, radio))[0]
)
},
removeFile: function (radio) {
radio.attr("data-removed", "").parents("tr").hide();
},
removeKeyword: function () {
$(this._builder.ref("keywordsList").getHTMLElement()).find("option:selected").remove();
},
chooseImage: function (e) {
var onFileChosen = function (data) {
if (data) {
$(e.target).parent().children("input[name=image]").val(data.urlPathRelativeToContextPath);
}
$(this._builder[0]).fadeIn();
}.bind(this);
Imcms.Editors.Content.showDialog({
onApply: $.proxy(onFileChosen, this),
onCancel: $.proxy(onFileChosen, this)
});
$(this._builder[0]).fadeOut();
},
setDateTimes: function () {
var dates = [
"created",
"modified",
"archived",
"published",
"publication-end"
];
for (var i = 0; i < dates.length; i++) {
var type = dates[i];
this.setDateTimeVal("date", type);
this.setDateTimeVal("time", type);
}
//?dateType=created&date=2010-12-23$time=17:55
$.ajax({
url: Imcms.contextPath + "/api/document/" + id + "?dateType=archive",
type: "POST"
})
},
apply: function () {
if (!$(this._builder[0]).find("form").valid()) {
return false;
}
this.setDateTimes();
this._options.onApply(this);
this.destroy();
},
cancel: function () {
this._options.onCancel(this);
this.destroy();
},
destroy: function () {
$(this._builder[0]).remove();
$(this._modal).remove();
},
serialize: function () {
var result = {languages: {}, access: {}, keywords: [], categories: {}},
$source = $(this._builder[0]),
formData = new FormData();
$source.find("[name]").filter(function () {
return !$(this).attr("data-node-key") && "file" !== $(this).attr("type") && !$(this).attr("ignored");
}).each(function () {
var $this = $(this);
if ($this.is("[type=checkbox]")) {
result[$this.attr("name")] = $this.is(":checked")
} else {
result[$this.attr("name")] = $this.val();
}
});
$source.find("[data-node-key=language]").each(function () {
var $dataElement = $(this);
var language = $dataElement.attr("data-node-value");
if (!Object.prototype.hasOwnProperty.call(result["languages"], language))
result["languages"][language] = {};
result["languages"][language][$dataElement.attr("name")] = $dataElement.attr("name") === "enabled" ?
($dataElement.is(":checked") ? true : false) : $dataElement.val();
});
$source.find("[data-role-name]").each(function () {
var role = {name: $(this).attr("data-role-name"), roleId: $(this).val()},
permission = $source.find("input[name=" + role.name.toLowerCase() + "-access]").filter(function () {
return $(this).prop("checked");
}).val();
result["access"][role.roleId] = {permission: permission, role: role};
});
$source.find("select[name=keywordsList]").children().each(function () {
result.keywords.push($(this).val());
});
$source.find("select[data-node-key=categories]").each(function () {
var $this = $(this);
if ($this.attr("multiple")) {
result.categories[$this.attr("name")] = $this.val() || [];
}
else {
result.categories[$this.attr("name")] = [$this.val() || ""];
}
});
if (this._options.type === 2) {
result.permissions = [{}, {}];
$source.find("input[data-node-key=permissions]").each(function () {
var $this = $(this);
var id = +$this.attr("data-node-value") - 1;
result.permissions[id][$this.attr("name")] = $this.is(":checked");
});
}
if (this._options.type === 8) {
result["removedFiles"] = $source.find("input[type=radio][data-removed]").map(function (pos, item) {
return $(item).val();
}).toArray();
formData.append("file", $source.find("input[name=file]")[0].files[0]);
}
formData.append("data", JSON.stringify(result));
formData.append("type", this._options.type);
formData.append("parent", this._options.parentDocumentId);
return formData;
},
deserialize: function (data) {
var $source = $(this._builder[0]);
$source.find("[name]").filter(function () {
return !$(this).attr("data-node-key") && "file" !== $(this).attr("type");
}).each(function () {
var $this = $(this);
if ($this.is("[type=checkbox]")) {
$this.prop("checked", data[$this.attr("name")]);
} else {
$this.val(data[$this.attr("name")]);
}
});
$source.find("[data-node-key=language]").each(function () {
var $dataElement = $(this);
var language = $dataElement.attr("data-node-value");
if (Object.prototype.hasOwnProperty.call(data.languages, language)) {
if ($dataElement.attr("name") === "enabled")
$dataElement.prop('checked', data.languages[language][$dataElement.attr("name")]);
else
$dataElement.val(data.languages[language][$dataElement.attr("name")]);
}
});
this._builder.ref("access").clear();
this._rowsCount = 0;
$.each(data.access, this.addRolePermission.bind(this));
$(this._builder.ref("keywordsList").getHTMLElement()).empty();
$.each(data.keywords, this.addKeyword.bind(this));
$.each(data.categories, function (categoryType, selectedCategories) {
selectedCategories.forEach(function (selectedCategory) {
$source
.find("select[name='" + categoryType + "']")
.find("option[value='" + selectedCategory + "']")
.attr("selected", "");
});
$($source.find("select[name='" + categoryType + "']")).multiselect();
});
if (this._options.type === 2 && data.permissions) {
$.each(data.permissions, function (index, value) {
var $elements = $source.find("[data-node-key=permissions]").filter("[data-node-value=" + ++index + "]");
$.each(value, function (key, val) {
if (val) {
$elements.filter("input[name=" + key + "]").attr("checked", "")
}
});
});
}
if (this._options.type === 8 && data.files) {
this._builder.ref("files").clear();
$.each(data.files, this.addFile.bind(this));
$(this._builder.ref("files").getHTMLElement())
.find("input[name=defaultFile]")
.filter('[value="' + data.defaultFile + '"]')
.prop('checked', true);
}
}
};
Imcms.Document.TypeViewer = function (options) {
this._options = Imcms.Utils.merge(options, this._options);
this.init();
};
Imcms.Document.TypeViewer.prototype = {
_builder: undefined,
_options: {
loader: undefined,
onApply: function () {
},
onCancel: function () {
}
},
init: function () {
var $builder;
this.buildView();
this.onLoaded();
$builder = $(this._builder[0]);
$builder.fadeIn("fast").css({
left: $(window).width() / 2 - $builder.width() / 2,
top: $(window).height() / 2 - $builder.height() / 2
});
},
buildView: function () {
this._builder = JSFormBuilder("<div>")
.form()
.div()
.class("imcms-header")
.div()
.class("imcms-title")
.html("Document Types")
.hidden()
.name("id")
.end()
.end()
.button()
.reference("closeButton")
.class("imcms-close-button")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.div()
.class("imcms-content")
.div()
.class("field select")
.select()
.label("Document Type")
.name("documentTypes")
.option("Text Document", 2)
.option("Url Document", 5)
.option("File Document", 8)
.end()
.end()
.div()
.class("field select")
.text()
.label("Document Parent")
.reference("parentDocument")
.name("parentDocument")
.disabled()
.end()
.button()
.on("click", this.openSearchDocumentDialog.bind(this))
.class("imcms-neutral browse")
.html("…")
.end()
.end()
.end()
.div()
.class("imcms-footer")
.div()
.class("buttons")
.button()
.class("imcms-positive")
.html("OK")
.on("click", $.proxy(this.apply, this))
.end()
.button()
.class("imcms-neutral")
.html("Cancel")
.on("click", $.proxy(this.cancel, this))
.end()
.end()
.end()
.end();
$(this._builder[0]).appendTo($("body")).addClass("document-type-viewer pop-up-form reset");
},
openSearchDocumentDialog: function () {
var documentSearchDialog = new Imcms.Document.DocumentSearchDialog(function (term, callback) {
Imcms.Editors.Document.filteredDocumentList(term, callback)
});
documentSearchDialog.result(function (data) {
$(this._builder.ref("parentDocument").getHTMLElement()).val(data.label).attr("data-id", data.id);
documentSearchDialog.dispose();
}.bind(this));
documentSearchDialog._dialog.parent().css("z-index", "99999999");
documentSearchDialog.open();
},
onLoaded: function (data) {
$(this._builder.ref("parentDocument").getHTMLElement()).val(Imcms.document.label).attr("data-id", Imcms.document.meta);
},
apply: function () {
this._options.onApply({
documentType: +$(this._builder[0]).find("select[name=documentTypes]").val(),
parentDocumentId: +$(this._builder[0]).find("input[name=parentDocument]").attr("data-id")
});
this.destroy();
},
cancel: function () {
this._options.onCancel();
this.destroy();
},
destroy: function () {
$(this._builder[0]).remove();
}
};
Imcms.Document.ListAdapter = function (container, loader) {
this._container = container;
this._loader = loader;
this.init();
};
Imcms.Document.ListAdapter.prototype = {
_container: {},
_ul: {},
_loader: {},
_pagerHandler: undefined,
init: function () {
this._loader.documentsList($.proxy(this.buildList, this));
this.buildPager();
},
buildList: function (data) {
$.each(data, $.proxy(this.addDocumentToList, this));
},
addDocumentToList: function (position, data) {
var deleteButton = $("<button>"),
row;
this._container.row(data.id, data.label, data.alias, data.type, $("<span>")
.append($("<button>")
.click($.proxy(this.copyDocument, this, data.id))
.addClass("imcms-positive")
.text("Copy")
.attr("type", "button"))
.append($("<button>")
.click($.proxy(this.editDocument, this, data.id))
.addClass("imcms-positive")
.text("Edit…")
.attr("type", "button"))
.append(deleteButton
.addClass("imcms-negative")
.attr("type", "button"))[0]
);
row = this._container.row(position);
if (data.isArchived) {
$(row).addClass("archived");
}
$(row).hover(function (e) {
if (e.shiftKey) {
deleteButton.attr("data-remove", true).text("");
}
else {
deleteButton.attr("data-remove", false).text(this.isArchived(row) ? "U" : "A");
}
}.bind(this));
deleteButton
.click($.proxy(this.deleteDocument, this, data.id, row));
},
buildPager: function () {
this._pagerHandler = new Imcms.Document.PagerHandler({
target: $(this._container.getHTMLElement()).parent()[0],
handler: this._loader.filteredDocumentList.bind(this._loader),
itemsPointer: function () {
var $source = $(this._container.getHTMLElement()).parent(),
height = $source.height(),
found = false,
rows = $source.find("table").find('tr'),
pointer = rows.length - 1,
index = rows.filter(function (pos, it) {
var result = false;
if ($(it).position().top > height) {
result = !found;
found = true;
}
return result;
}).index();
return index > -1 ? index : pointer;
}.bind(this),
resultProcessor: function (startIndex, data) {
this.buildList(data);
}.bind(this)
});
},
reload: function () {
this._container.clear();
this._loader.documentsList(function (data) {
this.buildList(data);
this._pagerHandler.reset();
}.bind(this));
},
deleteDocument: function (id, row) {
var deleteButton = $(row).find("button.imcms-negative"),
flag = deleteButton.attr("data-remove");
if (flag && flag.toString().toLowerCase() == "true") {
if (!confirm("Are you sure?")) {
return;
}
this._loader.deleteDocument(id);
$(row).remove();
} else if (this.isArchived(row)) {
this.unarchive(id, row);
}
else {
this.archive(id, row);
}
},
isArchived: function (row) {
return $(row).hasClass("archived");
},
archive: function (id, row) {
this._loader.archiveDocument(id);
$(row).addClass("archived");
},
unarchive: function (id, row) {
this._loader.unarchiveDocument(id);
$(row).removeClass("archived");
},
editDocument: function (id) {
this._loader.getDocument(id, $.proxy(this.showDocumentViewer, this));
},
copyDocument: function (id) {
this._loader.copyDocument(id, this.reload.bind(this));
},
showDocumentViewer: function (data) {
new Imcms.Document.Viewer({
data: data,
type: (+data.type) || undefined,
loader: this._loader,
target: $("body")[0],
onApply: $.proxy(this.saveDocument, this)
});
},
saveDocument: function (viewer) {
this._loader.update(viewer.serialize(), $.proxy(this.reload, this));
}
};
Imcms.Document.DocumentSearchDialog = function (source) {
this._source = source;
this.init();
};
Imcms.Document.DocumentSearchDialog.prototype = {
_source: null,
_currentTerm: "",
_builder: {},
_dialog: {},
_sort: "",
_order: "",
_selectedRow: {},
_pagerHandler: {},
_callback: function () {
},
init: function () {
this.buildContent();
this.buildDialog();
this.buildPager();
this.find();
},
buildContent: function () {
var that = this;
this._builder = JSFormBuilder("<DIV>")
.form()
.class("editor-menu-form")
.div()
.div()
.class("field")
.text()
.on("input", function () {
that.find(this.value());
})
.reference("searchField")
.placeholder("Type to find document")
.end()
.end()
.div()
.class("field")
.div()
.class("field-wrapper")
.table()
.on("click", $.proxy(this._onSelectElement, this))
.column("id")
.column("label")
.column("language")
.column("alias")
.reference("documentsTable")
.end()
.end()
.end()
.end()
.end();
},
sort: function (index) {
//var sortingType = $(this._builder[0]).find("input[name=sorting]:checked").val(),
// i = index,
// comparator = function (row1, row2) {
// return $($(row1).find("td")[i]).text().localeCompare($($(row2).find("td")[i]).text());
// },
// table = $(this._builder.ref("documentsTable").getHTMLElement());
//
//switch (sortingType) {
// default:
// case "id":
// i = 0;
// break;
// case "headline":
// i = 1;
// break;
// case "alias":
// i = 3;
// break;
//}
var oldSort = this._sort;
switch (index) {
default:
case 0:
this._sort = "meta_id";
break;
case 1:
this._sort = "meta_headline";
break;
case 2:
this._sort = "language";
break;
case 3:
this._sort = "alias";
break;
}
if (this._sort === oldSort) {
this._order = this._order === "asc" ? "desc" : "asc";
}
else {
this._order = "asc";
}
//table.find("tr").sort(comparator).detach().appendTo(table);
this.find(this._currentTerm);
},
buildDialog: function () {
this._dialog = $(this._builder[0]).dialog({
autoOpen: false,
height: 500,
width: 700,
modal: true,
buttons: {
"Add selected": $.proxy(this._onApply, this),
Cancel: function () {
$(this).dialog("close");
}
}
});
var dialog = $(this._builder[0]).parents(".ui-dialog").removeClass()
.addClass("pop-up-form menu-viewer reset").css({position: "fixed"}),
header = dialog.children(".ui-dialog-titlebar").removeClass()
.addClass("imcms-header").append($("<div>").addClass("imcms-title").text("DOCUMENT SELECTOR")),
content = dialog.children(".ui-dialog-content").removeClass()
.addClass("imcms-content"),
footer = dialog.children(".ui-dialog-buttonpane").removeClass()
.addClass("imcms-footer"),
buttons = footer.find(".ui-button").removeClass();
header.find(".ui-dialog-title").remove();
header.children("button").empty().removeClass().addClass("imcms-close-button");
$(buttons[0]).addClass("imcms-positive");
$(buttons[1]).addClass("imcms-neutral cancel-button");
},
buildPager: function () {
this._pagerHandler = new Imcms.Document.PagerHandler({
target: $(this._builder[0]).find(".field-wrapper")[0],
handler: this.pagingHandler.bind(this),
itemsPointer: function () {
var $source = $(this._builder[0]).find('.field-wrapper'),
height = $source.height(),
found = false,
rows = $source.find("table").find('tr'),
pointer = rows.length - 1,
index = rows.filter(function (pos, it) {
var result = false;
if ($(it).position().top > height) {
result = !found;
found = true;
}
return result;
}).index();
return index > -1 ? index : pointer;
}.bind(this),
resultProcessor: this.appendDataToTable.bind(this)
});
},
open: function () {
this._dialog.dialog("open");
},
dispose: function () {
this._dialog.remove();
},
find: function (word) {
this._currentTerm = word;
this._pagerHandler.reset();
this._source({term: word || "", sort: this._sort, order: this._order}, $.proxy(this.fillDataToTable, this));
},
pagingHandler: function (params, callback) {
params["term"] = this._currentTerm;
params["sort"] = this._sort;
params["order"] = this._order;
this._source(params, callback);
},
fillDataToTable: function (data) {
this.clearTable();
this.appendDataToTable(0, data);
},
clearTable: function () {
this._builder.ref("documentsTable").clear();
},
appendDataToTable: function (startIndex, data) {
$(this._builder.ref("documentsTable").getHTMLElement()).find("th").each(function (pos, item) {
$(item).find("div").remove();
});
for (var rowId in data) {
if (data.hasOwnProperty(rowId) && data[rowId]) {
this._builder.ref("documentsTable").row(data[rowId]);
}
}
$(this._builder.ref("documentsTable").getHTMLElement()).find("tr")
.filter(function (pos) {
return pos >= startIndex;
}).each(function (pos, item) {
$(item).on("dragstart", function (event) {
$(".ui-widget-overlay").css("display", "none");
event.originalEvent.dataTransfer.setData("data", JSON.stringify(data[pos - 1]));
}).on("dragend", function () {
$(".ui-widget-overlay").css("display", "block");
}).attr("draggable", true);
});
$(this._builder.ref("documentsTable").getHTMLElement()).find("th").each(function (pos, item) {
$("<div>").append($(item).html()).click(this.sort.bind(this, pos)).appendTo(item);
}.bind(this));
},
result: function (callback) {
this._callback = callback;
return this;
},
_onApply: function () {
var resultData = {id: this._selectedRow.children[0].innerHTML, label: this._selectedRow.children[1].innerHTML};
this._callback(resultData);
this._dialog.dialog("close");
},
_onSelectElement: function (e) {
var $table = $(e.currentTarget),
// tableOffset = $table.offset();
element = $table.find("tbody tr").filter(function (index, element) {
/* var offset, farCorner;
element = $(element);
offset = element.position();
//offset = {left: offset.left - tableOffset.left, top: offset.top - tableOffset.top};
farCorner = {right: offset.left + element.width(), bottom: offset.top + element.height()};
return offset.left <= e.offsetX && offset.top <= e.offsetY && e.offsetX <= farCorner.right && e.offsetY <= farCorner.bottom*/
return $.contains(element, e.target);
});
if (!element.length) {
return false;
}
element = element[0];
if (this._selectedRow)
this._selectedRow.className = "";
this._selectedRow = element;
this._selectedRow.className = "clicked";
}
};
Imcms.Document.PagerHandler = function (options) {
this._target = options.target;
this._options = Imcms.Utils.merge(options, this._options);
this.init();
};
Imcms.Document.PagerHandler.prototype = {
_target: undefined,
_waiter: undefined,
_isHandled: false,
_pageNumber: 1,
_options: {
count: 25,
handler: function () {
},
itemsPointer: function () {
return 0;
},
resultProcessor: function (data) {
},
waiterContent: ""
},
init: function () {
$(this._target).scroll(this.scrollHandler.bind(this)).bind('beforeShow', this.scrollHandler.bind(this));
this.scrollHandler();
},
handleRequest: function (skip) {
this._addWaiterToTarget();
this._isHandled = true;
this._options.handler({skip: skip, take: this._options.count}, this.requestCompleted.bind(this));
},
requestCompleted: function (data) {
this._options.resultProcessor(this._pageNumber * this._options.count, data);
this._pageNumber++;
this._removeWaiterFromTarget();
this._isHandled = false;
this.scrollHandler();
},
scrollHandler: function () {
if (this._isHandled) {
return;
}
var pointer = this._options.itemsPointer(),
currentItemsCount = this._pageNumber * this._options.count;
if (pointer >= currentItemsCount - 3) {
this.handleRequest(currentItemsCount)
}
},
_addWaiterToTarget: function () {
this._waiter = $("<div>")
.addClass("waiter")
.append(this._options.waiterContent)
.appendTo(this._target);
},
_removeWaiterFromTarget: function () {
this._waiter.remove();
},
reset: function () {
this._pageNumber = 1;
this.scrollHandler();
}
};
| Fixes.
| src/main/web/imcms/lang/scripts/imcms_document.js | Fixes. | <ide><path>rc/main/web/imcms/lang/scripts/imcms_document.js
<ide> $(this._builder[0]).fadeOut();
<ide> },
<ide> setDateTimes: function () {
<del> var dates = [
<del> "created",
<del> "modified",
<del> "archived",
<del> "published",
<del> "publication-end"
<del> ];
<del> for (var i = 0; i < dates.length; i++) {
<del> var type = dates[i];
<del> this.setDateTimeVal("date", type);
<del> this.setDateTimeVal("time", type);
<del> }
<del>//?dateType=created&date=2010-12-23$time=17:55
<del> $.ajax({
<del> url: Imcms.contextPath + "/api/document/" + id + "?dateType=archive",
<del> type: "POST"
<del> })
<add>// var dates = [
<add>// "created",
<add>// "modified",
<add>// "archived",
<add>// "published",
<add>// "publication-end"
<add>// ];
<add>// for (var i = 0; i < dates.length; i++) {
<add>// var type = dates[i];
<add>// this.setDateTimeVal("date", type);
<add>// this.setDateTimeVal("time", type);
<add>// }
<add>////?dateType=created&date=2010-12-23$time=17:55
<add>// $.ajax({
<add>// url: Imcms.contextPath + "/api/document/" + id + "?dateType=archive",
<add>// type: "POST"
<add>// })
<ide> },
<ide> apply: function () {
<ide> if (!$(this._builder[0]).find("form").valid()) { |
|
Java | apache-2.0 | fcd2a0017ea5b6701bd323cebd5084b38a25fdca | 0 | ruddell/generator-jhipster,hdurix/generator-jhipster,ctamisier/generator-jhipster,maniacneron/generator-jhipster,robertmilowski/generator-jhipster,baskeboler/generator-jhipster,ramzimaalej/generator-jhipster,ziogiugno/generator-jhipster,wmarques/generator-jhipster,gmarziou/generator-jhipster,ruddell/generator-jhipster,JulienMrgrd/generator-jhipster,danielpetisme/generator-jhipster,rkohel/generator-jhipster,liseri/generator-jhipster,dynamicguy/generator-jhipster,sendilkumarn/generator-jhipster,vivekmore/generator-jhipster,vivekmore/generator-jhipster,sendilkumarn/generator-jhipster,yongli82/generator-jhipster,erikkemperman/generator-jhipster,jkutner/generator-jhipster,atomfrede/generator-jhipster,cbornet/generator-jhipster,siliconharborlabs/generator-jhipster,liseri/generator-jhipster,lrkwz/generator-jhipster,ruddell/generator-jhipster,ctamisier/generator-jhipster,eosimosu/generator-jhipster,duderoot/generator-jhipster,gzsombor/generator-jhipster,PierreBesson/generator-jhipster,nkolosnjaji/generator-jhipster,dynamicguy/generator-jhipster,maniacneron/generator-jhipster,dalbelap/generator-jhipster,dimeros/generator-jhipster,Tcharl/generator-jhipster,erikkemperman/generator-jhipster,ramzimaalej/generator-jhipster,mraible/generator-jhipster,pascalgrimaud/generator-jhipster,stevehouel/generator-jhipster,ctamisier/generator-jhipster,deepu105/generator-jhipster,dimeros/generator-jhipster,Tcharl/generator-jhipster,stevehouel/generator-jhipster,eosimosu/generator-jhipster,cbornet/generator-jhipster,gmarziou/generator-jhipster,PierreBesson/generator-jhipster,wmarques/generator-jhipster,nkolosnjaji/generator-jhipster,duderoot/generator-jhipster,erikkemperman/generator-jhipster,gzsombor/generator-jhipster,pascalgrimaud/generator-jhipster,pascalgrimaud/generator-jhipster,PierreBesson/generator-jhipster,siliconharborlabs/generator-jhipster,ziogiugno/generator-jhipster,vivekmore/generator-jhipster,Tcharl/generator-jhipster,rkohel/generator-jhipster,Tcharl/generator-jhipster,mosoft521/generator-jhipster,gzsombor/generator-jhipster,siliconharborlabs/generator-jhipster,danielpetisme/generator-jhipster,sohibegit/generator-jhipster,mraible/generator-jhipster,dimeros/generator-jhipster,yongli82/generator-jhipster,cbornet/generator-jhipster,baskeboler/generator-jhipster,deepu105/generator-jhipster,baskeboler/generator-jhipster,dimeros/generator-jhipster,hdurix/generator-jhipster,xetys/generator-jhipster,robertmilowski/generator-jhipster,jhipster/generator-jhipster,PierreBesson/generator-jhipster,liseri/generator-jhipster,siliconharborlabs/generator-jhipster,ziogiugno/generator-jhipster,pascalgrimaud/generator-jhipster,danielpetisme/generator-jhipster,ramzimaalej/generator-jhipster,JulienMrgrd/generator-jhipster,deepu105/generator-jhipster,erikkemperman/generator-jhipster,hdurix/generator-jhipster,cbornet/generator-jhipster,atomfrede/generator-jhipster,nkolosnjaji/generator-jhipster,stevehouel/generator-jhipster,vivekmore/generator-jhipster,atomfrede/generator-jhipster,eosimosu/generator-jhipster,lrkwz/generator-jhipster,mraible/generator-jhipster,sendilkumarn/generator-jhipster,danielpetisme/generator-jhipster,ziogiugno/generator-jhipster,dynamicguy/generator-jhipster,nkolosnjaji/generator-jhipster,dimeros/generator-jhipster,mosoft521/generator-jhipster,sohibegit/generator-jhipster,erikkemperman/generator-jhipster,eosimosu/generator-jhipster,yongli82/generator-jhipster,rifatdover/generator-jhipster,atomfrede/generator-jhipster,ctamisier/generator-jhipster,PierreBesson/generator-jhipster,mosoft521/generator-jhipster,mraible/generator-jhipster,robertmilowski/generator-jhipster,JulienMrgrd/generator-jhipster,dalbelap/generator-jhipster,rifatdover/generator-jhipster,deepu105/generator-jhipster,JulienMrgrd/generator-jhipster,gmarziou/generator-jhipster,robertmilowski/generator-jhipster,dalbelap/generator-jhipster,pascalgrimaud/generator-jhipster,liseri/generator-jhipster,dalbelap/generator-jhipster,sohibegit/generator-jhipster,mraible/generator-jhipster,sohibegit/generator-jhipster,ctamisier/generator-jhipster,ruddell/generator-jhipster,siliconharborlabs/generator-jhipster,jkutner/generator-jhipster,baskeboler/generator-jhipster,deepu105/generator-jhipster,hdurix/generator-jhipster,cbornet/generator-jhipster,liseri/generator-jhipster,stevehouel/generator-jhipster,stevehouel/generator-jhipster,jhipster/generator-jhipster,jkutner/generator-jhipster,atomfrede/generator-jhipster,ruddell/generator-jhipster,baskeboler/generator-jhipster,xetys/generator-jhipster,mosoft521/generator-jhipster,jkutner/generator-jhipster,dynamicguy/generator-jhipster,gmarziou/generator-jhipster,eosimosu/generator-jhipster,mosoft521/generator-jhipster,lrkwz/generator-jhipster,hdurix/generator-jhipster,maniacneron/generator-jhipster,gmarziou/generator-jhipster,gzsombor/generator-jhipster,xetys/generator-jhipster,Tcharl/generator-jhipster,rkohel/generator-jhipster,sendilkumarn/generator-jhipster,nkolosnjaji/generator-jhipster,jkutner/generator-jhipster,xetys/generator-jhipster,maniacneron/generator-jhipster,sendilkumarn/generator-jhipster,wmarques/generator-jhipster,gzsombor/generator-jhipster,dalbelap/generator-jhipster,jhipster/generator-jhipster,duderoot/generator-jhipster,danielpetisme/generator-jhipster,maniacneron/generator-jhipster,yongli82/generator-jhipster,rkohel/generator-jhipster,wmarques/generator-jhipster,JulienMrgrd/generator-jhipster,rifatdover/generator-jhipster,yongli82/generator-jhipster,ziogiugno/generator-jhipster,duderoot/generator-jhipster,vivekmore/generator-jhipster,duderoot/generator-jhipster,rkohel/generator-jhipster,lrkwz/generator-jhipster,lrkwz/generator-jhipster,robertmilowski/generator-jhipster,sohibegit/generator-jhipster,jhipster/generator-jhipster,jhipster/generator-jhipster,wmarques/generator-jhipster | package <%=packageName%>.web.rest;
import com.codahale.metrics.annotation.Timed;
import <%=packageName%>.domain.Authority;<% if (authenticationType == 'cookie') { %>
import <%=packageName%>.domain.PersistentToken;<% } %>
import <%=packageName%>.domain.User;<% if (authenticationType == 'cookie') { %>
import <%=packageName%>.repository.PersistentTokenRepository;<% } %>
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.security.SecurityUtils;
import <%=packageName%>.service.MailService;
import <%=packageName%>.service.UserService;
import <%=packageName%>.web.rest.dto.UserDTO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;<% if (javaVersion == '8') { %>
import java.util.stream.Collectors;<% } %>
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping("/api")
public class AccountResource {
private final Logger log = LoggerFactory.getLogger(AccountResource.class);
@Inject
private UserRepository userRepository;
@Inject
private UserService userService;<% if (authenticationType == 'cookie') { %>
@Inject
private PersistentTokenRepository persistentTokenRepository;<% } %>
@Inject
private MailService mailService;
/**
* POST /register -> register the user.
*/
@RequestMapping(value = "/register",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {<% if (javaVersion == '8') { %>
return userRepository.findOneByLogin(userDTO.getLogin())
.map(user -> new ResponseEntity<>("login already in use", HttpStatus.BAD_REQUEST))
.orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail())
.map(user -> new ResponseEntity<>("e-mail address already in use", HttpStatus.BAD_REQUEST))
.orElseGet(() -> {
User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
userDTO.getLangKey());
String baseUrl = request.getScheme() + // "http"
"://" + // "://"
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort(); // "80"
mailService.sendActivationEmail(user, baseUrl);
return new ResponseEntity<>(HttpStatus.CREATED);
})
);<% } else { %>
User user = userRepository.findOneByLogin(userDTO.getLogin());
if (user != null) {
return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("login already in use");
} else {
if (userRepository.findOneByEmail(userDTO.getEmail()) != null) {
return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use");
}
user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
userDTO.getLangKey());
String baseUrl = request.getScheme() + // "http"
"://" + // "://"
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort(); // "80"
mailService.sendActivationEmail(user, baseUrl);
return new ResponseEntity<>(HttpStatus.CREATED);
}<% } %>
}
/**
* GET /activate -> activate the registered user.
*/
@RequestMapping(value = "/activate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<String> activateAccount(@RequestParam(value = "key") String key) {<% if (javaVersion == '8') { %>
return Optional.ofNullable(userService.activateRegistration(key))
.map(user -> new ResponseEntity<String>(HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User user = userService.activateRegistration(key);
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>(HttpStatus.OK);<% } %>
}
/**
* GET /authenticate -> check if the user is authenticated, and return its login.
*/
@RequestMapping(value = "/authenticate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
/**
* GET /account -> get the current user.
*/
@RequestMapping(value = "/account",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<UserDTO> getAccount() {<% if (javaVersion == '8') { %>
return Optional.ofNullable(userService.getUserWithAuthorities())
.map(user -> new ResponseEntity<>(
new UserDTO(
user.getLogin(),
null,
user.getFirstName(),
user.getLastName(),
user.getEmail(),
user.getLangKey(),
user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toList())),
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User user = userService.getUserWithAuthorities();
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
List<String> roles = new ArrayList<>();
for (Authority authority : user.getAuthorities()) {
roles.add(authority.getName());
}
return new ResponseEntity<>(
new UserDTO(
user.getLogin(),
null,
user.getFirstName(),
user.getLastName(),
user.getEmail(),
user.getLangKey(),
roles),
HttpStatus.OK);<% } %>
}
/**
* POST /account -> update the current user information.
*/
@RequestMapping(value = "/account",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<String> saveAccount(@RequestBody UserDTO userDTO) {<% if (javaVersion == '8') { %>
return userRepository
.findOneByLogin(userDTO.getLogin())
.filter(u -> u.getLogin().equals(SecurityUtils.getCurrentLogin()))
.map(u -> {
userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
return new ResponseEntity<String>(HttpStatus.OK);
})
.orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User userHavingThisLogin = userRepository.findOneByLogin(userDTO.getLogin());
if (userHavingThisLogin != null && !userHavingThisLogin.getLogin().equals(SecurityUtils.getCurrentLogin())) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
return new ResponseEntity<>(HttpStatus.OK);<% } %>
}
/**
* POST /change_password -> changes the current user's password
*/
@RequestMapping(value = "/account/change_password",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<?> changePassword(@RequestBody String password) {
if (StringUtils.isEmpty(password)) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
userService.changePassword(password);
return new ResponseEntity<>(HttpStatus.OK);
}<% if (authenticationType == 'cookie') { %>
/**
* GET /account/sessions -> get the current open sessions.
*/
@RequestMapping(value = "/account/sessions",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<PersistentToken>> getCurrentSessions() {<% if (javaVersion == '8') { %>
return userRepository.findOneByLogin(SecurityUtils.getCurrentLogin())
.map(user -> new ResponseEntity<>(
persistentTokenRepository.findByUser(user),
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User user = userRepository.findOneByLogin(SecurityUtils.getCurrentLogin());
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(
persistentTokenRepository.findByUser(user),
HttpStatus.OK);<% } %>
}
/**
* DELETE /account/sessions?series={series} -> invalidate an existing session.
*
* - You can only delete your own sessions, not any other user's session
* - If you delete one of your existing sessions, and that you are currently logged in on that session, you will
* still be able to use that session, until you quit your browser: it does not work in real time (there is
* no API for that), it only removes the "remember me" cookie
* - This is also true if you invalidate your current session: you will still be able to use it until you close
* your browser or that the session times out. But automatic login (the "remember me" cookie) will not work
* anymore.
* There is an API to invalidate the current session, but there is no API to check which session uses which
* cookie.
*/
@RequestMapping(value = "/account/sessions/{series}",
method = RequestMethod.DELETE)
@Timed
public void invalidateSession(@PathVariable String series) throws UnsupportedEncodingException {
String decodedSeries = URLDecoder.decode(series, "UTF-8");<% if (javaVersion == '8') { %>
userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).ifPresent(u -> {
persistentTokenRepository.findByUser(u).stream()
.filter(persistentToken -> StringUtils.equals(persistentToken.getSeries(), decodedSeries))
.findAny().ifPresent(t -> persistentTokenRepository.delete(decodedSeries));
});<% } else { %>
User user = userRepository.findOneByLogin(SecurityUtils.getCurrentLogin());
List<PersistentToken> persistentTokens = persistentTokenRepository.findByUser(user);
for (PersistentToken persistentToken : persistentTokens) {
if (StringUtils.equals(persistentToken.getSeries(), decodedSeries)) {
persistentTokenRepository.delete(decodedSeries);
}
}<% } %>
}<% } %>
}
| app/templates/src/main/java/package/web/rest/_AccountResource.java | package <%=packageName%>.web.rest;
import com.codahale.metrics.annotation.Timed;
import <%=packageName%>.domain.Authority;<% if (authenticationType == 'cookie') { %>
import <%=packageName%>.domain.PersistentToken;<% } %>
import <%=packageName%>.domain.User;<% if (authenticationType == 'cookie') { %>
import <%=packageName%>.repository.PersistentTokenRepository;<% } %>
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.security.SecurityUtils;
import <%=packageName%>.service.MailService;
import <%=packageName%>.service.UserService;
import <%=packageName%>.web.rest.dto.UserDTO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;<% if (javaVersion == '8') { %>
import java.util.stream.Collectors;<% } %>
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping("/api")
public class AccountResource {
private final Logger log = LoggerFactory.getLogger(AccountResource.class);
@Inject
private UserRepository userRepository;
@Inject
private UserService userService;<% if (authenticationType == 'cookie') { %>
@Inject
private PersistentTokenRepository persistentTokenRepository;<% } %>
@Inject
private MailService mailService;
/**
* POST /register -> register the user.
*/
@RequestMapping(value = "/register",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {<% if (javaVersion == '8') { %>
return userRepository.findOneByLogin(userDTO.getLogin())
.map(user -> new ResponseEntity<>("login already in use", HttpStatus.BAD_REQUEST))
.orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail())
.map(user -> new ResponseEntity<>("e-mail address already in use", HttpStatus.BAD_REQUEST))
.orElseGet(() -> {
User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
userDTO.getLangKey());
String baseUrl = request.getScheme() + // "http"
"://" + // "://"
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort(); // "80"
mailService.sendActivationEmail(user, baseUrl);
return new ResponseEntity<>(HttpStatus.CREATED);
})
);<% } else { %>
User user = userRepository.findOneByLogin(userDTO.getLogin());
if (user != null) {
return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("login already in use");
} else {
if (userRepository.findOneByEmail(userDTO.getEmail()) != null) {
return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use");
}
user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
userDTO.getLangKey());
String baseUrl = request.getScheme() + // "http"
"://" + // "://"
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort(); // "80"
mailService.sendActivationEmail(user, baseUrl);
return new ResponseEntity<>(HttpStatus.CREATED);
}<% } %>
}
/**
* GET /activate -> activate the registered user.
*/
@RequestMapping(value = "/activate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<String> activateAccount(@RequestParam(value = "key") String key) {<% if (javaVersion == '8') { %>
return Optional.ofNullable(userService.activateRegistration(key))
.map(user -> new ResponseEntity<String>(HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User user = userService.activateRegistration(key);
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>(HttpStatus.OK);<% } %>
}
/**
* GET /authenticate -> check if the user is authenticated, and return its login.
*/
@RequestMapping(value = "/authenticate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
/**
* GET /account -> get the current user.
*/
@RequestMapping(value = "/account",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<UserDTO> getAccount() {<% if (javaVersion == '8') { %>
return Optional.ofNullable(userService.getUserWithAuthorities())
.map(user -> new ResponseEntity<>(
new UserDTO(
user.getLogin(),
null,
user.getFirstName(),
user.getLastName(),
user.getEmail(),
user.getLangKey(),
user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toList())),
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User user = userService.getUserWithAuthorities();
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
List<String> roles = new ArrayList<>();
for (Authority authority : user.getAuthorities()) {
roles.add(authority.getName());
}
return new ResponseEntity<>(
new UserDTO(
user.getLogin(),
null,
user.getFirstName(),
user.getLastName(),
user.getEmail(),
user.getLangKey(),
roles),
HttpStatus.OK);<% } %>
}
/**
* POST /account -> update the current user information.
*/
@RequestMapping(value = "/account",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<String> saveAccount(@RequestBody UserDTO userDTO) {<% if (javaVersion == '8') { %>
return userRepository
.findOneByEmail(userDTO.getEmail())
.filter(u -> u.getLogin().equals(SecurityUtils.getCurrentLogin()))
.map(u -> {
userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
return new ResponseEntity<String>(HttpStatus.OK);
})
.orElseGet(() -> ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use"));<% } else { %>
User userHavingThisEmail = userRepository.findOneByEmail(userDTO.getEmail());
if (userHavingThisEmail != null && !userHavingThisEmail.getLogin().equals(SecurityUtils.getCurrentLogin())) {
return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use");
}
userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
return new ResponseEntity<>(HttpStatus.OK);<% } %>
}
/**
* POST /change_password -> changes the current user's password
*/
@RequestMapping(value = "/account/change_password",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<?> changePassword(@RequestBody String password) {
if (StringUtils.isEmpty(password)) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
userService.changePassword(password);
return new ResponseEntity<>(HttpStatus.OK);
}<% if (authenticationType == 'cookie') { %>
/**
* GET /account/sessions -> get the current open sessions.
*/
@RequestMapping(value = "/account/sessions",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<PersistentToken>> getCurrentSessions() {<% if (javaVersion == '8') { %>
return userRepository.findOneByLogin(SecurityUtils.getCurrentLogin())
.map(user -> new ResponseEntity<>(
persistentTokenRepository.findByUser(user),
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
User user = userRepository.findOneByLogin(SecurityUtils.getCurrentLogin());
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(
persistentTokenRepository.findByUser(user),
HttpStatus.OK);<% } %>
}
/**
* DELETE /account/sessions?series={series} -> invalidate an existing session.
*
* - You can only delete your own sessions, not any other user's session
* - If you delete one of your existing sessions, and that you are currently logged in on that session, you will
* still be able to use that session, until you quit your browser: it does not work in real time (there is
* no API for that), it only removes the "remember me" cookie
* - This is also true if you invalidate your current session: you will still be able to use it until you close
* your browser or that the session times out. But automatic login (the "remember me" cookie) will not work
* anymore.
* There is an API to invalidate the current session, but there is no API to check which session uses which
* cookie.
*/
@RequestMapping(value = "/account/sessions/{series}",
method = RequestMethod.DELETE)
@Timed
public void invalidateSession(@PathVariable String series) throws UnsupportedEncodingException {
String decodedSeries = URLDecoder.decode(series, "UTF-8");<% if (javaVersion == '8') { %>
userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).ifPresent(u -> {
persistentTokenRepository.findByUser(u).stream()
.filter(persistentToken -> StringUtils.equals(persistentToken.getSeries(), decodedSeries))
.findAny().ifPresent(t -> persistentTokenRepository.delete(decodedSeries));
});<% } else { %>
User user = userRepository.findOneByLogin(SecurityUtils.getCurrentLogin());
List<PersistentToken> persistentTokens = persistentTokenRepository.findByUser(user);
for (PersistentToken persistentToken : persistentTokens) {
if (StringUtils.equals(persistentToken.getSeries(), decodedSeries)) {
persistentTokenRepository.delete(decodedSeries);
}
}<% } %>
}<% } %>
}
| The user should be checked on his login, not his email
| app/templates/src/main/java/package/web/rest/_AccountResource.java | The user should be checked on his login, not his email | <ide><path>pp/templates/src/main/java/package/web/rest/_AccountResource.java
<ide> @Timed
<ide> public ResponseEntity<String> saveAccount(@RequestBody UserDTO userDTO) {<% if (javaVersion == '8') { %>
<ide> return userRepository
<del> .findOneByEmail(userDTO.getEmail())
<add> .findOneByLogin(userDTO.getLogin())
<ide> .filter(u -> u.getLogin().equals(SecurityUtils.getCurrentLogin()))
<ide> .map(u -> {
<ide> userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
<ide> return new ResponseEntity<String>(HttpStatus.OK);
<ide> })
<del> .orElseGet(() -> ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use"));<% } else { %>
<del> User userHavingThisEmail = userRepository.findOneByEmail(userDTO.getEmail());
<del> if (userHavingThisEmail != null && !userHavingThisEmail.getLogin().equals(SecurityUtils.getCurrentLogin())) {
<del> return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use");
<add> .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));<% } else { %>
<add> User userHavingThisLogin = userRepository.findOneByLogin(userDTO.getLogin());
<add> if (userHavingThisLogin != null && !userHavingThisLogin.getLogin().equals(SecurityUtils.getCurrentLogin())) {
<add> return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
<ide> }
<ide> userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail());
<ide> return new ResponseEntity<>(HttpStatus.OK);<% } %> |
|
Java | apache-2.0 | 207012835383e6c98f765e54cbee5bd45ab8914e | 0 | gdelafosse/incubator-tinkerpop,jorgebay/tinkerpop,dalaro/incubator-tinkerpop,newkek/incubator-tinkerpop,robertdale/tinkerpop,BrynCooke/incubator-tinkerpop,vtslab/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,velo/incubator-tinkerpop,rmagen/incubator-tinkerpop,robertdale/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,apache/incubator-tinkerpop,Lab41/tinkerpop3,RussellSpitzer/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,apache/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,velo/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,dalaro/incubator-tinkerpop,edgarRd/incubator-tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,vtslab/incubator-tinkerpop,samiunn/incubator-tinkerpop,artem-aliev/tinkerpop,samiunn/incubator-tinkerpop,newkek/incubator-tinkerpop,artem-aliev/tinkerpop,n-tran/incubator-tinkerpop,apache/tinkerpop,apache/tinkerpop,edgarRd/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,robertdale/tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,RedSeal-co/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,robertdale/tinkerpop,RussellSpitzer/incubator-tinkerpop,pluradj/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,jorgebay/tinkerpop,gdelafosse/incubator-tinkerpop,edgarRd/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,apache/tinkerpop,artem-aliev/tinkerpop,artem-aliev/tinkerpop,krlohnes/tinkerpop,mike-tr-adamson/incubator-tinkerpop,rmagen/incubator-tinkerpop,n-tran/incubator-tinkerpop,apache/tinkerpop,BrynCooke/incubator-tinkerpop,Lab41/tinkerpop3,samiunn/incubator-tinkerpop,pluradj/incubator-tinkerpop,vtslab/incubator-tinkerpop,jorgebay/tinkerpop,krlohnes/tinkerpop,dalaro/incubator-tinkerpop,apache/tinkerpop,mpollmeier/tinkerpop3,artem-aliev/tinkerpop,n-tran/incubator-tinkerpop,mpollmeier/tinkerpop3,newkek/incubator-tinkerpop,rmagen/incubator-tinkerpop,apache/incubator-tinkerpop,krlohnes/tinkerpop,velo/incubator-tinkerpop,krlohnes/tinkerpop | package com.tinkerpop.blueprints.io.graphml;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.io.GraphWriter;
import com.tinkerpop.blueprints.io.LexicographicalElementComparator;
import com.tinkerpop.blueprints.util.StreamFactory;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* GraphMLWriter writes a Graph to a GraphML OutputStream.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Joshua Shinavier (http://fortytwo.net)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphMLWriter implements GraphWriter {
private final XMLOutputFactory inputFactory = XMLOutputFactory.newInstance();
private final Graph graph;
private boolean normalize = false;
private final Optional<Map<String, String>> vertexKeyTypes;
private final Optional<Map<String, String>> edgeKeyTypes;
private final Optional<String> xmlSchemaLocation;
private final Optional<String> edgeLabelKey;
/**
* @param graph the Graph to pull the data from
*/
private GraphMLWriter(final Graph graph, final boolean normalize, final Map<String, String> vertexKeyTypes,
final Map<String, String> edgeKeyTypes, final String xmlSchemaLocation,
final String edgeLabelKey) {
this.graph = graph;
this.normalize = normalize;
this.vertexKeyTypes = Optional.ofNullable(vertexKeyTypes);
this.edgeKeyTypes = Optional.ofNullable(edgeKeyTypes);
this.xmlSchemaLocation = Optional.ofNullable(xmlSchemaLocation);
this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
}
/**
* Write the data in a Graph to a GraphML OutputStream.
*
* @param outputStream the GraphML OutputStream to write the Graph data to
* @throws IOException thrown if there is an error generating the GraphML data
*/
@Override
public void outputGraph(final OutputStream outputStream) throws IOException {
final Map<String, String> identifiedVertexKeyTypes = this.vertexKeyTypes.orElseGet(this::determineVertexTypes);
final Map<String, String> identifiedEdgeKeyTypes = this.edgeKeyTypes.orElseGet(this::determineEdgeTypes);
// adding the edge label key will push the label into the data portion of the graphml otherwise it
// will live with the edge data itself (which won't validate against the graphml schema)
if (this.edgeLabelKey.isPresent() && null == identifiedEdgeKeyTypes.get(this.edgeLabelKey.get()))
identifiedEdgeKeyTypes.put(this.edgeLabelKey.get(), GraphMLTokens.STRING);
try {
final XMLStreamWriter writer;
writer = configureWriter(outputStream);
writer.writeStartDocument();
writer.writeStartElement(GraphMLTokens.GRAPHML);
writeXmlNsAndSchema(writer);
writeTypes(identifiedVertexKeyTypes, identifiedEdgeKeyTypes, writer);
writer.writeStartElement(GraphMLTokens.GRAPH);
writer.writeAttribute(GraphMLTokens.ID, GraphMLTokens.G);
writer.writeAttribute(GraphMLTokens.EDGEDEFAULT, GraphMLTokens.DIRECTED);
writeVertices(writer);
writeEdges(writer);
writer.writeEndElement(); // graph
writer.writeEndElement(); // graphml
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (XMLStreamException xse) {
throw new IOException(xse);
}
}
private XMLStreamWriter configureWriter(final OutputStream outputStream) throws XMLStreamException {
final XMLStreamWriter utf8Writer = inputFactory.createXMLStreamWriter(outputStream, "UTF8");
if (normalize) {
final XMLStreamWriter writer = new GraphMLWriterHelper.IndentingXMLStreamWriter(utf8Writer);
((GraphMLWriterHelper.IndentingXMLStreamWriter) writer).setIndentStep(" ");
return writer;
} else
return utf8Writer;
}
private void writeTypes(final Map<String, String> identifiedVertexKeyTypes,
final Map<String, String> identifiedEdgeKeyTypes,
final XMLStreamWriter writer) throws XMLStreamException {
// <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
final Collection<String> vertexKeySet = getVertexKeysAndNormalizeIfRequired(identifiedVertexKeyTypes);
for (String key : vertexKeySet) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, identifiedVertexKeyTypes.get(key));
writer.writeEndElement();
}
final Collection<String> edgeKeySet = getEdgeKeysAndNormalizeIfRequired(identifiedEdgeKeyTypes);
for (String key : edgeKeySet) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, identifiedEdgeKeyTypes.get(key));
writer.writeEndElement();
}
}
private void writeEdges(final XMLStreamWriter writer) throws XMLStreamException {
if (normalize) {
final List<Edge> edges = StreamFactory.stream(graph.query().edges()).collect(Collectors.toList());
Collections.sort(edges, new LexicographicalElementComparator());
for (Edge edge : edges) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
if (this.edgeLabelKey.isPresent()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey.get());
writer.writeCharacters(edge.getLabel());
writer.writeEndElement();
} else {
// this will not comply with the graphml schema but is here so that the label is not
// mixed up with properties.
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
}
final List<String> keys = new ArrayList<>();
keys.addAll(edge.getPropertyKeys());
Collections.sort(keys);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
} else {
for (Edge edge : graph.query().edges()) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
for (String key : edge.getPropertyKeys()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
private void writeVertices(final XMLStreamWriter writer) throws XMLStreamException {
final Iterable<Vertex> vertices = getVerticesAndNormalizeIfRequired();
for (Vertex vertex : vertices) {
writer.writeStartElement(GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ID, vertex.getId().toString());
final Collection<String> keys = getElementKeysAndNormalizeIfRequired(vertex);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
// technically there can't be a null here as Blueprints forbids that occurrence even if Graph
// implementations support it, but out to empty string just in case.
writer.writeCharacters(vertex.getProperty(key).orElse("").toString());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
private Collection<String> getElementKeysAndNormalizeIfRequired(Element element) {
Collection<String> keys;
if (normalize) {
keys = new ArrayList<>();
keys.addAll(element.getPropertyKeys());
Collections.sort((List<String>) keys);
} else {
keys = element.getPropertyKeys();
}
return keys;
}
private Iterable<Vertex> getVerticesAndNormalizeIfRequired() {
Iterable<Vertex> vertices;
if (normalize) {
vertices = new ArrayList<>();
for (Vertex v : graph.query().vertices()) {
((Collection<Vertex>) vertices).add(v);
}
Collections.sort((List<Vertex>) vertices, new LexicographicalElementComparator());
} else {
vertices = graph.query().vertices();
}
return vertices;
}
private Collection<String> getEdgeKeysAndNormalizeIfRequired(final Map<String, String> identifiedEdgeKeyTypes) {
final Collection<String> edgeKeySet;
if (normalize) {
edgeKeySet = new ArrayList<>();
edgeKeySet.addAll(identifiedEdgeKeyTypes.keySet());
Collections.sort((List<String>) edgeKeySet);
} else {
edgeKeySet = identifiedEdgeKeyTypes.keySet();
}
return edgeKeySet;
}
private Collection<String> getVertexKeysAndNormalizeIfRequired(final Map<String, String> identifiedVertexKeyTypes) {
final Collection<String> keyset;
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(identifiedVertexKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else {
keyset = identifiedVertexKeyTypes.keySet();
}
return keyset;
}
private void writeXmlNsAndSchema(final XMLStreamWriter writer) throws XMLStreamException {
writer.writeAttribute(GraphMLTokens.XMLNS, GraphMLTokens.GRAPHML_XMLNS);
//XML Schema instance namespace definition (xsi)
writer.writeAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG,
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
//XML Schema location
writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
GraphMLTokens.GRAPHML_XMLNS + " " + this.xmlSchemaLocation.orElse(GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION));
}
private Map<String,String> determineVertexTypes() {
final Map<String, String> vertexKeyTypes = new HashMap<>();
for (Vertex vertex : graph.query().vertices()) {
for (String key : vertex.getPropertyKeys()) {
if (!vertexKeyTypes.containsKey(key)) {
vertexKeyTypes.put(key, GraphMLWriter.getStringType(vertex.getProperty(key).getValue()));
}
}
}
return vertexKeyTypes;
}
private Map<String,String> determineEdgeTypes() {
final Map<String, String> edgeKeyTypes = new HashMap<>();
for (Edge edge : graph.query().edges()) {
for (String key : edge.getPropertyKeys()) {
if (!edgeKeyTypes.containsKey(key)) {
edgeKeyTypes.put(key, GraphMLWriter.getStringType(edge.getProperty(key).getValue()));
}
}
}
return edgeKeyTypes;
}
private static String getStringType(final Object object) {
if (object instanceof String) {
return GraphMLTokens.STRING;
} else if (object instanceof Integer) {
return GraphMLTokens.INT;
} else if (object instanceof Long) {
return GraphMLTokens.LONG;
} else if (object instanceof Float) {
return GraphMLTokens.FLOAT;
} else if (object instanceof Double) {
return GraphMLTokens.DOUBLE;
} else if (object instanceof Boolean) {
return GraphMLTokens.BOOLEAN;
} else {
return GraphMLTokens.STRING;
}
}
public static final class Builder {
private final Graph g;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private String xmlSchemaLocation = null;
private String edgeLabelKey = null;
public Builder(final Graph g) {
if (null == g)
throw new IllegalArgumentException("Graph argument cannot be null");
this.g = g;
}
/**
* Normalized output is deterministic with respect to the order of elements and properties in the resulting
* XML document, and is compatible with line diff-based tools such as Git. Note: normalized output is
* memory-intensive and is not appropriate for very large graphs.
*
* @param normalize whether to normalize the output.
*/
public Builder setNormalize(final boolean normalize) {
this.normalize = normalize;
return this;
}
/**
* Map of the data types of the vertex keys.
*/
public Builder setVertexKeyTypes(final Map<String, String> vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
return this;
}
/**
* Map of the data types of the edge keys.
*/
public Builder setEdgeKeyTypes(final Map<String, String> edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
return this;
}
public Builder setXmlSchemaLocation(final String xmlSchemaLocation) {
this.xmlSchemaLocation = xmlSchemaLocation;
return this;
}
/**
* Set the name of the edge label in the GraphML. When this value is not set the value of the Edge.getLabel()
* is written as a "label" attribute on the edge element. This does not validate against the GraphML schema.
* If this value is set then the the value of Edge.getLabel() is written as a data element on the edge and
* the appropriate key element is added to define it in the GraphML
*
* @param edgeLabelKey if the label of an edge will be handled by the data property.
*/
public Builder setEdgeLabelKey(final String edgeLabelKey) {
this.edgeLabelKey = edgeLabelKey;
return this;
}
public GraphMLWriter build() {
return new GraphMLWriter(g, normalize, vertexKeyTypes, edgeKeyTypes, xmlSchemaLocation, edgeLabelKey);
}
}
}
| blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java | package com.tinkerpop.blueprints.io.graphml;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.io.GraphWriter;
import com.tinkerpop.blueprints.io.LexicographicalElementComparator;
import com.tinkerpop.blueprints.util.StreamFactory;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* GraphMLWriter writes a Graph to a GraphML OutputStream.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Joshua Shinavier (http://fortytwo.net)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphMLWriter implements GraphWriter {
private final XMLOutputFactory inputFactory = XMLOutputFactory.newInstance();
private final Graph graph;
private boolean normalize = false;
private Optional<Map<String, String>> vertexKeyTypes;
private Optional<Map<String, String>> edgeKeyTypes;
private Optional<String> xmlSchemaLocation;
private Optional<String> edgeLabelKey;
/**
* @param graph the Graph to pull the data from
*/
private GraphMLWriter(final Graph graph, final boolean normalize, final Map<String, String> vertexKeyTypes,
final Map<String, String> edgeKeyTypes, final String xmlSchemaLocation,
final String edgeLabelKey) {
this.graph = graph;
this.normalize = normalize;
this.vertexKeyTypes = Optional.ofNullable(vertexKeyTypes);
this.edgeKeyTypes = Optional.ofNullable(edgeKeyTypes);
this.xmlSchemaLocation = Optional.ofNullable(xmlSchemaLocation);
this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
}
/**
* Write the data in a Graph to a GraphML OutputStream.
*
* @param outputStream the GraphML OutputStream to write the Graph data to
* @throws IOException thrown if there is an error generating the GraphML data
*/
@Override
public void outputGraph(final OutputStream outputStream) throws IOException {
final Map<String, String> identifiedVertexKeyTypes = this.vertexKeyTypes.orElseGet(this::determineVertexTypes);
final Map<String, String> identifiedEdgeKeyTypes = this.edgeKeyTypes.orElseGet(this::determineEdgeTypes);
// adding the edge label key will push the label into the data portion of the graphml otherwise it
// will live with the edge data itself (which won't validate against the graphml schema)
if (this.edgeLabelKey.isPresent() && null == identifiedEdgeKeyTypes.get(this.edgeLabelKey.get()))
identifiedEdgeKeyTypes.put(this.edgeLabelKey.get(), GraphMLTokens.STRING);
try {
final XMLStreamWriter writer;
writer = configureWriter(outputStream);
writer.writeStartDocument();
writer.writeStartElement(GraphMLTokens.GRAPHML);
writeXmlNsAndSchema(writer);
writeTypes(identifiedVertexKeyTypes, identifiedEdgeKeyTypes, writer);
writer.writeStartElement(GraphMLTokens.GRAPH);
writer.writeAttribute(GraphMLTokens.ID, GraphMLTokens.G);
writer.writeAttribute(GraphMLTokens.EDGEDEFAULT, GraphMLTokens.DIRECTED);
writeVertices(writer);
writeEdges(writer);
writer.writeEndElement(); // graph
writer.writeEndElement(); // graphml
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (XMLStreamException xse) {
throw new IOException(xse);
}
}
private XMLStreamWriter configureWriter(final OutputStream outputStream) throws XMLStreamException {
final XMLStreamWriter utf8Writer = inputFactory.createXMLStreamWriter(outputStream, "UTF8");
if (normalize) {
final XMLStreamWriter writer = new GraphMLWriterHelper.IndentingXMLStreamWriter(utf8Writer);
((GraphMLWriterHelper.IndentingXMLStreamWriter) writer).setIndentStep(" ");
return writer;
} else
return utf8Writer;
}
private void writeTypes(final Map<String, String> identifiedVertexKeyTypes,
final Map<String, String> identifiedEdgeKeyTypes,
final XMLStreamWriter writer) throws XMLStreamException {
// <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
final Collection<String> vertexKeySet = getVertexKeysAndNormalizeIfRequired(identifiedVertexKeyTypes);
for (String key : vertexKeySet) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, identifiedVertexKeyTypes.get(key));
writer.writeEndElement();
}
final Collection<String> edgeKeySet = getEdgeKeysAndNormalizeIfRequired(identifiedEdgeKeyTypes);
for (String key : edgeKeySet) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, identifiedEdgeKeyTypes.get(key));
writer.writeEndElement();
}
}
private void writeEdges(final XMLStreamWriter writer) throws XMLStreamException {
if (normalize) {
final List<Edge> edges = StreamFactory.stream(graph.query().edges()).collect(Collectors.toList());
Collections.sort(edges, new LexicographicalElementComparator());
for (Edge edge : edges) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
if (this.edgeLabelKey.isPresent()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey.get());
writer.writeCharacters(edge.getLabel());
writer.writeEndElement();
} else {
// this will not comply with the graphml schema but is here so that the label is not
// mixed up with properties.
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
}
final List<String> keys = new ArrayList<>();
keys.addAll(edge.getPropertyKeys());
Collections.sort(keys);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
} else {
for (Edge edge : graph.query().edges()) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
for (String key : edge.getPropertyKeys()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
private void writeVertices(final XMLStreamWriter writer) throws XMLStreamException {
final Iterable<Vertex> vertices = getVerticesAndNormalizeIfRequired();
for (Vertex vertex : vertices) {
writer.writeStartElement(GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ID, vertex.getId().toString());
final Collection<String> keys = getElementKeysAndNormalizeIfRequired(vertex);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
// technically there can't be a null here as Blueprints forbids that occurrence even if Graph
// implementations support it, but out to empty string just in case.
writer.writeCharacters(vertex.getProperty(key).orElse("").toString());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
private Collection<String> getElementKeysAndNormalizeIfRequired(Element element) {
Collection<String> keys;
if (normalize) {
keys = new ArrayList<>();
keys.addAll(element.getPropertyKeys());
Collections.sort((List<String>) keys);
} else {
keys = element.getPropertyKeys();
}
return keys;
}
private Iterable<Vertex> getVerticesAndNormalizeIfRequired() {
Iterable<Vertex> vertices;
if (normalize) {
vertices = new ArrayList<>();
for (Vertex v : graph.query().vertices()) {
((Collection<Vertex>) vertices).add(v);
}
Collections.sort((List<Vertex>) vertices, new LexicographicalElementComparator());
} else {
vertices = graph.query().vertices();
}
return vertices;
}
private Collection<String> getEdgeKeysAndNormalizeIfRequired(final Map<String, String> identifiedEdgeKeyTypes) {
final Collection<String> edgeKeySet;
if (normalize) {
edgeKeySet = new ArrayList<>();
edgeKeySet.addAll(identifiedEdgeKeyTypes.keySet());
Collections.sort((List<String>) edgeKeySet);
} else {
edgeKeySet = identifiedEdgeKeyTypes.keySet();
}
return edgeKeySet;
}
private Collection<String> getVertexKeysAndNormalizeIfRequired(final Map<String, String> identifiedVertexKeyTypes) {
final Collection<String> keyset;
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(identifiedVertexKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else {
keyset = identifiedVertexKeyTypes.keySet();
}
return keyset;
}
private void writeXmlNsAndSchema(final XMLStreamWriter writer) throws XMLStreamException {
writer.writeAttribute(GraphMLTokens.XMLNS, GraphMLTokens.GRAPHML_XMLNS);
//XML Schema instance namespace definition (xsi)
writer.writeAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG,
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
//XML Schema location
writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
GraphMLTokens.GRAPHML_XMLNS + " " + this.xmlSchemaLocation.orElse(GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION));
}
private Map<String,String> determineVertexTypes() {
final Map<String, String> vertexKeyTypes = new HashMap<>();
for (Vertex vertex : graph.query().vertices()) {
for (String key : vertex.getPropertyKeys()) {
if (!vertexKeyTypes.containsKey(key)) {
vertexKeyTypes.put(key, GraphMLWriter.getStringType(vertex.getProperty(key).getValue()));
}
}
}
return vertexKeyTypes;
}
private Map<String,String> determineEdgeTypes() {
final Map<String, String> edgeKeyTypes = new HashMap<>();
for (Edge edge : graph.query().edges()) {
for (String key : edge.getPropertyKeys()) {
if (!edgeKeyTypes.containsKey(key)) {
edgeKeyTypes.put(key, GraphMLWriter.getStringType(edge.getProperty(key).getValue()));
}
}
}
return edgeKeyTypes;
}
private static String getStringType(final Object object) {
if (object instanceof String) {
return GraphMLTokens.STRING;
} else if (object instanceof Integer) {
return GraphMLTokens.INT;
} else if (object instanceof Long) {
return GraphMLTokens.LONG;
} else if (object instanceof Float) {
return GraphMLTokens.FLOAT;
} else if (object instanceof Double) {
return GraphMLTokens.DOUBLE;
} else if (object instanceof Boolean) {
return GraphMLTokens.BOOLEAN;
} else {
return GraphMLTokens.STRING;
}
}
public static final class Builder {
private final Graph g;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private String xmlSchemaLocation = null;
private String edgeLabelKey = null;
public Builder(final Graph g) {
if (null == g)
throw new IllegalArgumentException("Graph argument cannot be null");
this.g = g;
}
/**
* Normalized output is deterministic with respect to the order of elements and properties in the resulting
* XML document, and is compatible with line diff-based tools such as Git. Note: normalized output is
* memory-intensive and is not appropriate for very large graphs.
*
* @param normalize whether to normalize the output.
*/
public Builder setNormalize(final boolean normalize) {
this.normalize = normalize;
return this;
}
/**
* Map of the data types of the vertex keys.
*/
public Builder setVertexKeyTypes(final Map<String, String> vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
return this;
}
/**
* Map of the data types of the edge keys.
*/
public Builder setEdgeKeyTypes(final Map<String, String> edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
return this;
}
public Builder setXmlSchemaLocation(final String xmlSchemaLocation) {
this.xmlSchemaLocation = xmlSchemaLocation;
return this;
}
/**
* Set the name of the edge label in the GraphML. When this value is not set the value of the Edge.getLabel()
* is written as a "label" attribute on the edge element. This does not validate against the GraphML schema.
* If this value is set then the the value of Edge.getLabel() is written as a data element on the edge and
* the appropriate key element is added to define it in the GraphML
*
* @param edgeLabelKey if the label of an edge will be handled by the data property.
*/
public Builder setEdgeLabelKey(final String edgeLabelKey) {
this.edgeLabelKey = edgeLabelKey;
return this;
}
public GraphMLWriter build() {
return new GraphMLWriter(g, normalize, vertexKeyTypes, edgeKeyTypes, xmlSchemaLocation, edgeLabelKey);
}
}
}
| Declare member variables as final in GraphMLWriter.
| blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java | Declare member variables as final in GraphMLWriter. | <ide><path>lueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java
<ide> private final XMLOutputFactory inputFactory = XMLOutputFactory.newInstance();
<ide> private final Graph graph;
<ide> private boolean normalize = false;
<del> private Optional<Map<String, String>> vertexKeyTypes;
<del> private Optional<Map<String, String>> edgeKeyTypes;
<del>
<del> private Optional<String> xmlSchemaLocation;
<del> private Optional<String> edgeLabelKey;
<add>
<add> private final Optional<Map<String, String>> vertexKeyTypes;
<add> private final Optional<Map<String, String>> edgeKeyTypes;
<add> private final Optional<String> xmlSchemaLocation;
<add> private final Optional<String> edgeLabelKey;
<ide>
<ide> /**
<ide> * @param graph the Graph to pull the data from |
|
Java | apache-2.0 | adef9d69ffb25ec7979c05c3d294545028d909e0 | 0 | Liziyao/elasticsearch,MetSystem/elasticsearch,Asimov4/elasticsearch,ThiagoGarciaAlves/elasticsearch,kimimj/elasticsearch,dylan8902/elasticsearch,pranavraman/elasticsearch,wittyameta/elasticsearch,acchen97/elasticsearch,obourgain/elasticsearch,Widen/elasticsearch,lks21c/elasticsearch,nrkkalyan/elasticsearch,Clairebi/ElasticsearchClone,weipinghe/elasticsearch,s1monw/elasticsearch,wittyameta/elasticsearch,jpountz/elasticsearch,adrianbk/elasticsearch,weipinghe/elasticsearch,sarwarbhuiyan/elasticsearch,achow/elasticsearch,achow/elasticsearch,petabytedata/elasticsearch,brandonkearby/elasticsearch,martinstuga/elasticsearch,spiegela/elasticsearch,Stacey-Gammon/elasticsearch,Flipkart/elasticsearch,kevinkluge/elasticsearch,heng4fun/elasticsearch,likaiwalkman/elasticsearch,kubum/elasticsearch,sc0ttkclark/elasticsearch,drewr/elasticsearch,linglaiyao1314/elasticsearch,kubum/elasticsearch,nomoa/elasticsearch,lydonchandra/elasticsearch,Chhunlong/elasticsearch,szroland/elasticsearch,springning/elasticsearch,golubev/elasticsearch,markwalkom/elasticsearch,18098924759/elasticsearch,yynil/elasticsearch,JervyShi/elasticsearch,janmejay/elasticsearch,mohit/elasticsearch,wangtuo/elasticsearch,fubuki/elasticsearch,vrkansagara/elasticsearch,mkis-/elasticsearch,sposam/elasticsearch,lzo/elasticsearch-1,areek/elasticsearch,JervyShi/elasticsearch,amit-shar/elasticsearch,mohit/elasticsearch,GlenRSmith/elasticsearch,abibell/elasticsearch,mm0/elasticsearch,raishiv/elasticsearch,sneivandt/elasticsearch,zhiqinghuang/elasticsearch,sjohnr/elasticsearch,gingerwizard/elasticsearch,ImpressTV/elasticsearch,episerver/elasticsearch,socialrank/elasticsearch,Chhunlong/elasticsearch,skearns64/elasticsearch,jchampion/elasticsearch,jw0201/elastic,AndreKR/elasticsearch,EasonYi/elasticsearch,karthikjaps/elasticsearch,sposam/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,peschlowp/elasticsearch,huypx1292/elasticsearch,winstonewert/elasticsearch,ydsakyclguozi/elasticsearch,schonfeld/elasticsearch,kunallimaye/elasticsearch,fooljohnny/elasticsearch,lks21c/elasticsearch,maddin2016/elasticsearch,vorce/es-metrics,nknize/elasticsearch,mortonsykes/elasticsearch,fubuki/elasticsearch,masaruh/elasticsearch,lydonchandra/elasticsearch,nrkkalyan/elasticsearch,rajanm/elasticsearch,C-Bish/elasticsearch,lightslife/elasticsearch,micpalmia/elasticsearch,martinstuga/elasticsearch,davidvgalbraith/elasticsearch,caengcjd/elasticsearch,areek/elasticsearch,sjohnr/elasticsearch,xpandan/elasticsearch,libosu/elasticsearch,hafkensite/elasticsearch,mohsinh/elasticsearch,vingupta3/elasticsearch,bestwpw/elasticsearch,a2lin/elasticsearch,GlenRSmith/elasticsearch,obourgain/elasticsearch,Kakakakakku/elasticsearch,pablocastro/elasticsearch,jpountz/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,geidies/elasticsearch,mikemccand/elasticsearch,jeteve/elasticsearch,nezirus/elasticsearch,thecocce/elasticsearch,iamjakob/elasticsearch,shreejay/elasticsearch,nezirus/elasticsearch,smflorentino/elasticsearch,chirilo/elasticsearch,jango2015/elasticsearch,xpandan/elasticsearch,liweinan0423/elasticsearch,AshishThakur/elasticsearch,Rygbee/elasticsearch,hirdesh2008/elasticsearch,gingerwizard/elasticsearch,Liziyao/elasticsearch,bawse/elasticsearch,synhershko/elasticsearch,snikch/elasticsearch,rmuir/elasticsearch,janmejay/elasticsearch,xuzha/elasticsearch,KimTaehee/elasticsearch,Siddartha07/elasticsearch,markharwood/elasticsearch,lzo/elasticsearch-1,YosuaMichael/elasticsearch,fekaputra/elasticsearch,xingguang2013/elasticsearch,likaiwalkman/elasticsearch,pablocastro/elasticsearch,jango2015/elasticsearch,socialrank/elasticsearch,iantruslove/elasticsearch,sarwarbhuiyan/elasticsearch,alexshadow007/elasticsearch,Kakakakakku/elasticsearch,StefanGor/elasticsearch,rlugojr/elasticsearch,umeshdangat/elasticsearch,bestwpw/elasticsearch,adrianbk/elasticsearch,sauravmondallive/elasticsearch,bawse/elasticsearch,anti-social/elasticsearch,abibell/elasticsearch,rmuir/elasticsearch,ouyangkongtong/elasticsearch,liweinan0423/elasticsearch,IanvsPoplicola/elasticsearch,spiegela/elasticsearch,uschindler/elasticsearch,mnylen/elasticsearch,khiraiwa/elasticsearch,markwalkom/elasticsearch,wittyameta/elasticsearch,Asimov4/elasticsearch,areek/elasticsearch,sc0ttkclark/elasticsearch,Collaborne/elasticsearch,linglaiyao1314/elasticsearch,kubum/elasticsearch,glefloch/elasticsearch,loconsolutions/elasticsearch,iamjakob/elasticsearch,smflorentino/elasticsearch,elancom/elasticsearch,sjohnr/elasticsearch,uboness/elasticsearch,drewr/elasticsearch,naveenhooda2000/elasticsearch,fekaputra/elasticsearch,alexksikes/elasticsearch,kenshin233/elasticsearch,rmuir/elasticsearch,LewayneNaidoo/elasticsearch,zkidkid/elasticsearch,franklanganke/elasticsearch,VukDukic/elasticsearch,easonC/elasticsearch,alexkuk/elasticsearch,markllama/elasticsearch,slavau/elasticsearch,karthikjaps/elasticsearch,yuy168/elasticsearch,Microsoft/elasticsearch,andrestc/elasticsearch,achow/elasticsearch,nazarewk/elasticsearch,jsgao0/elasticsearch,uboness/elasticsearch,VukDukic/elasticsearch,sposam/elasticsearch,nellicus/elasticsearch,JervyShi/elasticsearch,jango2015/elasticsearch,F0lha/elasticsearch,opendatasoft/elasticsearch,strapdata/elassandra5-rc,vroyer/elassandra,franklanganke/elasticsearch,vrkansagara/elasticsearch,nrkkalyan/elasticsearch,truemped/elasticsearch,ESamir/elasticsearch,Chhunlong/elasticsearch,petabytedata/elasticsearch,strapdata/elassandra-test,baishuo/elasticsearch_v2.1.0-baishuo,alexkuk/elasticsearch,ZTE-PaaS/elasticsearch,phani546/elasticsearch,koxa29/elasticsearch,szroland/elasticsearch,camilojd/elasticsearch,feiqitian/elasticsearch,jaynblue/elasticsearch,tebriel/elasticsearch,zhaocloud/elasticsearch,nellicus/elasticsearch,onegambler/elasticsearch,kalburgimanjunath/elasticsearch,sreeramjayan/elasticsearch,onegambler/elasticsearch,achow/elasticsearch,Fsero/elasticsearch,s1monw/elasticsearch,a2lin/elasticsearch,hydro2k/elasticsearch,nellicus/elasticsearch,libosu/elasticsearch,zeroctu/elasticsearch,ESamir/elasticsearch,boliza/elasticsearch,thecocce/elasticsearch,alexbrasetvik/elasticsearch,franklanganke/elasticsearch,codebunt/elasticsearch,Stacey-Gammon/elasticsearch,ricardocerq/elasticsearch,zhiqinghuang/elasticsearch,MichaelLiZhou/elasticsearch,Collaborne/elasticsearch,trangvh/elasticsearch,lmenezes/elasticsearch,boliza/elasticsearch,MichaelLiZhou/elasticsearch,yynil/elasticsearch,rmuir/elasticsearch,rento19962/elasticsearch,alexkuk/elasticsearch,alexkuk/elasticsearch,tahaemin/elasticsearch,franklanganke/elasticsearch,synhershko/elasticsearch,fred84/elasticsearch,fforbeck/elasticsearch,kalburgimanjunath/elasticsearch,dpursehouse/elasticsearch,kubum/elasticsearch,chirilo/elasticsearch,knight1128/elasticsearch,tsohil/elasticsearch,abibell/elasticsearch,clintongormley/elasticsearch,micpalmia/elasticsearch,hanswang/elasticsearch,martinstuga/elasticsearch,iacdingping/elasticsearch,myelin/elasticsearch,abhijitiitr/es,Brijeshrpatel9/elasticsearch,pablocastro/elasticsearch,huanzhong/elasticsearch,fooljohnny/elasticsearch,jbertouch/elasticsearch,codebunt/elasticsearch,huypx1292/elasticsearch,jimhooker2002/elasticsearch,F0lha/elasticsearch,LewayneNaidoo/elasticsearch,KimTaehee/elasticsearch,easonC/elasticsearch,StefanGor/elasticsearch,jango2015/elasticsearch,NBSW/elasticsearch,rento19962/elasticsearch,micpalmia/elasticsearch,xpandan/elasticsearch,peschlowp/elasticsearch,sscarduzio/elasticsearch,henakamaMSFT/elasticsearch,Fsero/elasticsearch,fernandozhu/elasticsearch,andrestc/elasticsearch,thecocce/elasticsearch,overcome/elasticsearch,Helen-Zhao/elasticsearch,mcku/elasticsearch,javachengwc/elasticsearch,nrkkalyan/elasticsearch,cnfire/elasticsearch-1,jango2015/elasticsearch,tkssharma/elasticsearch,wbowling/elasticsearch,AshishThakur/elasticsearch,dongaihua/highlight-elasticsearch,sscarduzio/elasticsearch,markharwood/elasticsearch,artnowo/elasticsearch,nellicus/elasticsearch,jw0201/elastic,HarishAtGitHub/elasticsearch,Microsoft/elasticsearch,skearns64/elasticsearch,lzo/elasticsearch-1,nazarewk/elasticsearch,mmaracic/elasticsearch,wittyameta/elasticsearch,IanvsPoplicola/elasticsearch,djschny/elasticsearch,szroland/elasticsearch,trangvh/elasticsearch,queirozfcom/elasticsearch,sc0ttkclark/elasticsearch,YosuaMichael/elasticsearch,mgalushka/elasticsearch,strapdata/elassandra,EasonYi/elasticsearch,NBSW/elasticsearch,mjhennig/elasticsearch,kingaj/elasticsearch,apepper/elasticsearch,masterweb121/elasticsearch,mbrukman/elasticsearch,smflorentino/elasticsearch,queirozfcom/elasticsearch,javachengwc/elasticsearch,andrestc/elasticsearch,jpountz/elasticsearch,dongjoon-hyun/elasticsearch,onegambler/elasticsearch,amit-shar/elasticsearch,gingerwizard/elasticsearch,jimhooker2002/elasticsearch,mikemccand/elasticsearch,adrianbk/elasticsearch,overcome/elasticsearch,alexbrasetvik/elasticsearch,hanst/elasticsearch,vietlq/elasticsearch,coding0011/elasticsearch,queirozfcom/elasticsearch,liweinan0423/elasticsearch,humandb/elasticsearch,girirajsharma/elasticsearch,yuy168/elasticsearch,kimchy/elasticsearch,codebunt/elasticsearch,marcuswr/elasticsearch-dateline,vrkansagara/elasticsearch,ricardocerq/elasticsearch,nazarewk/elasticsearch,JSCooke/elasticsearch,fooljohnny/elasticsearch,fooljohnny/elasticsearch,fernandozhu/elasticsearch,pozhidaevak/elasticsearch,areek/elasticsearch,JSCooke/elasticsearch,sneivandt/elasticsearch,mgalushka/elasticsearch,wbowling/elasticsearch,Widen/elasticsearch,karthikjaps/elasticsearch,aglne/elasticsearch,tebriel/elasticsearch,andrestc/elasticsearch,ckclark/elasticsearch,drewr/elasticsearch,acchen97/elasticsearch,StefanGor/elasticsearch,xuzha/elasticsearch,ImpressTV/elasticsearch,slavau/elasticsearch,luiseduardohdbackup/elasticsearch,dpursehouse/elasticsearch,acchen97/elasticsearch,lydonchandra/elasticsearch,PhaedrusTheGreek/elasticsearch,LeoYao/elasticsearch,JervyShi/elasticsearch,hanswang/elasticsearch,ThiagoGarciaAlves/elasticsearch,fred84/elasticsearch,ulkas/elasticsearch,sreeramjayan/elasticsearch,caengcjd/elasticsearch,kalburgimanjunath/elasticsearch,wangyuxue/elasticsearch,mcku/elasticsearch,linglaiyao1314/elasticsearch,petabytedata/elasticsearch,mapr/elasticsearch,luiseduardohdbackup/elasticsearch,lchennup/elasticsearch,JervyShi/elasticsearch,sarwarbhuiyan/elasticsearch,hirdesh2008/elasticsearch,maddin2016/elasticsearch,sdauletau/elasticsearch,robin13/elasticsearch,slavau/elasticsearch,Liziyao/elasticsearch,mute/elasticsearch,jango2015/elasticsearch,vroyer/elasticassandra,ajhalani/elasticsearch,episerver/elasticsearch,infusionsoft/elasticsearch,apepper/elasticsearch,tsohil/elasticsearch,petabytedata/elasticsearch,diendt/elasticsearch,vinsonlou/elasticsearch,elancom/elasticsearch,MjAbuz/elasticsearch,ImpressTV/elasticsearch,btiernay/elasticsearch,masaruh/elasticsearch,markllama/elasticsearch,hechunwen/elasticsearch,geidies/elasticsearch,yuy168/elasticsearch,vroyer/elasticassandra,ydsakyclguozi/elasticsearch,glefloch/elasticsearch,brwe/elasticsearch,sscarduzio/elasticsearch,mm0/elasticsearch,weipinghe/elasticsearch,mmaracic/elasticsearch,slavau/elasticsearch,fforbeck/elasticsearch,sscarduzio/elasticsearch,apepper/elasticsearch,ImpressTV/elasticsearch,dataduke/elasticsearch,zhiqinghuang/elasticsearch,aparo/elasticsearch,khiraiwa/elasticsearch,gingerwizard/elasticsearch,MetSystem/elasticsearch,sposam/elasticsearch,Rygbee/elasticsearch,kcompher/elasticsearch,clintongormley/elasticsearch,artnowo/elasticsearch,snikch/elasticsearch,phani546/elasticsearch,kalburgimanjunath/elasticsearch,i-am-Nathan/elasticsearch,pritishppai/elasticsearch,iamjakob/elasticsearch,abibell/elasticsearch,shreejay/elasticsearch,xingguang2013/elasticsearch,mnylen/elasticsearch,ulkas/elasticsearch,girirajsharma/elasticsearch,xuzha/elasticsearch,Clairebi/ElasticsearchClone,kevinkluge/elasticsearch,yynil/elasticsearch,hanswang/elasticsearch,liweinan0423/elasticsearch,knight1128/elasticsearch,lks21c/elasticsearch,MjAbuz/elasticsearch,yanjunh/elasticsearch,loconsolutions/elasticsearch,lightslife/elasticsearch,lchennup/elasticsearch,ZTE-PaaS/elasticsearch,shreejay/elasticsearch,maddin2016/elasticsearch,chirilo/elasticsearch,kaneshin/elasticsearch,Stacey-Gammon/elasticsearch,ajhalani/elasticsearch,ydsakyclguozi/elasticsearch,jbertouch/elasticsearch,fred84/elasticsearch,mjhennig/elasticsearch,fekaputra/elasticsearch,achow/elasticsearch,jeteve/elasticsearch,sreeramjayan/elasticsearch,zhaocloud/elasticsearch,cnfire/elasticsearch-1,markllama/elasticsearch,sc0ttkclark/elasticsearch,vroyer/elassandra,jw0201/elastic,kevinkluge/elasticsearch,tkssharma/elasticsearch,mgalushka/elasticsearch,ulkas/elasticsearch,lmtwga/elasticsearch,Siddartha07/elasticsearch,hechunwen/elasticsearch,mkis-/elasticsearch,overcome/elasticsearch,chrismwendt/elasticsearch,xingguang2013/elasticsearch,kingaj/elasticsearch,btiernay/elasticsearch,Shepard1212/elasticsearch,markharwood/elasticsearch,bestwpw/elasticsearch,xuzha/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,MjAbuz/elasticsearch,andrewvc/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,sneivandt/elasticsearch,jchampion/elasticsearch,Ansh90/elasticsearch,caengcjd/elasticsearch,mikemccand/elasticsearch,zkidkid/elasticsearch,wenpos/elasticsearch,MetSystem/elasticsearch,Charlesdong/elasticsearch,nomoa/elasticsearch,rento19962/elasticsearch,aparo/elasticsearch,polyfractal/elasticsearch,Brijeshrpatel9/elasticsearch,Uiho/elasticsearch,jpountz/elasticsearch,areek/elasticsearch,raishiv/elasticsearch,mgalushka/elasticsearch,zhaocloud/elasticsearch,EasonYi/elasticsearch,kcompher/elasticsearch,xuzha/elasticsearch,caengcjd/elasticsearch,huanzhong/elasticsearch,VukDukic/elasticsearch,pritishppai/elasticsearch,djschny/elasticsearch,jchampion/elasticsearch,ivansun1010/elasticsearch,Ansh90/elasticsearch,MaineC/elasticsearch,nilabhsagar/elasticsearch,njlawton/elasticsearch,avikurapati/elasticsearch,fforbeck/elasticsearch,kimimj/elasticsearch,henakamaMSFT/elasticsearch,jimczi/elasticsearch,Brijeshrpatel9/elasticsearch,Siddartha07/elasticsearch,mute/elasticsearch,polyfractal/elasticsearch,diendt/elasticsearch,Charlesdong/elasticsearch,mbrukman/elasticsearch,strapdata/elassandra-test,jaynblue/elasticsearch,kenshin233/elasticsearch,opendatasoft/elasticsearch,amaliujia/elasticsearch,Charlesdong/elasticsearch,dylan8902/elasticsearch,elancom/elasticsearch,xuzha/elasticsearch,vvcephei/elasticsearch,vietlq/elasticsearch,kcompher/elasticsearch,obourgain/elasticsearch,feiqitian/elasticsearch,gingerwizard/elasticsearch,Uiho/elasticsearch,gmarz/elasticsearch,ajhalani/elasticsearch,linglaiyao1314/elasticsearch,alexksikes/elasticsearch,AleksKochev/elasticsearch,18098924759/elasticsearch,Clairebi/ElasticsearchClone,luiseduardohdbackup/elasticsearch,petmit/elasticsearch,dataduke/elasticsearch,aglne/elasticsearch,anti-social/elasticsearch,sc0ttkclark/elasticsearch,Clairebi/ElasticsearchClone,uschindler/elasticsearch,avikurapati/elasticsearch,Fsero/elasticsearch,robin13/elasticsearch,mjason3/elasticsearch,ulkas/elasticsearch,Charlesdong/elasticsearch,AleksKochev/elasticsearch,lightslife/elasticsearch,abhijitiitr/es,MisterAndersen/elasticsearch,wenpos/elasticsearch,kkirsche/elasticsearch,ricardocerq/elasticsearch,wittyameta/elasticsearch,skearns64/elasticsearch,Chhunlong/elasticsearch,heng4fun/elasticsearch,schonfeld/elasticsearch,kkirsche/elasticsearch,lightslife/elasticsearch,Siddartha07/elasticsearch,ulkas/elasticsearch,wbowling/elasticsearch,palecur/elasticsearch,xingguang2013/elasticsearch,GlenRSmith/elasticsearch,bawse/elasticsearch,a2lin/elasticsearch,gfyoung/elasticsearch,yuy168/elasticsearch,ThiagoGarciaAlves/elasticsearch,kevinkluge/elasticsearch,Helen-Zhao/elasticsearch,camilojd/elasticsearch,rento19962/elasticsearch,Widen/elasticsearch,tcucchietti/elasticsearch,yynil/elasticsearch,achow/elasticsearch,gingerwizard/elasticsearch,jimhooker2002/elasticsearch,elasticdog/elasticsearch,jimhooker2002/elasticsearch,kimchy/elasticsearch,cwurm/elasticsearch,YosuaMichael/elasticsearch,wangtuo/elasticsearch,avikurapati/elasticsearch,jbertouch/elasticsearch,episerver/elasticsearch,ESamir/elasticsearch,knight1128/elasticsearch,cnfire/elasticsearch-1,sarwarbhuiyan/elasticsearch,kalburgimanjunath/elasticsearch,raishiv/elasticsearch,ouyangkongtong/elasticsearch,ThiagoGarciaAlves/elasticsearch,umeshdangat/elasticsearch,camilojd/elasticsearch,LeoYao/elasticsearch,btiernay/elasticsearch,lks21c/elasticsearch,infusionsoft/elasticsearch,onegambler/elasticsearch,Uiho/elasticsearch,lydonchandra/elasticsearch,alexksikes/elasticsearch,pranavraman/elasticsearch,scottsom/elasticsearch,spiegela/elasticsearch,andrejserafim/elasticsearch,salyh/elasticsearch,jimhooker2002/elasticsearch,markharwood/elasticsearch,wenpos/elasticsearch,tkssharma/elasticsearch,alexshadow007/elasticsearch,heng4fun/elasticsearch,queirozfcom/elasticsearch,maddin2016/elasticsearch,davidvgalbraith/elasticsearch,golubev/elasticsearch,springning/elasticsearch,18098924759/elasticsearch,coding0011/elasticsearch,ZTE-PaaS/elasticsearch,mm0/elasticsearch,brwe/elasticsearch,jbertouch/elasticsearch,ouyangkongtong/elasticsearch,humandb/elasticsearch,sauravmondallive/elasticsearch,feiqitian/elasticsearch,cwurm/elasticsearch,rhoml/elasticsearch,zkidkid/elasticsearch,F0lha/elasticsearch,JervyShi/elasticsearch,HonzaKral/elasticsearch,Charlesdong/elasticsearch,mjason3/elasticsearch,Helen-Zhao/elasticsearch,amit-shar/elasticsearch,elasticdog/elasticsearch,AshishThakur/elasticsearch,bestwpw/elasticsearch,lightslife/elasticsearch,TonyChai24/ESSource,Shekharrajak/elasticsearch,kaneshin/elasticsearch,Helen-Zhao/elasticsearch,ThalaivaStars/OrgRepo1,adrianbk/elasticsearch,infusionsoft/elasticsearch,vrkansagara/elasticsearch,Rygbee/elasticsearch,hafkensite/elasticsearch,SergVro/elasticsearch,mikemccand/elasticsearch,tahaemin/elasticsearch,polyfractal/elasticsearch,dataduke/elasticsearch,clintongormley/elasticsearch,Liziyao/elasticsearch,zeroctu/elasticsearch,mute/elasticsearch,Uiho/elasticsearch,combinatorist/elasticsearch,overcome/elasticsearch,apepper/elasticsearch,jango2015/elasticsearch,HonzaKral/elasticsearch,geidies/elasticsearch,ckclark/elasticsearch,koxa29/elasticsearch,snikch/elasticsearch,jimczi/elasticsearch,F0lha/elasticsearch,brwe/elasticsearch,khiraiwa/elasticsearch,pranavraman/elasticsearch,scottsom/elasticsearch,IanvsPoplicola/elasticsearch,brandonkearby/elasticsearch,rhoml/elasticsearch,socialrank/elasticsearch,18098924759/elasticsearch,girirajsharma/elasticsearch,fekaputra/elasticsearch,luiseduardohdbackup/elasticsearch,robin13/elasticsearch,mm0/elasticsearch,TonyChai24/ESSource,HonzaKral/elasticsearch,TonyChai24/ESSource,PhaedrusTheGreek/elasticsearch,huypx1292/elasticsearch,camilojd/elasticsearch,hafkensite/elasticsearch,spiegela/elasticsearch,humandb/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,sc0ttkclark/elasticsearch,jeteve/elasticsearch,Charlesdong/elasticsearch,rento19962/elasticsearch,anti-social/elasticsearch,nellicus/elasticsearch,kalburgimanjunath/elasticsearch,schonfeld/elasticsearch,vvcephei/elasticsearch,MichaelLiZhou/elasticsearch,sreeramjayan/elasticsearch,zhaocloud/elasticsearch,myelin/elasticsearch,iacdingping/elasticsearch,LeoYao/elasticsearch,huypx1292/elasticsearch,amaliujia/elasticsearch,lchennup/elasticsearch,mohsinh/elasticsearch,apepper/elasticsearch,petmit/elasticsearch,iantruslove/elasticsearch,amit-shar/elasticsearch,gmarz/elasticsearch,elancom/elasticsearch,liweinan0423/elasticsearch,diendt/elasticsearch,Uiho/elasticsearch,TonyChai24/ESSource,davidvgalbraith/elasticsearch,jimhooker2002/elasticsearch,sdauletau/elasticsearch,IanvsPoplicola/elasticsearch,combinatorist/elasticsearch,yanjunh/elasticsearch,artnowo/elasticsearch,aglne/elasticsearch,schonfeld/elasticsearch,adrianbk/elasticsearch,lightslife/elasticsearch,socialrank/elasticsearch,mute/elasticsearch,jpountz/elasticsearch,tkssharma/elasticsearch,ThiagoGarciaAlves/elasticsearch,btiernay/elasticsearch,strapdata/elassandra5-rc,strapdata/elassandra,kaneshin/elasticsearch,rajanm/elasticsearch,hanst/elasticsearch,YosuaMichael/elasticsearch,hydro2k/elasticsearch,huanzhong/elasticsearch,s1monw/elasticsearch,MisterAndersen/elasticsearch,awislowski/elasticsearch,kingaj/elasticsearch,ThiagoGarciaAlves/elasticsearch,humandb/elasticsearch,marcuswr/elasticsearch-dateline,robin13/elasticsearch,djschny/elasticsearch,girirajsharma/elasticsearch,MichaelLiZhou/elasticsearch,franklanganke/elasticsearch,beiske/elasticsearch,fforbeck/elasticsearch,tcucchietti/elasticsearch,mcku/elasticsearch,jsgao0/elasticsearch,libosu/elasticsearch,hydro2k/elasticsearch,LewayneNaidoo/elasticsearch,boliza/elasticsearch,xingguang2013/elasticsearch,PhaedrusTheGreek/elasticsearch,fooljohnny/elasticsearch,zhiqinghuang/elasticsearch,cwurm/elasticsearch,pranavraman/elasticsearch,HarishAtGitHub/elasticsearch,strapdata/elassandra-test,milodky/elasticsearch,ZTE-PaaS/elasticsearch,qwerty4030/elasticsearch,Collaborne/elasticsearch,mnylen/elasticsearch,MetSystem/elasticsearch,chrismwendt/elasticsearch,zhiqinghuang/elasticsearch,beiske/elasticsearch,skearns64/elasticsearch,milodky/elasticsearch,sreeramjayan/elasticsearch,easonC/elasticsearch,strapdata/elassandra,zkidkid/elasticsearch,alexksikes/elasticsearch,salyh/elasticsearch,nrkkalyan/elasticsearch,franklanganke/elasticsearch,Shekharrajak/elasticsearch,JSCooke/elasticsearch,lydonchandra/elasticsearch,episerver/elasticsearch,wangtuo/elasticsearch,andrejserafim/elasticsearch,rlugojr/elasticsearch,opendatasoft/elasticsearch,MaineC/elasticsearch,abhijitiitr/es,tahaemin/elasticsearch,fforbeck/elasticsearch,codebunt/elasticsearch,tcucchietti/elasticsearch,markwalkom/elasticsearch,vinsonlou/elasticsearch,mute/elasticsearch,jaynblue/elasticsearch,mgalushka/elasticsearch,Kakakakakku/elasticsearch,truemped/elasticsearch,rajanm/elasticsearch,Microsoft/elasticsearch,Microsoft/elasticsearch,koxa29/elasticsearch,peschlowp/elasticsearch,lchennup/elasticsearch,rajanm/elasticsearch,wangyuxue/elasticsearch,ThalaivaStars/OrgRepo1,hanst/elasticsearch,Liziyao/elasticsearch,adrianbk/elasticsearch,mcku/elasticsearch,kunallimaye/elasticsearch,dylan8902/elasticsearch,Shepard1212/elasticsearch,dongjoon-hyun/elasticsearch,jchampion/elasticsearch,MaineC/elasticsearch,mohit/elasticsearch,Collaborne/elasticsearch,uschindler/elasticsearch,mmaracic/elasticsearch,vietlq/elasticsearch,kkirsche/elasticsearch,Flipkart/elasticsearch,mkis-/elasticsearch,wayeast/elasticsearch,ckclark/elasticsearch,iantruslove/elasticsearch,i-am-Nathan/elasticsearch,AleksKochev/elasticsearch,anti-social/elasticsearch,Rygbee/elasticsearch,nknize/elasticsearch,mortonsykes/elasticsearch,feiqitian/elasticsearch,scorpionvicky/elasticsearch,Rygbee/elasticsearch,HarishAtGitHub/elasticsearch,yanjunh/elasticsearch,Asimov4/elasticsearch,yongminxia/elasticsearch,ckclark/elasticsearch,aparo/elasticsearch,mjhennig/elasticsearch,loconsolutions/elasticsearch,lzo/elasticsearch-1,hafkensite/elasticsearch,javachengwc/elasticsearch,acchen97/elasticsearch,phani546/elasticsearch,petabytedata/elasticsearch,andrejserafim/elasticsearch,i-am-Nathan/elasticsearch,pablocastro/elasticsearch,salyh/elasticsearch,Shekharrajak/elasticsearch,ydsakyclguozi/elasticsearch,SergVro/elasticsearch,LeoYao/elasticsearch,golubev/elasticsearch,ESamir/elasticsearch,yynil/elasticsearch,fernandozhu/elasticsearch,petmit/elasticsearch,lchennup/elasticsearch,naveenhooda2000/elasticsearch,vorce/es-metrics,Ansh90/elasticsearch,zeroctu/elasticsearch,Widen/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,rhoml/elasticsearch,himanshuag/elasticsearch,pranavraman/elasticsearch,abibell/elasticsearch,apepper/elasticsearch,glefloch/elasticsearch,KimTaehee/elasticsearch,himanshuag/elasticsearch,jw0201/elastic,andrewvc/elasticsearch,mohsinh/elasticsearch,iacdingping/elasticsearch,vvcephei/elasticsearch,jimhooker2002/elasticsearch,Clairebi/ElasticsearchClone,luiseduardohdbackup/elasticsearch,mbrukman/elasticsearch,Rygbee/elasticsearch,awislowski/elasticsearch,ThalaivaStars/OrgRepo1,AshishThakur/elasticsearch,hechunwen/elasticsearch,djschny/elasticsearch,winstonewert/elasticsearch,ouyangkongtong/elasticsearch,Uiho/elasticsearch,trangvh/elasticsearch,mapr/elasticsearch,lzo/elasticsearch-1,ouyangkongtong/elasticsearch,maddin2016/elasticsearch,snikch/elasticsearch,adrianbk/elasticsearch,queirozfcom/elasticsearch,iacdingping/elasticsearch,glefloch/elasticsearch,vingupta3/elasticsearch,ouyangkongtong/elasticsearch,xpandan/elasticsearch,amaliujia/elasticsearch,polyfractal/elasticsearch,nomoa/elasticsearch,camilojd/elasticsearch,caengcjd/elasticsearch,C-Bish/elasticsearch,Shekharrajak/elasticsearch,wbowling/elasticsearch,phani546/elasticsearch,zhaocloud/elasticsearch,javachengwc/elasticsearch,ThalaivaStars/OrgRepo1,amaliujia/elasticsearch,awislowski/elasticsearch,nezirus/elasticsearch,kcompher/elasticsearch,zhaocloud/elasticsearch,himanshuag/elasticsearch,HarishAtGitHub/elasticsearch,rajanm/elasticsearch,gfyoung/elasticsearch,trangvh/elasticsearch,kingaj/elasticsearch,Siddartha07/elasticsearch,kaneshin/elasticsearch,onegambler/elasticsearch,wuranbo/elasticsearch,AshishThakur/elasticsearch,AleksKochev/elasticsearch,dantuffery/elasticsearch,avikurapati/elasticsearch,18098924759/elasticsearch,kenshin233/elasticsearch,rlugojr/elasticsearch,robin13/elasticsearch,GlenRSmith/elasticsearch,franklanganke/elasticsearch,mkis-/elasticsearch,dpursehouse/elasticsearch,PhaedrusTheGreek/elasticsearch,C-Bish/elasticsearch,F0lha/elasticsearch,mute/elasticsearch,wuranbo/elasticsearch,andrejserafim/elasticsearch,zhiqinghuang/elasticsearch,jw0201/elastic,sarwarbhuiyan/elasticsearch,easonC/elasticsearch,likaiwalkman/elasticsearch,vingupta3/elasticsearch,MetSystem/elasticsearch,bawse/elasticsearch,MisterAndersen/elasticsearch,mapr/elasticsearch,knight1128/elasticsearch,tkssharma/elasticsearch,lzo/elasticsearch-1,markharwood/elasticsearch,Fsero/elasticsearch,strapdata/elassandra-test,18098924759/elasticsearch,Stacey-Gammon/elasticsearch,mohit/elasticsearch,myelin/elasticsearch,camilojd/elasticsearch,rhoml/elasticsearch,markllama/elasticsearch,jprante/elasticsearch,palecur/elasticsearch,alexkuk/elasticsearch,tkssharma/elasticsearch,nilabhsagar/elasticsearch,weipinghe/elasticsearch,yuy168/elasticsearch,ImpressTV/elasticsearch,wuranbo/elasticsearch,wbowling/elasticsearch,strapdata/elassandra5-rc,dylan8902/elasticsearch,Shekharrajak/elasticsearch,TonyChai24/ESSource,rhoml/elasticsearch,brandonkearby/elasticsearch,mm0/elasticsearch,strapdata/elassandra-test,nellicus/elasticsearch,xingguang2013/elasticsearch,JackyMai/elasticsearch,fred84/elasticsearch,sposam/elasticsearch,khiraiwa/elasticsearch,anti-social/elasticsearch,wenpos/elasticsearch,Brijeshrpatel9/elasticsearch,nilabhsagar/elasticsearch,MisterAndersen/elasticsearch,Flipkart/elasticsearch,ImpressTV/elasticsearch,lydonchandra/elasticsearch,hechunwen/elasticsearch,gfyoung/elasticsearch,mnylen/elasticsearch,luiseduardohdbackup/elasticsearch,nazarewk/elasticsearch,pozhidaevak/elasticsearch,codebunt/elasticsearch,kaneshin/elasticsearch,C-Bish/elasticsearch,tcucchietti/elasticsearch,kenshin233/elasticsearch,diendt/elasticsearch,dantuffery/elasticsearch,boliza/elasticsearch,NBSW/elasticsearch,nrkkalyan/elasticsearch,Helen-Zhao/elasticsearch,ThalaivaStars/OrgRepo1,hafkensite/elasticsearch,lzo/elasticsearch-1,szroland/elasticsearch,ivansun1010/elasticsearch,queirozfcom/elasticsearch,hirdesh2008/elasticsearch,winstonewert/elasticsearch,mrorii/elasticsearch,MjAbuz/elasticsearch,vietlq/elasticsearch,JackyMai/elasticsearch,i-am-Nathan/elasticsearch,jpountz/elasticsearch,masterweb121/elasticsearch,likaiwalkman/elasticsearch,naveenhooda2000/elasticsearch,kubum/elasticsearch,loconsolutions/elasticsearch,aparo/elasticsearch,abhijitiitr/es,dylan8902/elasticsearch,uboness/elasticsearch,mrorii/elasticsearch,drewr/elasticsearch,scorpionvicky/elasticsearch,LewayneNaidoo/elasticsearch,pablocastro/elasticsearch,jimczi/elasticsearch,wayeast/elasticsearch,jchampion/elasticsearch,libosu/elasticsearch,vingupta3/elasticsearch,weipinghe/elasticsearch,Brijeshrpatel9/elasticsearch,boliza/elasticsearch,Stacey-Gammon/elasticsearch,NBSW/elasticsearch,abhijitiitr/es,areek/elasticsearch,Chhunlong/elasticsearch,gmarz/elasticsearch,wimvds/elasticsearch,szroland/elasticsearch,geidies/elasticsearch,gmarz/elasticsearch,marcuswr/elasticsearch-dateline,Liziyao/elasticsearch,ydsakyclguozi/elasticsearch,wuranbo/elasticsearch,diendt/elasticsearch,petmit/elasticsearch,tebriel/elasticsearch,wenpos/elasticsearch,scorpionvicky/elasticsearch,naveenhooda2000/elasticsearch,vietlq/elasticsearch,hirdesh2008/elasticsearch,mnylen/elasticsearch,tahaemin/elasticsearch,NBSW/elasticsearch,VukDukic/elasticsearch,dongjoon-hyun/elasticsearch,fubuki/elasticsearch,kevinkluge/elasticsearch,sarwarbhuiyan/elasticsearch,strapdata/elassandra,amaliujia/elasticsearch,dantuffery/elasticsearch,artnowo/elasticsearch,hafkensite/elasticsearch,pablocastro/elasticsearch,sauravmondallive/elasticsearch,pozhidaevak/elasticsearch,mgalushka/elasticsearch,himanshuag/elasticsearch,pritishppai/elasticsearch,caengcjd/elasticsearch,dataduke/elasticsearch,hanswang/elasticsearch,abibell/elasticsearch,queirozfcom/elasticsearch,mortonsykes/elasticsearch,dpursehouse/elasticsearch,KimTaehee/elasticsearch,Ansh90/elasticsearch,wimvds/elasticsearch,Flipkart/elasticsearch,alexshadow007/elasticsearch,Fsero/elasticsearch,andrestc/elasticsearch,mnylen/elasticsearch,feiqitian/elasticsearch,hydro2k/elasticsearch,geidies/elasticsearch,KimTaehee/elasticsearch,petabytedata/elasticsearch,milodky/elasticsearch,clintongormley/elasticsearch,marcuswr/elasticsearch-dateline,Chhunlong/elasticsearch,infusionsoft/elasticsearch,vvcephei/elasticsearch,aparo/elasticsearch,Shekharrajak/elasticsearch,karthikjaps/elasticsearch,sdauletau/elasticsearch,martinstuga/elasticsearch,knight1128/elasticsearch,mjason3/elasticsearch,iantruslove/elasticsearch,kalimatas/elasticsearch,wbowling/elasticsearch,ivansun1010/elasticsearch,mkis-/elasticsearch,huanzhong/elasticsearch,uschindler/elasticsearch,jeteve/elasticsearch,pritishppai/elasticsearch,truemped/elasticsearch,MichaelLiZhou/elasticsearch,lmtwga/elasticsearch,micpalmia/elasticsearch,umeshdangat/elasticsearch,jprante/elasticsearch,heng4fun/elasticsearch,skearns64/elasticsearch,dongaihua/highlight-elasticsearch,hafkensite/elasticsearch,schonfeld/elasticsearch,karthikjaps/elasticsearch,smflorentino/elasticsearch,vroyer/elasticassandra,s1monw/elasticsearch,petabytedata/elasticsearch,kalimatas/elasticsearch,kubum/elasticsearch,iantruslove/elasticsearch,pritishppai/elasticsearch,linglaiyao1314/elasticsearch,strapdata/elassandra5-rc,acchen97/elasticsearch,aglne/elasticsearch,overcome/elasticsearch,Siddartha07/elasticsearch,vorce/es-metrics,ThalaivaStars/OrgRepo1,dongjoon-hyun/elasticsearch,golubev/elasticsearch,peschlowp/elasticsearch,kaneshin/elasticsearch,raishiv/elasticsearch,qwerty4030/elasticsearch,elancom/elasticsearch,libosu/elasticsearch,cwurm/elasticsearch,lmenezes/elasticsearch,jaynblue/elasticsearch,sscarduzio/elasticsearch,myelin/elasticsearch,wayeast/elasticsearch,lmtwga/elasticsearch,HarishAtGitHub/elasticsearch,dpursehouse/elasticsearch,shreejay/elasticsearch,coding0011/elasticsearch,lchennup/elasticsearch,tsohil/elasticsearch,sdauletau/elasticsearch,beiske/elasticsearch,sauravmondallive/elasticsearch,cnfire/elasticsearch-1,mjhennig/elasticsearch,mcku/elasticsearch,SergVro/elasticsearch,VukDukic/elasticsearch,AndreKR/elasticsearch,geidies/elasticsearch,elasticdog/elasticsearch,mm0/elasticsearch,tkssharma/elasticsearch,mortonsykes/elasticsearch,Shepard1212/elasticsearch,milodky/elasticsearch,dantuffery/elasticsearch,yuy168/elasticsearch,nknize/elasticsearch,janmejay/elasticsearch,Rygbee/elasticsearch,LeoYao/elasticsearch,Widen/elasticsearch,iacdingping/elasticsearch,beiske/elasticsearch,rhoml/elasticsearch,iamjakob/elasticsearch,codebunt/elasticsearch,lydonchandra/elasticsearch,truemped/elasticsearch,markllama/elasticsearch,lmtwga/elasticsearch,lmtwga/elasticsearch,jaynblue/elasticsearch,pablocastro/elasticsearch,Shekharrajak/elasticsearch,tebriel/elasticsearch,jeteve/elasticsearch,henakamaMSFT/elasticsearch,clintongormley/elasticsearch,yuy168/elasticsearch,hirdesh2008/elasticsearch,GlenRSmith/elasticsearch,amit-shar/elasticsearch,kimimj/elasticsearch,kkirsche/elasticsearch,ricardocerq/elasticsearch,jeteve/elasticsearch,salyh/elasticsearch,ulkas/elasticsearch,LeoYao/elasticsearch,ajhalani/elasticsearch,alexkuk/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,pozhidaevak/elasticsearch,kingaj/elasticsearch,fernandozhu/elasticsearch,C-Bish/elasticsearch,jimczi/elasticsearch,TonyChai24/ESSource,markwalkom/elasticsearch,mohsinh/elasticsearch,tsohil/elasticsearch,elancom/elasticsearch,mrorii/elasticsearch,MetSystem/elasticsearch,zeroctu/elasticsearch,hydro2k/elasticsearch,rmuir/elasticsearch,vrkansagara/elasticsearch,KimTaehee/elasticsearch,sposam/elasticsearch,JSCooke/elasticsearch,KimTaehee/elasticsearch,rento19962/elasticsearch,ajhalani/elasticsearch,wittyameta/elasticsearch,elasticdog/elasticsearch,umeshdangat/elasticsearch,masterweb121/elasticsearch,davidvgalbraith/elasticsearch,rajanm/elasticsearch,karthikjaps/elasticsearch,andrejserafim/elasticsearch,wbowling/elasticsearch,koxa29/elasticsearch,nilabhsagar/elasticsearch,jimczi/elasticsearch,sdauletau/elasticsearch,Fsero/elasticsearch,zhiqinghuang/elasticsearch,knight1128/elasticsearch,humandb/elasticsearch,schonfeld/elasticsearch,Uiho/elasticsearch,AndreKR/elasticsearch,masterweb121/elasticsearch,szroland/elasticsearch,martinstuga/elasticsearch,iamjakob/elasticsearch,alexbrasetvik/elasticsearch,HonzaKral/elasticsearch,abibell/elasticsearch,MichaelLiZhou/elasticsearch,Asimov4/elasticsearch,zeroctu/elasticsearch,hydro2k/elasticsearch,alexshadow007/elasticsearch,avikurapati/elasticsearch,StefanGor/elasticsearch,fernandozhu/elasticsearch,mjhennig/elasticsearch,bawse/elasticsearch,andrejserafim/elasticsearch,pozhidaevak/elasticsearch,mmaracic/elasticsearch,infusionsoft/elasticsearch,phani546/elasticsearch,yongminxia/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,vrkansagara/elasticsearch,masaruh/elasticsearch,spiegela/elasticsearch,mikemccand/elasticsearch,kunallimaye/elasticsearch,kimchy/elasticsearch,EasonYi/elasticsearch,masaruh/elasticsearch,Kakakakakku/elasticsearch,wayeast/elasticsearch,onegambler/elasticsearch,gmarz/elasticsearch,Asimov4/elasticsearch,smflorentino/elasticsearch,Shepard1212/elasticsearch,sposam/elasticsearch,ivansun1010/elasticsearch,andrestc/elasticsearch,pritishppai/elasticsearch,heng4fun/elasticsearch,golubev/elasticsearch,huanzhong/elasticsearch,beiske/elasticsearch,YosuaMichael/elasticsearch,yongminxia/elasticsearch,masaruh/elasticsearch,zkidkid/elasticsearch,polyfractal/elasticsearch,chirilo/elasticsearch,loconsolutions/elasticsearch,kunallimaye/elasticsearch,LeoYao/elasticsearch,xingguang2013/elasticsearch,feiqitian/elasticsearch,vietlq/elasticsearch,wayeast/elasticsearch,opendatasoft/elasticsearch,ckclark/elasticsearch,easonC/elasticsearch,LewayneNaidoo/elasticsearch,StefanGor/elasticsearch,khiraiwa/elasticsearch,brwe/elasticsearch,khiraiwa/elasticsearch,AndreKR/elasticsearch,acchen97/elasticsearch,EasonYi/elasticsearch,vorce/es-metrics,petmit/elasticsearch,nknize/elasticsearch,MichaelLiZhou/elasticsearch,phani546/elasticsearch,combinatorist/elasticsearch,nomoa/elasticsearch,karthikjaps/elasticsearch,marcuswr/elasticsearch-dateline,coding0011/elasticsearch,clintongormley/elasticsearch,mmaracic/elasticsearch,Collaborne/elasticsearch,btiernay/elasticsearch,jw0201/elastic,ckclark/elasticsearch,scorpionvicky/elasticsearch,hanst/elasticsearch,wayeast/elasticsearch,davidvgalbraith/elasticsearch,salyh/elasticsearch,himanshuag/elasticsearch,elasticdog/elasticsearch,yongminxia/elasticsearch,huypx1292/elasticsearch,anti-social/elasticsearch,himanshuag/elasticsearch,springning/elasticsearch,janmejay/elasticsearch,Brijeshrpatel9/elasticsearch,aglne/elasticsearch,snikch/elasticsearch,wuranbo/elasticsearch,kkirsche/elasticsearch,rento19962/elasticsearch,thecocce/elasticsearch,Collaborne/elasticsearch,palecur/elasticsearch,tahaemin/elasticsearch,chirilo/elasticsearch,girirajsharma/elasticsearch,pritishppai/elasticsearch,chrismwendt/elasticsearch,weipinghe/elasticsearch,scottsom/elasticsearch,hirdesh2008/elasticsearch,mrorii/elasticsearch,iamjakob/elasticsearch,snikch/elasticsearch,jprante/elasticsearch,vingupta3/elasticsearch,slavau/elasticsearch,hanst/elasticsearch,njlawton/elasticsearch,kunallimaye/elasticsearch,kenshin233/elasticsearch,micpalmia/elasticsearch,ivansun1010/elasticsearch,a2lin/elasticsearch,djschny/elasticsearch,iantruslove/elasticsearch,likaiwalkman/elasticsearch,amit-shar/elasticsearch,likaiwalkman/elasticsearch,wimvds/elasticsearch,sauravmondallive/elasticsearch,polyfractal/elasticsearch,drewr/elasticsearch,nezirus/elasticsearch,apepper/elasticsearch,awislowski/elasticsearch,JackyMai/elasticsearch,myelin/elasticsearch,sauravmondallive/elasticsearch,raishiv/elasticsearch,iacdingping/elasticsearch,iantruslove/elasticsearch,markwalkom/elasticsearch,mkis-/elasticsearch,qwerty4030/elasticsearch,MaineC/elasticsearch,mute/elasticsearch,markllama/elasticsearch,rlugojr/elasticsearch,linglaiyao1314/elasticsearch,Clairebi/ElasticsearchClone,yanjunh/elasticsearch,mbrukman/elasticsearch,rmuir/elasticsearch,knight1128/elasticsearch,gingerwizard/elasticsearch,masterweb121/elasticsearch,alexbrasetvik/elasticsearch,libosu/elasticsearch,a2lin/elasticsearch,sc0ttkclark/elasticsearch,JackyMai/elasticsearch,tahaemin/elasticsearch,qwerty4030/elasticsearch,springning/elasticsearch,yanjunh/elasticsearch,amaliujia/elasticsearch,hydro2k/elasticsearch,yongminxia/elasticsearch,chrismwendt/elasticsearch,socialrank/elasticsearch,hechunwen/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,MetSystem/elasticsearch,fubuki/elasticsearch,humandb/elasticsearch,fubuki/elasticsearch,zeroctu/elasticsearch,wittyameta/elasticsearch,cnfire/elasticsearch-1,wangtuo/elasticsearch,mohsinh/elasticsearch,combinatorist/elasticsearch,jaynblue/elasticsearch,alexbrasetvik/elasticsearch,milodky/elasticsearch,alexksikes/elasticsearch,EasonYi/elasticsearch,scottsom/elasticsearch,dataduke/elasticsearch,nellicus/elasticsearch,scottsom/elasticsearch,Flipkart/elasticsearch,Shepard1212/elasticsearch,wimvds/elasticsearch,njlawton/elasticsearch,EasonYi/elasticsearch,caengcjd/elasticsearch,tebriel/elasticsearch,artnowo/elasticsearch,truemped/elasticsearch,brwe/elasticsearch,kimimj/elasticsearch,kalimatas/elasticsearch,andrestc/elasticsearch,hanswang/elasticsearch,easonC/elasticsearch,chrismwendt/elasticsearch,Chhunlong/elasticsearch,janmejay/elasticsearch,kingaj/elasticsearch,Kakakakakku/elasticsearch,mcku/elasticsearch,tcucchietti/elasticsearch,ImpressTV/elasticsearch,dataduke/elasticsearch,SergVro/elasticsearch,iamjakob/elasticsearch,mbrukman/elasticsearch,mmaracic/elasticsearch,luiseduardohdbackup/elasticsearch,naveenhooda2000/elasticsearch,jbertouch/elasticsearch,infusionsoft/elasticsearch,mgalushka/elasticsearch,masterweb121/elasticsearch,Microsoft/elasticsearch,lmtwga/elasticsearch,kevinkluge/elasticsearch,vingupta3/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,skearns64/elasticsearch,jprante/elasticsearch,mbrukman/elasticsearch,njlawton/elasticsearch,kingaj/elasticsearch,aglne/elasticsearch,lchennup/elasticsearch,trangvh/elasticsearch,jsgao0/elasticsearch,huypx1292/elasticsearch,MjAbuz/elasticsearch,drewr/elasticsearch,markllama/elasticsearch,HarishAtGitHub/elasticsearch,xpandan/elasticsearch,PhaedrusTheGreek/elasticsearch,fred84/elasticsearch,s1monw/elasticsearch,ouyangkongtong/elasticsearch,mapr/elasticsearch,pranavraman/elasticsearch,linglaiyao1314/elasticsearch,mjason3/elasticsearch,palecur/elasticsearch,awislowski/elasticsearch,MaineC/elasticsearch,ESamir/elasticsearch,diendt/elasticsearch,elancom/elasticsearch,andrewvc/elasticsearch,mm0/elasticsearch,gfyoung/elasticsearch,obourgain/elasticsearch,springning/elasticsearch,PhaedrusTheGreek/elasticsearch,tebriel/elasticsearch,AndreKR/elasticsearch,girirajsharma/elasticsearch,zeroctu/elasticsearch,peschlowp/elasticsearch,JackyMai/elasticsearch,vorce/es-metrics,vvcephei/elasticsearch,Ansh90/elasticsearch,hanst/elasticsearch,davidvgalbraith/elasticsearch,pranavraman/elasticsearch,markwalkom/elasticsearch,acchen97/elasticsearch,mnylen/elasticsearch,lks21c/elasticsearch,djschny/elasticsearch,episerver/elasticsearch,cnfire/elasticsearch-1,NBSW/elasticsearch,ckclark/elasticsearch,winstonewert/elasticsearch,AleksKochev/elasticsearch,bestwpw/elasticsearch,nilabhsagar/elasticsearch,winstonewert/elasticsearch,truemped/elasticsearch,dataduke/elasticsearch,chirilo/elasticsearch,slavau/elasticsearch,dylan8902/elasticsearch,mohit/elasticsearch,ZTE-PaaS/elasticsearch,obourgain/elasticsearch,brandonkearby/elasticsearch,koxa29/elasticsearch,Brijeshrpatel9/elasticsearch,kunallimaye/elasticsearch,nazarewk/elasticsearch,fooljohnny/elasticsearch,golubev/elasticsearch,mortonsykes/elasticsearch,kkirsche/elasticsearch,jprante/elasticsearch,weipinghe/elasticsearch,aparo/elasticsearch,kenshin233/elasticsearch,drewr/elasticsearch,yynil/elasticsearch,shreejay/elasticsearch,hanswang/elasticsearch,vingupta3/elasticsearch,kubum/elasticsearch,schonfeld/elasticsearch,sdauletau/elasticsearch,yongminxia/elasticsearch,springning/elasticsearch,opendatasoft/elasticsearch,mjhennig/elasticsearch,springning/elasticsearch,mrorii/elasticsearch,Ansh90/elasticsearch,i-am-Nathan/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,kalimatas/elasticsearch,cwurm/elasticsearch,nomoa/elasticsearch,huanzhong/elasticsearch,himanshuag/elasticsearch,wayeast/elasticsearch,strapdata/elassandra5-rc,Flipkart/elasticsearch,beiske/elasticsearch,tsohil/elasticsearch,opendatasoft/elasticsearch,onegambler/elasticsearch,dantuffery/elasticsearch,Widen/elasticsearch,rlugojr/elasticsearch,vietlq/elasticsearch,Liziyao/elasticsearch,javachengwc/elasticsearch,kalburgimanjunath/elasticsearch,kcompher/elasticsearch,jsgao0/elasticsearch,SergVro/elasticsearch,kunallimaye/elasticsearch,wimvds/elasticsearch,brandonkearby/elasticsearch,ESamir/elasticsearch,sjohnr/elasticsearch,kcompher/elasticsearch,MjAbuz/elasticsearch,nrkkalyan/elasticsearch,JSCooke/elasticsearch,sdauletau/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,alexshadow007/elasticsearch,mrorii/elasticsearch,nezirus/elasticsearch,Kakakakakku/elasticsearch,tsohil/elasticsearch,F0lha/elasticsearch,sneivandt/elasticsearch,hirdesh2008/elasticsearch,javachengwc/elasticsearch,palecur/elasticsearch,mbrukman/elasticsearch,martinstuga/elasticsearch,nknize/elasticsearch,wimvds/elasticsearch,qwerty4030/elasticsearch,sjohnr/elasticsearch,tsohil/elasticsearch,hechunwen/elasticsearch,ydsakyclguozi/elasticsearch,milodky/elasticsearch,coding0011/elasticsearch,AshishThakur/elasticsearch,Asimov4/elasticsearch,mjhennig/elasticsearch,achow/elasticsearch,sjohnr/elasticsearch,loconsolutions/elasticsearch,dylan8902/elasticsearch,thecocce/elasticsearch,NBSW/elasticsearch,jsgao0/elasticsearch,MisterAndersen/elasticsearch,djschny/elasticsearch,kevinkluge/elasticsearch,xpandan/elasticsearch,combinatorist/elasticsearch,areek/elasticsearch,umeshdangat/elasticsearch,infusionsoft/elasticsearch,Charlesdong/elasticsearch,koxa29/elasticsearch,ricardocerq/elasticsearch,vroyer/elassandra,jsgao0/elasticsearch,fubuki/elasticsearch,strapdata/elassandra,mapr/elasticsearch,lmtwga/elasticsearch,sneivandt/elasticsearch,markharwood/elasticsearch,jchampion/elasticsearch,kalimatas/elasticsearch,dongjoon-hyun/elasticsearch,uschindler/elasticsearch,PhaedrusTheGreek/elasticsearch,njlawton/elasticsearch,YosuaMichael/elasticsearch,cnfire/elasticsearch-1,MjAbuz/elasticsearch,wangtuo/elasticsearch,slavau/elasticsearch,socialrank/elasticsearch,AndreKR/elasticsearch,kimimj/elasticsearch,Siddartha07/elasticsearch,uboness/elasticsearch,IanvsPoplicola/elasticsearch,strapdata/elassandra-test,iacdingping/elasticsearch,kcompher/elasticsearch,smflorentino/elasticsearch,likaiwalkman/elasticsearch,masterweb121/elasticsearch,henakamaMSFT/elasticsearch,thecocce/elasticsearch,ivansun1010/elasticsearch,Widen/elasticsearch,ulkas/elasticsearch,18098924759/elasticsearch,sarwarbhuiyan/elasticsearch,alexbrasetvik/elasticsearch,beiske/elasticsearch,wimvds/elasticsearch,fekaputra/elasticsearch,bestwpw/elasticsearch,sreeramjayan/elasticsearch,Collaborne/elasticsearch,tahaemin/elasticsearch,truemped/elasticsearch,strapdata/elassandra-test,amit-shar/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,humandb/elasticsearch,hanswang/elasticsearch,wangyuxue/elasticsearch,henakamaMSFT/elasticsearch,socialrank/elasticsearch,huanzhong/elasticsearch,TonyChai24/ESSource,overcome/elasticsearch,janmejay/elasticsearch,btiernay/elasticsearch,Ansh90/elasticsearch,kimimj/elasticsearch,yongminxia/elasticsearch,gfyoung/elasticsearch,YosuaMichael/elasticsearch,fekaputra/elasticsearch,HarishAtGitHub/elasticsearch,jeteve/elasticsearch,vvcephei/elasticsearch,SergVro/elasticsearch,kimimj/elasticsearch,scorpionvicky/elasticsearch,mapr/elasticsearch,fekaputra/elasticsearch,glefloch/elasticsearch,Fsero/elasticsearch,lightslife/elasticsearch,bestwpw/elasticsearch,jbertouch/elasticsearch,mcku/elasticsearch,kenshin233/elasticsearch,btiernay/elasticsearch,mjason3/elasticsearch | /*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.gateway;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.*;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.MetaDataService;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.DiscoveryService;
import org.elasticsearch.threadpool.ThreadPool;
import javax.annotation.Nullable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.concurrent.Executors.*;
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.cluster.metadata.MetaData.*;
import static org.elasticsearch.common.unit.TimeValue.*;
import static org.elasticsearch.common.util.concurrent.DynamicExecutors.*;
/**
* @author kimchy (shay.banon)
*/
public class GatewayService extends AbstractLifecycleComponent<GatewayService> implements ClusterStateListener {
private final Gateway gateway;
private final ThreadPool threadPool;
private volatile ExecutorService executor;
private final ClusterService clusterService;
private final DiscoveryService discoveryService;
private final MetaDataService metaDataService;
private final TimeValue initialStateTimeout;
private final TimeValue recoverAfterTime;
private final int recoverAfterNodes;
private final AtomicBoolean readFromGateway = new AtomicBoolean();
@Inject public GatewayService(Settings settings, Gateway gateway, ClusterService clusterService, DiscoveryService discoveryService,
ThreadPool threadPool, MetaDataService metaDataService) {
super(settings);
this.gateway = gateway;
this.clusterService = clusterService;
this.discoveryService = discoveryService;
this.threadPool = threadPool;
this.metaDataService = metaDataService;
this.initialStateTimeout = componentSettings.getAsTime("initial_state_timeout", TimeValue.timeValueSeconds(30));
// allow to control a delay of when indices will get created
this.recoverAfterTime = componentSettings.getAsTime("recover_after_time", null);
this.recoverAfterNodes = componentSettings.getAsInt("recover_after_nodes", -1);
}
@Override protected void doStart() throws ElasticSearchException {
gateway.start();
this.executor = newSingleThreadExecutor(daemonThreadFactory(settings, "gateway"));
// if we received initial state, see if we can recover within the start phase, so we hold the
// node from starting until we recovered properly
if (discoveryService.initialStateReceived()) {
ClusterState clusterState = clusterService.state();
if (clusterState.nodes().localNodeMaster() && !clusterState.metaData().recoveredFromGateway()) {
if (recoverAfterNodes != -1 && clusterState.nodes().size() < recoverAfterNodes) {
logger.debug("Not recovering from gateway, nodes_size [" + clusterState.nodes().size() + "] < recover_after_nodes [" + recoverAfterNodes + "]");
} else {
if (readFromGateway.compareAndSet(false, true)) {
Boolean waited = readFromGateway(initialStateTimeout);
if (waited != null && !waited) {
logger.warn("Waited for {} for indices to be created from the gateway, and not all have been created", initialStateTimeout);
}
}
}
}
} else {
logger.debug("Can't wait on start for (possibly) reading state from gateway, will do it asynchronously");
}
clusterService.add(this);
}
@Override protected void doStop() throws ElasticSearchException {
clusterService.remove(this);
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
gateway.stop();
}
@Override protected void doClose() throws ElasticSearchException {
gateway.close();
}
@Override public void clusterChanged(final ClusterChangedEvent event) {
if (!lifecycle.started()) {
return;
}
if (event.localNodeMaster()) {
if (!event.state().metaData().recoveredFromGateway()) {
ClusterState clusterState = event.state();
if (recoverAfterNodes != -1 && clusterState.nodes().size() < recoverAfterNodes) {
logger.debug("Not recovering from gateway, nodes_size [" + clusterState.nodes().size() + "] < recover_after_nodes [" + recoverAfterNodes + "]");
} else {
if (readFromGateway.compareAndSet(false, true)) {
executor.execute(new Runnable() {
@Override public void run() {
readFromGateway(null);
}
});
}
}
} else {
writeToGateway(event);
}
}
}
private void writeToGateway(final ClusterChangedEvent event) {
if (!event.metaDataChanged()) {
return;
}
executor.execute(new Runnable() {
@Override public void run() {
logger.debug("Writing to gateway");
try {
gateway.write(event.state().metaData());
// TODO, we need to remember that we failed, maybe add a retry scheduler?
} catch (Exception e) {
logger.error("Failed to write to gateway", e);
}
}
});
}
/**
* Reads from the gateway. If the waitTimeout is set, will wait till all the indices
* have been created from the meta data read from the gateway. Return value only applicable
* when waiting, and indicates that everything was created within teh wait timeout.
*/
private Boolean readFromGateway(@Nullable TimeValue waitTimeout) {
logger.debug("Reading state from gateway...");
MetaData metaData;
try {
metaData = gateway.read();
} catch (Exception e) {
logger.error("Failed to read from gateway", e);
markMetaDataAsReadFromGateway("failure");
return false;
}
if (metaData == null) {
logger.debug("No state read from gateway");
markMetaDataAsReadFromGateway("no state");
return true;
}
final MetaData fMetaData = metaData;
final CountDownLatch latch = new CountDownLatch(fMetaData.indices().size());
if (recoverAfterTime != null) {
logger.debug("Delaying initial state index creation for [{}]", recoverAfterTime);
threadPool.schedule(new Runnable() {
@Override public void run() {
updateClusterStateFromGateway(fMetaData, latch);
}
}, recoverAfterTime);
} else {
updateClusterStateFromGateway(fMetaData, latch);
}
// if we delay indices creation, then waiting for them does not make sense
if (recoverAfterTime != null) {
return null;
}
if (waitTimeout != null) {
try {
return latch.await(waitTimeout.millis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// ignore
}
}
return null;
}
private void markMetaDataAsReadFromGateway(String reason) {
clusterService.submitStateUpdateTask("gateway (marked as read, reason=" + reason + ")", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
MetaData.Builder metaDataBuilder = newMetaDataBuilder()
.metaData(currentState.metaData())
// mark the metadata as read from gateway
.markAsRecoveredFromGateway();
return newClusterStateBuilder().state(currentState).metaData(metaDataBuilder).build();
}
});
}
private void updateClusterStateFromGateway(final MetaData fMetaData, final CountDownLatch latch) {
clusterService.submitStateUpdateTask("gateway (recovered meta-data)", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
MetaData.Builder metaDataBuilder = newMetaDataBuilder()
.metaData(currentState.metaData()).maxNumberOfShardsPerNode(fMetaData.maxNumberOfShardsPerNode());
// mark the metadata as read from gateway
metaDataBuilder.markAsRecoveredFromGateway();
// go over the meta data and create indices, we don't really need to copy over
// the meta data per index, since we create the index and it will be added automatically
for (final IndexMetaData indexMetaData : fMetaData) {
threadPool.execute(new Runnable() {
@Override public void run() {
try {
metaDataService.createIndex("gateway", indexMetaData.index(), indexMetaData.settings(), indexMetaData.mappings(), timeValueMillis(initialStateTimeout.millis() - 1000));
} catch (Exception e) {
logger.error("Failed to create index [" + indexMetaData.index() + "]", e);
} finally {
latch.countDown();
}
}
});
}
return newClusterStateBuilder().state(currentState).metaData(metaDataBuilder).build();
}
});
}
}
| modules/elasticsearch/src/main/java/org/elasticsearch/gateway/GatewayService.java | /*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.gateway;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.*;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.MetaDataService;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.DiscoveryService;
import org.elasticsearch.threadpool.ThreadPool;
import javax.annotation.Nullable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.concurrent.Executors.*;
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.cluster.metadata.MetaData.*;
import static org.elasticsearch.common.unit.TimeValue.*;
import static org.elasticsearch.common.util.concurrent.DynamicExecutors.*;
/**
* @author kimchy (shay.banon)
*/
public class GatewayService extends AbstractLifecycleComponent<GatewayService> implements ClusterStateListener {
private final Gateway gateway;
private final ThreadPool threadPool;
private volatile ExecutorService executor;
private final ClusterService clusterService;
private final DiscoveryService discoveryService;
private final MetaDataService metaDataService;
private final TimeValue initialStateTimeout;
private final TimeValue delayIndexCreation;
private final AtomicBoolean readFromGateway = new AtomicBoolean();
@Inject public GatewayService(Settings settings, Gateway gateway, ClusterService clusterService, DiscoveryService discoveryService,
ThreadPool threadPool, MetaDataService metaDataService) {
super(settings);
this.gateway = gateway;
this.clusterService = clusterService;
this.discoveryService = discoveryService;
this.threadPool = threadPool;
this.metaDataService = metaDataService;
this.initialStateTimeout = componentSettings.getAsTime("initial_state_timeout", TimeValue.timeValueSeconds(30));
// allow to control a delay of when indices will get created
this.delayIndexCreation = componentSettings.getAsTime("delay_index_creation", null);
}
@Override protected void doStart() throws ElasticSearchException {
gateway.start();
this.executor = newSingleThreadExecutor(daemonThreadFactory(settings, "gateway"));
// if we received initial state, see if we can recover within the start phase, so we hold the
// node from starting until we recovered properly
if (discoveryService.initialStateReceived()) {
ClusterState clusterState = clusterService.state();
if (clusterState.nodes().localNodeMaster() && !clusterState.metaData().recoveredFromGateway()) {
if (readFromGateway.compareAndSet(false, true)) {
Boolean waited = readFromGateway(initialStateTimeout);
if (waited != null && !waited) {
logger.warn("Waited for {} for indices to be created from the gateway, and not all have been created", initialStateTimeout);
}
}
}
} else {
logger.debug("Can't wait on start for (possibly) reading state from gateway, will do it asynchronously");
}
clusterService.add(this);
}
@Override protected void doStop() throws ElasticSearchException {
clusterService.remove(this);
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
gateway.stop();
}
@Override protected void doClose() throws ElasticSearchException {
gateway.close();
}
@Override public void clusterChanged(final ClusterChangedEvent event) {
if (!lifecycle.started()) {
return;
}
if (event.localNodeMaster()) {
if (!event.state().metaData().recoveredFromGateway() && readFromGateway.compareAndSet(false, true)) {
executor.execute(new Runnable() {
@Override public void run() {
readFromGateway(null);
}
});
} else {
writeToGateway(event);
}
}
}
private void writeToGateway(final ClusterChangedEvent event) {
if (!event.metaDataChanged()) {
return;
}
executor.execute(new Runnable() {
@Override public void run() {
logger.debug("Writing to gateway");
try {
gateway.write(event.state().metaData());
// TODO, we need to remember that we failed, maybe add a retry scheduler?
} catch (Exception e) {
logger.error("Failed to write to gateway", e);
}
}
});
}
/**
* Reads from the gateway. If the waitTimeout is set, will wait till all the indices
* have been created from the meta data read from the gateway. Return value only applicable
* when waiting, and indicates that everything was created within teh wait timeout.
*/
private Boolean readFromGateway(@Nullable TimeValue waitTimeout) {
// we are the first master, go ahead and read and create indices
logger.debug("First master in the cluster, reading state from gateway");
MetaData metaData;
try {
metaData = gateway.read();
} catch (Exception e) {
logger.error("Failed to read from gateway", e);
markMetaDataAsReadFromGateway("failure");
return false;
}
if (metaData == null) {
logger.debug("No state read from gateway");
markMetaDataAsReadFromGateway("no state");
return true;
}
final MetaData fMetaData = metaData;
final CountDownLatch latch = new CountDownLatch(fMetaData.indices().size());
if (delayIndexCreation != null) {
logger.debug("Delaying initial state index creation for [{}]", delayIndexCreation);
threadPool.schedule(new Runnable() {
@Override public void run() {
updateClusterStateFromGateway(fMetaData, latch);
}
}, delayIndexCreation);
} else {
updateClusterStateFromGateway(fMetaData, latch);
}
// if we delay indices creation, then waiting for them does not make sense
if (delayIndexCreation != null) {
return null;
}
if (waitTimeout != null) {
try {
return latch.await(waitTimeout.millis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// ignore
}
}
return null;
}
private void markMetaDataAsReadFromGateway(String reason) {
clusterService.submitStateUpdateTask("gateway (marked as read, reason=" + reason + ")", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
MetaData.Builder metaDataBuilder = newMetaDataBuilder()
.metaData(currentState.metaData())
// mark the metadata as read from gateway
.markAsRecoveredFromGateway();
return newClusterStateBuilder().state(currentState).metaData(metaDataBuilder).build();
}
});
}
private void updateClusterStateFromGateway(final MetaData fMetaData, final CountDownLatch latch) {
clusterService.submitStateUpdateTask("gateway (recovered meta-data)", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
MetaData.Builder metaDataBuilder = newMetaDataBuilder()
.metaData(currentState.metaData()).maxNumberOfShardsPerNode(fMetaData.maxNumberOfShardsPerNode());
// mark the metadata as read from gateway
metaDataBuilder.markAsRecoveredFromGateway();
// go over the meta data and create indices, we don't really need to copy over
// the meta data per index, since we create the index and it will be added automatically
for (final IndexMetaData indexMetaData : fMetaData) {
threadPool.execute(new Runnable() {
@Override public void run() {
try {
metaDataService.createIndex("gateway", indexMetaData.index(), indexMetaData.settings(), indexMetaData.mappings(), timeValueMillis(initialStateTimeout.millis() - 1000));
} catch (Exception e) {
logger.error("Failed to create index [" + indexMetaData.index() + "]", e);
} finally {
latch.countDown();
}
}
});
}
return newClusterStateBuilder().state(currentState).metaData(metaDataBuilder).build();
}
});
}
}
| Gateway: Allow to configure a `recovery_after_time` and `recover_after_nodes`, closes #223.
| modules/elasticsearch/src/main/java/org/elasticsearch/gateway/GatewayService.java | Gateway: Allow to configure a `recovery_after_time` and `recover_after_nodes`, closes #223. | <ide><path>odules/elasticsearch/src/main/java/org/elasticsearch/gateway/GatewayService.java
<ide>
<ide> private final TimeValue initialStateTimeout;
<ide>
<del> private final TimeValue delayIndexCreation;
<add> private final TimeValue recoverAfterTime;
<add> private final int recoverAfterNodes;
<ide>
<ide>
<ide> private final AtomicBoolean readFromGateway = new AtomicBoolean();
<ide> this.metaDataService = metaDataService;
<ide> this.initialStateTimeout = componentSettings.getAsTime("initial_state_timeout", TimeValue.timeValueSeconds(30));
<ide> // allow to control a delay of when indices will get created
<del> this.delayIndexCreation = componentSettings.getAsTime("delay_index_creation", null);
<add> this.recoverAfterTime = componentSettings.getAsTime("recover_after_time", null);
<add> this.recoverAfterNodes = componentSettings.getAsInt("recover_after_nodes", -1);
<ide> }
<ide>
<ide> @Override protected void doStart() throws ElasticSearchException {
<ide> if (discoveryService.initialStateReceived()) {
<ide> ClusterState clusterState = clusterService.state();
<ide> if (clusterState.nodes().localNodeMaster() && !clusterState.metaData().recoveredFromGateway()) {
<del> if (readFromGateway.compareAndSet(false, true)) {
<del> Boolean waited = readFromGateway(initialStateTimeout);
<del> if (waited != null && !waited) {
<del> logger.warn("Waited for {} for indices to be created from the gateway, and not all have been created", initialStateTimeout);
<add> if (recoverAfterNodes != -1 && clusterState.nodes().size() < recoverAfterNodes) {
<add> logger.debug("Not recovering from gateway, nodes_size [" + clusterState.nodes().size() + "] < recover_after_nodes [" + recoverAfterNodes + "]");
<add> } else {
<add> if (readFromGateway.compareAndSet(false, true)) {
<add> Boolean waited = readFromGateway(initialStateTimeout);
<add> if (waited != null && !waited) {
<add> logger.warn("Waited for {} for indices to be created from the gateway, and not all have been created", initialStateTimeout);
<add> }
<ide> }
<ide> }
<ide> }
<ide> return;
<ide> }
<ide> if (event.localNodeMaster()) {
<del> if (!event.state().metaData().recoveredFromGateway() && readFromGateway.compareAndSet(false, true)) {
<del> executor.execute(new Runnable() {
<del> @Override public void run() {
<del> readFromGateway(null);
<add> if (!event.state().metaData().recoveredFromGateway()) {
<add> ClusterState clusterState = event.state();
<add> if (recoverAfterNodes != -1 && clusterState.nodes().size() < recoverAfterNodes) {
<add> logger.debug("Not recovering from gateway, nodes_size [" + clusterState.nodes().size() + "] < recover_after_nodes [" + recoverAfterNodes + "]");
<add> } else {
<add> if (readFromGateway.compareAndSet(false, true)) {
<add> executor.execute(new Runnable() {
<add> @Override public void run() {
<add> readFromGateway(null);
<add> }
<add> });
<ide> }
<del> });
<add> }
<ide> } else {
<ide> writeToGateway(event);
<ide> }
<ide> * when waiting, and indicates that everything was created within teh wait timeout.
<ide> */
<ide> private Boolean readFromGateway(@Nullable TimeValue waitTimeout) {
<del> // we are the first master, go ahead and read and create indices
<del> logger.debug("First master in the cluster, reading state from gateway");
<add> logger.debug("Reading state from gateway...");
<ide> MetaData metaData;
<ide> try {
<ide> metaData = gateway.read();
<ide> }
<ide> final MetaData fMetaData = metaData;
<ide> final CountDownLatch latch = new CountDownLatch(fMetaData.indices().size());
<del> if (delayIndexCreation != null) {
<del> logger.debug("Delaying initial state index creation for [{}]", delayIndexCreation);
<add> if (recoverAfterTime != null) {
<add> logger.debug("Delaying initial state index creation for [{}]", recoverAfterTime);
<ide> threadPool.schedule(new Runnable() {
<ide> @Override public void run() {
<ide> updateClusterStateFromGateway(fMetaData, latch);
<ide> }
<del> }, delayIndexCreation);
<add> }, recoverAfterTime);
<ide> } else {
<ide> updateClusterStateFromGateway(fMetaData, latch);
<ide> }
<ide> // if we delay indices creation, then waiting for them does not make sense
<del> if (delayIndexCreation != null) {
<add> if (recoverAfterTime != null) {
<ide> return null;
<ide> }
<ide> if (waitTimeout != null) { |
|
Java | mit | 53dafbf8f7495474e48719f47cfbbb7bcf83ed3e | 0 | csmith/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,DMDirc/DMDirc,DMDirc/DMDirc,greboid/DMDirc,csmith/DMDirc,csmith/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client | /*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package uk.org.ownage.dmdirc.commandparser.commands.channel;
import java.awt.Color;
import java.util.Map;
import uk.org.ownage.dmdirc.Channel;
import uk.org.ownage.dmdirc.ChannelClientProperty;
import uk.org.ownage.dmdirc.Config;
import uk.org.ownage.dmdirc.Server;
import uk.org.ownage.dmdirc.commandparser.ChannelCommand;
import uk.org.ownage.dmdirc.commandparser.CommandManager;
import uk.org.ownage.dmdirc.commandparser.CommandWindow;
import uk.org.ownage.dmdirc.parser.ChannelClientInfo;
import uk.org.ownage.dmdirc.parser.ChannelInfo;
import uk.org.ownage.dmdirc.ui.ChannelFrame;
import uk.org.ownage.dmdirc.ui.messages.ColourManager;
/**
* Allows the user to set a nickname on the channel to use a custom colour.
* @author chris
*/
public final class SetNickColour extends ChannelCommand {
/** Creates a new instance of SetNickColour. */
public SetNickColour() {
super();
CommandManager.registerCommand(this);
}
/**
* Executes this command.
* @param origin The frame in which this command was issued
* @param server The server object that this command is associated with
* @param channel The channel object that this command is associated with
* @param args The user supplied arguments
*/
@SuppressWarnings("unchecked")
public void execute(final CommandWindow origin, final Server server,
final Channel channel, final String... args) {
int offset = 0;
boolean nicklist = true;
boolean text = true;
if (args.length > offset && args[offset].equalsIgnoreCase("--nicklist")) {
text = false;
offset++;
} else if (args.length > offset && args[offset].equalsIgnoreCase("--text")) {
nicklist = false;
offset++;
}
if (args.length <= offset) {
origin.addLine("commandUsage", Config.getCommandChar(),
"setnickcolour", "[--nicklist|--text] <nick> [colour]");
return;
}
final ChannelClientInfo target = channel.getChannelInfo().getUser(args[offset]);
offset++;
if (target == null) {
origin.addLine("commandError", "No such nickname!");
} else if (args.length <= offset) {
// We're removing the colour
if (nicklist) {
target.getMap().remove(ChannelClientProperty.NICKLIST_FOREGROUND);
}
if (text) {
target.getMap().remove(ChannelClientProperty.TEXT_FOREGROUND);
}
((ChannelFrame) channel.getFrame()).getNickList().repaint();
} else {
// We're setting the colour
final Color newColour = ColourManager.parseColour(args[offset], null);
if (newColour == null) {
origin.addLine("commandError", "Invalid colour specified.");
return;
}
if (nicklist) {
target.getMap().put(ChannelClientProperty.NICKLIST_FOREGROUND, newColour);
}
if (text) {
target.getMap().put(ChannelClientProperty.TEXT_FOREGROUND, newColour);
}
((ChannelFrame) channel.getFrame()).getNickList().repaint();
}
}
/** {@inheritDoc}. */
public String getName() {
return "setnickcolour";
}
/** {@inheritDoc}. */
public boolean showInHelp() {
return true;
}
/** {@inheritDoc}. */
public boolean isPolyadic() {
return true;
}
/** {@inheritDoc}. */
public int getArity() {
return 0;
}
/** {@inheritDoc}. */
public String getHelp() {
return "setnickcolour [--nicklist|--text] <nick> [colour] - set the specified person's display colour";
}
} | src/uk/org/ownage/dmdirc/commandparser/commands/channel/SetNickColour.java | /*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package uk.org.ownage.dmdirc.commandparser.commands.channel;
import java.awt.Color;
import java.util.Map;
import uk.org.ownage.dmdirc.Channel;
import uk.org.ownage.dmdirc.ChannelClientProperty;
import uk.org.ownage.dmdirc.Server;
import uk.org.ownage.dmdirc.commandparser.ChannelCommand;
import uk.org.ownage.dmdirc.commandparser.CommandManager;
import uk.org.ownage.dmdirc.commandparser.CommandWindow;
import uk.org.ownage.dmdirc.parser.ChannelClientInfo;
import uk.org.ownage.dmdirc.parser.ChannelInfo;
import uk.org.ownage.dmdirc.ui.ChannelFrame;
import uk.org.ownage.dmdirc.ui.messages.ColourManager;
/**
* Allows the user to set a nickname on the channel to use a custom colour.
* @author chris
*/
public final class SetNickColour extends ChannelCommand {
/** Creates a new instance of SetNickColour. */
public SetNickColour() {
super();
CommandManager.registerCommand(this);
}
/**
* Executes this command.
* @param origin The frame in which this command was issued
* @param server The server object that this command is associated with
* @param channel The channel object that this command is associated with
* @param args The user supplied arguments
*/
@SuppressWarnings("unchecked")
public void execute(final CommandWindow origin, final Server server,
final Channel channel, final String... args) {
final ChannelClientInfo target = channel.getChannelInfo().getUser(args[0]);
if (target == null) {
origin.addLine("commandError", "No such nickname!");
} else {
final Color newColour = ColourManager.parseColour(args[1], null);
if (newColour == null) {
origin.addLine("commandError", "Invalid colour specified.");
} else {
target.getMap().put(ChannelClientProperty.NICKLIST_FOREGROUND, newColour);
target.getMap().put(ChannelClientProperty.TEXT_FOREGROUND, newColour);
((ChannelFrame) channel.getFrame()).getNickList().repaint();
}
}
}
/** {@inheritDoc}. */
public String getName() {
return "setnickcolour";
}
/** {@inheritDoc}. */
public boolean showInHelp() {
return true;
}
/** {@inheritDoc}. */
public boolean isPolyadic() {
return false;
}
/** {@inheritDoc}. */
public int getArity() {
return 2;
}
/** {@inheritDoc}. */
public String getHelp() {
return "setnickcolour <nick> <colour> - set the specified person's display colour";
}
} | /setnickcolour can now independently set or remove the nicklist or text colours (or both)
git-svn-id: 50f83ef66c13f323b544ac924010c921a9f4a0f7@1262 00569f92-eb28-0410-84fd-f71c24880f43
| src/uk/org/ownage/dmdirc/commandparser/commands/channel/SetNickColour.java | /setnickcolour can now independently set or remove the nicklist or text colours (or both) | <ide><path>rc/uk/org/ownage/dmdirc/commandparser/commands/channel/SetNickColour.java
<ide> import java.util.Map;
<ide> import uk.org.ownage.dmdirc.Channel;
<ide> import uk.org.ownage.dmdirc.ChannelClientProperty;
<add>import uk.org.ownage.dmdirc.Config;
<ide> import uk.org.ownage.dmdirc.Server;
<ide> import uk.org.ownage.dmdirc.commandparser.ChannelCommand;
<ide> import uk.org.ownage.dmdirc.commandparser.CommandManager;
<ide> @SuppressWarnings("unchecked")
<ide> public void execute(final CommandWindow origin, final Server server,
<ide> final Channel channel, final String... args) {
<del> final ChannelClientInfo target = channel.getChannelInfo().getUser(args[0]);
<add>
<add> int offset = 0;
<add> boolean nicklist = true;
<add> boolean text = true;
<add>
<add> if (args.length > offset && args[offset].equalsIgnoreCase("--nicklist")) {
<add> text = false;
<add> offset++;
<add> } else if (args.length > offset && args[offset].equalsIgnoreCase("--text")) {
<add> nicklist = false;
<add> offset++;
<add> }
<add>
<add> if (args.length <= offset) {
<add> origin.addLine("commandUsage", Config.getCommandChar(),
<add> "setnickcolour", "[--nicklist|--text] <nick> [colour]");
<add> return;
<add> }
<add>
<add> final ChannelClientInfo target = channel.getChannelInfo().getUser(args[offset]);
<add> offset++;
<ide>
<ide> if (target == null) {
<ide> origin.addLine("commandError", "No such nickname!");
<add> } else if (args.length <= offset) {
<add> // We're removing the colour
<add> if (nicklist) {
<add> target.getMap().remove(ChannelClientProperty.NICKLIST_FOREGROUND);
<add> }
<add> if (text) {
<add> target.getMap().remove(ChannelClientProperty.TEXT_FOREGROUND);
<add> }
<add> ((ChannelFrame) channel.getFrame()).getNickList().repaint();
<ide> } else {
<del> final Color newColour = ColourManager.parseColour(args[1], null);
<add> // We're setting the colour
<add> final Color newColour = ColourManager.parseColour(args[offset], null);
<ide> if (newColour == null) {
<ide> origin.addLine("commandError", "Invalid colour specified.");
<del> } else {
<add> return;
<add> }
<add> if (nicklist) {
<ide> target.getMap().put(ChannelClientProperty.NICKLIST_FOREGROUND, newColour);
<add> }
<add> if (text) {
<ide> target.getMap().put(ChannelClientProperty.TEXT_FOREGROUND, newColour);
<del> ((ChannelFrame) channel.getFrame()).getNickList().repaint();
<ide> }
<add> ((ChannelFrame) channel.getFrame()).getNickList().repaint();
<ide> }
<ide> }
<ide>
<ide>
<ide> /** {@inheritDoc}. */
<ide> public boolean isPolyadic() {
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> /** {@inheritDoc}. */
<ide> public int getArity() {
<del> return 2;
<add> return 0;
<ide> }
<ide>
<ide> /** {@inheritDoc}. */
<ide> public String getHelp() {
<del> return "setnickcolour <nick> <colour> - set the specified person's display colour";
<add> return "setnickcolour [--nicklist|--text] <nick> [colour] - set the specified person's display colour";
<ide> }
<ide>
<ide> } |
|
Java | bsd-3-clause | efa71c767f080dac8b3317f06d0dbdd34f0baaa1 | 0 | NCIEVS/evsrestapi,NCIEVS/evsrestapi,NCIEVS/evsrestapi |
package gov.nih.nci.evs.api.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import gov.nih.nci.evs.api.aop.RecordMetricDB;
import gov.nih.nci.evs.api.model.Terminology;
import gov.nih.nci.evs.api.model.evs.EvsVersionInfo;
import gov.nih.nci.evs.api.service.SparqlQueryManagerService;
import gov.nih.nci.evs.api.util.EVSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* Controller for /metadata endpoints.
*/
@RestController
@RequestMapping("${nci.evs.application.contextPath}")
@Api(tags = "Metadata endpoints")
public class MetadataController {
/** The Constant log. */
@SuppressWarnings("unused")
private static final Logger logger =
LoggerFactory.getLogger(MetadataController.class);
/** The sparql query manager service. */
@Autowired
SparqlQueryManagerService sparqlQueryManagerService;
/**
* Returns the version info.
*
* @return the version info
* @throws IOException Signals that an I/O exception has occurred.
*/
@ApiOperation(value = "Gets terminologies loaded into the API", response = EvsVersionInfo.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved the requested information"),
@ApiResponse(code = 401, message = "Not authorized to view this resource"),
@ApiResponse(code = 403, message = "Access to resource is forbidden"),
@ApiResponse(code = 404, message = "Resource not found")
})
@ApiImplicitParams({
@ApiImplicitParam(name = "db", value = "Specify either 'monthly' or 'weekly', if not specified defaults to 'monthly'", required = false, dataType = "string", paramType = "query")
})
@RecordMetricDB
@RequestMapping(method = RequestMethod.GET, value = "/metadata/terminologies", produces = "application/json")
public @ResponseBody List<Terminology> getTerminologies() throws IOException {
final Terminology monthlyNcit =
new Terminology(sparqlQueryManagerService.getEvsVersionInfo("monthly"));
monthlyNcit.getTags().put("monthly", "true");
// Monthly is the latest published version
monthlyNcit.setLatest(true);
final Terminology weeklyNcit =
new Terminology(sparqlQueryManagerService.getEvsVersionInfo("weekly"));
// If these are equal, there's only one version, return it
if (monthlyNcit.equals(weeklyNcit)) {
return EVSUtils.asList(monthlyNcit);
}
// Otherwise, there are two versions
else {
weeklyNcit.getTags().put("weekly", "true");
weeklyNcit.setLatest(false);
return EVSUtils.asList(monthlyNcit, weeklyNcit);
}
}
}
| src/main/java/gov/nih/nci/evs/api/controller/MetadataController.java |
package gov.nih.nci.evs.api.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import gov.nih.nci.evs.api.aop.RecordMetricDB;
import gov.nih.nci.evs.api.model.Terminology;
import gov.nih.nci.evs.api.model.evs.EvsVersionInfo;
import gov.nih.nci.evs.api.service.SparqlQueryManagerService;
import gov.nih.nci.evs.api.util.EVSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* Controller for /metadata endpoints.
*/
@RestController
@RequestMapping("${nci.evs.application.contextPath}")
@Api(tags = "Metadata endpoints")
public class MetadataController {
/** The Constant log. */
@SuppressWarnings("unused")
private static final Logger logger =
LoggerFactory.getLogger(MetadataController.class);
/** The sparql query manager service. */
@Autowired
SparqlQueryManagerService sparqlQueryManagerService;
/**
* Returns the version info.
*
* @return the version info
* @throws IOException Signals that an I/O exception has occurred.
*/
@ApiOperation(value = "Gets terminologies loaded into the API", response = EvsVersionInfo.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved the requested information"),
@ApiResponse(code = 401, message = "Not authorized to view this resource"),
@ApiResponse(code = 403, message = "Access to resource is forbidden"),
@ApiResponse(code = 404, message = "Resource not found")
})
@ApiImplicitParams({
@ApiImplicitParam(name = "db", value = "Specify either 'monthly' or 'weekly', if not specified defaults to 'monthly'", required = false, dataType = "string", paramType = "query")
})
@RecordMetricDB
@RequestMapping(method = RequestMethod.GET, value = "/metadata/terminologies", produces = "application/json")
public @ResponseBody List<Terminology> getTerminologies() throws IOException {
final Terminology monthlyNcit =
new Terminology(sparqlQueryManagerService.getEvsVersionInfo("monthly"));
monthlyNcit.getTags().put("monthly", "true");
final Terminology weeklyNcit =
new Terminology(sparqlQueryManagerService.getEvsVersionInfo("weekly"));
if (monthlyNcit.equals(weeklyNcit)) {
monthlyNcit.setLatest(true);
return EVSUtils.asList(monthlyNcit);
} else {
weeklyNcit.getTags().put("weekly", "true");
weeklyNcit.setLatest(true);
return EVSUtils.asList(monthlyNcit, weeklyNcit);
}
}
}
| Fix so that the latest version of NCI is monthly not weekly
| src/main/java/gov/nih/nci/evs/api/controller/MetadataController.java | Fix so that the latest version of NCI is monthly not weekly | <ide><path>rc/main/java/gov/nih/nci/evs/api/controller/MetadataController.java
<ide> final Terminology monthlyNcit =
<ide> new Terminology(sparqlQueryManagerService.getEvsVersionInfo("monthly"));
<ide> monthlyNcit.getTags().put("monthly", "true");
<add> // Monthly is the latest published version
<add> monthlyNcit.setLatest(true);
<ide>
<ide> final Terminology weeklyNcit =
<ide> new Terminology(sparqlQueryManagerService.getEvsVersionInfo("weekly"));
<ide>
<add> // If these are equal, there's only one version, return it
<ide> if (monthlyNcit.equals(weeklyNcit)) {
<del> monthlyNcit.setLatest(true);
<ide> return EVSUtils.asList(monthlyNcit);
<del> } else {
<add> }
<add> // Otherwise, there are two versions
<add> else {
<ide> weeklyNcit.getTags().put("weekly", "true");
<del> weeklyNcit.setLatest(true);
<add> weeklyNcit.setLatest(false);
<ide> return EVSUtils.asList(monthlyNcit, weeklyNcit);
<ide> }
<ide> } |
|
Java | bsd-3-clause | a8f310c821fd930c3fd3c94b75901ad0c51a3117 | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.types.standard;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.xins.common.types.Type;
import org.xins.common.types.TypeValueException;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.text.FastStringBuffer;
/**
* Standard type <em>_timestamp</em>.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public class Timestamp extends Type {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Formatter used to convert the String representation as a
* {@link java.util.Date}.
*/
private static DateFormat FORMATTER;
/**
* The only instance of this class. This field is never <code>null</code>.
*/
public final static Timestamp SINGLETON = new Timestamp();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Constructs a <code>Timestamp.Value</code> with the value of the current
* time.
*
* @return
* the {@link Value} initialed with the current time,
* never <code>null</code>.
*/
public static Value now() {
Calendar today = Calendar.getInstance();
int year = today.get(Calendar.YEAR);
int month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DAY_OF_MONTH);
int hour = today.get(Calendar.HOUR);
int minutes = today.get(Calendar.MINUTE);
int seconds = today.get(Calendar.SECOND);
return new Value(year, month, day, hour, minutes, seconds);
}
/**
* Constructs a <code>Timestamp.Value</code> from the specified string
* which is guaranteed to be non-<code>null</code>.
*
* @param string
* the string to convert in the ISO format YYYYMMDDhhmmss,
* cannot be <code>null</code>.
*
* @return
* the {@link Value} object, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static Value fromStringForRequired(String string)
throws IllegalArgumentException, TypeValueException {
// Check preconditions
MandatoryArgumentChecker.check("string", string);
return (Value) SINGLETON.fromString(string);
}
/**
* Constructs a <code>Timestamp.Value</code> from the specified string.
*
* @param string
* the string to convert in the ISO format YYYYMMDDhhmmss,
* can be <code>null</code>.
*
* @return
* the {@link Value}, or <code>null</code> if
* <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static Value fromStringForOptional(String string)
throws TypeValueException {
return (Value) SINGLETON.fromString(string);
}
/**
* Converts the specified <code>Timestamp.Value</code> to a string.
*
* @param value
* the value to convert, can be <code>null</code>.
*
* @return
* the textual representation of the value in the ISO format YYYYMMDDhhmmss,
* or <code>null</code> if and only if <code>value == null</code>.
*/
public static String toString(Value value) {
// Short-circuit if the argument is null
if (value == null) {
return null;
}
return toString(value.getYear(),
value.getMonthOfYear(),
value.getDayOfMonth(),
value.getHourOfDay(),
value.getMinuteOfHour(),
value.getSecondOfMinute());
}
/**
* Converts the specified combination of a year, month, day, hour,
* minute and second to a string.
*
* @param year
* the year, must be >=0 and <= 9999.
*
* @param month
* the month of the year, must be >= 1 and <= 12.
*
* @param day
* the day of the month, must be >= 1 and <= 31.
*
* @param hour
* the hour of the day, must be >= 0 and <= 23.
*
* @param minute
* the minute of the hour, must be >= 0 and <= 59.
*
* @param second
* the second of the minute, must be >= 0 and <= 59.
*
* @return
* the textual representation of the value in the ISO format YYYYMMDDhhmmss,
* never <code>null</code>.
*/
private static String toString(int year, int month, int day, int hour, int minute, int second) {
// Use a buffer to create the string
FastStringBuffer buffer = new FastStringBuffer(8);
// Append the year
if (year < 10) {
buffer.append("000");
} else if (year < 100) {
buffer.append("00");
} else if (year < 1000) {
buffer.append('0');
}
buffer.append(year);
// Append the month
if (month < 10) {
buffer.append('0');
}
buffer.append(month);
// Append the day
if (day < 10) {
buffer.append('0');
}
buffer.append(day);
// Append the hour
if (hour < 10) {
buffer.append('0');
}
buffer.append(hour);
// Append the minute
if (minute < 10) {
buffer.append('0');
}
buffer.append(minute);
// Append the second
if (second < 10) {
buffer.append('0');
}
buffer.append(second);
return buffer.toString();
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>Timestamp</code> instance.
* This constructor is private, the field {@link #SINGLETON} should be
* used.
*/
private Timestamp() {
super("_timestamp", Value.class);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected final boolean isValidValueImpl(String value) {
// First check the length
if (value.length() != 14) {
return false;
}
// Convert all 3 components of the string to integers
int y, m, d, h, mn, s;
try {
y = Integer.parseInt(value.substring(0, 4));
m = Integer.parseInt(value.substring(4, 6));
d = Integer.parseInt(value.substring(6, 8));
h = Integer.parseInt(value.substring(8, 10));
mn = Integer.parseInt(value.substring(10, 12));
s = Integer.parseInt(value.substring(12, 14));
} catch (NumberFormatException nfe) {
return false;
}
// Check that the values are in the correct range
return (y >= 0) && (m >= 1) && (m <= 12) && (d >= 1) && (d <= 31) &&
(h >= 0) && (h <= 23) && (mn >= 0) && (mn <= 59) && (s >= 0) && (s <= 59);
}
protected final Object fromStringImpl(String string)
throws TypeValueException {
// Convert all 3 components of the string to integers
int y, m, d, h, mn, s;
try {
y = Integer.parseInt(string.substring(0, 4));
m = Integer.parseInt(string.substring(4, 6));
d = Integer.parseInt(string.substring(6, 8));
h = Integer.parseInt(string.substring(8, 10));
mn = Integer.parseInt(string.substring(10, 12));
s = Integer.parseInt(string.substring(12, 14));
} catch (NumberFormatException nfe) {
// Should never happen, since isValidValueImpl(String) will have been
// called
throw new TypeValueException(this, string);
}
// Check that the values are in the correct range
return new Value(y, m, d, h, mn, s);
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
// Check preconditions
MandatoryArgumentChecker.check("value", value);
// The argument must be a PropertyReader
return toString((Value) value);
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Timestamp value, composed of a year, month, day, hour, minute and a second.
*
* @version $Revision$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public static final class Value {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new timestamp value. The values will not be checked.
*
* @param year
* the year, including century, e.g. <code>2005</code>.
*
* @param month
* the month of the year in the range 1-12, e.g. <code>11</code> for
* November.
*
* @param day
* the day of the month in the range 1-31, e.g. <code>1</code> for
* the first day of the month.
*
* @param hour
* the hour of the day in the range 0-23, e.g. <code>22</code> for 10
* o'clock at night.
*
* @param minute
* the minute of the hour in the range 0-59, e.g. <code>0</code> for
* first minute of the hour.
*
* @param second
* the second of the minute in the range 0-59, e.g. <code>0</code>
* for the first second of the minute.
*/
public Value(int year, int month, int day,
int hour, int minute, int second) {
// Store values unchecked
_year = year;
_month = month;
_day = day;
_hour = hour;
_minute = minute;
_second = second;
// TODO: Should we not check the values ?!
// Convert to string, and store that
_asString = Timestamp.toString(year, month, day,
hour, minute, second);
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The year, including century. E.g. <code>2005</code>.
*/
private final int _year;
/**
* The month of the year, 1-based. E.g. <code>11</code> for November.
*/
private final int _month;
/**
* The day of the month, 1-based. E.g. <code>1</code> for the first day
* of the month.
*/
private final int _day;
/**
* The hour of the day, 0-based. E.g. <code>22</code> for 10 o'clock at
* night, or <code>0</code> for the first hour of the day.
*/
private final int _hour;
/**
* The minute of the hour, 0-based. E.g. <code>0</code> for first minute
* of the hour.
*/
private final int _minute;
/**
* The second of the minute, 0-based. E.g. <code>0</code> for the first
* second of the minute.
*/
private final int _second;
/**
* Textual representation of this timestamp. Formatted as:
*
* <blockquote><em>YYYYMMDDhhmmss</em></blockquote>
*
* where:
* <ul>
* <li><em>YYYY</em> is the 4-digit year, e.g. 2005;
* <li><em>MM</em> is the 2-digit month of the year, e.g. 03 for
* March;
* <li><em>DD</em> is the 2-digit day of the month, e.g. 01 for the
* first day of the month;
* <li><em>hh</em> is the number of hours since the beginning of the
* day;
* <li><em>mm</em> is the number of minutes since the beginning of
* the hour;
* <li><em>ss</em> is the number of seconds since the beginning of
* the minute;
* </ul>
*/
private final String _asString;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns the year.
*
* @return
* the year, between 0 and 9999 (inclusive).
*/
public int getYear() {
return _year;
}
/**
* Returns the month of the year.
*
* @return
* the month of the year, between 1 and 12 (inclusive).
*/
public int getMonthOfYear() {
return _month;
}
/**
* Returns the day of the month.
*
* @return
* the day of the month, between 1 and 31 (inclusive).
*/
public int getDayOfMonth() {
return _day;
}
/**
* Returns the hour of the day.
*
* @return
* the hour of the day, between 0 and 23 (inclusive).
*/
public int getHourOfDay() {
return _hour;
}
/**
* Returns the minute of the hour.
*
* @return
* the minute of the hour, between 0 and 59 (inclusive).
*/
public int getMinuteOfHour() {
return _minute;
}
/**
* Returns the second of the minute.
*
* @return
* the second of the minute, between 0 and 59 (inclusive).
*/
public int getSecondOfMinute() {
return _second;
}
public boolean equals(Object obj) {
if (!(obj instanceof Value)) {
return false;
}
Value obj2 = (Value) obj;
return obj2.getYear() == _year && obj2.getMonthOfYear() == _month &&
obj2.getDayOfMonth() == _day && obj2.getHourOfDay() == _hour &&
obj2.getMinuteOfHour() == _minute && obj2.getSecondOfMinute() == _second;
}
public int hashCode() {
return _asString.hashCode();
}
/**
* @return
* The {@link java.util.Date} corresponding to this value.
*/
public java.util.Date toDate() {
if (FORMATTER == null) {
FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");
}
try {
return FORMATTER.parse(_asString);
} catch (ParseException pex) {
// TODO Log programming error.
return null;
}
}
/**
* @return
* The textual representation of this timestamp. Composed of the year (YYYY),
* month (MM), day (DD), hour (hh), minute (mm) and second (ss)
* in the format: <em>YYYYMMDDhhmmss</em>.
*/
public String toString() {
return _asString;
}
}
}
| src/java-common/org/xins/common/types/standard/Timestamp.java | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.types.standard;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.xins.common.types.Type;
import org.xins.common.types.TypeValueException;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.text.FastStringBuffer;
/**
* Standard type <em>_timestamp</em>.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public class Timestamp extends Type {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Formatter used to convert the String representation as a
* {@link java.util.Date}.
*/
private static DateFormat FORMATTER;
/**
* The only instance of this class. This field is never <code>null</code>.
*/
public final static Timestamp SINGLETON = new Timestamp();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Constructs a <code>Timestamp.Value</code> with the value of the current
* time.
*
* @return
* the {@link Value} initialed with the current time,
* never <code>null</code>.
*/
public static Value now() {
Calendar today = Calendar.getInstance();
int year = today.get(Calendar.YEAR);
int month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DAY_OF_MONTH);
int hour = today.get(Calendar.HOUR);
int minutes = today.get(Calendar.MINUTE);
int seconds = today.get(Calendar.SECOND);
return new Value(year, month, day, hour, minutes, seconds);
}
/**
* Constructs a <code>Timestamp.Value</code> from the specified string
* which is guaranteed to be non-<code>null</code>.
*
* @param string
* the string to convert in the ISO format YYYYMMDDhhmmss,
* cannot be <code>null</code>.
*
* @return
* the {@link Value} object, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static Value fromStringForRequired(String string)
throws IllegalArgumentException, TypeValueException {
// Check preconditions
MandatoryArgumentChecker.check("string", string);
return (Value) SINGLETON.fromString(string);
}
/**
* Constructs a <code>Timestamp.Value</code> from the specified string.
*
* @param string
* the string to convert in the ISO format YYYYMMDDhhmmss,
* can be <code>null</code>.
*
* @return
* the {@link Value}, or <code>null</code> if
* <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static Value fromStringForOptional(String string)
throws TypeValueException {
return (Value) SINGLETON.fromString(string);
}
/**
* Converts the specified <code>Timestamp.Value</code> to a string.
*
* @param value
* the value to convert, can be <code>null</code>.
*
* @return
* the textual representation of the value in the ISO format YYYYMMDDhhmmss,
* or <code>null</code> if and only if <code>value == null</code>.
*/
public static String toString(Value value) {
// Short-circuit if the argument is null
if (value == null) {
return null;
}
return toString(value.getYear(),
value.getMonthOfYear(),
value.getDayOfMonth(),
value.getHourOfDay(),
value.getMinuteOfHour(),
value.getSecondOfMinute());
}
/**
* Converts the specified combination of a year, month, day, hour,
* minute and second to a string.
*
* @param year
* the year, must be >=0 and <= 9999.
*
* @param month
* the month of the year, must be >= 1 and <= 12.
*
* @param day
* the day of the month, must be >= 1 and <= 31.
*
* @param hour
* the hour of the day, must be >= 0 and <= 23.
*
* @param minute
* the minute of the hour, must be >= 0 and <= 59.
*
* @param second
* the second of the minute, must be >= 0 and <= 59.
*
* @return
* the textual representation of the value in the ISO format YYYYMMDDhhmmss,
* never <code>null</code>.
*/
private static String toString(int year, int month, int day, int hour, int minute, int second) {
// Use a buffer to create the string
FastStringBuffer buffer = new FastStringBuffer(8);
// Append the year
if (year < 10) {
buffer.append("000");
} else if (year < 100) {
buffer.append("00");
} else if (year < 1000) {
buffer.append('0');
}
buffer.append(year);
// Append the month
if (month < 10) {
buffer.append('0');
}
buffer.append(month);
// Append the day
if (day < 10) {
buffer.append('0');
}
buffer.append(day);
// Append the hour
if (hour < 10) {
buffer.append('0');
}
buffer.append(hour);
// Append the minute
if (minute < 10) {
buffer.append('0');
}
buffer.append(minute);
// Append the second
if (second < 10) {
buffer.append('0');
}
buffer.append(second);
return buffer.toString();
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>Timestamp</code> instance.
* This constructor is private, the field {@link #SINGLETON} should be
* used.
*/
private Timestamp() {
super("_timestamp", Value.class);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected final boolean isValidValueImpl(String value) {
// First check the length
if (value.length() != 14) {
return false;
}
// Convert all 3 components of the string to integers
int y, m, d, h, mn, s;
try {
y = Integer.parseInt(value.substring(0, 4));
m = Integer.parseInt(value.substring(4, 6));
d = Integer.parseInt(value.substring(6, 8));
h = Integer.parseInt(value.substring(8, 10));
mn = Integer.parseInt(value.substring(10, 12));
s = Integer.parseInt(value.substring(12, 14));
} catch (NumberFormatException nfe) {
return false;
}
// Check that the values are in the correct range
return (y >= 0) && (m >= 1) && (m <= 12) && (d >= 1) && (d <= 31) &&
(h >= 0) && (h <= 23) && (mn >= 0) && (mn <= 59) && (s >= 0) && (s <= 59);
}
protected final Object fromStringImpl(String string)
throws TypeValueException {
// Convert all 3 components of the string to integers
int y, m, d, h, mn, s;
try {
y = Integer.parseInt(string.substring(0, 4));
m = Integer.parseInt(string.substring(4, 6));
d = Integer.parseInt(string.substring(6, 8));
h = Integer.parseInt(string.substring(8, 10));
mn = Integer.parseInt(string.substring(10, 12));
s = Integer.parseInt(string.substring(12, 14));
} catch (NumberFormatException nfe) {
// Should never happen, since isValidValueImpl(String) will have been
// called
throw new TypeValueException(this, string);
}
// Check that the values are in the correct range
return new Value(y, m, d, h, mn, s);
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
// Check preconditions
MandatoryArgumentChecker.check("value", value);
// The argument must be a PropertyReader
return toString((Value) value);
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Timestamp value, composed of a year, month, day, hour, minute and a second.
*
* @version $Revision$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public static final class Value {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new timestamp value. The values will not be checked.
*
* @param year
* the year, e.g. <code>2004</code>.
*
* @param month
* the month of the year, e.g. <code>11</code> for November.
*
* @param day
* the day of the month, e.g. <code>1</code> for the first day of the
* month.
*
* @param hour
* the hour of the day, e.g. <code>22</code> or <code>0</code> for
* the first hour of the day.
*
* @param minute
* the minute of the hour, e.g. <code>0</code> for first minute of
* the hour.
*
* @param second
* the second of the minute, e.g. <code>0</code> for the first second
* of the minute.
*/
public Value(int year, int month, int day, int hour, int minute, int second) {
_year = year;
_month = month;
_day = day;
_hour = hour;
_minute = minute;
_second = second;
_asString = Timestamp.toString(year, month, day, hour, minute, second);
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The year. E.g. <code>2004</code>.
*/
private final int _year;
/**
* The month of the year. E.g. <code>11</code> for November.
*/
private final int _month;
/**
* The day of the month. E.g. <code>1</code> for the first day of the
* month.
*/
private final int _day;
/**
* The hour of the day. E.g. <code>22</code> or <code>0</code> for
* the first hour of the day.
*/
private final int _hour;
/**
* The minute of the hour. E.g. <code>0</code> for first minute of
* the hour.
*/
private final int _minute;
/**
* The second of the minute. E.g. <code>0</code> for the first second
* of the minute.
*/
private final int _second;
/**
* Textual representation of this timestamp. Composed of the year (YYYY),
* month (MM), day (DD), hour (hh), minute (mm) and second (ss)
* in the format: <em>YYYYMMDDhhmmss</em>.
*/
private final String _asString;
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns the year.
*
* @return
* the year, between 0 and 9999 (inclusive).
*/
public int getYear() {
return _year;
}
/**
* Returns the month of the year.
*
* @return
* the month of the year, between 1 and 12 (inclusive).
*/
public int getMonthOfYear() {
return _month;
}
/**
* Returns the day of the month.
*
* @return
* the day of the month, between 1 and 31 (inclusive).
*/
public int getDayOfMonth() {
return _day;
}
/**
* Returns the hour of the day.
*
* @return
* the hour of the day, between 0 and 23 (inclusive).
*/
public int getHourOfDay() {
return _hour;
}
/**
* Returns the minute of the hour.
*
* @return
* the minute of the hour, between 0 and 59 (inclusive).
*/
public int getMinuteOfHour() {
return _minute;
}
/**
* Returns the second of the minute.
*
* @return
* the second of the minute, between 0 and 59 (inclusive).
*/
public int getSecondOfMinute() {
return _second;
}
public boolean equals(Object obj) {
if (!(obj instanceof Value)) {
return false;
}
Value obj2 = (Value) obj;
return obj2.getYear() == _year && obj2.getMonthOfYear() == _month &&
obj2.getDayOfMonth() == _day && obj2.getHourOfDay() == _hour &&
obj2.getMinuteOfHour() == _minute && obj2.getSecondOfMinute() == _second;
}
public int hashCode() {
return _asString.hashCode();
}
/**
* @return
* The {@link java.util.Date} corresponding to this value.
*/
public java.util.Date toDate() {
if (FORMATTER == null) {
FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");
}
try {
return FORMATTER.parse(_asString);
} catch (ParseException pex) {
// TODO Log programming error.
return null;
}
}
/**
* @return
* The textual representation of this timestamp. Composed of the year (YYYY),
* month (MM), day (DD), hour (hh), minute (mm) and second (ss)
* in the format: <em>YYYYMMDDhhmmss</em>.
*/
public String toString() {
return _asString;
}
}
}
| Formatting slightly improved.
| src/java-common/org/xins/common/types/standard/Timestamp.java | Formatting slightly improved. | <ide><path>rc/java-common/org/xins/common/types/standard/Timestamp.java
<ide> * Constructs a new timestamp value. The values will not be checked.
<ide> *
<ide> * @param year
<del> * the year, e.g. <code>2004</code>.
<add> * the year, including century, e.g. <code>2005</code>.
<ide> *
<ide> * @param month
<del> * the month of the year, e.g. <code>11</code> for November.
<add> * the month of the year in the range 1-12, e.g. <code>11</code> for
<add> * November.
<ide> *
<ide> * @param day
<del> * the day of the month, e.g. <code>1</code> for the first day of the
<del> * month.
<add> * the day of the month in the range 1-31, e.g. <code>1</code> for
<add> * the first day of the month.
<ide> *
<ide> * @param hour
<del> * the hour of the day, e.g. <code>22</code> or <code>0</code> for
<del> * the first hour of the day.
<add> * the hour of the day in the range 0-23, e.g. <code>22</code> for 10
<add> * o'clock at night.
<ide> *
<ide> * @param minute
<del> * the minute of the hour, e.g. <code>0</code> for first minute of
<del> * the hour.
<add> * the minute of the hour in the range 0-59, e.g. <code>0</code> for
<add> * first minute of the hour.
<ide> *
<ide> * @param second
<del> * the second of the minute, e.g. <code>0</code> for the first second
<del> * of the minute.
<del> */
<del> public Value(int year, int month, int day, int hour, int minute, int second) {
<add> * the second of the minute in the range 0-59, e.g. <code>0</code>
<add> * for the first second of the minute.
<add> */
<add> public Value(int year, int month, int day,
<add> int hour, int minute, int second) {
<add>
<add> // Store values unchecked
<ide> _year = year;
<ide> _month = month;
<ide> _day = day;
<ide> _minute = minute;
<ide> _second = second;
<ide>
<del> _asString = Timestamp.toString(year, month, day, hour, minute, second);
<del> }
<add> // TODO: Should we not check the values ?!
<add>
<add> // Convert to string, and store that
<add> _asString = Timestamp.toString(year, month, day,
<add> hour, minute, second);
<add> }
<add>
<ide>
<ide> //----------------------------------------------------------------------
<ide> // Fields
<ide> //----------------------------------------------------------------------
<ide>
<ide> /**
<del> * The year. E.g. <code>2004</code>.
<add> * The year, including century. E.g. <code>2005</code>.
<ide> */
<ide> private final int _year;
<ide>
<ide> /**
<del> * The month of the year. E.g. <code>11</code> for November.
<add> * The month of the year, 1-based. E.g. <code>11</code> for November.
<ide> */
<ide> private final int _month;
<ide>
<ide> /**
<del> * The day of the month. E.g. <code>1</code> for the first day of the
<del> * month.
<add> * The day of the month, 1-based. E.g. <code>1</code> for the first day
<add> * of the month.
<ide> */
<ide> private final int _day;
<ide>
<ide> /**
<del> * The hour of the day. E.g. <code>22</code> or <code>0</code> for
<del> * the first hour of the day.
<add> * The hour of the day, 0-based. E.g. <code>22</code> for 10 o'clock at
<add> * night, or <code>0</code> for the first hour of the day.
<ide> */
<ide> private final int _hour;
<ide>
<ide> /**
<del> * The minute of the hour. E.g. <code>0</code> for first minute of
<del> * the hour.
<add> * The minute of the hour, 0-based. E.g. <code>0</code> for first minute
<add> * of the hour.
<ide> */
<ide> private final int _minute;
<ide>
<ide> /**
<del> * The second of the minute. E.g. <code>0</code> for the first second
<del> * of the minute.
<add> * The second of the minute, 0-based. E.g. <code>0</code> for the first
<add> * second of the minute.
<ide> */
<ide> private final int _second;
<ide>
<ide> /**
<del> * Textual representation of this timestamp. Composed of the year (YYYY),
<del> * month (MM), day (DD), hour (hh), minute (mm) and second (ss)
<del> * in the format: <em>YYYYMMDDhhmmss</em>.
<add> * Textual representation of this timestamp. Formatted as:
<add> *
<add> * <blockquote><em>YYYYMMDDhhmmss</em></blockquote>
<add> *
<add> * where:
<add> * <ul>
<add> * <li><em>YYYY</em> is the 4-digit year, e.g. 2005;
<add> * <li><em>MM</em> is the 2-digit month of the year, e.g. 03 for
<add> * March;
<add> * <li><em>DD</em> is the 2-digit day of the month, e.g. 01 for the
<add> * first day of the month;
<add> * <li><em>hh</em> is the number of hours since the beginning of the
<add> * day;
<add> * <li><em>mm</em> is the number of minutes since the beginning of
<add> * the hour;
<add> * <li><em>ss</em> is the number of seconds since the beginning of
<add> * the minute;
<add> * </ul>
<ide> */
<ide> private final String _asString;
<ide> |
|
Java | apache-2.0 | 8529afdc3e3ce2317b9cf7ed08f8a9986fa160da | 0 | seven332/Nimingban,seven332/Nimingban,xdujiang/Nimingban,xdujiang/Nimingban | /*
* Copyright 2015 Hippo Seven
*
* 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.hippo.nimingban;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import com.hippo.conaco.Conaco;
import com.hippo.nimingban.client.NMBClient;
import com.hippo.nimingban.network.NMBHttpClient;
import com.hippo.vectorold.content.VectorContext;
import java.io.File;
public class NMBApplication extends Application {
private NMBHttpClient mNMBHttpClient;
private NMBClient mNMBClient;
private Conaco mConaco;
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(VectorContext.wrapContext(newBase));
}
@NonNull
public static NMBHttpClient getNMBHttpClient(@NonNull Context context) {
NMBApplication application = ((NMBApplication) context.getApplicationContext());
if (application.mNMBHttpClient == null) {
application.mNMBHttpClient = new NMBHttpClient();
}
return application.mNMBHttpClient;
}
@NonNull
public static NMBClient getNMBClient(@NonNull Context context) {
NMBApplication application = ((NMBApplication) context.getApplicationContext());
if (application.mNMBClient == null) {
application.mNMBClient = new NMBClient(application);
}
return application.mNMBClient;
}
private static int getMemoryCacheMaxSize(Context context) {
final ActivityManager activityManager = (ActivityManager) context.
getSystemService(Context.ACTIVITY_SERVICE);
return Math.min(20 * 1024 * 1024,
Math.round(0.2f * activityManager.getMemoryClass() * 1024 * 1024));
}
@NonNull
public static Conaco getConaco(@NonNull Context context) {
NMBApplication application = ((NMBApplication) context.getApplicationContext());
if (application.mConaco == null) {
Conaco.Builder builder = new Conaco.Builder();
builder.hasMemoryCache = true;
builder.memoryCacheMaxSize = getMemoryCacheMaxSize(context);
builder.hasDiskCache = true;
builder.diskCacheDir = new File(context.getCacheDir(), "conaco");
builder.diskCacheMaxSize = 20 * 1024 * 1024;
builder.httpClient = getNMBHttpClient(context);
application.mConaco = builder.build();
}
return application.mConaco;
}
}
| app/src/main/java/com/hippo/nimingban/NMBApplication.java | /*
* Copyright 2015 Hippo Seven
*
* 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.hippo.nimingban;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import com.hippo.conaco.Conaco;
import com.hippo.nimingban.client.NMBClient;
import com.hippo.nimingban.network.NMBHttpClient;
import java.io.File;
public class NMBApplication extends Application {
private NMBHttpClient mNMBHttpClient;
private NMBClient mNMBClient;
private Conaco mConaco;
@NonNull
public static NMBHttpClient getNMBHttpClient(@NonNull Context context) {
NMBApplication application = ((NMBApplication) context.getApplicationContext());
if (application.mNMBHttpClient == null) {
application.mNMBHttpClient = new NMBHttpClient();
}
return application.mNMBHttpClient;
}
@NonNull
public static NMBClient getNMBClient(@NonNull Context context) {
NMBApplication application = ((NMBApplication) context.getApplicationContext());
if (application.mNMBClient == null) {
application.mNMBClient = new NMBClient(application);
}
return application.mNMBClient;
}
private static int getMemoryCacheMaxSize(Context context) {
final ActivityManager activityManager = (ActivityManager) context.
getSystemService(Context.ACTIVITY_SERVICE);
return Math.min(20 * 1024 * 1024,
Math.round(0.2f * activityManager.getMemoryClass() * 1024 * 1024));
}
@NonNull
public static Conaco getConaco(@NonNull Context context) {
NMBApplication application = ((NMBApplication) context.getApplicationContext());
if (application.mConaco == null) {
Conaco.Builder builder = new Conaco.Builder();
builder.hasMemoryCache = true;
builder.memoryCacheMaxSize = getMemoryCacheMaxSize(context);
builder.hasDiskCache = true;
builder.diskCacheDir = new File(context.getCacheDir(), "conaco");
builder.diskCacheMaxSize = 20 * 1024 * 1024;
builder.httpClient = getNMBHttpClient(context);
application.mConaco = builder.build();
}
return application.mConaco;
}
}
| NMBApplication add super.attachBaseContext(VectorContext.wrapContext(newBase))
| app/src/main/java/com/hippo/nimingban/NMBApplication.java | NMBApplication add super.attachBaseContext(VectorContext.wrapContext(newBase)) | <ide><path>pp/src/main/java/com/hippo/nimingban/NMBApplication.java
<ide> import com.hippo.conaco.Conaco;
<ide> import com.hippo.nimingban.client.NMBClient;
<ide> import com.hippo.nimingban.network.NMBHttpClient;
<add>import com.hippo.vectorold.content.VectorContext;
<ide>
<ide> import java.io.File;
<ide>
<ide> private NMBHttpClient mNMBHttpClient;
<ide> private NMBClient mNMBClient;
<ide> private Conaco mConaco;
<add>
<add> @Override
<add> protected void attachBaseContext(Context newBase) {
<add> super.attachBaseContext(VectorContext.wrapContext(newBase));
<add> }
<ide>
<ide> @NonNull
<ide> public static NMBHttpClient getNMBHttpClient(@NonNull Context context) { |
|
Java | apache-2.0 | 684067a40b7c07ea37b58f6be83decfd7526113a | 0 | FFY00/Helios,samczsun/Helios,helios-decompiler/standalone-app,FFY00/Helios,samczsun/Helios,helios-decompiler/Helios,helios-decompiler/Helios | /*
* Copyright 2015 Sam Sun <[email protected]>
*
* 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.samczsun.helios;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonValue;
import com.samczsun.helios.api.events.Events;
import com.samczsun.helios.api.events.requests.RecentFileRequest;
import com.samczsun.helios.api.events.requests.TreeUpdateRequest;
import com.samczsun.helios.bootloader.BootSequence;
import com.samczsun.helios.bootloader.Splash;
import com.samczsun.helios.gui.BackgroundTaskGui;
import com.samczsun.helios.gui.GUI;
import com.samczsun.helios.handler.BackgroundTaskHandler;
import com.samczsun.helios.handler.ExceptionHandler;
import com.samczsun.helios.handler.addons.AddonHandler;
import com.samczsun.helios.tasks.AddFilesTask;
import com.samczsun.helios.utils.FileChooserUtil;
import com.samczsun.helios.utils.SWTUtil;
import org.apache.commons.io.IOUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.objectweb.asm.tree.ClassNode;
import javax.swing.UIManager;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Helios {
private static final Map<String, LoadedFile> files = new HashMap<>();
private static final List<Process> processes = new ArrayList<>();
private static Boolean python2Verified = null;
private static Boolean python3Verified = null;
private static Boolean javaRtVerified = null;
private static GUI gui;
private static BackgroundTaskHandler backgroundTaskHandler;
private static BackgroundTaskGui backgroundTaskGui;
public static void main(String[] args, Shell shell, Splash splashScreen) {
try {
if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
} catch (Exception exception) { //Not important. No point notifying the user
}
splashScreen.updateState(BootSequence.LOADING_SETTINGS);
Settings.loadSettings();
backgroundTaskGui = new BackgroundTaskGui();
backgroundTaskHandler = new BackgroundTaskHandler();
splashScreen.updateState(BootSequence.LOADING_ADDONS);
AddonHandler.registerPreloadedAddons();
for (File file : Constants.ADDONS_DIR.listFiles()) {
AddonHandler
.getAllHandlers()
.stream()
.filter(handler -> handler.accept(file))
.findFirst()
.ifPresent(handler -> {
handler.run(file);
});
}
splashScreen.updateState(BootSequence.SETTING_UP_GUI);
gui = new GUI(shell);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
Settings.saveSettings();
getBackgroundTaskHandler().shutdown();
processes.forEach(Process::destroy);
}));
splashScreen.updateState(BootSequence.COMPLETE);
while (!splashScreen.isDisposed()) ;
Display.getDefault().syncExec(() -> getGui().getShell().open());
}
public static List<LoadedFile> getFilesForName(String fileName) {
return files
.values()
.stream()
.filter(loadedFile -> loadedFile.getFiles().containsKey(fileName))
.collect(Collectors.toList());
}
public static void loadFile(File fileToLoad) throws IOException {
LoadedFile loadedFile = new LoadedFile(fileToLoad);
files.put(loadedFile.getName(), loadedFile);
}
public static List<ClassNode> loadAllClasses() {
List<ClassNode> classNodes = new ArrayList<>();
for (LoadedFile loadedFile : files.values()) {
for (String s : loadedFile.getFiles().keySet()) {
ClassNode loaded = loadedFile.getClassNode(s);
if (loaded != null) {
classNodes.add(loaded);
}
}
}
return classNodes;
}
public static void openFiles(final File[] files, final boolean recentFiles) {
submitBackgroundTask(new AddFilesTask(files, recentFiles));
}
public static void resetWorkSpace(boolean ask) {
if (ask && !SWTUtil.promptForYesNo(Constants.REPO_NAME + " - New Workspace",
"You have not yet saved your workspace. Are you sure you wish to create a new one?")) {
return;
}
files.clear();
getGui().getTreeManager().reset();
getGui().getClassManager().reset();
processes.forEach(Process::destroyForcibly);
processes.clear();
}
public static Process launchProcess(ProcessBuilder launch) throws IOException {
Process process = launch.start();
processes.add(process);
submitBackgroundTask(() -> {
try {
process.waitFor();
if (!process.isAlive()) {
processes.remove(process);
}
} catch (InterruptedException e) {
ExceptionHandler.handle(e);
}
});
return process;
}
public static void addRecentFile(File f) {
if (!f.getAbsolutePath().isEmpty()) {
JsonArray array = Settings.RECENT_FILES.get().asArray();
array.add(f.getAbsolutePath());
while (array.size() > Settings.MAX_RECENTFILES.get().asInt()) {
array.remove(0);
}
updateRecentFiles();
}
}
public static void updateRecentFiles() {
Events.callEvent(new RecentFileRequest(Settings.RECENT_FILES
.get()
.asArray()
.values()
.stream()
.map(JsonValue::asString)
.collect(Collectors.toList())));
}
public static void promptForFilesToOpen() {
submitBackgroundTask(() -> {
List<String> validExtensions = Arrays.asList("jar", "zip", "class", "apk", "dex");
List<File> files1 = FileChooserUtil.chooseFiles(Settings.LAST_DIRECTORY.get().asString(), validExtensions,
true);
if (files1.size() > 0) {
Settings.LAST_DIRECTORY.set(files1.get(0).getAbsolutePath());
try {
Helios.openFiles(files1.toArray(new File[files1.size()]), true);
} catch (Exception e1) {
ExceptionHandler.handle(e1);
}
}
});
}
public static void promptForRefresh() {
if (SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Refresh", "Are you sure you wish to refresh?")) {
for (LoadedFile loadedFile : Helios.files.values()) {
try {
loadedFile.reset();
} catch (IOException e) {
ExceptionHandler.handle(e);
}
}
Events.callEvent(new TreeUpdateRequest());
}
}
public static void promptForCustomPath() {
Display.getDefault().asyncExec(() -> {
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
shell.setImage(Resources.ICON.getImage());
shell.setText("Set your PATH variable");
final Text text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.WRAP);
text.setText(Settings.PATH.get().asString());
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = text.getLineHeight();
gridData.widthHint = 512;
text.setLayoutData(gridData);
shell.addShellListener(new ShellAdapter() {
@Override
public void shellClosed(ShellEvent e) {
Settings.PATH.set(text.getText());
}
});
shell.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ESC) {
shell.close();
}
}
});
shell.pack();
SWTUtil.center(shell);
shell.open();
});
}
public static boolean ensurePython3Set() {
return ensurePython3Set0(false);
}
public static boolean ensurePython2Set() {
return ensurePython2Set0(false);
}
public static boolean ensureJavaRtSet() {
return ensureJavaRtSet0(false);
}
private static boolean ensurePython3Set0(boolean forceCheck) {
String python3Location = Settings.PYTHON3_LOCATION.get().asString();
if (python3Location.isEmpty()) {
SWTUtil.showMessage("You need to set the location of the Python/PyPy 3.x executable", true);
setLocationOf(Settings.PYTHON3_LOCATION);
python3Location = Settings.PYTHON3_LOCATION.get().asString();
}
if (python3Location.isEmpty()) {
return false;
}
if (python3Verified == null || forceCheck) {
try {
Process process = new ProcessBuilder(python3Location, "-V").start();
String result = IOUtils.toString(process.getInputStream());
String error = IOUtils.toString(process.getErrorStream());
python3Verified = error.startsWith("Python 3") || result.startsWith("Python 3");
} catch (Throwable t) {
t.printStackTrace();
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
SWTUtil.showMessage(
"The Python 3.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString());
python3Verified = false;
}
}
return python3Verified;
}
private static boolean ensurePython2Set0(boolean forceCheck) {
String python2Location = Settings.PYTHON2_LOCATION.get().asString();
if (python2Location.isEmpty()) {
SWTUtil.showMessage("You need to set the location of the Python/PyPy 2.x executable", true);
setLocationOf(Settings.PYTHON2_LOCATION);
python2Location = Settings.PYTHON2_LOCATION.get().asString();
}
if (python2Location.isEmpty()) {
return false;
}
if (python2Verified == null || forceCheck) {
try {
Process process = new ProcessBuilder(python2Location, "-V").start();
String result = IOUtils.toString(process.getInputStream());
String error = IOUtils.toString(process.getErrorStream());
python2Verified = error.startsWith("Python 2") || result.startsWith("Python 2");
} catch (Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
SWTUtil.showMessage(
"The Python 2.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString());
t.printStackTrace();
python2Verified = false;
}
}
return python2Verified;
}
private static boolean ensureJavaRtSet0(boolean forceCheck) {
String javaRtLocation = Settings.RT_LOCATION.get().asString();
if (javaRtLocation.isEmpty()) {
SWTUtil.showMessage("You need to set the location of Java's rt.jar", true);
setLocationOf(Settings.RT_LOCATION);
javaRtLocation = Settings.RT_LOCATION.get().asString();
}
if (javaRtLocation.isEmpty()) {
return false;
}
if (javaRtVerified == null || forceCheck) {
ZipFile zipFile = null;
try {
File rtjar = new File(javaRtLocation);
if (rtjar.exists()) {
zipFile = new ZipFile(rtjar);
ZipEntry object = zipFile.getEntry("java/lang/Object.class");
if (object != null) {
javaRtVerified = true;
}
}
} catch (Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
SWTUtil.showMessage(
"The selected Java rt.jar is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString());
t.printStackTrace();
javaRtVerified = false;
} finally {
IOUtils.closeQuietly(zipFile);
}
}
return javaRtVerified;
}
public static void checkHotKey(Event e) {
if (e.doit) {
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
if (e.keyCode == 'o') {
promptForFilesToOpen();
e.doit = false;
} else if (e.keyCode == 'n') {
resetWorkSpace(true);
e.doit = false;
} else if (e.keyCode == 't') {
getGui().getClassManager().handleNewTabRequest();
e.doit = false;
} else if (e.keyCode == 'w') {
if ((e.stateMask & SWT.SHIFT) == SWT.SHIFT) {
getGui().getClassManager().closeCurrentInnerTab();
} else {
getGui().getClassManager().closeCurrentTab();
}
e.doit = false;
} else if (e.keyCode == 'f') {
getGui().getSearchPopup().open();
e.doit = false;
}
} else {
if (e.keyCode == SWT.F5) {
promptForRefresh();
e.doit = false;
}
}
}
}
public static LoadedFile getLoadedFile(String file) {
return files.get(file);
}
public static void submitBackgroundTask(Runnable runnable) {
getBackgroundTaskHandler().submit(runnable);
}
public static Collection<LoadedFile> getAllFiles() {
return Collections.unmodifiableCollection(files.values());
}
public static Map<String, byte[]> getAllLoadedData() {
Map<String, byte[]> data = new HashMap<>();
for (LoadedFile loadedFile : files.values()) {
data.putAll(loadedFile.getData());
}
return data;
}
public static BackgroundTaskHandler getBackgroundTaskHandler() {
return backgroundTaskHandler;
}
/*
These are to somewhat separate GUI and logic
*/
public static GUI getGui() {
return gui;
}
public static void setLocationOf(Settings setting) {
String temp = setting.get().asString();
String currentFile = temp == null || temp.isEmpty() ? System.getProperty("user.home") : temp;
List<File> files = FileChooserUtil.chooseFiles(currentFile, Collections.emptyList(), false);
if (!files.isEmpty()) {
setting.set(files.get(0).getAbsolutePath());
if (setting == Settings.PYTHON2_LOCATION) {
ensurePython2Set0(true);
} else if (setting == Settings.PYTHON3_LOCATION) {
ensurePython3Set0(true);
} else if (setting == Settings.RT_LOCATION) {
ensureJavaRtSet0(true);
}
}
}
} | src/main/java/com/samczsun/helios/Helios.java | /*
* Copyright 2015 Sam Sun <[email protected]>
*
* 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.samczsun.helios;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonValue;
import com.samczsun.helios.api.events.Events;
import com.samczsun.helios.api.events.requests.RecentFileRequest;
import com.samczsun.helios.api.events.requests.TreeUpdateRequest;
import com.samczsun.helios.bootloader.BootSequence;
import com.samczsun.helios.bootloader.Splash;
import com.samczsun.helios.gui.BackgroundTaskGui;
import com.samczsun.helios.gui.GUI;
import com.samczsun.helios.handler.BackgroundTaskHandler;
import com.samczsun.helios.handler.ExceptionHandler;
import com.samczsun.helios.handler.addons.AddonHandler;
import com.samczsun.helios.tasks.AddFilesTask;
import com.samczsun.helios.utils.FileChooserUtil;
import com.samczsun.helios.utils.SWTUtil;
import org.apache.commons.io.IOUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.objectweb.asm.tree.ClassNode;
import javax.swing.UIManager;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Helios {
private static final Map<String, LoadedFile> files = new HashMap<>();
private static final List<Process> processes = new ArrayList<>();
private static Boolean python2Verified = null;
private static Boolean python3Verified = null;
private static Boolean javaRtVerified = null;
private static GUI gui;
private static BackgroundTaskHandler backgroundTaskHandler;
private static BackgroundTaskGui backgroundTaskGui;
public static void main(String[] args, Shell shell, Splash splashScreen) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exception) { //Not important. No point notifying the user
}
splashScreen.updateState(BootSequence.LOADING_SETTINGS);
Settings.loadSettings();
backgroundTaskGui = new BackgroundTaskGui();
backgroundTaskHandler = new BackgroundTaskHandler();
splashScreen.updateState(BootSequence.LOADING_ADDONS);
AddonHandler.registerPreloadedAddons();
for (File file : Constants.ADDONS_DIR.listFiles()) {
AddonHandler
.getAllHandlers()
.stream()
.filter(handler -> handler.accept(file))
.findFirst()
.ifPresent(handler -> {
handler.run(file);
});
}
splashScreen.updateState(BootSequence.SETTING_UP_GUI);
gui = new GUI(shell);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
Settings.saveSettings();
getBackgroundTaskHandler().shutdown();
processes.forEach(Process::destroy);
}));
splashScreen.updateState(BootSequence.COMPLETE);
while (!splashScreen.isDisposed()) ;
Display.getDefault().syncExec(() -> getGui().getShell().open());
}
public static List<LoadedFile> getFilesForName(String fileName) {
return files
.values()
.stream()
.filter(loadedFile -> loadedFile.getFiles().containsKey(fileName))
.collect(Collectors.toList());
}
public static void loadFile(File fileToLoad) throws IOException {
LoadedFile loadedFile = new LoadedFile(fileToLoad);
files.put(loadedFile.getName(), loadedFile);
}
public static List<ClassNode> loadAllClasses() {
List<ClassNode> classNodes = new ArrayList<>();
for (LoadedFile loadedFile : files.values()) {
for (String s : loadedFile.getFiles().keySet()) {
ClassNode loaded = loadedFile.getClassNode(s);
if (loaded != null) {
classNodes.add(loaded);
}
}
}
return classNodes;
}
public static void openFiles(final File[] files, final boolean recentFiles) {
submitBackgroundTask(new AddFilesTask(files, recentFiles));
}
public static void resetWorkSpace(boolean ask) {
if (ask && !SWTUtil.promptForYesNo(Constants.REPO_NAME + " - New Workspace",
"You have not yet saved your workspace. Are you sure you wish to create a new one?")) {
return;
}
files.clear();
getGui().getTreeManager().reset();
getGui().getClassManager().reset();
processes.forEach(Process::destroyForcibly);
processes.clear();
}
public static Process launchProcess(ProcessBuilder launch) throws IOException {
Process process = launch.start();
processes.add(process);
submitBackgroundTask(() -> {
try {
process.waitFor();
if (!process.isAlive()) {
processes.remove(process);
}
} catch (InterruptedException e) {
ExceptionHandler.handle(e);
}
});
return process;
}
public static void addRecentFile(File f) {
if (!f.getAbsolutePath().isEmpty()) {
JsonArray array = Settings.RECENT_FILES.get().asArray();
array.add(f.getAbsolutePath());
while (array.size() > Settings.MAX_RECENTFILES.get().asInt()) {
array.remove(0);
}
updateRecentFiles();
}
}
public static void updateRecentFiles() {
Events.callEvent(new RecentFileRequest(Settings.RECENT_FILES
.get()
.asArray()
.values()
.stream()
.map(JsonValue::asString)
.collect(Collectors.toList())));
}
public static void promptForFilesToOpen() {
submitBackgroundTask(() -> {
List<String> validExtensions = Arrays.asList("jar", "zip", "class", "apk", "dex");
List<File> files1 = FileChooserUtil.chooseFiles(Settings.LAST_DIRECTORY.get().asString(), validExtensions,
true);
if (files1.size() > 0) {
Settings.LAST_DIRECTORY.set(files1.get(0).getAbsolutePath());
try {
Helios.openFiles(files1.toArray(new File[files1.size()]), true);
} catch (Exception e1) {
ExceptionHandler.handle(e1);
}
}
});
}
public static void promptForRefresh() {
if (SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Refresh", "Are you sure you wish to refresh?")) {
for (LoadedFile loadedFile : Helios.files.values()) {
try {
loadedFile.reset();
} catch (IOException e) {
ExceptionHandler.handle(e);
}
}
Events.callEvent(new TreeUpdateRequest());
}
}
public static void promptForCustomPath() {
Display.getDefault().asyncExec(() -> {
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
shell.setImage(Resources.ICON.getImage());
shell.setText("Set your PATH variable");
final Text text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.WRAP);
text.setText(Settings.PATH.get().asString());
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = text.getLineHeight();
gridData.widthHint = 512;
text.setLayoutData(gridData);
shell.addShellListener(new ShellAdapter() {
@Override
public void shellClosed(ShellEvent e) {
Settings.PATH.set(text.getText());
}
});
shell.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ESC) {
shell.close();
}
}
});
shell.pack();
SWTUtil.center(shell);
shell.open();
});
}
public static boolean ensurePython3Set() {
return ensurePython3Set0(false);
}
public static boolean ensurePython2Set() {
return ensurePython2Set0(false);
}
public static boolean ensureJavaRtSet() {
return ensureJavaRtSet0(false);
}
private static boolean ensurePython3Set0(boolean forceCheck) {
String python3Location = Settings.PYTHON3_LOCATION.get().asString();
if (python3Location.isEmpty()) {
SWTUtil.showMessage("You need to set the location of the Python/PyPy 3.x executable", true);
setLocationOf(Settings.PYTHON3_LOCATION);
python3Location = Settings.PYTHON3_LOCATION.get().asString();
}
if (python3Location.isEmpty()) {
return false;
}
if (python3Verified == null || forceCheck) {
try {
Process process = new ProcessBuilder(python3Location, "-V").start();
String result = IOUtils.toString(process.getInputStream());
String error = IOUtils.toString(process.getErrorStream());
python3Verified = error.startsWith("Python 3") || result.startsWith("Python 3");
} catch (Throwable t) {
t.printStackTrace();
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
SWTUtil.showMessage(
"The Python 3.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString());
python3Verified = false;
}
}
return python3Verified;
}
private static boolean ensurePython2Set0(boolean forceCheck) {
String python2Location = Settings.PYTHON2_LOCATION.get().asString();
if (python2Location.isEmpty()) {
SWTUtil.showMessage("You need to set the location of the Python/PyPy 2.x executable", true);
setLocationOf(Settings.PYTHON2_LOCATION);
python2Location = Settings.PYTHON2_LOCATION.get().asString();
}
if (python2Location.isEmpty()) {
return false;
}
if (python2Verified == null || forceCheck) {
try {
Process process = new ProcessBuilder(python2Location, "-V").start();
String result = IOUtils.toString(process.getInputStream());
String error = IOUtils.toString(process.getErrorStream());
python2Verified = error.startsWith("Python 2") || result.startsWith("Python 2");
} catch (Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
SWTUtil.showMessage(
"The Python 2.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString());
t.printStackTrace();
python2Verified = false;
}
}
return python2Verified;
}
private static boolean ensureJavaRtSet0(boolean forceCheck) {
String javaRtLocation = Settings.RT_LOCATION.get().asString();
if (javaRtLocation.isEmpty()) {
SWTUtil.showMessage("You need to set the location of Java's rt.jar", true);
setLocationOf(Settings.RT_LOCATION);
javaRtLocation = Settings.RT_LOCATION.get().asString();
}
if (javaRtLocation.isEmpty()) {
return false;
}
if (javaRtVerified == null || forceCheck) {
ZipFile zipFile = null;
try {
File rtjar = new File(javaRtLocation);
if (rtjar.exists()) {
zipFile = new ZipFile(rtjar);
ZipEntry object = zipFile.getEntry("java/lang/Object.class");
if (object != null) {
javaRtVerified = true;
}
}
} catch (Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
SWTUtil.showMessage(
"The selected Java rt.jar is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString());
t.printStackTrace();
javaRtVerified = false;
} finally {
IOUtils.closeQuietly(zipFile);
}
}
return javaRtVerified;
}
public static void checkHotKey(Event e) {
if (e.doit) {
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
if (e.keyCode == 'o') {
promptForFilesToOpen();
e.doit = false;
} else if (e.keyCode == 'n') {
resetWorkSpace(true);
e.doit = false;
} else if (e.keyCode == 't') {
getGui().getClassManager().handleNewTabRequest();
e.doit = false;
} else if (e.keyCode == 'w') {
if ((e.stateMask & SWT.SHIFT) == SWT.SHIFT) {
getGui().getClassManager().closeCurrentInnerTab();
} else {
getGui().getClassManager().closeCurrentTab();
}
e.doit = false;
} else if (e.keyCode == 'f') {
getGui().getSearchPopup().open();
e.doit = false;
}
} else {
if (e.keyCode == SWT.F5) {
promptForRefresh();
e.doit = false;
}
}
}
}
public static LoadedFile getLoadedFile(String file) {
return files.get(file);
}
public static void submitBackgroundTask(Runnable runnable) {
getBackgroundTaskHandler().submit(runnable);
}
public static Collection<LoadedFile> getAllFiles() {
return Collections.unmodifiableCollection(files.values());
}
public static Map<String, byte[]> getAllLoadedData() {
Map<String, byte[]> data = new HashMap<>();
for (LoadedFile loadedFile : files.values()) {
data.putAll(loadedFile.getData());
}
return data;
}
public static BackgroundTaskHandler getBackgroundTaskHandler() {
return backgroundTaskHandler;
}
/*
These are to somewhat separate GUI and logic
*/
public static GUI getGui() {
return gui;
}
public static void setLocationOf(Settings setting) {
String temp = setting.get().asString();
String currentFile = temp == null || temp.isEmpty() ? System.getProperty("user.home") : temp;
List<File> files = FileChooserUtil.chooseFiles(currentFile, Collections.emptyList(), false);
if (!files.isEmpty()) {
setting.set(files.get(0).getAbsolutePath());
if (setting == Settings.PYTHON2_LOCATION) {
ensurePython2Set0(true);
} else if (setting == Settings.PYTHON3_LOCATION) {
ensurePython3Set0(true);
} else if (setting == Settings.RT_LOCATION) {
ensureJavaRtSet0(true);
}
}
}
} | Fix #6
| src/main/java/com/samczsun/helios/Helios.java | Fix #6 | <ide><path>rc/main/java/com/samczsun/helios/Helios.java
<ide>
<ide> public static void main(String[] args, Shell shell, Splash splashScreen) {
<ide> try {
<del> UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
<add> if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
<add> UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
<add> }
<ide> } catch (Exception exception) { //Not important. No point notifying the user
<ide> }
<ide> splashScreen.updateState(BootSequence.LOADING_SETTINGS); |
|
Java | mit | 098d47e019ec9fd75e0ca325fc37b40b3f5457d0 | 0 | seanmonstar/ServiceDroid | package com.monstarlab.servicedroid.util;
import com.monstarlab.servicedroid.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.webkit.WebView;
public class Changelog {
//private static final int V_1_0 = 1;
//private static final int V_1_1 = 2;
private static final int V_1_2 = 3;
//private static final int V_1_2_1 = 4; //just bug fixes, no changelog needed
//private static final int V_1_2_2 = 5; //just bug fixes, no changelog needed
private static final int CURRENT_VERSION = V_1_2;
private static final String PREFS_NAME = "Changelog";
private static final String PREFS_CHANGELOG_VERSION = "lastSeenChangelogVersion";
public static void showFirstTime(final Context c) {
if (hasSeenMessage(c)) {
// do nothing
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(c);
final WebView webView = new WebView(c);
int title = R.string.whats_new;
builder.setTitle(title);
builder.setView(webView);
builder.setCancelable(false);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
markMessageSeen(c);
}
});
String message = getMessage(c);
if(TextUtils.isEmpty(message)) {
return;
}
webView.loadDataWithBaseURL(null, message, "text/html", "UTF-8", "about:blank");
builder.show();
}
}
/*private static int isNewOrUpdated(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
int lastVersion = settings.getInt(LAST_VERSION, -1);
return lastVersion == -1 ? STATUS_NEW : STATUS_UPDATED;
}*/
/*private static int getVersion(Context c) {
int versionCode = 0;
try {
//current version
PackageInfo packageInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
versionCode = packageInfo.versionCode;
} catch (NameNotFoundException e) {
//then just return 0
}
return versionCode;
}*/
private static boolean hasSeenMessage(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
return settings.getInt(PREFS_CHANGELOG_VERSION, 0) >= CURRENT_VERSION;
}
private static void markMessageSeen(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
Editor editor=settings.edit();
editor.putInt(PREFS_CHANGELOG_VERSION, CURRENT_VERSION);
editor.commit();
}
private static String getMessage(Context c) {
StringBuilder message = new StringBuilder();
String[] features = c.getResources().getStringArray(R.array.changelog);
message.append("<html><body>");
message.append("<b>v1.3</b>");
message.append("<ul>");
for(int i = 0; i < features.length; i++) {
message.append("<li>" + features[i] + "</li>");
}
message.append("</ul>");
message.append("<b>" + c.getString(R.string.enjoy_servicedroid) + "</b>");
message.append("<ul>");
message.append("<li>" + c.getString(R.string.give_review) + "</li>");
message.append("</ul>");
message.append("</body></html>");
return message.toString();
}
}
| src/com/monstarlab/servicedroid/util/Changelog.java | package com.monstarlab.servicedroid.util;
import com.monstarlab.servicedroid.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.webkit.WebView;
public class Changelog {
//private static final int V_1_0 = 1;
//private static final int V_1_1 = 2;
private static final int V_1_2 = 3;
//private static final int V_1_2_1 = 4; //just bug fixes, no changelog needed
//private static final int V_1_2_2 = 5; //just bug fixes, no changelog needed
private static final int CURRENT_VERSION = V_1_2;
private static final String PREFS_NAME = "Changelog";
private static final String PREFS_CHANGELOG_VERSION = "lastSeenChangelogVersion";
public static void showFirstTime(final Context c) {
if (hasSeenMessage(c)) {
// do nothing
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(c);
final WebView webView = new WebView(c);
int title = R.string.whats_new;
builder.setTitle(title);
builder.setView(webView);
builder.setCancelable(false);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
markMessageSeen(c);
}
});
String message = getMessage(c);
if(TextUtils.isEmpty(message)) {
return;
}
//builder.setMessage(message);
webView.loadData(message, "text/html", "utf-8");
builder.show();
}
}
/*private static int isNewOrUpdated(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
int lastVersion = settings.getInt(LAST_VERSION, -1);
return lastVersion == -1 ? STATUS_NEW : STATUS_UPDATED;
}*/
/*private static int getVersion(Context c) {
int versionCode = 0;
try {
//current version
PackageInfo packageInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
versionCode = packageInfo.versionCode;
} catch (NameNotFoundException e) {
//then just return 0
}
return versionCode;
}*/
private static boolean hasSeenMessage(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
return settings.getInt(PREFS_CHANGELOG_VERSION, 0) >= CURRENT_VERSION;
}
private static void markMessageSeen(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
Editor editor=settings.edit();
editor.putInt(PREFS_CHANGELOG_VERSION, CURRENT_VERSION);
editor.commit();
}
private static String getMessage(Context c) {
StringBuilder message = new StringBuilder();
String[] features = c.getResources().getStringArray(R.array.changelog);
message.append("<html><body>");
message.append("<b>v1.3</b>");
message.append("<ul>");
for(int i = 0; i < features.length; i++) {
message.append("<li>" + features[i] + "</li>");
}
message.append("</ul>");
message.append("<b>" + c.getString(R.string.enjoy_servicedroid) + "</b>");
message.append("<ul>");
message.append("<li>" + c.getString(R.string.give_review) + "</li>");
message.append("</ul>");
message.append("</body></html>");
return message.toString();
}
}
| fixes What's New encoding for extended ascii characters
| src/com/monstarlab/servicedroid/util/Changelog.java | fixes What's New encoding for extended ascii characters | <ide><path>rc/com/monstarlab/servicedroid/util/Changelog.java
<ide> return;
<ide> }
<ide>
<del> //builder.setMessage(message);
<del> webView.loadData(message, "text/html", "utf-8");
<add> webView.loadDataWithBaseURL(null, message, "text/html", "UTF-8", "about:blank");
<ide> builder.show();
<ide> }
<ide> } |
|
Java | mit | 9b63527d41f592cd6d64fedc79bf0a37c3aec70f | 0 | nsalminen/maze | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Window;
import Utilities.MazeKeyListener;
import Game.*;
import Sprites.*;
import UserInterface.ScoreBoard;
import UserInterface.StepCounter;
import Utilities.FileReaderWriter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.util.Map;
import java.util.Random;
/**
*
* @author Yasen
*/
public class GamePanel extends javax.swing.JPanel {
/**
* Creates new form MazePanelForm
*/
public FileReaderWriter frw;
public Goal goal;
public Player player;
public Maze maze;
public Cursor cursor;
public PortalGun portalGun;
public StepCounter counter;
public TimeMachine timeMachine;
public ScoreBoard scoreBoard;
public Map<String, Integer> highscores;
//The size of each block in pixels
public final int blockSize = 40;
public int[][] hardMaze = {
{1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1},
{0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1},
{0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0},
{0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1},
{1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1},
{1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1},
{1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1},
{0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1},
{1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1}};
public Helper helper;
private MainWindow parent;
public GamePanel(MainWindow p) {
initComponents();
parent = p;
this.setSize(hardMaze.length * blockSize, hardMaze.length * blockSize);
frw = new FileReaderWriter();
prepGame(getGraphics());
MazeKeyListener listener = new MazeKeyListener(this);
this.addKeyListener(listener);
this.setFocusable(true);
}
private int random() {
Random random = new Random();
return Math.abs(random.nextInt());
}
public void prepGame(Graphics g) {
maze = new Maze(hardMaze, this);
goal = new Goal((hardMaze.length-1), (hardMaze[0].length-1), this);
player = new Player(0, 0, this,getGraphics());
cursor = new Cursor(hardMaze[0].length-1, 0, this);
counter = new StepCounter((hardMaze.length*blockSize)+blockSize, 0 , this);
scoreBoard = new ScoreBoard((hardMaze.length*blockSize)+blockSize, 0 , this);
int porty;
int portx ;
//Collections.shuffle(maze.floors);
portx = maze.floors.get(random()% maze.floors.size()).yIndex;
porty = maze.floors.get(random()% maze.floors.size()).xIndex;
portalGun = new PortalGun(portx, porty, this);
portx = maze.floors.get(random() % maze.floors.size()).yIndex;
porty = maze.floors.get(random() % maze.floors.size()).xIndex;
timeMachine = new TimeMachine(portx, porty, this);
portx = maze.floors.get(random() % maze.floors.size()).yIndex;
porty = maze.floors.get(random() % maze.floors.size()).xIndex;
helper = new Helper(portx, porty, this);
}
/**
* Determines which action has to be executed after the user activated a
* key.
*
* @param key A variable that passes the key code of the active key
*/
public void updateGame(KeyEvent e) {
keyInput(e.getKeyCode());
repaint();
checkGoal();
//checkPortalGun();
}
public void gameOver() {
parent.gameOver();;
}
public void checkGoal() {
if (maze.nodes[goal.yIndex][goal.xIndex].popOccupant().getClass().getCanonicalName().equals("Sprites.Player")) {
gameOver();
}
}
public void keyInput(int key) {
switch (key) {
case KeyEvent.VK_W:
player.move('N');
break;
case KeyEvent.VK_D:
player.move('E');
break;
case KeyEvent.VK_S:
player.move('S');
break;
case KeyEvent.VK_A:
player.move('W');
break;
case KeyEvent.VK_SPACE:
player.shoot();
break;
case KeyEvent.VK_UP:
cursor.move('N');
break;
case KeyEvent.VK_RIGHT:
cursor.move('E');
break;
case KeyEvent.VK_DOWN:
cursor.move('S');
break;
case KeyEvent.VK_LEFT:
cursor.move('W');
break;
case KeyEvent.VK_CONTROL:
cursor.printCurrentNode();
}
}
@Override
public void repaint() {
super.repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
maze.paintMaze(g);
counter.drawSteps(g);
scoreBoard.drawBoard(g);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Maze/src/Window/GamePanel.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Window;
import Utilities.MazeKeyListener;
import Game.*;
import Sprites.*;
import UserInterface.ScoreBoard;
import UserInterface.StepCounter;
import Utilities.FileReaderWriter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.util.Map;
import java.util.Random;
/**
*
* @author Yasen
*/
public class GamePanel extends javax.swing.JPanel {
/**
* Creates new form MazePanelForm
*/
public FileReaderWriter frw;
public Goal goal;
public Player player;
public Maze maze;
public Cursor cursor;
public PortalGun portalGun;
public StepCounter counter;
public TimeMachine timeMachine;
public ScoreBoard scoreBoard;
public Map<String, Integer> highscores;
//The size of each block in pixels
public final int blockSize = 40;
public int[][] hardMaze = {
{1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1},
{0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1},
{0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0},
{0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1},
{1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1},
{1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1},
{1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1},
{0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1},
{1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1}};
private MainWindow parent;
public GamePanel(MainWindow p) {
initComponents();
parent = p;
this.setSize(hardMaze.length * blockSize, hardMaze.length * blockSize);
frw = new FileReaderWriter();
prepGame(getGraphics());
MazeKeyListener listener = new MazeKeyListener(this);
this.addKeyListener(listener);
this.setFocusable(true);
}
private int random() {
Random random = new Random();
return Math.abs(random.nextInt());
}
public void prepGame(Graphics g) {
maze = new Maze(hardMaze, this);
goal = new Goal((hardMaze.length-1), (hardMaze[0].length-1), this);
player = new Player(0, 0, this,getGraphics());
cursor = new Cursor(hardMaze[0].length-1, 0, this);
counter = new StepCounter((hardMaze.length*blockSize)+blockSize, 0 , this);
scoreBoard = new ScoreBoard((hardMaze.length*blockSize)+blockSize, 0 , this);
int porty;
int portx ;
//Collections.shuffle(maze.floors);
portx = maze.floors.get(random()% maze.floors.size()).yIndex;
porty = maze.floors.get(random()% maze.floors.size()).xIndex;
portalGun = new PortalGun(portx, porty, this);
portx = maze.floors.get(random() % maze.floors.size()).yIndex;
porty = maze.floors.get(random() % maze.floors.size()).xIndex;
timeMachine = new TimeMachine(portx, porty, this);
portx = maze.floors.get(random() % maze.floors.size()).yIndex;
porty = maze.floors.get(random() % maze.floors.size()).xIndex;
helper = new Helper(portx, porty, this);
}
/**
* Determines which action has to be executed after the user activated a
* key.
*
* @param key A variable that passes the key code of the active key
*/
public void updateGame(KeyEvent e) {
keyInput(e.getKeyCode());
repaint();
checkGoal();
//checkPortalGun();
}
public void gameOver() {
parent.gameOver();;
}
public void checkGoal() {
if (maze.nodes[goal.yIndex][goal.xIndex].popOccupant().getClass().getCanonicalName().equals("Sprites.Player")) {
gameOver();
}
}
public void keyInput(int key) {
switch (key) {
case KeyEvent.VK_W:
player.move('N');
break;
case KeyEvent.VK_D:
player.move('E');
break;
case KeyEvent.VK_S:
player.move('S');
break;
case KeyEvent.VK_A:
player.move('W');
break;
case KeyEvent.VK_SPACE:
player.shoot();
break;
case KeyEvent.VK_UP:
cursor.move('N');
break;
case KeyEvent.VK_RIGHT:
cursor.move('E');
break;
case KeyEvent.VK_DOWN:
cursor.move('S');
break;
case KeyEvent.VK_LEFT:
cursor.move('W');
break;
case KeyEvent.VK_CONTROL:
cursor.printCurrentNode();
}
}
@Override
public void repaint() {
super.repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
maze.paintMaze(g);
counter.drawSteps(g);
scoreBoard.drawBoard(g);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| ANd at long last the epic work of Nels and the exemplary code of Yasen was merged into a shining ball of awesome that for years to come would bring happinness to t he hearts of the people. | Maze/src/Window/GamePanel.java | ANd at long last the epic work of Nels and the exemplary code of Yasen was merged into a shining ball of awesome that for years to come would bring happinness to t he hearts of the people. | <ide><path>aze/src/Window/GamePanel.java
<ide> {1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1},
<ide> {1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1}};
<ide>
<add> public Helper helper;
<ide> private MainWindow parent;
<ide>
<ide> public GamePanel(MainWindow p) { |
|
Java | apache-2.0 | 9ec9217a76202cb4c97182de5cf34aa4a6bce0d5 | 0 | vadmeste/minio-java,minio/minio-java,balamurugana/minio-java | /*
* Minio Java Library for Amazon S3 Compatible Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.security.*;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.lang.*;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.io.*;
import org.xmlpull.v1.XmlPullParserException;
import org.joda.time.DateTime;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.Response;
import com.google.common.io.ByteStreams;
import io.minio.*;
import io.minio.messages.*;
import io.minio.errors.*;
public class FunctionalTest {
public static final int MB = 1024 * 1024;
public static final SecureRandom random = new SecureRandom();
public static final String bucketName = getRandomName();
public static String endpoint;
public static String accessKey;
public static String secretKey;
public static MinioClient client = null;
public static void println(Object ...args) {
boolean space = false;
if (args.length > 0) {
for (Object arg : args) {
if (space) {
System.out.print(" ");
}
System.out.print(arg.toString());
space = true;
}
}
System.out.println();
}
public static String createFile(int size) throws IOException {
String fileName = getRandomName();
byte[] data = new byte[size];
random.nextBytes(data);
OutputStream out = new BufferedOutputStream(Files.newOutputStream(Paths.get(fileName), CREATE, APPEND));
out.write(data, 0, data.length);
out.close();
return fileName;
}
public static String getRandomName() {
return "minio-java-test-" + new BigInteger(32, random).toString(32);
}
// Test: makeBucket(String bucketName)
public static void makeBucket_test1() throws Exception {
println("Test: makeBucket(String bucketName)");
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
}
// Test: makeBucket(String bucketName, String region)
public static void makeBucket_test2() throws Exception {
println("Test: makeBucket(String bucketName, String region)");
String name = getRandomName();
client.makeBucket(name, "eu-west-1");
client.removeBucket(name);
}
// Test: makeBucket(String bucketName, Acl acl)
public static void makeBucket_test3() throws Exception {
println("Test: makeBucket(String bucketName, Acl acl)");
String name = getRandomName();
client.makeBucket(name, Acl.PUBLIC_READ_WRITE);
client.removeBucket(name);
}
// Test: makeBucket(String bucketName, String region, Acl acl)
public static void makeBucket_test4() throws Exception {
println("Test: makeBucket(String bucketName, String region, Acl acl)");
String name = getRandomName();
client.makeBucket(name, "eu-west-1", Acl.PUBLIC_READ_WRITE);
client.removeBucket(name);
}
// Test: listBuckets()
public static void listBuckets_test() throws Exception {
println("Test: listBuckets()");
for (Bucket bucket : client.listBuckets()) {
println(bucket);
}
}
// Test: bucketExists(String bucketName)
public static void bucketExists_test() throws Exception {
println("Test: bucketExists(String bucketName)");
String name = getRandomName();
client.makeBucket(name);
if (!client.bucketExists(name)) {
println("FAILED");
}
client.removeBucket(name);
}
// Test: removeBucket(String bucketName)
public static void removeBucket_test() throws Exception {
println("Test: removeBucket(String bucketName)");
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
}
// Test: getBucketAcl(String bucketName)
public static void getBucketAcl_test() throws Exception {
println("Test: getBucketAcl(String bucketName)");
String name = getRandomName();
client.makeBucket(name, Acl.PRIVATE);
Acl acl = client.getBucketAcl(name);
if (acl != Acl.PRIVATE) {
println("FAILED.", "expected =", Acl.PRIVATE, "received =", acl);
}
client.removeBucket(name);
}
// Test: setBucketAcl(String bucketName, Acl acl)
public static void setBucketAcl_test() throws Exception {
println("Test: setBucketAcl(String bucketName, Acl acl)");
String name = getRandomName();
client.makeBucket(name);
client.setBucketAcl(name, Acl.PUBLIC_READ_WRITE);
client.removeBucket(name);
}
public static void setup() throws Exception {
client.makeBucket(bucketName);
}
public static void teardown() throws Exception {
client.removeBucket(bucketName);
}
// Test: putObject(String bucketName, String objectName, String fileName)
public static void putObject_test1() throws Exception {
println("Test: putObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: multipart: putObject(String bucketName, String objectName, String fileName)
public static void putObject_test2() throws Exception {
println("Test: multipart: putObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(13 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: multipart resume: putObject(String bucketName, String objectName, String fileName)
public static void putObject_test3() throws Exception {
println("Test: multipart resume: putObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(13 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 20 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)
public static void putObject_test4() throws Exception {
println("Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)");
String fileName = createFile(3 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
client.putObject(bucketName, fileName, is, 1024 * 1024, null);
is.close();
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: statObject(String bucketName, String objectName)
public static void statObject_test() throws Exception {
println("Test: statObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.statObject(bucketName, fileName);
client.removeObject(bucketName, fileName);
}
// Test: getObject(String bucketName, String objectName)
public static void getObject_test1() throws Exception {
println("Test: getObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
InputStream is = client.getObject(bucketName, fileName);
is.close();
client.removeObject(bucketName, fileName);
}
// Test: getObject(String bucketName, String objectName, long offset)
public static void getObject_test2() throws Exception {
println("Test: getObject(String bucketName, String objectName, long offset)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
InputStream is = client.getObject(bucketName, fileName, 1000L);
is.close();
client.removeObject(bucketName, fileName);
}
// Test: getObject(String bucketName, String objectName, long offset, Long length)
public static void getObject_test3() throws Exception {
println("Test: getObject(String bucketName, String objectName, long offset, Long length)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
InputStream is = client.getObject(bucketName, fileName, 1000L, 1024 * 1024L);
is.close();
client.removeObject(bucketName, fileName);
}
// Test: getObject(String bucketName, String objectName, String fileName)
public static void getObject_test4() throws Exception {
println("Test: getObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.getObject(bucketName, fileName, fileName + ".downloaded");
Files.delete(Paths.get(fileName + ".downloaded"));
client.removeObject(bucketName, fileName);
}
// Test: listObjects(final String bucketName)
public static void listObject_test1() throws Exception {
int i;
println("Test: listObjects(final String bucketName)");
String[] fileNames = new String[3];
for (i = 0; i < 3; i++) {
String fileName = createFile(1 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
fileNames[i] = fileName;
}
i = 0;
for (Result r : client.listObjects(bucketName)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
for (i = 0; i < 3; i++) {
client.removeObject(bucketName, fileNames[i]);
}
}
// Test: listObjects(bucketName, final String prefix)
public static void listObject_test2() throws Exception {
int i;
println("Test: listObjects(final String bucketName, final String prefix)");
String[] fileNames = new String[3];
for (i = 0; i < 3; i++) {
String fileName = createFile(1 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
fileNames[i] = fileName;
}
i = 0;
for (Result r : client.listObjects(bucketName, "minio")) {
println(i++, r.get());
if (i == 10) {
break;
}
}
for (i = 0; i < 3; i++) {
client.removeObject(bucketName, fileNames[i]);
}
}
// Test: listObjects(bucketName, final String prefix, final boolean recursive)
public static void listObject_test3() throws Exception {
int i;
println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)");
String[] fileNames = new String[3];
for (i = 0; i < 3; i++) {
String fileName = createFile(1 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
fileNames[i] = fileName;
}
i = 0;
for (Result r : client.listObjects(bucketName, "minio", true)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
for (i = 0; i < 3; i++) {
client.removeObject(bucketName, fileNames[i]);
}
}
// Test: removeObject(String bucketName, String objectName)
public static void removeObject_test() throws Exception {
println("Test: removeObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: listIncompleteUploads(String bucketName)
public static void listIncompleteUploads_test1() throws Exception {
println("Test: listIncompleteUploads(String bucketName)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
}
// Test: listIncompleteUploads(String bucketName, String prefix)
public static void listIncompleteUploads_test2() throws Exception {
println("Test: listIncompleteUploads(String bucketName, String prefix)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
}
// Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)
public static void listIncompleteUploads_test3() throws Exception {
println("Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
}
// Test: removeIncompleteUpload(String bucketName, String objectName)
public static void removeIncompleteUploads_test() throws Exception {
println("Test: removeIncompleteUpload(String bucketName, String objectName)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
}
// public String presignedGetObject(String bucketName, String objectName)
public static void presignedGetObject_test1() throws Exception {
println("Test: presignedGetObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
String urlString = client.presignedGetObject(bucketName, fileName);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("GET", null)
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (response.isSuccessful()) {
OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
ByteStreams.copy(response.body().byteStream(), os);
response.body().close();
os.close();
} else {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
println("CONTENT DIFFERS");
}
Files.delete(Paths.get(fileName));
Files.delete(Paths.get(fileName + ".downloaded"));
client.removeObject(bucketName, fileName);
}
// Test: presignedGetObject(String bucketName, String objectName, Integer expires)
public static void presignedGetObject_test2() throws Exception {
println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
String urlString = client.presignedGetObject(bucketName, fileName, 3600);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("GET", null)
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (response.isSuccessful()) {
OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
ByteStreams.copy(response.body().byteStream(), os);
response.body().close();
os.close();
} else {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
println("CONTENT DIFFERS");
}
Files.delete(Paths.get(fileName));
Files.delete(Paths.get(fileName + ".downloaded"));
client.removeObject(bucketName, fileName);
}
// public String presignedPutObject(String bucketName, String objectName)
public static void presignedPutObject_test1() throws Exception {
println("Test: presignedPutObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
String urlString = client.presignedPutObject(bucketName, fileName);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (!response.isSuccessful()) {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: presignedPutObject(String bucketName, String objectName, Integer expires)
public static void presignedPutObject_test2() throws Exception {
println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
String fileName = createFile(3 * MB);
String urlString = client.presignedPutObject(bucketName, fileName, 3600);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (!response.isSuccessful()) {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
// Test: presignedPostPolicy(PostPolicy policy)
public static void presignedPostPolicy_test() throws Exception {
println("Test: presignedPostPolicy(PostPolicy policy)");
String fileName = createFile(3 * MB);
PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
Map<String, String> formData = client.presignedPostPolicy(policy);
MultipartBuilder multipartBuilder = new MultipartBuilder();
multipartBuilder.type(MultipartBuilder.FORM);
for (Map.Entry<String, String> entry : formData.entrySet()) {
multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (!response.isSuccessful()) {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
}
public static void main(String[] args) {
if (args.length != 3) {
println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY>");
return;
}
endpoint = args[0];
accessKey = args[1];
secretKey = args[2];
try {
client = new MinioClient(endpoint, accessKey, secretKey);
makeBucket_test1();
// makeBucket_test2(); - throws exception due to Amazon S3 region issue
makeBucket_test3();
// makeBucket_test4(); - throws exception due to Amazon S3 region issue
listBuckets_test();
bucketExists_test();
removeBucket_test();
getBucketAcl_test();
setBucketAcl_test();
setup();
putObject_test1();
putObject_test2();
putObject_test3();
putObject_test4();
statObject_test();
getObject_test1();
getObject_test2();
getObject_test3();
getObject_test4();
listObject_test1();
listObject_test2();
listObject_test3();
removeObject_test();
listIncompleteUploads_test1();
listIncompleteUploads_test2();
listIncompleteUploads_test3();
removeIncompleteUploads_test();
presignedGetObject_test1();
presignedGetObject_test2();
presignedPutObject_test1();
presignedPutObject_test2();
presignedPostPolicy_test();
teardown();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
| test/FunctionalTest.java | /*
* Minio Java Library for Amazon S3 Compatible Cloud Storage, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.security.*;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.lang.*;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.io.*;
import org.xmlpull.v1.XmlPullParserException;
import org.joda.time.DateTime;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.Response;
import com.google.common.io.ByteStreams;
import io.minio.*;
import io.minio.messages.*;
import io.minio.errors.*;
public class FunctionalTest {
public static final int MB = 1024 * 1024;
public static final SecureRandom random = new SecureRandom();
public static final String bucketName = getRandomName();
public static String endpoint;
public static String accessKey;
public static String secretKey;
public static MinioClient client = null;
public static void println(Object ...args) {
boolean space = false;
if (args.length > 0) {
for (Object arg : args) {
if (space) {
System.out.print(" ");
}
System.out.print(arg.toString());
space = true;
}
}
System.out.println();
}
public static String createFile(int size) throws IOException {
String fileName = getRandomName();
byte[] data = new byte[size];
random.nextBytes(data);
OutputStream out = new BufferedOutputStream(Files.newOutputStream(Paths.get(fileName), CREATE, APPEND));
out.write(data, 0, data.length);
out.close();
return fileName;
}
public static String getRandomName() {
return "minio-java-test-" + new BigInteger(32, random).toString(32);
}
// Test: makeBucket(String bucketName)
public static void makeBucket_test1() {
try {
println("Test: makeBucket(String bucketName)");
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: makeBucket(String bucketName, String region)
public static void makeBucket_test2() {
try {
println("Test: makeBucket(String bucketName, String region)");
String name = getRandomName();
client.makeBucket(name, "eu-west-1");
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: makeBucket(String bucketName, Acl acl)
public static void makeBucket_test3() {
try {
println("Test: makeBucket(String bucketName, Acl acl)");
String name = getRandomName();
client.makeBucket(name, Acl.PUBLIC_READ_WRITE);
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: makeBucket(String bucketName, String region, Acl acl)
public static void makeBucket_test4() {
try {
println("Test: makeBucket(String bucketName, String region, Acl acl)");
String name = getRandomName();
client.makeBucket(name, "eu-west-1", Acl.PUBLIC_READ_WRITE);
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listBuckets()
public static void listBuckets_test() {
try {
println("Test: listBuckets()");
for (Bucket bucket : client.listBuckets()) {
println(bucket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: bucketExists(String bucketName)
public static void bucketExists_test() {
try {
println("Test: bucketExists(String bucketName)");
String name = getRandomName();
client.makeBucket(name);
if (!client.bucketExists(name)) {
println("FAILED");
}
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: removeBucket(String bucketName)
public static void removeBucket_test() {
try {
println("Test: removeBucket(String bucketName)");
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: getBucketAcl(String bucketName)
public static void getBucketAcl_test() {
try {
println("Test: getBucketAcl(String bucketName)");
String name = getRandomName();
client.makeBucket(name, Acl.PRIVATE);
Acl acl = client.getBucketAcl(name);
if (acl != Acl.PRIVATE) {
println("FAILED.", "expected =", Acl.PRIVATE, "received =", acl);
}
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: setBucketAcl(String bucketName, Acl acl)
public static void setBucketAcl_test() {
try {
println("Test: setBucketAcl(String bucketName, Acl acl)");
String name = getRandomName();
client.makeBucket(name);
client.setBucketAcl(name, Acl.PUBLIC_READ_WRITE);
client.removeBucket(name);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setup() {
try {
client.makeBucket(bucketName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void teardown() {
try {
client.removeBucket(bucketName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: putObject(String bucketName, String objectName, String fileName)
public static void putObject_test1() {
try {
println("Test: putObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: multipart: putObject(String bucketName, String objectName, String fileName)
public static void putObject_test2() {
try {
println("Test: multipart: putObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(13 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: multipart resume: putObject(String bucketName, String objectName, String fileName)
public static void putObject_test3() {
try {
println("Test: multipart resume: putObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(13 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 20 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)
public static void putObject_test4() {
try {
println("Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)");
String fileName = createFile(3 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
client.putObject(bucketName, fileName, is, 1024 * 1024, null);
is.close();
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: statObject(String bucketName, String objectName)
public static void statObject_test() {
try {
println("Test: statObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.statObject(bucketName, fileName);
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: getObject(String bucketName, String objectName)
public static void getObject_test1() {
try {
println("Test: getObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
InputStream is = client.getObject(bucketName, fileName);
is.close();
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: getObject(String bucketName, String objectName, long offset)
public static void getObject_test2() {
try {
println("Test: getObject(String bucketName, String objectName, long offset)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
InputStream is = client.getObject(bucketName, fileName, 1000L);
is.close();
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: getObject(String bucketName, String objectName, long offset, Long length)
public static void getObject_test3() {
try {
println("Test: getObject(String bucketName, String objectName, long offset, Long length)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
InputStream is = client.getObject(bucketName, fileName, 1000L, 1024 * 1024L);
is.close();
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: getObject(String bucketName, String objectName, String fileName)
public static void getObject_test4() {
try {
println("Test: getObject(String bucketName, String objectName, String fileName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.getObject(bucketName, fileName, fileName + ".downloaded");
Files.delete(Paths.get(fileName + ".downloaded"));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listObjects(final String bucketName)
public static void listObject_test1() {
try {
int i;
println("Test: listObjects(final String bucketName)");
String[] fileNames = new String[3];
for (i = 0; i < 3; i++) {
String fileName = createFile(1 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
fileNames[i] = fileName;
}
i = 0;
for (Result r : client.listObjects(bucketName)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
for (i = 0; i < 3; i++) {
client.removeObject(bucketName, fileNames[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listObjects(bucketName, final String prefix)
public static void listObject_test2() {
try {
int i;
println("Test: listObjects(final String bucketName, final String prefix)");
String[] fileNames = new String[3];
for (i = 0; i < 3; i++) {
String fileName = createFile(1 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
fileNames[i] = fileName;
}
i = 0;
for (Result r : client.listObjects(bucketName, "minio")) {
println(i++, r.get());
if (i == 10) {
break;
}
}
for (i = 0; i < 3; i++) {
client.removeObject(bucketName, fileNames[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listObjects(bucketName, final String prefix, final boolean recursive)
public static void listObject_test3() {
try {
int i;
println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)");
String[] fileNames = new String[3];
for (i = 0; i < 3; i++) {
String fileName = createFile(1 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
fileNames[i] = fileName;
}
i = 0;
for (Result r : client.listObjects(bucketName, "minio", true)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
for (i = 0; i < 3; i++) {
client.removeObject(bucketName, fileNames[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: removeObject(String bucketName, String objectName)
public static void removeObject_test() {
try {
println("Test: removeObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listIncompleteUploads(String bucketName)
public static void listIncompleteUploads_test1() {
try {
println("Test: listIncompleteUploads(String bucketName)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listIncompleteUploads(String bucketName, String prefix)
public static void listIncompleteUploads_test2() {
try {
println("Test: listIncompleteUploads(String bucketName, String prefix)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)
public static void listIncompleteUploads_test3() {
try {
println("Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: removeIncompleteUpload(String bucketName, String objectName)
public static void removeIncompleteUploads_test() {
try {
println("Test: removeIncompleteUpload(String bucketName, String objectName)");
String fileName = createFile(6 * MB);
InputStream is = Files.newInputStream(Paths.get(fileName));
try {
client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
} catch (InsufficientDataException e) {
}
is.close();
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
println(i++, r.get());
if (i == 10) {
break;
}
}
Files.delete(Paths.get(fileName));
client.removeIncompleteUpload(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// public String presignedGetObject(String bucketName, String objectName)
public static void presignedGetObject_test1() {
try {
println("Test: presignedGetObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
String urlString = client.presignedGetObject(bucketName, fileName);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("GET", null)
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (response.isSuccessful()) {
OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
ByteStreams.copy(response.body().byteStream(), os);
response.body().close();
os.close();
} else {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
println("CONTENT DIFFERS");
}
Files.delete(Paths.get(fileName));
Files.delete(Paths.get(fileName + ".downloaded"));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: presignedGetObject(String bucketName, String objectName, Integer expires)
public static void presignedGetObject_test2() {
try {
println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
String fileName = createFile(3 * MB);
client.putObject(bucketName, fileName, fileName);
String urlString = client.presignedGetObject(bucketName, fileName, 3600);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("GET", null)
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (response.isSuccessful()) {
OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
ByteStreams.copy(response.body().byteStream(), os);
response.body().close();
os.close();
} else {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
println("CONTENT DIFFERS");
}
Files.delete(Paths.get(fileName));
Files.delete(Paths.get(fileName + ".downloaded"));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// public String presignedPutObject(String bucketName, String objectName)
public static void presignedPutObject_test1() {
try {
println("Test: presignedPutObject(String bucketName, String objectName)");
String fileName = createFile(3 * MB);
String urlString = client.presignedPutObject(bucketName, fileName);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (!response.isSuccessful()) {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: presignedPutObject(String bucketName, String objectName, Integer expires)
public static void presignedPutObject_test2() {
try {
println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
String fileName = createFile(3 * MB);
String urlString = client.presignedPutObject(bucketName, fileName, 3600);
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (!response.isSuccessful()) {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
// Test: presignedPostPolicy(PostPolicy policy)
public static void presignedPostPolicy_test() {
try {
println("Test: presignedPostPolicy(PostPolicy policy)");
String fileName = createFile(3 * MB);
PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
Map<String, String> formData = client.presignedPostPolicy(policy);
MultipartBuilder multipartBuilder = new MultipartBuilder();
multipartBuilder.type(MultipartBuilder.FORM);
for (Map.Entry<String, String> entry : formData.entrySet()) {
multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response != null) {
if (!response.isSuccessful()) {
println("FAILED");
}
} else {
println("NO RESPONSE");
}
Files.delete(Paths.get(fileName));
client.removeObject(bucketName, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 3) {
println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY>");
return;
}
endpoint = args[0];
accessKey = args[1];
secretKey = args[2];
try {
client = new MinioClient(endpoint, accessKey, secretKey);
} catch (Exception e) {
e.printStackTrace();
return;
}
makeBucket_test1();
// makeBucket_test2(); - throws exception due to Amazon S3 region issue
makeBucket_test3();
// makeBucket_test4(); - throws exception due to Amazon S3 region issue
listBuckets_test();
bucketExists_test();
removeBucket_test();
getBucketAcl_test();
setBucketAcl_test();
setup();
putObject_test1();
putObject_test2();
putObject_test3();
putObject_test4();
statObject_test();
getObject_test1();
getObject_test2();
getObject_test3();
getObject_test4();
listObject_test1();
listObject_test2();
listObject_test3();
removeObject_test();
listIncompleteUploads_test1();
listIncompleteUploads_test2();
listIncompleteUploads_test3();
removeIncompleteUploads_test();
presignedGetObject_test1();
presignedGetObject_test2();
presignedPutObject_test1();
presignedPutObject_test2();
presignedPostPolicy_test();
teardown();
}
}
| fix functional test to stop execution other tests on failure.
| test/FunctionalTest.java | fix functional test to stop execution other tests on failure. | <ide><path>est/FunctionalTest.java
<ide>
<ide>
<ide> // Test: makeBucket(String bucketName)
<del> public static void makeBucket_test1() {
<add> public static void makeBucket_test1() throws Exception {
<add> println("Test: makeBucket(String bucketName)");
<add> String name = getRandomName();
<add> client.makeBucket(name);
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: makeBucket(String bucketName, String region)
<add> public static void makeBucket_test2() throws Exception {
<add> println("Test: makeBucket(String bucketName, String region)");
<add> String name = getRandomName();
<add> client.makeBucket(name, "eu-west-1");
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: makeBucket(String bucketName, Acl acl)
<add> public static void makeBucket_test3() throws Exception {
<add> println("Test: makeBucket(String bucketName, Acl acl)");
<add> String name = getRandomName();
<add> client.makeBucket(name, Acl.PUBLIC_READ_WRITE);
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: makeBucket(String bucketName, String region, Acl acl)
<add> public static void makeBucket_test4() throws Exception {
<add> println("Test: makeBucket(String bucketName, String region, Acl acl)");
<add> String name = getRandomName();
<add> client.makeBucket(name, "eu-west-1", Acl.PUBLIC_READ_WRITE);
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: listBuckets()
<add> public static void listBuckets_test() throws Exception {
<add> println("Test: listBuckets()");
<add> for (Bucket bucket : client.listBuckets()) {
<add> println(bucket);
<add> }
<add> }
<add>
<add>
<add> // Test: bucketExists(String bucketName)
<add> public static void bucketExists_test() throws Exception {
<add> println("Test: bucketExists(String bucketName)");
<add> String name = getRandomName();
<add> client.makeBucket(name);
<add> if (!client.bucketExists(name)) {
<add> println("FAILED");
<add> }
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: removeBucket(String bucketName)
<add> public static void removeBucket_test() throws Exception {
<add> println("Test: removeBucket(String bucketName)");
<add> String name = getRandomName();
<add> client.makeBucket(name);
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: getBucketAcl(String bucketName)
<add> public static void getBucketAcl_test() throws Exception {
<add> println("Test: getBucketAcl(String bucketName)");
<add> String name = getRandomName();
<add> client.makeBucket(name, Acl.PRIVATE);
<add> Acl acl = client.getBucketAcl(name);
<add> if (acl != Acl.PRIVATE) {
<add> println("FAILED.", "expected =", Acl.PRIVATE, "received =", acl);
<add> }
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> // Test: setBucketAcl(String bucketName, Acl acl)
<add> public static void setBucketAcl_test() throws Exception {
<add> println("Test: setBucketAcl(String bucketName, Acl acl)");
<add> String name = getRandomName();
<add> client.makeBucket(name);
<add> client.setBucketAcl(name, Acl.PUBLIC_READ_WRITE);
<add> client.removeBucket(name);
<add> }
<add>
<add>
<add> public static void setup() throws Exception {
<add> client.makeBucket(bucketName);
<add> }
<add>
<add>
<add> public static void teardown() throws Exception {
<add> client.removeBucket(bucketName);
<add> }
<add>
<add>
<add> // Test: putObject(String bucketName, String objectName, String fileName)
<add> public static void putObject_test1() throws Exception {
<add> println("Test: putObject(String bucketName, String objectName, String fileName)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: multipart: putObject(String bucketName, String objectName, String fileName)
<add> public static void putObject_test2() throws Exception {
<add> println("Test: multipart: putObject(String bucketName, String objectName, String fileName)");
<add> String fileName = createFile(13 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: multipart resume: putObject(String bucketName, String objectName, String fileName)
<add> public static void putObject_test3() throws Exception {
<add> println("Test: multipart resume: putObject(String bucketName, String objectName, String fileName)");
<add> String fileName = createFile(13 * MB);
<add> InputStream is = Files.newInputStream(Paths.get(fileName));
<ide> try {
<del> println("Test: makeBucket(String bucketName)");
<del> String name = getRandomName();
<del> client.makeBucket(name);
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: makeBucket(String bucketName, String region)
<del> public static void makeBucket_test2() {
<del> try {
<del> println("Test: makeBucket(String bucketName, String region)");
<del> String name = getRandomName();
<del> client.makeBucket(name, "eu-west-1");
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: makeBucket(String bucketName, Acl acl)
<del> public static void makeBucket_test3() {
<del> try {
<del> println("Test: makeBucket(String bucketName, Acl acl)");
<del> String name = getRandomName();
<del> client.makeBucket(name, Acl.PUBLIC_READ_WRITE);
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: makeBucket(String bucketName, String region, Acl acl)
<del> public static void makeBucket_test4() {
<del> try {
<del> println("Test: makeBucket(String bucketName, String region, Acl acl)");
<del> String name = getRandomName();
<del> client.makeBucket(name, "eu-west-1", Acl.PUBLIC_READ_WRITE);
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listBuckets()
<del> public static void listBuckets_test() {
<del> try {
<del> println("Test: listBuckets()");
<del> for (Bucket bucket : client.listBuckets()) {
<del> println(bucket);
<del> }
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: bucketExists(String bucketName)
<del> public static void bucketExists_test() {
<del> try {
<del> println("Test: bucketExists(String bucketName)");
<del> String name = getRandomName();
<del> client.makeBucket(name);
<del> if (!client.bucketExists(name)) {
<del> println("FAILED");
<del> }
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: removeBucket(String bucketName)
<del> public static void removeBucket_test() {
<del> try {
<del> println("Test: removeBucket(String bucketName)");
<del> String name = getRandomName();
<del> client.makeBucket(name);
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: getBucketAcl(String bucketName)
<del> public static void getBucketAcl_test() {
<del> try {
<del> println("Test: getBucketAcl(String bucketName)");
<del> String name = getRandomName();
<del> client.makeBucket(name, Acl.PRIVATE);
<del> Acl acl = client.getBucketAcl(name);
<del> if (acl != Acl.PRIVATE) {
<del> println("FAILED.", "expected =", Acl.PRIVATE, "received =", acl);
<del> }
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: setBucketAcl(String bucketName, Acl acl)
<del> public static void setBucketAcl_test() {
<del> try {
<del> println("Test: setBucketAcl(String bucketName, Acl acl)");
<del> String name = getRandomName();
<del> client.makeBucket(name);
<del> client.setBucketAcl(name, Acl.PUBLIC_READ_WRITE);
<del> client.removeBucket(name);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> public static void setup() {
<del> try {
<del> client.makeBucket(bucketName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> public static void teardown() {
<del> try {
<del> client.removeBucket(bucketName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: putObject(String bucketName, String objectName, String fileName)
<del> public static void putObject_test1() {
<del> try {
<del> println("Test: putObject(String bucketName, String objectName, String fileName)");
<del> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, is, 20 * 1024 * 1024, null);
<add> } catch (InsufficientDataException e) {
<add> }
<add> is.close();
<add>
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)
<add> public static void putObject_test4() throws Exception {
<add> println("Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)");
<add> String fileName = createFile(3 * MB);
<add> InputStream is = Files.newInputStream(Paths.get(fileName));
<add> client.putObject(bucketName, fileName, is, 1024 * 1024, null);
<add> is.close();
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: statObject(String bucketName, String objectName)
<add> public static void statObject_test() throws Exception {
<add> println("Test: statObject(String bucketName, String objectName)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> client.statObject(bucketName, fileName);
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: getObject(String bucketName, String objectName)
<add> public static void getObject_test1() throws Exception {
<add> println("Test: getObject(String bucketName, String objectName)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> InputStream is = client.getObject(bucketName, fileName);
<add> is.close();
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: getObject(String bucketName, String objectName, long offset)
<add> public static void getObject_test2() throws Exception {
<add> println("Test: getObject(String bucketName, String objectName, long offset)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> InputStream is = client.getObject(bucketName, fileName, 1000L);
<add> is.close();
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: getObject(String bucketName, String objectName, long offset, Long length)
<add> public static void getObject_test3() throws Exception {
<add> println("Test: getObject(String bucketName, String objectName, long offset, Long length)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> InputStream is = client.getObject(bucketName, fileName, 1000L, 1024 * 1024L);
<add> is.close();
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: getObject(String bucketName, String objectName, String fileName)
<add> public static void getObject_test4() throws Exception {
<add> println("Test: getObject(String bucketName, String objectName, String fileName)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> client.getObject(bucketName, fileName, fileName + ".downloaded");
<add> Files.delete(Paths.get(fileName + ".downloaded"));
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: listObjects(final String bucketName)
<add> public static void listObject_test1() throws Exception {
<add> int i;
<add> println("Test: listObjects(final String bucketName)");
<add> String[] fileNames = new String[3];
<add> for (i = 0; i < 3; i++) {
<add> String fileName = createFile(1 * MB);
<ide> client.putObject(bucketName, fileName, fileName);
<ide> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: multipart: putObject(String bucketName, String objectName, String fileName)
<del> public static void putObject_test2() {
<del> try {
<del> println("Test: multipart: putObject(String bucketName, String objectName, String fileName)");
<del> String fileName = createFile(13 * MB);
<add> fileNames[i] = fileName;
<add> }
<add>
<add> i = 0;
<add> for (Result r : client.listObjects(bucketName)) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> for (i = 0; i < 3; i++) {
<add> client.removeObject(bucketName, fileNames[i]);
<add> }
<add> }
<add>
<add>
<add> // Test: listObjects(bucketName, final String prefix)
<add> public static void listObject_test2() throws Exception {
<add> int i;
<add> println("Test: listObjects(final String bucketName, final String prefix)");
<add> String[] fileNames = new String[3];
<add> for (i = 0; i < 3; i++) {
<add> String fileName = createFile(1 * MB);
<ide> client.putObject(bucketName, fileName, fileName);
<ide> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: multipart resume: putObject(String bucketName, String objectName, String fileName)
<del> public static void putObject_test3() {
<del> try {
<del> println("Test: multipart resume: putObject(String bucketName, String objectName, String fileName)");
<del> String fileName = createFile(13 * MB);
<del> InputStream is = Files.newInputStream(Paths.get(fileName));
<del> try {
<del> client.putObject(bucketName, fileName, is, 20 * 1024 * 1024, null);
<del> } catch (InsufficientDataException e) {
<del> }
<del> is.close();
<del>
<add> fileNames[i] = fileName;
<add> }
<add>
<add> i = 0;
<add> for (Result r : client.listObjects(bucketName, "minio")) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> for (i = 0; i < 3; i++) {
<add> client.removeObject(bucketName, fileNames[i]);
<add> }
<add> }
<add>
<add>
<add> // Test: listObjects(bucketName, final String prefix, final boolean recursive)
<add> public static void listObject_test3() throws Exception {
<add> int i;
<add> println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)");
<add> String[] fileNames = new String[3];
<add> for (i = 0; i < 3; i++) {
<add> String fileName = createFile(1 * MB);
<ide> client.putObject(bucketName, fileName, fileName);
<ide> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)
<del> public static void putObject_test4() {
<add> fileNames[i] = fileName;
<add> }
<add>
<add> i = 0;
<add> for (Result r : client.listObjects(bucketName, "minio", true)) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> for (i = 0; i < 3; i++) {
<add> client.removeObject(bucketName, fileNames[i]);
<add> }
<add> }
<add>
<add>
<add> // Test: removeObject(String bucketName, String objectName)
<add> public static void removeObject_test() throws Exception {
<add> println("Test: removeObject(String bucketName, String objectName)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: listIncompleteUploads(String bucketName)
<add> public static void listIncompleteUploads_test1() throws Exception {
<add> println("Test: listIncompleteUploads(String bucketName)");
<add> String fileName = createFile(6 * MB);
<add> InputStream is = Files.newInputStream(Paths.get(fileName));
<ide> try {
<del> println("Test: putObject(String bucketName, String objectName, String contentType, long size, InputStream body)");
<del> String fileName = createFile(3 * MB);
<del> InputStream is = Files.newInputStream(Paths.get(fileName));
<del> client.putObject(bucketName, fileName, is, 1024 * 1024, null);
<del> is.close();
<del> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: statObject(String bucketName, String objectName)
<del> public static void statObject_test() {
<add> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<add> } catch (InsufficientDataException e) {
<add> }
<add> is.close();
<add>
<add> int i = 0;
<add> for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeIncompleteUpload(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: listIncompleteUploads(String bucketName, String prefix)
<add> public static void listIncompleteUploads_test2() throws Exception {
<add> println("Test: listIncompleteUploads(String bucketName, String prefix)");
<add> String fileName = createFile(6 * MB);
<add> InputStream is = Files.newInputStream(Paths.get(fileName));
<ide> try {
<del> println("Test: statObject(String bucketName, String objectName)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> client.statObject(bucketName, fileName);
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: getObject(String bucketName, String objectName)
<del> public static void getObject_test1() {
<add> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<add> } catch (InsufficientDataException e) {
<add> }
<add> is.close();
<add>
<add> int i = 0;
<add> for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeIncompleteUpload(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)
<add> public static void listIncompleteUploads_test3() throws Exception {
<add> println("Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)");
<add> String fileName = createFile(6 * MB);
<add> InputStream is = Files.newInputStream(Paths.get(fileName));
<ide> try {
<del> println("Test: getObject(String bucketName, String objectName)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> InputStream is = client.getObject(bucketName, fileName);
<del> is.close();
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: getObject(String bucketName, String objectName, long offset)
<del> public static void getObject_test2() {
<add> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<add> } catch (InsufficientDataException e) {
<add> }
<add> is.close();
<add>
<add> int i = 0;
<add> for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeIncompleteUpload(bucketName, fileName);
<add> }
<add>
<add>
<add> // Test: removeIncompleteUpload(String bucketName, String objectName)
<add> public static void removeIncompleteUploads_test() throws Exception {
<add> println("Test: removeIncompleteUpload(String bucketName, String objectName)");
<add> String fileName = createFile(6 * MB);
<add> InputStream is = Files.newInputStream(Paths.get(fileName));
<ide> try {
<del> println("Test: getObject(String bucketName, String objectName, long offset)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> InputStream is = client.getObject(bucketName, fileName, 1000L);
<del> is.close();
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: getObject(String bucketName, String objectName, long offset, Long length)
<del> public static void getObject_test3() {
<del> try {
<del> println("Test: getObject(String bucketName, String objectName, long offset, Long length)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> InputStream is = client.getObject(bucketName, fileName, 1000L, 1024 * 1024L);
<del> is.close();
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: getObject(String bucketName, String objectName, String fileName)
<del> public static void getObject_test4() {
<del> try {
<del> println("Test: getObject(String bucketName, String objectName, String fileName)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> client.getObject(bucketName, fileName, fileName + ".downloaded");
<del> Files.delete(Paths.get(fileName + ".downloaded"));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listObjects(final String bucketName)
<del> public static void listObject_test1() {
<del> try {
<del> int i;
<del> println("Test: listObjects(final String bucketName)");
<del> String[] fileNames = new String[3];
<del> for (i = 0; i < 3; i++) {
<del> String fileName = createFile(1 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> fileNames[i] = fileName;
<del> }
<del>
<del> i = 0;
<del> for (Result r : client.listObjects(bucketName)) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> for (i = 0; i < 3; i++) {
<del> client.removeObject(bucketName, fileNames[i]);
<del> }
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listObjects(bucketName, final String prefix)
<del> public static void listObject_test2() {
<del> try {
<del> int i;
<del> println("Test: listObjects(final String bucketName, final String prefix)");
<del> String[] fileNames = new String[3];
<del> for (i = 0; i < 3; i++) {
<del> String fileName = createFile(1 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> fileNames[i] = fileName;
<del> }
<del>
<del> i = 0;
<del> for (Result r : client.listObjects(bucketName, "minio")) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> for (i = 0; i < 3; i++) {
<del> client.removeObject(bucketName, fileNames[i]);
<del> }
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listObjects(bucketName, final String prefix, final boolean recursive)
<del> public static void listObject_test3() {
<del> try {
<del> int i;
<del> println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)");
<del> String[] fileNames = new String[3];
<del> for (i = 0; i < 3; i++) {
<del> String fileName = createFile(1 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> fileNames[i] = fileName;
<del> }
<del>
<del> i = 0;
<del> for (Result r : client.listObjects(bucketName, "minio", true)) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> for (i = 0; i < 3; i++) {
<del> client.removeObject(bucketName, fileNames[i]);
<del> }
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: removeObject(String bucketName, String objectName)
<del> public static void removeObject_test() {
<del> try {
<del> println("Test: removeObject(String bucketName, String objectName)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listIncompleteUploads(String bucketName)
<del> public static void listIncompleteUploads_test1() {
<del> try {
<del> println("Test: listIncompleteUploads(String bucketName)");
<del> String fileName = createFile(6 * MB);
<del> InputStream is = Files.newInputStream(Paths.get(fileName));
<del> try {
<del> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<del> } catch (InsufficientDataException e) {
<del> }
<del> is.close();
<del>
<del> int i = 0;
<del> for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeIncompleteUpload(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listIncompleteUploads(String bucketName, String prefix)
<del> public static void listIncompleteUploads_test2() {
<del> try {
<del> println("Test: listIncompleteUploads(String bucketName, String prefix)");
<del> String fileName = createFile(6 * MB);
<del> InputStream is = Files.newInputStream(Paths.get(fileName));
<del> try {
<del> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<del> } catch (InsufficientDataException e) {
<del> }
<del> is.close();
<del>
<del> int i = 0;
<del> for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeIncompleteUpload(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)
<del> public static void listIncompleteUploads_test3() {
<del> try {
<del> println("Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)");
<del> String fileName = createFile(6 * MB);
<del> InputStream is = Files.newInputStream(Paths.get(fileName));
<del> try {
<del> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<del> } catch (InsufficientDataException e) {
<del> }
<del> is.close();
<del>
<del> int i = 0;
<del> for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeIncompleteUpload(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<del> }
<del>
<del>
<del> // Test: removeIncompleteUpload(String bucketName, String objectName)
<del> public static void removeIncompleteUploads_test() {
<del> try {
<del> println("Test: removeIncompleteUpload(String bucketName, String objectName)");
<del> String fileName = createFile(6 * MB);
<del> InputStream is = Files.newInputStream(Paths.get(fileName));
<del> try {
<del> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<del> } catch (InsufficientDataException e) {
<del> }
<del> is.close();
<del>
<del> int i = 0;
<del> for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
<del> println(i++, r.get());
<del> if (i == 10) {
<del> break;
<del> }
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeIncompleteUpload(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> client.putObject(bucketName, fileName, is, 9 * 1024 * 1024, null);
<add> } catch (InsufficientDataException e) {
<add> }
<add> is.close();
<add>
<add> int i = 0;
<add> for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
<add> println(i++, r.get());
<add> if (i == 10) {
<add> break;
<add> }
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeIncompleteUpload(bucketName, fileName);
<ide> }
<ide>
<ide>
<ide> // public String presignedGetObject(String bucketName, String objectName)
<del> public static void presignedGetObject_test1() {
<del> try {
<del> println("Test: presignedGetObject(String bucketName, String objectName)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del>
<del> String urlString = client.presignedGetObject(bucketName, fileName);
<del> Request.Builder requestBuilder = new Request.Builder();
<del> Request request = requestBuilder
<del> .url(HttpUrl.parse(urlString))
<del> .method("GET", null)
<del> .build();
<del> OkHttpClient transport = new OkHttpClient();
<del> Response response = transport.newCall(request).execute();
<del>
<del> if (response != null) {
<del> if (response.isSuccessful()) {
<del> OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
<del> ByteStreams.copy(response.body().byteStream(), os);
<del> response.body().close();
<del> os.close();
<del> } else {
<del> println("FAILED");
<del> }
<add> public static void presignedGetObject_test1() throws Exception {
<add> println("Test: presignedGetObject(String bucketName, String objectName)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add>
<add> String urlString = client.presignedGetObject(bucketName, fileName);
<add> Request.Builder requestBuilder = new Request.Builder();
<add> Request request = requestBuilder
<add> .url(HttpUrl.parse(urlString))
<add> .method("GET", null)
<add> .build();
<add> OkHttpClient transport = new OkHttpClient();
<add> Response response = transport.newCall(request).execute();
<add>
<add> if (response != null) {
<add> if (response.isSuccessful()) {
<add> OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
<add> ByteStreams.copy(response.body().byteStream(), os);
<add> response.body().close();
<add> os.close();
<ide> } else {
<del> println("NO RESPONSE");
<del> }
<del>
<del> if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
<del> Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
<del> println("CONTENT DIFFERS");
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> Files.delete(Paths.get(fileName + ".downloaded"));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> println("FAILED");
<add> }
<add> } else {
<add> println("NO RESPONSE");
<add> }
<add>
<add> if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
<add> Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
<add> println("CONTENT DIFFERS");
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> Files.delete(Paths.get(fileName + ".downloaded"));
<add> client.removeObject(bucketName, fileName);
<ide> }
<ide>
<ide> // Test: presignedGetObject(String bucketName, String objectName, Integer expires)
<del> public static void presignedGetObject_test2() {
<del> try {
<del> println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
<del> String fileName = createFile(3 * MB);
<del> client.putObject(bucketName, fileName, fileName);
<del>
<del> String urlString = client.presignedGetObject(bucketName, fileName, 3600);
<del> Request.Builder requestBuilder = new Request.Builder();
<del> Request request = requestBuilder
<del> .url(HttpUrl.parse(urlString))
<del> .method("GET", null)
<del> .build();
<del> OkHttpClient transport = new OkHttpClient();
<del> Response response = transport.newCall(request).execute();
<del>
<del> if (response != null) {
<del> if (response.isSuccessful()) {
<del> OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
<del> ByteStreams.copy(response.body().byteStream(), os);
<del> response.body().close();
<del> os.close();
<del> } else {
<del> println("FAILED");
<del> }
<add> public static void presignedGetObject_test2() throws Exception {
<add> println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
<add> String fileName = createFile(3 * MB);
<add> client.putObject(bucketName, fileName, fileName);
<add>
<add> String urlString = client.presignedGetObject(bucketName, fileName, 3600);
<add> Request.Builder requestBuilder = new Request.Builder();
<add> Request request = requestBuilder
<add> .url(HttpUrl.parse(urlString))
<add> .method("GET", null)
<add> .build();
<add> OkHttpClient transport = new OkHttpClient();
<add> Response response = transport.newCall(request).execute();
<add>
<add> if (response != null) {
<add> if (response.isSuccessful()) {
<add> OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE);
<add> ByteStreams.copy(response.body().byteStream(), os);
<add> response.body().close();
<add> os.close();
<ide> } else {
<del> println("NO RESPONSE");
<del> }
<del>
<del> if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
<del> Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
<del> println("CONTENT DIFFERS");
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> Files.delete(Paths.get(fileName + ".downloaded"));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> println("FAILED");
<add> }
<add> } else {
<add> println("NO RESPONSE");
<add> }
<add>
<add> if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
<add> Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
<add> println("CONTENT DIFFERS");
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> Files.delete(Paths.get(fileName + ".downloaded"));
<add> client.removeObject(bucketName, fileName);
<ide> }
<ide>
<ide>
<ide> // public String presignedPutObject(String bucketName, String objectName)
<del> public static void presignedPutObject_test1() {
<del> try {
<del> println("Test: presignedPutObject(String bucketName, String objectName)");
<del> String fileName = createFile(3 * MB);
<del> String urlString = client.presignedPutObject(bucketName, fileName);
<del>
<del> Request.Builder requestBuilder = new Request.Builder();
<del> Request request = requestBuilder
<del> .url(HttpUrl.parse(urlString))
<del> .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
<del> .build();
<del> OkHttpClient transport = new OkHttpClient();
<del> Response response = transport.newCall(request).execute();
<del>
<del> if (response != null) {
<del> if (!response.isSuccessful()) {
<del> println("FAILED");
<del> }
<del> } else {
<del> println("NO RESPONSE");
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> public static void presignedPutObject_test1() throws Exception {
<add> println("Test: presignedPutObject(String bucketName, String objectName)");
<add> String fileName = createFile(3 * MB);
<add> String urlString = client.presignedPutObject(bucketName, fileName);
<add>
<add> Request.Builder requestBuilder = new Request.Builder();
<add> Request request = requestBuilder
<add> .url(HttpUrl.parse(urlString))
<add> .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
<add> .build();
<add> OkHttpClient transport = new OkHttpClient();
<add> Response response = transport.newCall(request).execute();
<add>
<add> if (response != null) {
<add> if (!response.isSuccessful()) {
<add> println("FAILED");
<add> }
<add> } else {
<add> println("NO RESPONSE");
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<ide> }
<ide>
<ide>
<ide> // Test: presignedPutObject(String bucketName, String objectName, Integer expires)
<del> public static void presignedPutObject_test2() {
<del> try {
<del> println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
<del> String fileName = createFile(3 * MB);
<del> String urlString = client.presignedPutObject(bucketName, fileName, 3600);
<del>
<del> Request.Builder requestBuilder = new Request.Builder();
<del> Request request = requestBuilder
<del> .url(HttpUrl.parse(urlString))
<del> .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
<del> .build();
<del> OkHttpClient transport = new OkHttpClient();
<del> Response response = transport.newCall(request).execute();
<del>
<del> if (response != null) {
<del> if (!response.isSuccessful()) {
<del> println("FAILED");
<del> }
<del> } else {
<del> println("NO RESPONSE");
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> public static void presignedPutObject_test2() throws Exception {
<add> println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
<add> String fileName = createFile(3 * MB);
<add> String urlString = client.presignedPutObject(bucketName, fileName, 3600);
<add>
<add> Request.Builder requestBuilder = new Request.Builder();
<add> Request request = requestBuilder
<add> .url(HttpUrl.parse(urlString))
<add> .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName))))
<add> .build();
<add> OkHttpClient transport = new OkHttpClient();
<add> Response response = transport.newCall(request).execute();
<add>
<add> if (response != null) {
<add> if (!response.isSuccessful()) {
<add> println("FAILED");
<add> }
<add> } else {
<add> println("NO RESPONSE");
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<ide> }
<ide>
<ide>
<ide> // Test: presignedPostPolicy(PostPolicy policy)
<del> public static void presignedPostPolicy_test() {
<del> try {
<del> println("Test: presignedPostPolicy(PostPolicy policy)");
<del> String fileName = createFile(3 * MB);
<del> PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
<del> Map<String, String> formData = client.presignedPostPolicy(policy);
<del>
<del> MultipartBuilder multipartBuilder = new MultipartBuilder();
<del> multipartBuilder.type(MultipartBuilder.FORM);
<del> for (Map.Entry<String, String> entry : formData.entrySet()) {
<del> multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
<del> }
<del> multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));
<del>
<del> Request.Builder requestBuilder = new Request.Builder();
<del> Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
<del> OkHttpClient transport = new OkHttpClient();
<del> Response response = transport.newCall(request).execute();
<del>
<del> if (response != null) {
<del> if (!response.isSuccessful()) {
<del> println("FAILED");
<del> }
<del> } else {
<del> println("NO RESPONSE");
<del> }
<del>
<del> Files.delete(Paths.get(fileName));
<del> client.removeObject(bucketName, fileName);
<del> } catch (Exception e) {
<del> e.printStackTrace();
<del> }
<add> public static void presignedPostPolicy_test() throws Exception {
<add> println("Test: presignedPostPolicy(PostPolicy policy)");
<add> String fileName = createFile(3 * MB);
<add> PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
<add> Map<String, String> formData = client.presignedPostPolicy(policy);
<add>
<add> MultipartBuilder multipartBuilder = new MultipartBuilder();
<add> multipartBuilder.type(MultipartBuilder.FORM);
<add> for (Map.Entry<String, String> entry : formData.entrySet()) {
<add> multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
<add> }
<add> multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));
<add>
<add> Request.Builder requestBuilder = new Request.Builder();
<add> Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
<add> OkHttpClient transport = new OkHttpClient();
<add> Response response = transport.newCall(request).execute();
<add>
<add> if (response != null) {
<add> if (!response.isSuccessful()) {
<add> println("FAILED");
<add> }
<add> } else {
<add> println("NO RESPONSE");
<add> }
<add>
<add> Files.delete(Paths.get(fileName));
<add> client.removeObject(bucketName, fileName);
<ide> }
<ide>
<ide>
<ide>
<ide> try {
<ide> client = new MinioClient(endpoint, accessKey, secretKey);
<add>
<add> makeBucket_test1();
<add> // makeBucket_test2(); - throws exception due to Amazon S3 region issue
<add> makeBucket_test3();
<add> // makeBucket_test4(); - throws exception due to Amazon S3 region issue
<add>
<add> listBuckets_test();
<add>
<add> bucketExists_test();
<add>
<add> removeBucket_test();
<add>
<add> getBucketAcl_test();
<add>
<add> setBucketAcl_test();
<add>
<add> setup();
<add>
<add> putObject_test1();
<add> putObject_test2();
<add> putObject_test3();
<add> putObject_test4();
<add>
<add> statObject_test();
<add>
<add> getObject_test1();
<add> getObject_test2();
<add> getObject_test3();
<add> getObject_test4();
<add>
<add> listObject_test1();
<add> listObject_test2();
<add> listObject_test3();
<add>
<add> removeObject_test();
<add>
<add> listIncompleteUploads_test1();
<add> listIncompleteUploads_test2();
<add> listIncompleteUploads_test3();
<add>
<add> removeIncompleteUploads_test();
<add>
<add> presignedGetObject_test1();
<add> presignedGetObject_test2();
<add>
<add> presignedPutObject_test1();
<add> presignedPutObject_test2();
<add>
<add> presignedPostPolicy_test();
<add>
<add> teardown();
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> return;
<ide> }
<del>
<del> makeBucket_test1();
<del> // makeBucket_test2(); - throws exception due to Amazon S3 region issue
<del> makeBucket_test3();
<del> // makeBucket_test4(); - throws exception due to Amazon S3 region issue
<del>
<del> listBuckets_test();
<del>
<del> bucketExists_test();
<del>
<del> removeBucket_test();
<del>
<del> getBucketAcl_test();
<del>
<del> setBucketAcl_test();
<del>
<del> setup();
<del>
<del> putObject_test1();
<del> putObject_test2();
<del> putObject_test3();
<del> putObject_test4();
<del>
<del> statObject_test();
<del>
<del> getObject_test1();
<del> getObject_test2();
<del> getObject_test3();
<del> getObject_test4();
<del>
<del> listObject_test1();
<del> listObject_test2();
<del> listObject_test3();
<del>
<del> removeObject_test();
<del>
<del> listIncompleteUploads_test1();
<del> listIncompleteUploads_test2();
<del> listIncompleteUploads_test3();
<del>
<del> removeIncompleteUploads_test();
<del>
<del> presignedGetObject_test1();
<del> presignedGetObject_test2();
<del>
<del> presignedPutObject_test1();
<del> presignedPutObject_test2();
<del>
<del> presignedPostPolicy_test();
<del>
<del> teardown();
<ide> }
<ide> } |
|
Java | apache-2.0 | 662ec418650e048c26a68269fe001004cc7cc833 | 0 | permazen/permazen,archiecobbs/jsimpledb,archiecobbs/jsimpledb,tempbottle/jsimpledb,archiecobbs/jsimpledb,tempbottle/jsimpledb,tempbottle/jsimpledb,permazen/permazen,permazen/permazen |
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.schema;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.dellroad.stuff.graph.TopologicalSorter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles the initialization and schema maintenance of a database.
*
* <p>
* In this class, a <b>database</b> is some stateful object whose structure and/or content may need to change over time.
* <b>Updates</b> are uniquely named objects capable of making such changes. Databases are also capable of storing the
* names of the already-applied updates.
*
* <p>
* Given a database and a set of current updates, this class will ensure that a database is initialized if necessary
* and up-to-date with respect to the updates.
*
* <p>
* The primary method is {@link #initializeAndUpdateDatabase initializeAndUpdateDatabase()}, which will:
* <ul>
* <li>Initialize an {@linkplain #databaseNeedsInitialization empty} database (if necessary);</li>
* <li>Apply any outstanding {@link SchemaUpdate}s as needed, ordered properly according to
* their {@linkplain SchemaUpdate#getRequiredPredecessors predecessor constraints}; and</li>
* <li>Keep track of which {@link SchemaUpdate}s have already been applied across restarts.</li>
* </ul>
* </p>
*
* @param <D> database type
* @param <T> database transaction type
*/
public abstract class AbstractSchemaUpdater<D, T> {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
private Collection<? extends SchemaUpdate<T>> updates;
private boolean ignoreUnrecognizedUpdates;
/**
* Get the configured updates. This property is required.
*
* @return configured updates
* @see #setUpdates setUpdates()
*/
public Collection<? extends SchemaUpdate<T>> getUpdates() {
return this.updates;
}
/**
* Configure the updates.
* This should be the set of all updates that may need to be applied to the database.
*
* <p>
* For any given application, ideally this set should be "write only" in the sense that once an update is added to the set
* and applied to one or more actual databases, the update and its name should thereafter never change. Otherwise,
* it would be possible for different databases to have inconsistent schemas even though the same updates were recorded.
*
* <p>
* Furthermore, if not configured to {@linkplain #setIgnoreUnrecognizedUpdates ignore unrecognized updates already applied}
* (the default behavior), then updates must never be removed from this set as the application evolves;
* see {@link #setIgnoreUnrecognizedUpdates} for more information on the rationale.
*
* @param updates all updates; each update must have a unique {@link SchemaUpdate#getName name}.
* @see #getUpdates
* @see #setIgnoreUnrecognizedUpdates
*/
public void setUpdates(Collection<? extends SchemaUpdate<T>> updates) {
this.updates = updates;
}
/**
* Determine whether unrecognized updates are ignored or cause an exception.
*
* @return true if unrecognized updates should be ignored, false if they should cause an exception to be thrown
* @see #setIgnoreUnrecognizedUpdates setIgnoreUnrecognizedUpdates()
*/
public boolean isIgnoreUnrecognizedUpdates() {
return this.ignoreUnrecognizedUpdates;
}
/**
* Configure behavior when an unknown update is registered as having already been applied in the database.
*
* <p>
* The default behavior is <code>false</code>, which results in an exception being thrown. This protects against
* accidental downgrades (i.e., running older code against a database with a newer schema), which are not supported.
* However, this also requires that all updates that might ever possibly have been applied to the database be
* present in the set of configured updates.
*
* <p>
* Setting this to <code>true</code> will result in unrecognized updates simply being ignored.
* This setting loses the downgrade protection but allows obsolete schema updates to be dropped over time.
*
* @param ignoreUnrecognizedUpdates whether to ignore unrecognized updates
* @see #isIgnoreUnrecognizedUpdates
*/
public void setIgnoreUnrecognizedUpdates(boolean ignoreUnrecognizedUpdates) {
this.ignoreUnrecognizedUpdates = ignoreUnrecognizedUpdates;
}
/**
* Perform database schema initialization and updates.
*
* <p>
* This method applies the following logic: if the {@linkplain #databaseNeedsInitialization database needs initialization},
* then {@linkplain #initializeDatabase initialize the database} and {@linkplain #recordUpdateApplied record} each update
* as having been applied; otherwise, {@linkplain #apply apply} any {@linkplain #getAppliedUpdateNames unapplied updates}
* as needed.
*
* <p>
* Note this implies the database initialization must initialize the database to its current, up-to-date state
* (with respect to the set of all available updates), not its original, pre-update state.
*
* <p>
* The database initialization step, and each of the update steps, is {@linkplain #applyInTransaction performed within
* its own transaction}.
*
* @param database the database to initialize (if necessary) and update
* @return true if successful, false if database initialization was needed but could not be applied for some reason
* (database dependent: database not started, etc.)
* @throws Exception if an update fails
* @throws IllegalStateException if this instance is not configured to {@linkplain #setIgnoreUnrecognizedUpdates ignore
* unrecognized updates} and an unrecognized update has already been applied
* @throws IllegalArgumentException if two configured updates have the same name
* @throws IllegalArgumentException if any configured update has a required predecessor which is not also a configured update
* (i.e., if the updates are not transitively closed under predecessors)
*/
public synchronized boolean initializeAndUpdateDatabase(final D database) throws Exception {
// Log
this.log.info("verifying database " + database);
// First, initialize if necessary
final boolean[] initialized = new boolean[1];
this.applyInTransaction(database, new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
// Already initialized?
if (!AbstractSchemaUpdater.this.databaseNeedsInitialization(transaction)) {
AbstractSchemaUpdater.this.log.debug("detected already-initialized database " + database);
initialized[0] = true;
return;
}
// Initialize database
AbstractSchemaUpdater.this.log.info("uninitialized database detected; initializing " + database);
initialized[0] = AbstractSchemaUpdater.this.initializeDatabase(transaction);
if (!initialized[0])
return;
// Record all schema updates as having already been applied
for (String updateName : AbstractSchemaUpdater.this.getAllUpdateNames())
AbstractSchemaUpdater.this.recordUpdateApplied(transaction, updateName);
}
});
// Was database initialized?
if (!initialized[0]) {
this.log.info("database verification aborted because database was not initialized: " + database);
return false;
}
// Next, apply any new updates
this.applySchemaUpdates(database);
// Done
this.log.info("database verification completed for " + database);
return true;
}
/**
* Determine if the given schema update name is valid. Valid names are non-empty and
* have no leading or trailing whitespace.
*/
public static boolean isValidUpdateName(String updateName) {
return updateName.length() > 0 && updateName.trim().length() == updateName.length();
}
/**
* Determine if the database needs initialization.
*
* <p>
* If so, {@link #initializeDatabase} will eventually be invoked.
*
* @param transaction open transaction
* @throws Exception if an error occurs while accessing the database
*/
protected abstract boolean databaseNeedsInitialization(T transaction) throws Exception;
/**
* Initialize an uninitialized database. This should create and initialize the database schema and content,
* including whatever portion of that is used to track schema updates.
*
* @param transaction open transaction
* @return true if database was initialized, false otherwise
* @throws Exception if an error occurs while accessing the database
*/
protected abstract boolean initializeDatabase(T transaction) throws Exception;
/**
* Begin a transaction on the given database.
* The transaction will always eventually either be
* {@linkplain #commitTransaction committed} or {@linkplain #rollbackTransaction rolled back}.
*
* @param database database
* @return transaction handle
* @throws Exception if an error occurs while accessing the database
*/
protected abstract T openTransaction(D database) throws Exception;
/**
* Commit a previously opened transaction.
*
* @param transaction open transaction previously returned from {@link #openTransaction openTransaction()}
* @throws Exception if an error occurs while accessing the database
*/
protected abstract void commitTransaction(T transaction) throws Exception;
/**
* Roll back a previously opened transaction.
* This method will also be invoked if {@link #commitTransaction commitTransaction()} throws an exception.
*
* @param transaction open transaction previously returned from {@link #openTransaction openTransaction()}
* @throws Exception if an error occurs while accessing the database
*/
protected abstract void rollbackTransaction(T transaction) throws Exception;
/**
* Determine which updates have already been applied to the database.
*
* @param transaction open transaction
* @throws Exception if an error occurs while accessing the database
*/
protected abstract Set<String> getAppliedUpdateNames(T transaction) throws Exception;
/**
* Record an update as having been applied to the database.
*
* @param transaction open transaction
* @param name update name
* @throws IllegalStateException if the update has already been recorded in the database
* @throws Exception if an error occurs while accessing the database
*/
protected abstract void recordUpdateApplied(T transaction, String name) throws Exception;
/**
* Determine the preferred ordering of two updates that do not have any predecessor constraints
* (including implied indirect constraints) between them.
*
* <p>
* The {@link Comparator} returned by the implementation in {@link AbstractSchemaUpdater} simply sorts updates by name.
* Subclasses may override if necessary.
*
* @return a {@link Comparator} that sorts incomparable updates in the order they should be applied
*/
protected Comparator<SchemaUpdate<T>> getOrderingTieBreaker() {
return new UpdateByNameComparator();
}
/**
* Generate the update name for one action within a multi-action update.
*
* <p>
* The implementation in {@link AbstractSchemaUpdater} just adds a suffix using {@code index + 1}, padded to
* 5 digits, producing names like {@code name-00001}, {@code name-00002}, etc.
*
* @param update the schema update
* @param index the index of the action (zero based)
* @see SchemaUpdate#isSingleAction
*/
protected String generateMultiUpdateName(SchemaUpdate<T> update, int index) {
return String.format("%s-%05d", update.getName(), index + 1);
}
/**
* Get the names of all updates including multi-action updates.
*/
protected List<String> getAllUpdateNames() throws Exception {
ArrayList<SchemaUpdate<T>> updateList = new ArrayList<SchemaUpdate<T>>(this.getUpdates());
ArrayList<String> updateNameList = new ArrayList<String>(updateList.size());
Collections.sort(updateList, new UpdateByNameComparator());
for (SchemaUpdate<T> update : updateList)
updateNameList.addAll(this.getUpdateNames(update));
return updateNameList;
}
/**
* Execute a database action within an existing transaction.
*
* <p>
* All database operations in {@link AbstractSchemaUpdater} are performed via this method;
* subclasses are encouraged to follow this pattern.
*
* <p>
* The implementation in {@link AbstractSchemaUpdater} simply invokes {@link DatabaseAction#apply action.apply()};
* subclasses may override if desired.
*
* @throws Exception if an error occurs while accessing the database
*/
protected void apply(T transaction, DatabaseAction<T> action) throws Exception {
action.apply(transaction);
}
/**
* Execute a database action. A new transaction will be created, used, and closed.
* Delegates to {@link #apply apply()} for the actual execution of the action.
*
* <p>
* If the action or {@link #commitTransaction commitTransaction()} fails, the transaction
* is {@linkplain #rollbackTransaction rolled back}.
*
* @throws Exception if an error occurs while accessing the database
*/
protected void applyInTransaction(D database, DatabaseAction<T> action) throws Exception {
T transaction = this.openTransaction(database);
boolean success = false;
try {
this.apply(transaction, action);
this.commitTransaction(transaction);
success = true;
} finally {
if (!success)
this.rollbackTransaction(transaction);
}
}
/**
* Apply schema updates to an initialized database.
*/
private void applySchemaUpdates(D database) throws Exception {
// Sanity check
final HashSet<SchemaUpdate<T>> allUpdates = new HashSet<SchemaUpdate<T>>(this.getUpdates());
if (allUpdates == null)
throw new IllegalArgumentException("no updates configured");
// Create mapping from update name to update; multiple updates will have multiple names
TreeMap<String, SchemaUpdate<T>> updateMap = new TreeMap<String, SchemaUpdate<T>>();
for (SchemaUpdate<T> update : allUpdates) {
for (String updateName : this.getUpdateNames(update)) {
if (!isValidUpdateName(updateName))
throw new IllegalArgumentException("illegal schema update name `" + updateName + "'");
if (updateMap.put(updateName, update) != null)
throw new IllegalArgumentException("duplicate schema update name `" + updateName + "'");
}
}
this.log.debug("these are all known schema updates: " + updateMap.keySet());
// Verify updates are transitively closed under predecessor constraints
for (SchemaUpdate<T> update : allUpdates) {
for (SchemaUpdate<T> predecessor : update.getRequiredPredecessors()) {
if (!allUpdates.contains(predecessor)) {
throw new IllegalArgumentException("schema update `" + update.getName()
+ "' has a required predecessor named `" + predecessor.getName() + "' that is not a configured update");
}
}
}
// Sort updates in the order we should to apply them
List<SchemaUpdate<T>> updateList = new TopologicalSorter<SchemaUpdate<T>>(allUpdates,
new SchemaUpdateEdgeLister<T>(), this.getOrderingTieBreaker()).sortEdgesReversed();
// Determine which updates have already been applied
final HashSet<String> appliedUpdateNames = new HashSet<String>();
this.applyInTransaction(database, new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
appliedUpdateNames.addAll(AbstractSchemaUpdater.this.getAppliedUpdateNames(transaction));
}
});
this.log.debug("these are the already-applied schema updates: " + appliedUpdateNames);
// Check whether any unknown updates have been applied
TreeSet<String> unknownUpdateNames = new TreeSet<String>(appliedUpdateNames);
unknownUpdateNames.removeAll(updateMap.keySet());
if (!unknownUpdateNames.isEmpty()) {
if (!this.isIgnoreUnrecognizedUpdates()) {
throw new IllegalStateException(unknownUpdateNames.size()
+ " unrecognized update(s) have already been applied: " + unknownUpdateNames);
}
this.log.info("ignoring " + unknownUpdateNames.size()
+ " unrecognized update(s) already applied: " + unknownUpdateNames);
}
// Remove the already-applied updates
updateMap.keySet().removeAll(appliedUpdateNames);
HashSet<SchemaUpdate<T>> remainingUpdates = new HashSet<SchemaUpdate<T>>(updateMap.values());
for (Iterator<SchemaUpdate<T>> i = updateList.iterator(); i.hasNext(); ) {
if (!remainingUpdates.contains(i.next()))
i.remove();
}
// Now are any updates needed?
if (updateList.isEmpty()) {
this.log.info("no schema updates are required");
return;
}
// Log which updates we're going to apply
final LinkedHashSet<String> remainingUpdateNames = new LinkedHashSet<String>(updateMap.size());
for (SchemaUpdate<T> update : updateList) {
ArrayList<String> updateNames = this.getUpdateNames(update);
updateNames.removeAll(appliedUpdateNames);
remainingUpdateNames.addAll(updateNames);
}
this.log.info("applying " + remainingUpdateNames.size() + " schema update(s): " + remainingUpdateNames);
// Apply and record each unapplied update
for (SchemaUpdate<T> nextUpdate : updateList) {
final RecordingUpdateHandler updateHandler = new RecordingUpdateHandler(nextUpdate, remainingUpdateNames);
this.applyInTransaction(database, new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
updateHandler.process(transaction);
}
});
}
}
// Get all update names, expanding multi-updates as necessary
private ArrayList<String> getUpdateNames(SchemaUpdate<T> update) throws Exception {
final ArrayList<String> names = new ArrayList<String>();
UpdateHandler updateHandler = new UpdateHandler(update) {
@Override
protected void handleSingleUpdate(T transaction, DatabaseAction<T> action) {
names.add(this.update.getName());
}
@Override
protected void handleMultiUpdate(T transaction, DatabaseAction<T> action, int index) {
names.add(AbstractSchemaUpdater.this.generateMultiUpdateName(this.update, index));
}
};
updateHandler.process(null);
return names;
}
// Apply and record an update, all within a single transaction
private void applyAndRecordUpdate(T transaction, String name, final DatabaseAction<T> action) throws Exception {
if (action != null) {
this.log.info("applying schema update `" + name + "'");
this.apply(transaction, action);
} else
this.log.info("recording empty schema update `" + name + "'");
this.recordUpdateApplied(transaction, name);
}
private class RecordingUpdateHandler extends UpdateHandler {
private final Set<String> remainingUpdateNames;
public RecordingUpdateHandler(SchemaUpdate<T> update, Set<String> remainingUpdateNames) {
super(update);
this.remainingUpdateNames = remainingUpdateNames;
}
@Override
protected void handleEmptyUpdate(T transaction) throws Exception {
assert this.remainingUpdateNames.contains(this.update.getName());
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, this.update.getName(), null);
}
@Override
protected void handleSingleUpdate(T transaction, DatabaseAction<T> action) throws Exception {
assert this.remainingUpdateNames.contains(this.update.getName());
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, this.update.getName(), action);
}
@Override
protected void handleSingleMultiUpdate(T transaction, final List<? extends DatabaseAction<T>> actions)
throws Exception {
assert this.remainingUpdateNames.contains(this.update.getName());
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, this.update.getName(), new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
for (DatabaseAction<T> action : actions)
AbstractSchemaUpdater.this.apply(transaction, action);
}
});
}
@Override
protected void handleMultiUpdate(T transaction, DatabaseAction<T> action, int index) throws Exception {
String updateName = AbstractSchemaUpdater.this.generateMultiUpdateName(this.update, index);
if (!this.remainingUpdateNames.contains(updateName)) // a partially completed multi-update
return;
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, updateName, action);
}
}
// Adapter class for handling updates of various types
private class UpdateHandler {
protected final SchemaUpdate<T> update;
private final List<? extends DatabaseAction<T>> actions;
public UpdateHandler(SchemaUpdate<T> update) {
this.update = update;
this.actions = update.getDatabaseActions();
}
public final void process(T transaction) throws Exception {
switch (this.actions.size()) {
case 0:
this.handleEmptyUpdate(transaction);
break;
case 1:
this.handleSingleUpdate(transaction, this.actions.get(0));
break;
default:
if (update.isSingleAction()) {
this.handleSingleMultiUpdate(transaction, actions);
break;
} else {
int index = 0;
for (DatabaseAction<T> action : this.actions)
this.handleMultiUpdate(transaction, action, index++);
}
break;
}
}
protected void handleEmptyUpdate(T transaction) throws Exception {
this.handleSingleUpdate(transaction, null);
}
protected void handleSingleUpdate(T transaction, DatabaseAction<T> action) throws Exception {
}
protected void handleSingleMultiUpdate(T transaction, List<? extends DatabaseAction<T>> actions) throws Exception {
this.handleSingleUpdate(transaction, null);
}
protected void handleMultiUpdate(T transaction, DatabaseAction<T> action, int index) throws Exception {
}
}
// Sorts updates by name
private class UpdateByNameComparator implements Comparator<SchemaUpdate<T>> {
@Override
public int compare(SchemaUpdate<T> update1, SchemaUpdate<T> update2) {
return update1.getName().compareTo(update2.getName());
}
}
}
| src/java/org/dellroad/stuff/schema/AbstractSchemaUpdater.java |
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.schema;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.dellroad.stuff.graph.TopologicalSorter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles the initialization and schema maintenance of a database.
*
* <p>
* In this class, a <b>database</b> is some stateful object whose structure and/or content may need to change over time.
* <b>Updates</b> are uniquely named objects capable of making such changes. Databases are also capable of storing the
* names of the already-applied updates.
*
* <p>
* Given a database and a set of current updates, this class will ensure that a database is initialized if necessary
* and up-to-date with respect to the updates.
*
* <p>
* The primary method is {@link #initializeAndUpdateDatabase initializeAndUpdateDatabase()}, which will:
* <ul>
* <li>Initialize an {@linkplain #databaseNeedsInitialization empty} database (if necessary);</li>
* <li>Apply any outstanding {@link SchemaUpdate}s as needed, ordered properly according to
* their {@linkplain SchemaUpdate#getRequiredPredecessors predecessor constraints}; and</li>
* <li>Keep track of which {@link SchemaUpdate}s have already been applied across restarts.</li>
* </ul>
* </p>
*
* @param <D> database type
* @param <T> database transaction type
*/
public abstract class AbstractSchemaUpdater<D, T> {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
private Collection<? extends SchemaUpdate<T>> updates;
private boolean ignoreUnrecognizedUpdates;
/**
* Get the configured updates. This property is required.
*
* @return configured updates
* @see #setUpdates setUpdates()
*/
public Collection<? extends SchemaUpdate<T>> getUpdates() {
return this.updates;
}
/**
* Configure the updates.
* This should be the set of all updates that may need to be applied to the database.
*
* <p>
* For any given application, ideally this set should be "write only" in the sense that once an update is added to the set
* and applied to one or more actual databases, the update and its name should thereafter never change. Otherwise,
* it would be possible for different databases to have inconsistent schemas even though the same updates were recorded.
*
* <p>
* Furthermore, if not configured to {@linkplain #setIgnoreUnrecognizedUpdates ignore unrecognized updates already applied}
* (the default behavior), then updates must never be removed from this set as the application evolves;
* see {@link #setIgnoreUnrecognizedUpdates} for more information on the rationale.
*
* @param updates all updates; each update must have a unique {@link SchemaUpdate#getName name}.
* @see #getUpdates
* @see #setIgnoreUnrecognizedUpdates
*/
public void setUpdates(Collection<? extends SchemaUpdate<T>> updates) {
this.updates = updates;
}
/**
* Determine whether unrecognized updates are ignored or cause an exception.
*
* @return true if unrecognized updates should be ignored, false if they should cause an exception to be thrown
* @see #setIgnoreUnrecognizedUpdates setIgnoreUnrecognizedUpdates()
*/
public boolean isIgnoreUnrecognizedUpdates() {
return this.ignoreUnrecognizedUpdates;
}
/**
* Configure behavior when an unknown update is registered as having already been applied in the database.
*
* <p>
* The default behavior is <code>false</code>, which results in an exception being thrown. This protects against
* accidental downgrades (i.e., running older code against a database with a newer schema), which are not supported.
* However, this also requires that all updates that might ever possibly have been applied to the database be
* present in the set of configured updates.
*
* <p>
* Setting this to <code>true</code> will result in unrecognized updates simply being ignored.
* This setting loses the downgrade protection but allows obsolete schema updates to be dropped over time.
*
* @param ignoreUnrecognizedUpdates whether to ignore unrecognized updates
* @see #isIgnoreUnrecognizedUpdates
*/
public void setIgnoreUnrecognizedUpdates(boolean ignoreUnrecognizedUpdates) {
this.ignoreUnrecognizedUpdates = ignoreUnrecognizedUpdates;
}
/**
* Perform database schema initialization and updates.
*
* <p>
* This method applies the following logic: if the {@linkplain #databaseNeedsInitialization database needs initialization},
* then {@linkplain #initializeDatabase initialize the database} and {@linkplain #recordUpdateApplied record} each update
* as having been applied; otherwise, {@linkplain #apply apply} any {@linkplain #getAppliedUpdateNames unapplied updates}
* as needed.
*
* <p>
* Note this implies the database initialization must initialize the database to its current, up-to-date state
* (with respect to the set of all available updates), not its original, pre-update state.
*
* <p>
* The database initialization step, and each of the update steps, is {@linkplain #applyInTransaction performed within
* its own transaction}.
*
* @param database the database to initialize (if necessary) and update
* @return true if successful, false if database initialization was needed but not applied
* @throws Exception if an update fails
* @throws IllegalStateException if this instance is not configured to {@linkplain #setIgnoreUnrecognizedUpdates ignore
* unrecognized updates} and an unrecognized update has already been applied
* @throws IllegalArgumentException if two configured updates have the same name
* @throws IllegalArgumentException if any configured update has a required predecessor which is not also a configured update
* (i.e., if the updates are not transitively closed under predecessors)
*/
public synchronized boolean initializeAndUpdateDatabase(final D database) throws Exception {
// Log
this.log.info("verifying database " + database);
// First, initialize if necessary
final boolean[] initialized = new boolean[1];
this.applyInTransaction(database, new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
// Already initialized?
if (!AbstractSchemaUpdater.this.databaseNeedsInitialization(transaction)) {
AbstractSchemaUpdater.this.log.debug("detected already-initialized database " + database);
initialized[0] = true;
return;
}
// Initialize database
AbstractSchemaUpdater.this.log.info("uninitialized database detected; initializing " + database);
initialized[0] = AbstractSchemaUpdater.this.initializeDatabase(transaction);
if (!initialized[0])
return;
// Record all schema updates as having already been applied
for (String updateName : AbstractSchemaUpdater.this.getAllUpdateNames())
AbstractSchemaUpdater.this.recordUpdateApplied(transaction, updateName);
}
});
// Was database initialized?
if (!initialized[0]) {
this.log.info("database verification aborted because database was not initialized: " + database);
return false;
}
// Next, apply any new updates
this.applySchemaUpdates(database);
// Done
this.log.info("database verification completed for " + database);
return true;
}
/**
* Determine if the given schema update name is valid. Valid names are non-empty and
* have no leading or trailing whitespace.
*/
public static boolean isValidUpdateName(String updateName) {
return updateName.length() > 0 && updateName.trim().length() == updateName.length();
}
/**
* Determine if the database needs initialization.
*
* <p>
* If so, {@link #initializeDatabase} will eventually be invoked.
*
* @param transaction open transaction
* @throws Exception if an error occurs while accessing the database
*/
protected abstract boolean databaseNeedsInitialization(T transaction) throws Exception;
/**
* Initialize an uninitialized database. This should create and initialize the database schema and content,
* including whatever portion of that is used to track schema updates.
*
* @param transaction open transaction
* @return true if database was initialized, false otherwise
* @throws Exception if an error occurs while accessing the database
*/
protected abstract boolean initializeDatabase(T transaction) throws Exception;
/**
* Begin a transaction on the given database.
* The transaction will always eventually either be
* {@linkplain #commitTransaction committed} or {@linkplain #rollbackTransaction rolled back}.
*
* @param database database
* @return transaction handle
* @throws Exception if an error occurs while accessing the database
*/
protected abstract T openTransaction(D database) throws Exception;
/**
* Commit a previously opened transaction.
*
* @param transaction open transaction previously returned from {@link #openTransaction openTransaction()}
* @throws Exception if an error occurs while accessing the database
*/
protected abstract void commitTransaction(T transaction) throws Exception;
/**
* Roll back a previously opened transaction.
* This method will also be invoked if {@link #commitTransaction commitTransaction()} throws an exception.
*
* @param transaction open transaction previously returned from {@link #openTransaction openTransaction()}
* @throws Exception if an error occurs while accessing the database
*/
protected abstract void rollbackTransaction(T transaction) throws Exception;
/**
* Determine which updates have already been applied to the database.
*
* @param transaction open transaction
* @throws Exception if an error occurs while accessing the database
*/
protected abstract Set<String> getAppliedUpdateNames(T transaction) throws Exception;
/**
* Record an update as having been applied to the database.
*
* @param transaction open transaction
* @param name update name
* @throws IllegalStateException if the update has already been recorded in the database
* @throws Exception if an error occurs while accessing the database
*/
protected abstract void recordUpdateApplied(T transaction, String name) throws Exception;
/**
* Determine the preferred ordering of two updates that do not have any predecessor constraints
* (including implied indirect constraints) between them.
*
* <p>
* The {@link Comparator} returned by the implementation in {@link AbstractSchemaUpdater} simply sorts updates by name.
* Subclasses may override if necessary.
*
* @return a {@link Comparator} that sorts incomparable updates in the order they should be applied
*/
protected Comparator<SchemaUpdate<T>> getOrderingTieBreaker() {
return new UpdateByNameComparator();
}
/**
* Generate the update name for one action within a multi-action update.
*
* <p>
* The implementation in {@link AbstractSchemaUpdater} just adds a suffix using {@code index + 1}, padded to
* 5 digits, producing names like {@code name-00001}, {@code name-00002}, etc.
*
* @param update the schema update
* @param index the index of the action (zero based)
* @see SchemaUpdate#isSingleAction
*/
protected String generateMultiUpdateName(SchemaUpdate<T> update, int index) {
return String.format("%s-%05d", update.getName(), index + 1);
}
/**
* Get the names of all updates including multi-action updates.
*/
protected List<String> getAllUpdateNames() throws Exception {
ArrayList<SchemaUpdate<T>> updateList = new ArrayList<SchemaUpdate<T>>(this.getUpdates());
ArrayList<String> updateNameList = new ArrayList<String>(updateList.size());
Collections.sort(updateList, new UpdateByNameComparator());
for (SchemaUpdate<T> update : updateList)
updateNameList.addAll(this.getUpdateNames(update));
return updateNameList;
}
/**
* Execute a database action within an existing transaction.
*
* <p>
* All database operations in {@link AbstractSchemaUpdater} are performed via this method;
* subclasses are encouraged to follow this pattern.
*
* <p>
* The implementation in {@link AbstractSchemaUpdater} simply invokes {@link DatabaseAction#apply action.apply()};
* subclasses may override if desired.
*
* @throws Exception if an error occurs while accessing the database
*/
protected void apply(T transaction, DatabaseAction<T> action) throws Exception {
action.apply(transaction);
}
/**
* Execute a database action. A new transaction will be created, used, and closed.
* Delegates to {@link #apply apply()} for the actual execution of the action.
*
* <p>
* If the action or {@link #commitTransaction commitTransaction()} fails, the transaction
* is {@linkplain #rollbackTransaction rolled back}.
*
* @throws Exception if an error occurs while accessing the database
*/
protected void applyInTransaction(D database, DatabaseAction<T> action) throws Exception {
T transaction = this.openTransaction(database);
boolean success = false;
try {
this.apply(transaction, action);
this.commitTransaction(transaction);
success = true;
} finally {
if (!success)
this.rollbackTransaction(transaction);
}
}
/**
* Apply schema updates to an initialized database.
*/
private void applySchemaUpdates(D database) throws Exception {
// Sanity check
final HashSet<SchemaUpdate<T>> allUpdates = new HashSet<SchemaUpdate<T>>(this.getUpdates());
if (allUpdates == null)
throw new IllegalArgumentException("no updates configured");
// Create mapping from update name to update; multiple updates will have multiple names
TreeMap<String, SchemaUpdate<T>> updateMap = new TreeMap<String, SchemaUpdate<T>>();
for (SchemaUpdate<T> update : allUpdates) {
for (String updateName : this.getUpdateNames(update)) {
if (!isValidUpdateName(updateName))
throw new IllegalArgumentException("illegal schema update name `" + updateName + "'");
if (updateMap.put(updateName, update) != null)
throw new IllegalArgumentException("duplicate schema update name `" + updateName + "'");
}
}
this.log.debug("these are all known schema updates: " + updateMap.keySet());
// Verify updates are transitively closed under predecessor constraints
for (SchemaUpdate<T> update : allUpdates) {
for (SchemaUpdate<T> predecessor : update.getRequiredPredecessors()) {
if (!allUpdates.contains(predecessor)) {
throw new IllegalArgumentException("schema update `" + update.getName()
+ "' has a required predecessor named `" + predecessor.getName() + "' that is not a configured update");
}
}
}
// Sort updates in the order we should to apply them
List<SchemaUpdate<T>> updateList = new TopologicalSorter<SchemaUpdate<T>>(allUpdates,
new SchemaUpdateEdgeLister<T>(), this.getOrderingTieBreaker()).sortEdgesReversed();
// Determine which updates have already been applied
final HashSet<String> appliedUpdateNames = new HashSet<String>();
this.applyInTransaction(database, new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
appliedUpdateNames.addAll(AbstractSchemaUpdater.this.getAppliedUpdateNames(transaction));
}
});
this.log.debug("these are the already-applied schema updates: " + appliedUpdateNames);
// Check whether any unknown updates have been applied
TreeSet<String> unknownUpdateNames = new TreeSet<String>(appliedUpdateNames);
unknownUpdateNames.removeAll(updateMap.keySet());
if (!unknownUpdateNames.isEmpty()) {
if (!this.isIgnoreUnrecognizedUpdates()) {
throw new IllegalStateException(unknownUpdateNames.size()
+ " unrecognized update(s) have already been applied: " + unknownUpdateNames);
}
this.log.info("ignoring " + unknownUpdateNames.size()
+ " unrecognized update(s) already applied: " + unknownUpdateNames);
}
// Remove the already-applied updates
updateMap.keySet().removeAll(appliedUpdateNames);
HashSet<SchemaUpdate<T>> remainingUpdates = new HashSet<SchemaUpdate<T>>(updateMap.values());
for (Iterator<SchemaUpdate<T>> i = updateList.iterator(); i.hasNext(); ) {
if (!remainingUpdates.contains(i.next()))
i.remove();
}
// Now are any updates needed?
if (updateList.isEmpty()) {
this.log.info("no schema updates are required");
return;
}
// Log which updates we're going to apply
final LinkedHashSet<String> remainingUpdateNames = new LinkedHashSet<String>(updateMap.size());
for (SchemaUpdate<T> update : updateList) {
ArrayList<String> updateNames = this.getUpdateNames(update);
updateNames.removeAll(appliedUpdateNames);
remainingUpdateNames.addAll(updateNames);
}
this.log.info("applying " + remainingUpdateNames.size() + " schema update(s): " + remainingUpdateNames);
// Apply and record each unapplied update
for (SchemaUpdate<T> nextUpdate : updateList) {
final RecordingUpdateHandler updateHandler = new RecordingUpdateHandler(nextUpdate, remainingUpdateNames);
this.applyInTransaction(database, new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
updateHandler.process(transaction);
}
});
}
}
// Get all update names, expanding multi-updates as necessary
private ArrayList<String> getUpdateNames(SchemaUpdate<T> update) throws Exception {
final ArrayList<String> names = new ArrayList<String>();
UpdateHandler updateHandler = new UpdateHandler(update) {
@Override
protected void handleSingleUpdate(T transaction, DatabaseAction<T> action) {
names.add(this.update.getName());
}
@Override
protected void handleMultiUpdate(T transaction, DatabaseAction<T> action, int index) {
names.add(AbstractSchemaUpdater.this.generateMultiUpdateName(this.update, index));
}
};
updateHandler.process(null);
return names;
}
// Apply and record an update, all within a single transaction
private void applyAndRecordUpdate(T transaction, String name, final DatabaseAction<T> action) throws Exception {
if (action != null) {
this.log.info("applying schema update `" + name + "'");
this.apply(transaction, action);
} else
this.log.info("recording empty schema update `" + name + "'");
this.recordUpdateApplied(transaction, name);
}
private class RecordingUpdateHandler extends UpdateHandler {
private final Set<String> remainingUpdateNames;
public RecordingUpdateHandler(SchemaUpdate<T> update, Set<String> remainingUpdateNames) {
super(update);
this.remainingUpdateNames = remainingUpdateNames;
}
@Override
protected void handleEmptyUpdate(T transaction) throws Exception {
assert this.remainingUpdateNames.contains(this.update.getName());
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, this.update.getName(), null);
}
@Override
protected void handleSingleUpdate(T transaction, DatabaseAction<T> action) throws Exception {
assert this.remainingUpdateNames.contains(this.update.getName());
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, this.update.getName(), action);
}
@Override
protected void handleSingleMultiUpdate(T transaction, final List<? extends DatabaseAction<T>> actions)
throws Exception {
assert this.remainingUpdateNames.contains(this.update.getName());
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, this.update.getName(), new DatabaseAction<T>() {
@Override
public void apply(T transaction) throws Exception {
for (DatabaseAction<T> action : actions)
AbstractSchemaUpdater.this.apply(transaction, action);
}
});
}
@Override
protected void handleMultiUpdate(T transaction, DatabaseAction<T> action, int index) throws Exception {
String updateName = AbstractSchemaUpdater.this.generateMultiUpdateName(this.update, index);
if (!this.remainingUpdateNames.contains(updateName)) // a partially completed multi-update
return;
AbstractSchemaUpdater.this.applyAndRecordUpdate(transaction, updateName, action);
}
}
// Adapter class for handling updates of various types
private class UpdateHandler {
protected final SchemaUpdate<T> update;
private final List<? extends DatabaseAction<T>> actions;
public UpdateHandler(SchemaUpdate<T> update) {
this.update = update;
this.actions = update.getDatabaseActions();
}
public final void process(T transaction) throws Exception {
switch (this.actions.size()) {
case 0:
this.handleEmptyUpdate(transaction);
break;
case 1:
this.handleSingleUpdate(transaction, this.actions.get(0));
break;
default:
if (update.isSingleAction()) {
this.handleSingleMultiUpdate(transaction, actions);
break;
} else {
int index = 0;
for (DatabaseAction<T> action : this.actions)
this.handleMultiUpdate(transaction, action, index++);
}
break;
}
}
protected void handleEmptyUpdate(T transaction) throws Exception {
this.handleSingleUpdate(transaction, null);
}
protected void handleSingleUpdate(T transaction, DatabaseAction<T> action) throws Exception {
}
protected void handleSingleMultiUpdate(T transaction, List<? extends DatabaseAction<T>> actions) throws Exception {
this.handleSingleUpdate(transaction, null);
}
protected void handleMultiUpdate(T transaction, DatabaseAction<T> action, int index) throws Exception {
}
}
// Sorts updates by name
private class UpdateByNameComparator implements Comparator<SchemaUpdate<T>> {
@Override
public int compare(SchemaUpdate<T> update1, SchemaUpdate<T> update2) {
return update1.getName().compareTo(update2.getName());
}
}
}
| Javadoc tweak.
| src/java/org/dellroad/stuff/schema/AbstractSchemaUpdater.java | Javadoc tweak. | <ide><path>rc/java/org/dellroad/stuff/schema/AbstractSchemaUpdater.java
<ide> * its own transaction}.
<ide> *
<ide> * @param database the database to initialize (if necessary) and update
<del> * @return true if successful, false if database initialization was needed but not applied
<add> * @return true if successful, false if database initialization was needed but could not be applied for some reason
<add> * (database dependent: database not started, etc.)
<ide> * @throws Exception if an update fails
<ide> * @throws IllegalStateException if this instance is not configured to {@linkplain #setIgnoreUnrecognizedUpdates ignore
<ide> * unrecognized updates} and an unrecognized update has already been applied |
|
Java | mit | error: pathspec 'easy/Defibrillators/src/main/java/Solution.java' did not match any file(s) known to git
| 88a97418d5cd5f1c5894b6420bd9507246feadda | 1 | joand/codingame,joand/codingame,joand/codingame,joand/codingame,joand/codingame,joand/codingame | import java.util.*;
import java.io.*;
import java.math.*;
class Solution {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String LON = in.next();
String LAT = in.next();
double lon = Math.toRadians(Double.parseDouble(LON.replaceAll(",",".")));
double lat = Math.toRadians(Double.parseDouble(LAT.replaceAll(",",".")));
int N = in.nextInt();
in.nextLine();
String[] DEFIB = new String[N];
String[][] prts = new String[N][6];
double[] y = new double[N];
double[] x = new double[N];
double d;
for (int i = 0; i < N; i++) {
DEFIB[i] = in.nextLine();
String[] parts = DEFIB[i].split(";");
for(int j=0; j<6; j++)
{
prts[i][j] = parts[j];
}
}
for(int i=0;i<N;i++)
{
x[i] = Math.toRadians(Double.parseDouble(prts[i][4].replaceAll(",",".")));
y[i] = Math.toRadians(Double.parseDouble(prts[i][5].replaceAll(",",".")));
}
double temp,xx,yy;
temp =1000000000;
int odp=0;
for(int i=0; i<N; i++)
{
xx=(x[i]-lon)*Math.cos((lat+y[i])/2);
yy=lat-y[i];
d=Math.sqrt(Math.pow(xx,2)+Math.pow(yy,2))*6371;
if(temp > d) { odp = i;temp = d; //System.out.println("Aktualny temp "+temp);
}
}
System.out.println(prts[odp][1]);
}
}
| easy/Defibrillators/src/main/java/Solution.java | Defibrillators java solution | easy/Defibrillators/src/main/java/Solution.java | Defibrillators java solution | <ide><path>asy/Defibrillators/src/main/java/Solution.java
<add>import java.util.*;
<add>import java.io.*;
<add>import java.math.*;
<add>
<add>
<add>class Solution {
<add>
<add> public static void main(String args[]) {
<add> Scanner in = new Scanner(System.in);
<add> String LON = in.next();
<add> String LAT = in.next();
<add> double lon = Math.toRadians(Double.parseDouble(LON.replaceAll(",",".")));
<add> double lat = Math.toRadians(Double.parseDouble(LAT.replaceAll(",",".")));
<add> int N = in.nextInt();
<add> in.nextLine();
<add> String[] DEFIB = new String[N];
<add> String[][] prts = new String[N][6];
<add> double[] y = new double[N];
<add> double[] x = new double[N];
<add> double d;
<add> for (int i = 0; i < N; i++) {
<add> DEFIB[i] = in.nextLine();
<add> String[] parts = DEFIB[i].split(";");
<add> for(int j=0; j<6; j++)
<add> {
<add> prts[i][j] = parts[j];
<add> }
<add> }
<add> for(int i=0;i<N;i++)
<add> {
<add> x[i] = Math.toRadians(Double.parseDouble(prts[i][4].replaceAll(",",".")));
<add> y[i] = Math.toRadians(Double.parseDouble(prts[i][5].replaceAll(",",".")));
<add> }
<add> double temp,xx,yy;
<add> temp =1000000000;
<add> int odp=0;
<add> for(int i=0; i<N; i++)
<add> {
<add> xx=(x[i]-lon)*Math.cos((lat+y[i])/2);
<add> yy=lat-y[i];
<add> d=Math.sqrt(Math.pow(xx,2)+Math.pow(yy,2))*6371;
<add> if(temp > d) { odp = i;temp = d; //System.out.println("Aktualny temp "+temp);
<add> }
<add>
<add>
<add> }
<add>
<add> System.out.println(prts[odp][1]);
<add> }
<add>} |
|
JavaScript | mit | 26d681897e54892c43c0c68ffbed667cef7be865 | 0 | xudafeng/webdriver-server,macacajs/webdriver-server | /* ================================================================
* webdriver-server by xdf(xudafeng[at]126.com)
* first created at : Tue Mar 17 2015 00:16:10 GMT+0800 (CST)
*
* ================================================================
* Copyright xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
const koa = require('koa');
const path = require('path');
const installer = require('node-installer');
const bodyParser = require('koa-bodyparser');
const router = require('./router');
const _ = require('../common/helper');
const logger = require('../common/logger');
const middlewares = require('./middlewares');
const responseHandler = require('./responseHandler');
function WebdriverServer() {
this.desiredCapabilities = null;
this.sessions = new Map();
this.device = null;
this.isProxy = false;
}
WebdriverServer.prototype.start = function *(caps) {
this.desiredCapabilities = caps;
this.isProxy = false;
// inject device
this.device = this.detectDevice();
caps.app = _.configApp(caps.app);
yield this.device.startDevice(caps);
return this.desiredCapabilities;
};
WebdriverServer.prototype.detectDevice = function() {
let platformName = this.desiredCapabilities.platformName.toLowerCase();
switch (platformName) {
case 'ios':
var IOS = installer('macaca-ios')
return new IOS(this.desiredCapabilities);
break;
case 'android':
var Android = installer('macaca-android');
return new Android(this.desiredCapabilities);
break;
}
};
exports.init = (options) => {
return new Promise((resolve, reject) => {
logger.debug('webdriver server start with config:\n %j', options);
const app = koa();
var webdriverServer = new WebdriverServer();
app.use(function *(next) {
this.webdriverServer = webdriverServer;
yield next;
});
app.use(bodyParser());
middlewares(app);
app.use(responseHandler);
router(app);
app.listen(options.port, resolve);
});
};
| lib/server/index.js | /* ================================================================
* webdriver-server by xdf(xudafeng[at]126.com)
* first created at : Tue Mar 17 2015 00:16:10 GMT+0800 (CST)
*
* ================================================================
* Copyright xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
const koa = require('koa');
const path = require('path');
const installer = require('node-installer');
const bodyParser = require('koa-bodyparser');
const router = require('./router');
const _ = require('../common/helper');
const logger = require('../common/logger');
const middlewares = require('./middlewares');
const responseHandler = require('./responseHandler');
function WebdriverServer() {
this.desiredCapabilities = null;
this.sessions = new Map();
this.device = null;
this.isProxy = false;
}
WebdriverServer.prototype.start = function *(caps) {
this.desiredCapabilities = caps;
// inject device
this.device = this.detectDevice();
caps.app = _.configApp(caps.app);
yield this.device.startDevice(caps);
return this.desiredCapabilities;
};
WebdriverServer.prototype.detectDevice = function() {
let platformName = this.desiredCapabilities.platformName.toLowerCase();
switch (platformName) {
case 'ios':
var IOS = installer('macaca-ios')
return new IOS(this.desiredCapabilities);
break;
case 'android':
var Android = installer('macaca-android');
return new Android(this.desiredCapabilities);
break;
}
};
exports.init = (options) => {
return new Promise((resolve, reject) => {
logger.debug('webdriver server start with config:\n %j', options);
const app = koa();
var webdriverServer = new WebdriverServer();
app.use(function *(next) {
this.webdriverServer = webdriverServer;
yield next;
});
app.use(bodyParser());
middlewares(app);
app.use(responseHandler);
router(app);
app.listen(options.port, resolve);
});
};
| Fix isProxy property when start
| lib/server/index.js | Fix isProxy property when start | <ide><path>ib/server/index.js
<ide>
<ide> WebdriverServer.prototype.start = function *(caps) {
<ide> this.desiredCapabilities = caps;
<add> this.isProxy = false;
<ide> // inject device
<ide> this.device = this.detectDevice();
<ide> caps.app = _.configApp(caps.app); |
|
Java | apache-2.0 | 49b6e5d8dd7563b36c3f5f7f837d8127e4c237ec | 0 | leepc12/BigDataScript,leepc12/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,leepc12/BigDataScript,pcingola/BigDataScript,leepc12/BigDataScript,pcingola/BigDataScript,leepc12/BigDataScript,pcingola/BigDataScript,leepc12/BigDataScript,leepc12/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript | package ca.mcgill.mcb.pcingola.bigDataScript.cluster.commandParser;
import java.util.ArrayList;
import ca.mcgill.mcb.pcingola.bigDataScript.cluster.host.Host;
import ca.mcgill.mcb.pcingola.bigDataScript.osCmd.Ssh;
import ca.mcgill.mcb.pcingola.bigDataScript.util.Gpr;
/**
* A generic command parser
* This is a class that is used to send commands and parse responses from hosts
*
* @author [email protected]
*/
public class CommandParser {
public static int MAX_DETAILS_LINES = 20;
public static int MAX_LINE_LEN = 80;
public static final String[] EMPTY_STRING_ARRAY = new String[0];
public static boolean debug = false;
Host host;
Ssh ssh;
String cmd;
public CommandParser(Host host, String cmd) {
this.host = host;
this.cmd = createCmd(cmd);
if (debug) Gpr.debug("cmd=" + this.cmd);
}
/**
* Create a list of commands and 'identifier' lines (echo '#cmdname')
* @param cmd
* @return
*/
String createCmd(String cmd) {
StringBuilder sb = new StringBuilder();
String cmds[] = cmd.split(";");
for (String c : cmds) {
c = c.trim();
sb.append("echo '#" + c + "';" + c + ";");
}
return sb.toString();
}
public void parse() {
parse(true);
}
/**
* Parse command's output
*/
public void parse(boolean updateAlive) {
try {
//---
// Connect and get answer from server
//---
Ssh ssh = new Ssh(host);
String result = ssh.exec(cmd);
if (debug) Gpr.debug("\n---------- RESULT:Start ----------\n" + result + "---------- RESULT:End ----------");
// Parse results (if any)
if ((result != null) && (result.length() > 0)) {
//---
// Parse the results. Split each command and parse separately
//---
String command = null;
result.replace('\r', ' ');
String res[] = result.split("\n");
ArrayList<String> lines = new ArrayList<String>();
for (String line : res) {
// New 'command'?
if (line.startsWith("#")) {
// Parse old section
if (command != null) parse(command, lines);
// Create new command
command = line.substring(1).replaceAll(" ", "_").trim();
lines = new ArrayList<String>();
} else lines.add(line);
}
// Parse last command
if (command != null) parse(command, lines);
// We were able to connect and got some results, so probably the host is alive.
if (updateAlive) host.getHealth().setAlive(true);
} else {
if (debug) Gpr.debug("Error trying to connect: Empty result string");
// Could not connect
host.getHealth().setAlive(false);
}
// Store results
String key = this.getClass().getSimpleName().substring("CommandParser".length()); // Command parser name (minus the 'CommandParser' prefix)
host.getHealth().setNote(key, result);
} catch (Exception e) {
if (debug) Gpr.debug("Error trying to connect:\n" + e);
// Could not connect
host.getHealth().setAlive(false);
}
}
public void parse(String cmdResult[]) {
throw new RuntimeException("This should never be invoked!");
}
/**
* Invoke a command parser
* @param command
* @param lines
*/
public void parse(String command, ArrayList<String> lines) {
String cmdResult[] = lines.toArray(EMPTY_STRING_ARRAY);
CommandParser cp = null;
if (command.startsWith("df")) cp = new CommandParserDf(host);
else if (command.startsWith("sysctl")) cp = new CommandParserSystemProfiler(host);
else if (command.startsWith("top")) cp = new CommandParserTop(host);
else if (command.startsWith("uname")) cp = new CommandParserUname(host);
else if (command.startsWith("uptime")) cp = new CommandParserUptime(host);
else if (command.startsWith("who")) cp = new CommandParserWho(host);
else if (command.startsWith("cat_/proc/meminfo")) cp = new CommandParserMemInfo(host);
else if (command.startsWith("cat_/proc/cpuinfo")) cp = new CommandParserCpuInfo(host);
else throw new RuntimeException("Unknown parser for command '" + command + "'");
// Parse
if (debug) Gpr.debug("Parsing: " + command);
cp.parse(cmdResult);
}
}
| src/ca/mcgill/mcb/pcingola/bigDataScript/cluster/commandParser/CommandParser.java | package ca.mcgill.mcb.pcingola.bigDataScript.cluster.commandParser;
import java.util.ArrayList;
import ca.mcgill.mcb.pcingola.bigDataScript.cluster.host.Host;
import ca.mcgill.mcb.pcingola.bigDataScript.osCmd.Ssh;
import ca.mcgill.mcb.pcingola.bigDataScript.util.Gpr;
/**
* A generic command parser
* This is a class that is used to send commands and parse responses from hosts
*
* @author [email protected]
*/
public class CommandParser {
public static int MAX_DETAILS_LINES = 20;
public static int MAX_LINE_LEN = 80;
public static final String[] EMPTY_STRING_ARRAY = new String[0];
public static boolean debug = false;
Host host;
Ssh ssh;
String cmd;
public CommandParser(Host host, String cmd) {
this.host = host;
this.cmd = createCmd(cmd);
if (debug) Gpr.debug("cmd=" + this.cmd);
}
/**
* Create a list of commands and 'identifier' lines (echo '#cmdname')
* @param cmd
* @return
*/
String createCmd(String cmd) {
StringBuilder sb = new StringBuilder();
String cmds[] = cmd.split(";");
for (String c : cmds) {
c = c.trim();
sb.append("echo '#" + c + "';" + c + ";");
}
return sb.toString();
}
public void parse() {
parse(true);
}
/**
* Parse command's output
*/
public void parse(boolean updateAlive) {
try {
//---
// Connect and get answer from server
//---
Ssh ssh = new Ssh(host);
String result = ssh.exec(cmd);
if (debug) Gpr.debug("\n---------- RESULT:Start ----------\n" + result + "---------- RESULT:End ----------");
// Parse results (if any)
if ((result != null) && (result.length() > 0)) {
//---
// Parse the results. Split each command and parse separately
//---
String command = null;
String res[] = result.split("\n");
ArrayList<String> lines = new ArrayList<String>();
for (String line : res) {
// New 'command'?
if (line.startsWith("#")) {
// Parse old section
if (command != null) parse(command, lines);
// Create new command
command = line.substring(1).replaceAll(" ", "_").trim();
lines = new ArrayList<String>();
} else lines.add(line);
}
// Parse last command
if (command != null) parse(command, lines);
// We were able to connect and got some results, so probably the host is alive.
if (updateAlive) host.getHealth().setAlive(true);
} else {
if (debug) Gpr.debug("Error trying to connect: Empty result string");
// Could not connect
host.getHealth().setAlive(false);
}
// Store results
String key = this.getClass().getSimpleName().substring("CommandParser".length()); // Command parser name (minus the 'CommandParser' prefix)
host.getHealth().setNote(key, result);
} catch (Exception e) {
if (debug) Gpr.debug("Error trying to connect:\n" + e);
// Could not connect
host.getHealth().setAlive(false);
}
}
public void parse(String cmdResult[]) {
throw new RuntimeException("This should never be invoked!");
}
/**
* Invoke a command parser
* @param command
* @param lines
*/
public void parse(String command, ArrayList<String> lines) {
String cmdResult[] = lines.toArray(EMPTY_STRING_ARRAY);
CommandParser cp = null;
if (command.startsWith("df")) cp = new CommandParserDf(host);
else if (command.startsWith("sysctl")) cp = new CommandParserSystemProfiler(host);
else if (command.startsWith("top")) cp = new CommandParserTop(host);
else if (command.startsWith("uname")) cp = new CommandParserUname(host);
else if (command.startsWith("uptime")) cp = new CommandParserUptime(host);
else if (command.startsWith("who")) cp = new CommandParserWho(host);
else if (command.startsWith("cat_/proc/meminfo")) cp = new CommandParserMemInfo(host);
else if (command.startsWith("cat_/proc/cpuinfo")) cp = new CommandParserCpuInfo(host);
else throw new RuntimeException("Unknown parser for command '" + command + "'");
// Parse
if (debug) Gpr.debug("Parsing: " + command);
cp.parse(cmdResult);
}
}
| Project updated
| src/ca/mcgill/mcb/pcingola/bigDataScript/cluster/commandParser/CommandParser.java | Project updated | <ide><path>rc/ca/mcgill/mcb/pcingola/bigDataScript/cluster/commandParser/CommandParser.java
<ide> // Parse the results. Split each command and parse separately
<ide> //---
<ide> String command = null;
<add> result.replace('\r', ' ');
<ide> String res[] = result.split("\n");
<ide> ArrayList<String> lines = new ArrayList<String>();
<ide> |
|
Java | mit | ca53b4ff70a4b679e63ba2b2b5fe6d3556ca0089 | 0 | andresdominguez/ddescriber,andresdominguez/ddescriber | package com.karateca;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author Andres Dominguez.
*/
public class DDescirberAction extends AnAction {
protected Project project;
protected EditorImpl editor;
protected VirtualFile virtualFile;
protected DocumentImpl document;
private JsUnitFinder jsUnitFinder;
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(e.getData(PlatformDataKeys.EDITOR) != null);
}
public void actionPerformed(AnActionEvent actionEvent) {
project = actionEvent.getData(PlatformDataKeys.PROJECT);
editor = (EditorImpl) actionEvent.getData(PlatformDataKeys.EDITOR);
virtualFile = actionEvent.getData(PlatformDataKeys.VIRTUAL_FILE);
document = (DocumentImpl) editor.getDocument();
jsUnitFinder = new JsUnitFinder(project, document, editor, virtualFile);
// Async callback to get the search results for it( and describe(
jsUnitFinder.addResultsReadyListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
if (changeEvent.getSource().equals("LinesFound")) {
processSearchResultsAndShowDialog();
}
}
});
jsUnitFinder.findText("iit\\(|ddescribe\\(|it\\(|describe\\(", true);
}
private void processSearchResultsAndShowDialog() {
// Filter the hierarchy.
int currentIndentation = Integer.MAX_VALUE;
List<LineFindResult> hierarchy = new ArrayList<LineFindResult>();
// Find all the parents from the current scope.
for (LineFindResult line : jsUnitFinder.getLineFindResults()) {
if (line.getIndentation() < currentIndentation) {
currentIndentation = line.getIndentation();
hierarchy.add(line);
}
}
showDialog(hierarchy);
}
private void showDialog(final List<LineFindResult> hierarchy) {
List<String> itemNames = new ArrayList<String>();
for (LineFindResult lineFindResult : hierarchy) {
itemNames.add(lineFindResult.getLineText());
}
final JBList theList = new JBList(itemNames.toArray());
JBPopupFactory.getInstance()
.createListPopupBuilder(theList)
.setTitle("Select the test or suite to add / remove")
.setItemChoosenCallback(new Runnable() {
public void run() {
processSelectedLine(theList, hierarchy);
}
})
.createPopup().
showCenteredInCurrentWindow(project);
}
private void processSelectedLine(final JBList theList, final List<LineFindResult> hierarchy) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
int selectedIndex = theList.getSelectedIndex();
LineFindResult lineFindResult = hierarchy.get(selectedIndex);
changeSelectedLine(lineFindResult);
}
});
}
private void changeSelectedLine(LineFindResult lineFindResult) {
int start = lineFindResult.getStartOffset();
int end = lineFindResult.getEndOffset();
String newText = "";
boolean markedForRun = lineFindResult.isMarkedForRun();
if (lineFindResult.isDescribe()) {
newText = markedForRun ? "describe(" : "ddescribe(";
} else {
newText = markedForRun ? "it(" : "iit(";
}
document.replaceString(start, end, newText);
}
}
| src/com/karateca/DDescirberAction.java | package com.karateca;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author Andres Dominguez.
*/
public class DDescirberAction extends AnAction {
protected Project project;
protected EditorImpl editor;
protected VirtualFile virtualFile;
protected DocumentImpl document;
private JsUnitFinder jsUnitFinder;
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(e.getData(PlatformDataKeys.EDITOR) != null);
}
public void actionPerformed(AnActionEvent actionEvent) {
project = actionEvent.getData(PlatformDataKeys.PROJECT);
editor = (EditorImpl) actionEvent.getData(PlatformDataKeys.EDITOR);
virtualFile = actionEvent.getData(PlatformDataKeys.VIRTUAL_FILE);
document = (DocumentImpl) editor.getDocument();
jsUnitFinder = new JsUnitFinder(project, document, editor, virtualFile);
// Async callback to get the search results for it( and describe(
jsUnitFinder.addResultsReadyListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
if (changeEvent.getSource().equals("LinesFound")) {
processSearchResultsAndShowDialog();
}
}
});
jsUnitFinder.findText("iit\\(|ddescribe\\(|it\\(|describe\\(", true);
}
private void processSearchResultsAndShowDialog() {
// Filter the hierarchy.
int currentIndentation = Integer.MAX_VALUE;
List<LineFindResult> hierarchy = new ArrayList<LineFindResult>();
// Find all the parents from the current scope.
for (LineFindResult line : jsUnitFinder.getLineFindResults()) {
if (line.getIndentation() < currentIndentation) {
currentIndentation = line.getIndentation();
hierarchy.add(line);
}
}
showDialog(hierarchy);
}
private void showDialog(final List<LineFindResult> hierarchy) {
List<String> itemNames = new ArrayList<String>();
for (LineFindResult lineFindResult : hierarchy) {
itemNames.add(lineFindResult.getLineText());
}
final JBList theList = new JBList(itemNames.toArray());
JBPopupFactory.getInstance()
.createListPopupBuilder(theList)
.setTitle("Select the test or suite to add / remove")
.setItemChoosenCallback(new Runnable() {
public void run() {
processSelectedLine(theList, hierarchy);
}
})
.createPopup().
showCenteredInCurrentWindow(project);
}
private void processSelectedLine(final JBList theList, final List<LineFindResult> hierarchy) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
int selectedIndex = theList.getSelectedIndex();
LineFindResult lineFindResult = hierarchy.get(selectedIndex);
changeSelectedLine(lineFindResult);
}
});
}
private void changeSelectedLine(LineFindResult lineFindResult) {
int start = lineFindResult.getStartOffset();
int end = lineFindResult.getEndOffset();
String newText = "";
boolean markedForRun = lineFindResult.isMarkedForRun();
if (lineFindResult.isDescribe()) {
newText = markedForRun ? "describe(" : "ddescribe(";
} else {
newText = markedForRun ? "it(" : "iit(";
}
document.replaceString(start, end, newText);
}
}
| working!
| src/com/karateca/DDescirberAction.java | working! | <ide><path>rc/com/karateca/DDescirberAction.java
<ide> String newText = "";
<ide> boolean markedForRun = lineFindResult.isMarkedForRun();
<ide> if (lineFindResult.isDescribe()) {
<del>
<ide> newText = markedForRun ? "describe(" : "ddescribe(";
<ide> } else {
<ide> newText = markedForRun ? "it(" : "iit("; |
|
Java | apache-2.0 | 5090edc38e3da30a4e4ac438fcdfeefbbd7401e6 | 0 | RoboSwag/components,TouchInstinct/RoboSwag-components | /*
* Copyright (c) 2015 RoboSwag (Gavriil Sitnikov, Vsevolod Ivanov)
*
* This file is part of RoboSwag library.
*
* 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 ru.touchin.roboswag.components.navigation;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import ru.touchin.roboswag.core.log.Lc;
import rx.functions.Func1;
/**
* Created by Gavriil Sitnikov on 07/03/2016.
* Navigation which is controlling using {@link android.support.v4.app.FragmentManager} as controller.
*/
public class FragmentNavigation {
protected static final String TOP_FRAGMENT_TAG_MARK = "TOP_FRAGMENT";
protected static final String WITH_TARGET_FRAGMENT_TAG_MARK = "FRAGMENT_WITH_TARGET";
@NonNull
private final Context context;
@NonNull
private final FragmentManager fragmentManager;
@IdRes
private final int containerViewId;
public FragmentNavigation(@NonNull final Context context, @NonNull final FragmentManager fragmentManager, @IdRes final int containerViewId) {
this.context = context;
this.fragmentManager = fragmentManager;
this.containerViewId = containerViewId;
}
@NonNull
public FragmentManager getFragmentManager() {
return fragmentManager;
}
@NonNull
public Context getContext() {
return context;
}
/**
* Returns if last fragment in stack is top (added by setFragment) like fragment from sidebar menu.
*
* @return True if last fragment on stack has TOP_FRAGMENT_TAG_MARK.
*/
public boolean isCurrentFragmentTop() {
if (fragmentManager.getBackStackEntryCount() == 0) {
return true;
}
final String topFragmentTag = fragmentManager
.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1)
.getName();
return topFragmentTag != null && topFragmentTag.contains(TOP_FRAGMENT_TAG_MARK);
}
@SuppressLint("InlinedApi")//TODO?
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
return item.getItemId() == android.R.id.home && back();
}
@SuppressLint("CommitTransaction")
protected void addToStack(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Fragment targetFragment,
@Nullable final Bundle args,
@Nullable final String backStackTag,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
if (fragmentManager.isDestroyed()) {
Lc.assertion("FragmentManager is destroyed");
return;
}
final Fragment fragment = Fragment.instantiate(context, fragmentClass.getName(), args);
if (targetFragment != null) {
fragment.setTargetFragment(targetFragment, 0);
}
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
.replace(containerViewId, fragment, null)
.addToBackStack(backStackTag);
if (fragmentManager.getBackStackEntryCount() != 0) {
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
if (transactionSetup != null) {
transactionSetup.call(fragmentTransaction).commit();
} else {
fragmentTransaction.commit();
}
}
public boolean back() {
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStack();
return true;
}
return false;
}
public boolean backTo(@NonNull final Func1<FragmentManager.BackStackEntry, Boolean> condition) {
final int stackSize = fragmentManager.getBackStackEntryCount();
Integer id = null;
for (int i = stackSize - 2; i >= 0; i--) {
final FragmentManager.BackStackEntry backStackEntry = fragmentManager.getBackStackEntryAt(i);
id = backStackEntry.getId();
if (condition.call(backStackEntry)) {
break;
}
}
if (id != null) {
fragmentManager.popBackStack(id, 0);
return true;
}
return false;
}
@SuppressWarnings("PMD.ShortMethodName")
public boolean up() {
return backTo(backStackEntry ->
backStackEntry.getName() != null && backStackEntry.getName().endsWith(TOP_FRAGMENT_TAG_MARK));
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass) {
addToStack(fragmentClass, null, null, null, null);
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Bundle args) {
addToStack(fragmentClass, null, args, null, null);
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, null, null, transactionSetup);
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, args, null, transactionSetup);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment) {
addToStack(fragmentClass, targetFragment, null, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, null);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment,
@NonNull final Bundle args) {
addToStack(fragmentClass, targetFragment, args, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, null);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, targetFragment, null, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, transactionSetup);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, targetFragment, args, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, transactionSetup);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass) {
addToStack(fragmentClass, null, null, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, null);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Bundle args) {
addToStack(fragmentClass, null, args, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, null);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, null, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, transactionSetup);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, args, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, transactionSetup);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass) {
setInitial(fragmentClass, null, null);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Bundle args) {
setInitial(fragmentClass, args, null);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
setInitial(fragmentClass, null, transactionSetup);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
beforeSetInitialActions();
setAsTop(fragmentClass, args, transactionSetup);
}
protected void beforeSetInitialActions() {
if (fragmentManager.isDestroyed()) {
Lc.assertion("FragmentManager is destroyed");
return;
}
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
}
| src/main/java/ru/touchin/roboswag/components/navigation/FragmentNavigation.java | /*
* Copyright (c) 2015 RoboSwag (Gavriil Sitnikov, Vsevolod Ivanov)
*
* This file is part of RoboSwag library.
*
* 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 ru.touchin.roboswag.components.navigation;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import ru.touchin.roboswag.core.log.Lc;
import rx.functions.Func1;
/**
* Created by Gavriil Sitnikov on 07/03/2016.
* Navigation which is controlling using {@link android.support.v4.app.FragmentManager} as controller.
*/
public class FragmentNavigation {
protected static final String TOP_FRAGMENT_TAG_MARK = "TOP_FRAGMENT";
protected static final String WITH_TARGET_FRAGMENT_TAG_MARK = "FRAGMENT_WITH_TARGET";
@NonNull
private final Context context;
@NonNull
private final FragmentManager fragmentManager;
@IdRes
private final int containerViewId;
public FragmentNavigation(@NonNull final Context context, @NonNull final FragmentManager fragmentManager, @IdRes final int containerViewId) {
this.context = context;
this.fragmentManager = fragmentManager;
this.containerViewId = containerViewId;
}
@NonNull
public FragmentManager getFragmentManager() {
return fragmentManager;
}
@NonNull
public Context getContext() {
return context;
}
/**
* Returns if last fragment in stack is top (added by setFragment) like fragment from sidebar menu.
*
* @return True if last fragment on stack has TOP_FRAGMENT_TAG_MARK.
*/
public boolean isCurrentFragmentTop() {
if (fragmentManager.getBackStackEntryCount() == 0) {
return true;
}
final String topFragmentTag = fragmentManager
.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1)
.getName();
return topFragmentTag != null && topFragmentTag.contains(TOP_FRAGMENT_TAG_MARK);
}
@SuppressLint("InlinedApi")//TODO?
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
return item.getItemId() == android.R.id.home && back();
}
@SuppressLint("CommitTransaction")
protected void addToStack(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Fragment targetFragment,
@Nullable final Bundle args,
@Nullable final String backStackTag,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
if (fragmentManager.isDestroyed()) {
Lc.assertion("FragmentManager is destroyed");
return;
}
final Fragment fragment = Fragment.instantiate(context, fragmentClass.getName(), args);
if (targetFragment != null) {
fragment.setTargetFragment(targetFragment, 0);
}
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
.replace(containerViewId, fragment, null)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(backStackTag);
if (transactionSetup != null) {
transactionSetup.call(fragmentTransaction).commit();
} else {
fragmentTransaction.commit();
}
}
public boolean back() {
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStack();
return true;
}
return false;
}
public boolean backTo(@NonNull final Func1<FragmentManager.BackStackEntry, Boolean> condition) {
final int stackSize = fragmentManager.getBackStackEntryCount();
Integer id = null;
for (int i = stackSize - 2; i >= 0; i--) {
final FragmentManager.BackStackEntry backStackEntry = fragmentManager.getBackStackEntryAt(i);
id = backStackEntry.getId();
if (condition.call(backStackEntry)) {
break;
}
}
if (id != null) {
fragmentManager.popBackStack(id, 0);
return true;
}
return false;
}
@SuppressWarnings("PMD.ShortMethodName")
public boolean up() {
return backTo(backStackEntry ->
backStackEntry.getName() != null && backStackEntry.getName().endsWith(TOP_FRAGMENT_TAG_MARK));
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass) {
addToStack(fragmentClass, null, null, null, null);
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Bundle args) {
addToStack(fragmentClass, null, args, null, null);
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, null, null, transactionSetup);
}
public void push(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, args, null, transactionSetup);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment) {
addToStack(fragmentClass, targetFragment, null, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, null);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment,
@NonNull final Bundle args) {
addToStack(fragmentClass, targetFragment, args, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, null);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, targetFragment, null, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, transactionSetup);
}
public void pushForResult(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Fragment targetFragment,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, targetFragment, args, fragmentClass.getName() + ';' + WITH_TARGET_FRAGMENT_TAG_MARK, transactionSetup);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass) {
addToStack(fragmentClass, null, null, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, null);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Bundle args) {
addToStack(fragmentClass, null, args, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, null);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, null, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, transactionSetup);
}
public void setAsTop(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
addToStack(fragmentClass, null, args, fragmentClass.getName() + ';' + TOP_FRAGMENT_TAG_MARK, transactionSetup);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass) {
setInitial(fragmentClass, null, null);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Bundle args) {
setInitial(fragmentClass, args, null);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass,
@NonNull final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
setInitial(fragmentClass, null, transactionSetup);
}
public void setInitial(@NonNull final Class<? extends Fragment> fragmentClass,
@Nullable final Bundle args,
@Nullable final Func1<FragmentTransaction, FragmentTransaction> transactionSetup) {
beforeSetInitialActions();
setAsTop(fragmentClass, args, transactionSetup);
}
protected void beforeSetInitialActions() {
if (fragmentManager.isDestroyed()) {
Lc.assertion("FragmentManager is destroyed");
return;
}
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
}
| fragment animation disabled for first fragment
| src/main/java/ru/touchin/roboswag/components/navigation/FragmentNavigation.java | fragment animation disabled for first fragment | <ide><path>rc/main/java/ru/touchin/roboswag/components/navigation/FragmentNavigation.java
<ide>
<ide> final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
<ide> .replace(containerViewId, fragment, null)
<del> .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
<ide> .addToBackStack(backStackTag);
<add> if (fragmentManager.getBackStackEntryCount() != 0) {
<add> fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
<add> }
<ide> if (transactionSetup != null) {
<ide> transactionSetup.call(fragmentTransaction).commit();
<ide> } else { |
|
Java | apache-2.0 | 0f8f94dc10001639362d69f01d6b562c3f16063b | 0 | 4treesCH/strolch,eitchnet/strolch,4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,eitchnet/strolch,eitchnet/strolch,4treesCH/strolch | /*
* Copyright 2015 Robert von Burg <[email protected]>
*
* 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 li.strolch.rest.filters;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_CERTIFICATE;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_REQUEST_SOURCE;
import static li.strolch.utils.helper.StringHelper.isNotEmpty;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import li.strolch.exception.StrolchAccessDeniedException;
import li.strolch.exception.StrolchNotAuthenticatedException;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.utils.helper.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This authentication request filter secures any requests to a Strolch server, by verifying that the request contains
* either the cookie {@link StrolchRestfulConstants#STROLCH_AUTHORIZATION} containing the authorization token, or the
* header {@link HttpHeaders#AUTHORIZATION} with the authorization token as its value.
*
* <br>
*
* Sub classes should override {@link #validateSession(ContainerRequestContext, String)} to add further validation.
*
* @author Reto Breitenmoser <[email protected]>
* @author Robert von Burg <[email protected]>
*/
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationRequestFilter implements ContainerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationRequestFilter.class);
@Context
private HttpServletRequest request;
private Set<String> unsecuredPaths;
/**
* Defines the set of paths which are considered to be unsecured, i.e. can be requested without having logged in
* prior to the request
*
* @return the set of unsecured paths
*/
protected Set<String> getUnsecuredPaths() {
Set<String> paths = new HashSet<>();
paths.add("strolch/authentication");
paths.add("strolch/authentication/sso");
paths.add("strolch/version");
return paths;
}
/**
* Validates if the path for the given request is for an unsecured path, i.e. no authorization is required
*
* @param requestContext
* the request context
*
* @return true if the request context is for an unsecured path, false if not, meaning authorization must be
* validated
*/
protected boolean isUnsecuredPath(ContainerRequestContext requestContext) {
// we have to allow OPTIONS for CORS
if (requestContext.getMethod().equals("OPTIONS"))
return true;
List<String> matchedURIs = requestContext.getUriInfo().getMatchedURIs();
// we allow unauthorized access to the authentication service
if (this.unsecuredPaths == null)
this.unsecuredPaths = getUnsecuredPaths();
return matchedURIs.stream().anyMatch(s -> this.unsecuredPaths.contains(s));
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String remoteIp = getRemoteIp(this.request);
logger.info("Remote IP: " + remoteIp + ": " + requestContext.getMethod() + " " + requestContext.getUriInfo()
.getRequestUri());
if (isUnsecuredPath(requestContext))
return;
try {
validateSession(requestContext, remoteIp);
} catch (StrolchNotAuthenticatedException e) {
logger.error(e.getMessage());
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("User is not authenticated!").build()); //$NON-NLS-1$
} catch (StrolchAccessDeniedException e) {
logger.error(e.getMessage());
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("User is not authorized!").build()); //$NON-NLS-1$
} catch (Exception e) {
logger.error(e.getMessage());
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("User cannot access the resource.").build()); //$NON-NLS-1$
}
}
/**
* Validate the given request context by checking for the authorization cookie or header and then verifying a
* session exists and is valid with the given authoriation token
*
* <br>
*
* Sub classes should override this method and first call super. If the return value is non-null, then further
* validation can be performed
*
* @param requestContext
* the request context for the secured path
* @param remoteIp
* the remote IP
*
* @return the certificate for the validated session, or null, of the request is aborted to no missing or invalid
* authorization token
*/
protected Certificate validateSession(ContainerRequestContext requestContext, String remoteIp) {
String sessionId = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (StringHelper.isEmpty(sessionId)) {
Cookie cookie = requestContext.getCookies().get(StrolchRestfulConstants.STROLCH_AUTHORIZATION);
if (cookie == null) {
logger.error(
"No Authorization header or cookie on request to URL " + requestContext.getUriInfo().getPath());
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("Missing Authorization!") //$NON-NLS-1$
.build());
return null;
}
sessionId = cookie.getValue();
if (StringHelper.isEmpty(sessionId)) {
logger.error("Authorization Cookie value missing on request to URL " + requestContext.getUriInfo()
.getPath());
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("Missing Authorization!") //$NON-NLS-1$
.build());
return null;
}
}
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance()
.getComponent(StrolchSessionHandler.class);
Certificate certificate = sessionHandler.validate(sessionId, remoteIp);
requestContext.setProperty(STROLCH_CERTIFICATE, certificate);
requestContext.setProperty(STROLCH_REQUEST_SOURCE, remoteIp);
return certificate;
}
public static String getRemoteIp(HttpServletRequest request) {
String remoteHost = request.getRemoteHost();
String remoteAddr = request.getRemoteAddr();
StringBuilder sb = new StringBuilder();
if (remoteHost.equals(remoteAddr))
sb.append(remoteAddr);
else {
sb.append(remoteHost).append(": (").append(remoteAddr).append(")");
}
String xForwardedFor = request.getHeader("X-Forwarded-For");
if (isNotEmpty(xForwardedFor))
sb.append(" (fwd)=> ").append(xForwardedFor);
return sb.toString();
}
}
| li.strolch.rest/src/main/java/li/strolch/rest/filters/AuthenticationRequestFilter.java | /*
* Copyright 2015 Robert von Burg <[email protected]>
*
* 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 li.strolch.rest.filters;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_CERTIFICATE;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_REQUEST_SOURCE;
import static li.strolch.utils.helper.StringHelper.isNotEmpty;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import li.strolch.exception.StrolchAccessDeniedException;
import li.strolch.exception.StrolchNotAuthenticatedException;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.utils.helper.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This authentication request filter secures any requests to a Strolch server, by verifying that the request contains
* either the cookie {@link StrolchRestfulConstants#STROLCH_AUTHORIZATION} containing the authorization token, or the
* header {@link HttpHeaders#AUTHORIZATION} with the authorization token as its value.
*
* <br>
*
* Sub classes should override {@link #validateSession(ContainerRequestContext, String)} to add further validation.
*
* @author Reto Breitenmoser <[email protected]>
* @author Robert von Burg <[email protected]>
*/
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationRequestFilter implements ContainerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationRequestFilter.class);
@Context
private HttpServletRequest request;
private Set<String> unsecuredPaths;
/**
* Defines the set of paths which are considered to be unsecured, i.e. can be requested without having logged in
* prior to the request
*
* @return the set of unsecured paths
*/
protected Set<String> getUnsecuredPaths() {
Set<String> paths = new HashSet<>();
paths.add("strolch/authentication");
paths.add("strolch/authentication/sso");
paths.add("strolch/version");
return paths;
}
/**
* Validates if the path for the given request is for an unsecured path, i.e. no authorization is required
*
* @param requestContext
* the request context
*
* @return true if the request context is for an unsecured path, false if not, meaning authorization must be
* validated
*/
protected boolean isUnsecuredPath(ContainerRequestContext requestContext) {
// we have to allow OPTIONS for CORS
if (requestContext.getMethod().equals("OPTIONS"))
return true;
List<String> matchedURIs = requestContext.getUriInfo().getMatchedURIs();
// we allow unauthorized access to the authentication service
if (this.unsecuredPaths == null)
this.unsecuredPaths = getUnsecuredPaths();
return matchedURIs.stream().anyMatch(s -> this.unsecuredPaths.contains(s));
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String remoteIp = getRemoteIp(this.request);
logger.info("Remote IP: " + remoteIp + ": " + requestContext.getMethod() + " " + requestContext.getUriInfo()
.getRequestUri());
if (isUnsecuredPath(requestContext))
return;
try {
validateSession(requestContext, remoteIp);
} catch (StrolchNotAuthenticatedException e) {
logger.error(e.getMessage());
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("User is not authenticated!").build()); //$NON-NLS-1$
} catch (StrolchAccessDeniedException e) {
logger.error(e.getMessage());
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("User is not authorized!").build()); //$NON-NLS-1$
} catch (Exception e) {
logger.error(e.getMessage());
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("User cannot access the resource.").build()); //$NON-NLS-1$
}
}
/**
* Validate the given request context by checking for the authorization cookie or header and then verifying a
* session exists and is valid with the given authoriation token
*
* <br>
*
* Sub classes should override this method and first call super. If the return value is non-null, then further
* validation can be performed
*
* @param requestContext
* the request context for the secured path
* @param remoteIp
* the remote IP
*
* @return the certificate for the validated session, or null, of the request is aborted to no missing or invalid
* authorization token
*/
protected Certificate validateSession(ContainerRequestContext requestContext, String remoteIp) {
String sessionId = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (StringHelper.isEmpty(sessionId)) {
Cookie cookie = requestContext.getCookies().get(StrolchRestfulConstants.STROLCH_AUTHORIZATION);
if (cookie == null) {
logger.error(
"No Authorization header or cookie on request to URL " + requestContext.getUriInfo().getPath());
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("Missing Authorization!") //$NON-NLS-1$
.build());
return null;
}
sessionId = cookie.getValue();
if (StringHelper.isEmpty(sessionId)) {
logger.error("Authorization Cookie value missing on request to URL " + requestContext.getUriInfo()
.getPath());
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.entity("Missing Authorization!") //$NON-NLS-1$
.build());
return null;
}
}
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance()
.getComponent(StrolchSessionHandler.class);
Certificate certificate = sessionHandler.validate(sessionId, remoteIp);
requestContext.setProperty(STROLCH_CERTIFICATE, certificate);
requestContext.setProperty(STROLCH_REQUEST_SOURCE, remoteIp);
return certificate;
}
public static String getRemoteIp(HttpServletRequest request) {
String remoteUser = request.getRemoteUser();
String remoteHost = request.getRemoteHost();
String remoteAddr = request.getRemoteAddr();
StringBuilder sb = new StringBuilder();
if (isNotEmpty(remoteUser))
sb.append(remoteUser).append(": ");
if (remoteHost.equals(remoteAddr))
sb.append(remoteAddr);
else {
sb.append(remoteUser).append(": (").append(remoteAddr).append(")");
}
String xForwardedFor = request.getHeader("X-Forwarded-For");
if (isNotEmpty(xForwardedFor))
sb.append(" (fwd)=> ").append(xForwardedFor);
return sb.toString();
}
}
| [Minor] Don't add remoteUser to remoteIp
| li.strolch.rest/src/main/java/li/strolch/rest/filters/AuthenticationRequestFilter.java | [Minor] Don't add remoteUser to remoteIp | <ide><path>i.strolch.rest/src/main/java/li/strolch/rest/filters/AuthenticationRequestFilter.java
<ide>
<ide> public static String getRemoteIp(HttpServletRequest request) {
<ide>
<del> String remoteUser = request.getRemoteUser();
<ide> String remoteHost = request.getRemoteHost();
<ide> String remoteAddr = request.getRemoteAddr();
<ide>
<ide> StringBuilder sb = new StringBuilder();
<del> if (isNotEmpty(remoteUser))
<del> sb.append(remoteUser).append(": ");
<del>
<ide> if (remoteHost.equals(remoteAddr))
<ide> sb.append(remoteAddr);
<ide> else {
<del> sb.append(remoteUser).append(": (").append(remoteAddr).append(")");
<add> sb.append(remoteHost).append(": (").append(remoteAddr).append(")");
<ide> }
<ide>
<ide> String xForwardedFor = request.getHeader("X-Forwarded-For"); |
|
JavaScript | mit | ab52db26cdb8bab27ae6ebaba1e7fc051f20076f | 0 | opbeat/opbeat-react,opbeat/opbeat-angular,jahtalab/opbeat-js,opbeat/opbeat-js-core,jahtalab/opbeat-js,opbeat/opbeat-js-core,opbeat/opbeat-angular,jahtalab/opbeat-js,opbeat/opbeat-react,opbeat/opbeat-react,opbeat/opbeat-angular | exports.config = {
//
// ==================
// Specify Test Files
// ==================
// Define which test specs should run. The pattern is relative to the directory
// from which `wdio` was called. Notice that, if you are calling `wdio` from an
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
// directory is where your package.json resides, so `wdio` will be called from there.
//
specs: [
'./e2e_test/**/*.spec.js'
],
// Patterns to exclude.
exclude: [
'./e2e_test/node_modules/**/*.*'
// 'path/to/excluded/files'
],
//
// ============
// Capabilities
// ============
// Define your capabilities here. WebdriverIO can run multiple capabilties at the same
// time. Depending on the number of capabilities, WebdriverIO launches several test
// sessions. Within your capabilities you can overwrite the spec and exclude option in
// order to group specific specs to a specific capability.
//
// If you have trouble getting all important capabilities together, check out the
// Sauce Labs platform configurator - a great tool to configure your capabilities:
// https://docs.saucelabs.com/reference/platforms-configurator
//
capabilities: [
// {
// browserName: 'phantomjs',
// 'phantomjs.binary.path': require('phantomjs').path
// },
{
browserName: 'chrome'
}
],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity: silent | verbose | command | data | result | error
logLevel: 'command',
//
// Enables colors for log output.
coloredLogs: true,
//
// Saves a screenshot to a given path if a command fails.
screenshotPath: './errorShots/',
//
// Set a base URL in order to shorten url command calls. If your url parameter starts
// with "/", the base url gets prepended.
baseUrl: 'http://localhost:8000',
//
// Default timeout for all waitForXXX commands.
waitforTimeout: 10000,
//
// Initialize the browser instance with a WebdriverIO plugin. The object should have the
// plugin name as key and the desired plugin options as property. Make sure you have
// the plugin installed before running any tests. The following plugins are currently
// available:
// WebdriverCSS: https://github.com/webdriverio/webdrivercss
// WebdriverRTC: https://github.com/webdriverio/webdriverrtc
// Browserevent: https://github.com/webdriverio/browserevent
// plugins: {
// webdrivercss: {
// screenshotRoot: 'my-shots',
// failedComparisonsRoot: 'diffs',
// misMatchTolerance: 0.05,
// screenWidth: [320,480,640,1024]
// },
// webdriverrtc: {},
// browserevent: {}
// },
//
// Framework you want to run your specs with.
// The following are supported: mocha, jasmine and cucumber
// see also: http://webdriver.io/guide/testrunner/frameworks.html
//
// Make sure you have the node package for the specific framework installed before running
// any tests. If not please install the following package:
// Mocha: `$ npm install mocha`
// Jasmine: `$ npm install jasmine`
// Cucumber: `$ npm install cucumber`
framework: 'jasmine',
//
// Test reporter for stdout.
// The following are supported: dot (default), spec and xunit
// see also: http://webdriver.io/guide/testrunner/reporters.html
reporter: 'spec',
//
// Options to be passed to Jasmine.
jasmineNodeOpts: {
//
// Jasmine default timeout
defaultTimeoutInterval: 10000,
//
// The Jasmine framework allows it to intercept each assertion in order to log the state of the application
// or website depending on the result. For example it is pretty handy to take a screenshot everytime
// an assertion fails.
expectationResultHandler: function (passed, assertion) {
/**
* only take screenshot if assertion failed
*/
if (passed) {
return
}
var title = assertion.message.replace(/\s/g, '-')
browser.saveScreenshot(('./errorShots/assertionError_' + title + '.png'))
}
},
//
// =====
// Hooks
// =====
// Run functions before or after the test. If one of them returns with a promise, WebdriverIO
// will wait until that promise got resolved to continue.
//
// Gets executed before all workers get launched.
onPrepare: function () {
// do something
},
//
// Gets executed before test execution begins. At this point you will have access to all global
// variables like `browser`. It is the perfect place to define custom commands.
before: function () {
// do something
},
//
// Gets executed after all tests are done. You still have access to all global variables from
// the test.
after: function (failures, pid) {
// do something
},
//
// Gets executed after all workers got shut down and the process is about to exit. It is not
// possible to defer the end of the process using a promise.
onComplete: function () {
// do something
}
}
| wdio.conf.js | exports.config = {
//
// ==================
// Specify Test Files
// ==================
// Define which test specs should run. The pattern is relative to the directory
// from which `wdio` was called. Notice that, if you are calling `wdio` from an
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
// directory is where your package.json resides, so `wdio` will be called from there.
//
specs: [
'./e2e_test/**/*.spec.js'
],
// Patterns to exclude.
exclude: [
'./e2e_test/libs/**/*.*'
// 'path/to/excluded/files'
],
//
// ============
// Capabilities
// ============
// Define your capabilities here. WebdriverIO can run multiple capabilties at the same
// time. Depending on the number of capabilities, WebdriverIO launches several test
// sessions. Within your capabilities you can overwrite the spec and exclude option in
// order to group specific specs to a specific capability.
//
// If you have trouble getting all important capabilities together, check out the
// Sauce Labs platform configurator - a great tool to configure your capabilities:
// https://docs.saucelabs.com/reference/platforms-configurator
//
capabilities: [
// {
// browserName: 'phantomjs',
// 'phantomjs.binary.path': require('phantomjs').path
// },
{
browserName: 'chrome'
}
],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity: silent | verbose | command | data | result | error
logLevel: 'command',
//
// Enables colors for log output.
coloredLogs: true,
//
// Saves a screenshot to a given path if a command fails.
screenshotPath: './errorShots/',
//
// Set a base URL in order to shorten url command calls. If your url parameter starts
// with "/", the base url gets prepended.
baseUrl: 'http://localhost:8000',
//
// Default timeout for all waitForXXX commands.
waitforTimeout: 10000,
//
// Initialize the browser instance with a WebdriverIO plugin. The object should have the
// plugin name as key and the desired plugin options as property. Make sure you have
// the plugin installed before running any tests. The following plugins are currently
// available:
// WebdriverCSS: https://github.com/webdriverio/webdrivercss
// WebdriverRTC: https://github.com/webdriverio/webdriverrtc
// Browserevent: https://github.com/webdriverio/browserevent
// plugins: {
// webdrivercss: {
// screenshotRoot: 'my-shots',
// failedComparisonsRoot: 'diffs',
// misMatchTolerance: 0.05,
// screenWidth: [320,480,640,1024]
// },
// webdriverrtc: {},
// browserevent: {}
// },
//
// Framework you want to run your specs with.
// The following are supported: mocha, jasmine and cucumber
// see also: http://webdriver.io/guide/testrunner/frameworks.html
//
// Make sure you have the node package for the specific framework installed before running
// any tests. If not please install the following package:
// Mocha: `$ npm install mocha`
// Jasmine: `$ npm install jasmine`
// Cucumber: `$ npm install cucumber`
framework: 'jasmine',
//
// Test reporter for stdout.
// The following are supported: dot (default), spec and xunit
// see also: http://webdriver.io/guide/testrunner/reporters.html
reporter: 'spec',
//
// Options to be passed to Jasmine.
jasmineNodeOpts: {
//
// Jasmine default timeout
defaultTimeoutInterval: 10000,
//
// The Jasmine framework allows it to intercept each assertion in order to log the state of the application
// or website depending on the result. For example it is pretty handy to take a screenshot everytime
// an assertion fails.
expectationResultHandler: function (passed, assertion) {
/**
* only take screenshot if assertion failed
*/
if (passed) {
return
}
var title = assertion.message.replace(/\s/g, '-')
browser.saveScreenshot(('./errorShots/assertionError_' + title + '.png'))
}
},
//
// =====
// Hooks
// =====
// Run functions before or after the test. If one of them returns with a promise, WebdriverIO
// will wait until that promise got resolved to continue.
//
// Gets executed before all workers get launched.
onPrepare: function () {
// do something
},
//
// Gets executed before test execution begins. At this point you will have access to all global
// variables like `browser`. It is the perfect place to define custom commands.
before: function () {
// do something
},
//
// Gets executed after all tests are done. You still have access to all global variables from
// the test.
after: function (failures, pid) {
// do something
},
//
// Gets executed after all workers got shut down and the process is about to exit. It is not
// possible to defer the end of the process using a promise.
onComplete: function () {
// do something
}
}
| fix webdriver config
| wdio.conf.js | fix webdriver config | <ide><path>dio.conf.js
<ide> ],
<ide> // Patterns to exclude.
<ide> exclude: [
<del> './e2e_test/libs/**/*.*'
<add> './e2e_test/node_modules/**/*.*'
<ide> // 'path/to/excluded/files'
<ide> ],
<ide> // |
|
Java | apache-2.0 | error: pathspec 'src/main/parse/Check.java' did not match any file(s) known to git
| 4726c64b2b6e616b4cb3585947fceac6f3a84440 | 1 | ogasawaraShinnosuke/tips,ogasawaraShinnosuke/tips | package parse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class TranMastSearch {
// ID、Hash
private static String _input_path = "dammy.txt";
// Hash(元)
private static String _check_path = "dammy.txt";
public static void main(String[] args) throws FileNotFoundException, IOException {
set_path();
try (
BufferedReader in = new BufferedReader(new FileReader(
new File(_input_path)));
BufferedReader check = new BufferedReader(new FileReader(
new File(_check_path))))
{
Map<String, Long> map = addMap(in);
List<String> list = addList(check);
if (map == null || map.isEmpty() || list == null || list.isEmpty())
throw new FileNotFoundException();
for (String str : list) {
Long id = map.get(str);
if (id == null) {
System.out.println(String.format("ERROR HASH [%s]", str));
}
}
} finally {}
}
private static List<String> addList(BufferedReader check) throws IOException {
List<String> list = new ArrayList<String>();
String line;
while ((line = check.readLine()) != null) {
if (StringUtils.isBlank(line))
continue;
list.add(line);
}
return list;
}
private static Map<String, Long> addMap(BufferedReader in) throws IOException {
Map<String, Long> map = new HashMap<String, Long>();
String line;
while ((line = in.readLine()) != null) {
if (StringUtils.isBlank(line))
continue;
String[] lines = line.split("\t");
if (lines == null || lines.length != 2)
continue;
map.put(lines[1], Long.parseLong(lines[0]));
}
return map;
}
private static void set_path() {
_input_path = "../data/input";
_check_path = "../data/check";
}
}
| src/main/parse/Check.java | Create Check.java | src/main/parse/Check.java | Create Check.java | <ide><path>rc/main/parse/Check.java
<add>package parse;
<add>
<add>import java.io.BufferedReader;
<add>import java.io.File;
<add>import java.io.FileNotFoundException;
<add>import java.io.FileReader;
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>
<add>import org.apache.commons.lang3.StringUtils;
<add>
<add>public class TranMastSearch {
<add>
<add> // ID、Hash
<add> private static String _input_path = "dammy.txt";
<add> // Hash(元)
<add> private static String _check_path = "dammy.txt";
<add>
<add> public static void main(String[] args) throws FileNotFoundException, IOException {
<add> set_path();
<add> try (
<add> BufferedReader in = new BufferedReader(new FileReader(
<add> new File(_input_path)));
<add> BufferedReader check = new BufferedReader(new FileReader(
<add> new File(_check_path))))
<add> {
<add> Map<String, Long> map = addMap(in);
<add> List<String> list = addList(check);
<add> if (map == null || map.isEmpty() || list == null || list.isEmpty())
<add> throw new FileNotFoundException();
<add> for (String str : list) {
<add> Long id = map.get(str);
<add> if (id == null) {
<add> System.out.println(String.format("ERROR HASH [%s]", str));
<add> }
<add> }
<add> } finally {}
<add> }
<add>
<add> private static List<String> addList(BufferedReader check) throws IOException {
<add> List<String> list = new ArrayList<String>();
<add> String line;
<add> while ((line = check.readLine()) != null) {
<add> if (StringUtils.isBlank(line))
<add> continue;
<add> list.add(line);
<add> }
<add> return list;
<add> }
<add>
<add> private static Map<String, Long> addMap(BufferedReader in) throws IOException {
<add> Map<String, Long> map = new HashMap<String, Long>();
<add> String line;
<add> while ((line = in.readLine()) != null) {
<add> if (StringUtils.isBlank(line))
<add> continue;
<add> String[] lines = line.split("\t");
<add> if (lines == null || lines.length != 2)
<add> continue;
<add> map.put(lines[1], Long.parseLong(lines[0]));
<add> }
<add> return map;
<add> }
<add>
<add> private static void set_path() {
<add> _input_path = "../data/input";
<add> _check_path = "../data/check";
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 0e84a71367d0d3c488a0769aadb18b583ecb9a81 | 0 | JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support | /*
* Copyright 2000-2011 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.buildServer.nuget.server.feed.server.controllers.requests;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.BuildServerListener;
import jetbrains.buildServer.serverSide.executors.ExecutorServices;
import jetbrains.buildServer.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* @author Eugene Petrenko ([email protected])
* Date: 01.12.11 13:57
*/
public class RecentNuGetRequestsDumper {
private static final Logger LOG = Logger.getInstance(RecentNuGetRequestsDumper.class.getName());
public RecentNuGetRequestsDumper(@NotNull final RecentNuGetRequests requests,
@NotNull final ExecutorServices services,
@NotNull final EventDispatcher<BuildServerListener> events) {
final Runnable command = new Runnable() {
public void run() {
final Collection<String> recentRequests = requests.getRecentRequests();
if (recentRequests.isEmpty()) return;
LOG.info("NuGet recent requests: " + recentRequests);
}
};
final ScheduledFuture<?> future = services.getNormalExecutorService().scheduleWithFixedDelay(command, 60, 60, TimeUnit.MINUTES);
events.addListener(new BuildServerAdapter(){
@Override
public void serverShutdown() {
command.run();
future.cancel(false);
}
});
}
}
| nuget-server/src/jetbrains/buildServer/nuget/server/feed/server/controllers/requests/RecentNuGetRequestsDumper.java | /*
* Copyright 2000-2011 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.buildServer.nuget.server.feed.server.controllers.requests;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.BuildServerListener;
import jetbrains.buildServer.serverSide.executors.ExecutorServices;
import jetbrains.buildServer.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* @author Eugene Petrenko ([email protected])
* Date: 01.12.11 13:57
*/
public class RecentNuGetRequestsDumper {
private static final Logger LOG = Logger.getInstance(RecentNuGetRequestsDumper.class.getName());
public RecentNuGetRequestsDumper(@NotNull final RecentNuGetRequests requests,
@NotNull final ExecutorServices services,
@NotNull final EventDispatcher<BuildServerListener> events) {
final Runnable command = new Runnable() {
public void run() {
final Collection<String> recentRequests = requests.getRecentRequests();
if (recentRequests.isEmpty()) return;
StringBuilder sb = new StringBuilder();
sb.append("NuGet recent requests:\r\n");
for (String s : recentRequests) {
sb.append(s).append("\r\n");
}
LOG.info(sb.toString());
}
};
final ScheduledFuture<?> future = services.getNormalExecutorService().scheduleWithFixedDelay(command, 60, 60, TimeUnit.MINUTES);
events.addListener(new BuildServerAdapter(){
@Override
public void serverShutdown() {
command.run();
future.cancel(false);
}
});
}
}
| update recent NuGet feed requests logging
| nuget-server/src/jetbrains/buildServer/nuget/server/feed/server/controllers/requests/RecentNuGetRequestsDumper.java | update recent NuGet feed requests logging | <ide><path>uget-server/src/jetbrains/buildServer/nuget/server/feed/server/controllers/requests/RecentNuGetRequestsDumper.java
<ide> public void run() {
<ide> final Collection<String> recentRequests = requests.getRecentRequests();
<ide> if (recentRequests.isEmpty()) return;
<del>
<del> StringBuilder sb = new StringBuilder();
<del> sb.append("NuGet recent requests:\r\n");
<del> for (String s : recentRequests) {
<del> sb.append(s).append("\r\n");
<del> }
<del> LOG.info(sb.toString());
<add> LOG.info("NuGet recent requests: " + recentRequests);
<ide> }
<ide> };
<ide> final ScheduledFuture<?> future = services.getNormalExecutorService().scheduleWithFixedDelay(command, 60, 60, TimeUnit.MINUTES); |
|
Java | apache-2.0 | bc642085901a1d7d19cc5c095499147b66131341 | 0 | stevek-ngdata/lilyproject,NGDATA/lilyproject,stevek-ngdata/lilyproject,NGDATA/lilyproject,stevek-ngdata/lilyproject,NGDATA/lilyproject | /*
* Copyright 2012 NGDATA nv
*
* 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.lilyproject.indexer.integration;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.lilyproject.indexer.model.indexerconf.IndexCase;
import org.lilyproject.indexer.model.indexerconf.IndexRecordFilter;
import org.lilyproject.indexer.model.util.IndexInfo;
import org.lilyproject.indexer.model.util.IndexesInfo;
import org.lilyproject.repository.api.FieldTypes;
import org.lilyproject.repository.api.Record;
import org.lilyproject.repository.api.Repository;
import org.lilyproject.repository.api.RepositoryException;
import org.lilyproject.util.hbase.LilyHBaseSchema.Table;
import org.lilyproject.util.hbase.RepoAndTableUtil;
import org.lilyproject.util.repo.RecordEvent;
import org.lilyproject.util.repo.RecordEvent.IndexRecordFilterData;
import org.lilyproject.util.repo.RecordEvent.Type;
import org.mockito.Mockito;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
public class IndexRecordFilterHookTest {
private Record oldRecord;
private Record newRecord;
private Repository repository;
private FieldTypes fieldTypes;
private IndexesInfo indexesInfo;
private IndexRecordFilterHook indexFilterHook;
@Before
public void setUp() {
oldRecord = mock(Record.class);
newRecord = mock(Record.class);
repository = mock(Repository.class);
fieldTypes = mock(FieldTypes.class);
indexesInfo = mock(IndexesInfo.class);
indexFilterHook = spy(new IndexRecordFilterHook(indexesInfo));
when(repository.getRepositoryName()).thenReturn(RepoAndTableUtil.DEFAULT_REPOSITORY);
}
@Test
public void testBeforeUpdate() throws RepositoryException, InterruptedException {
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.UPDATE);
recordEvent.setTableName(Table.RECORD.name);
indexFilterHook.beforeUpdate(newRecord, oldRecord, repository, fieldTypes, recordEvent);
IndexRecordFilterData idxFilterData = recordEvent.getIndexRecordFilterData();
assertTrue(idxFilterData.getOldRecordExists());
assertTrue(idxFilterData.getNewRecordExists());
verify(indexFilterHook).calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, idxFilterData);
}
@Test
public void testBeforeCreate() throws RepositoryException, InterruptedException {
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.CREATE);
recordEvent.setTableName(Table.RECORD.name);
indexFilterHook.beforeCreate(newRecord, repository, fieldTypes, recordEvent);
IndexRecordFilterData idxFilterData = recordEvent.getIndexRecordFilterData();
assertFalse(idxFilterData.getOldRecordExists());
assertTrue(idxFilterData.getNewRecordExists());
verify(indexFilterHook).calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, null, newRecord, idxFilterData);
}
@Test
public void testBeforeDelete() throws RepositoryException, InterruptedException {
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.DELETE);
recordEvent.setTableName(Table.RECORD.name);
indexFilterHook.beforeDelete(oldRecord, repository, fieldTypes, recordEvent);
IndexRecordFilterData idxFilterData = recordEvent.getIndexRecordFilterData();
assertTrue(idxFilterData.getOldRecordExists());
assertFalse(idxFilterData.getNewRecordExists());
verify(indexFilterHook).calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, null, idxFilterData);
}
@Test
public void testCalculateIndexInclusion_MoreInclusionsThanExclusions() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusionA = createMockIndexInfo("includeA", true);
IndexInfo inclusionB = createMockIndexInfo("includeB", true);
IndexInfo exclusion = createMockIndexInfo("exclude", false);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusionA, inclusionB, exclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionInclusions(ImmutableSet.of("includeA", "includeB"));
}
@Test
public void testCalculateIndexInclusion_MoreExclusionsThanInclusions() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusion = createMockIndexInfo("include", true);
IndexInfo exclusionA = createMockIndexInfo("excludeA", false);
IndexInfo exclusionB = createMockIndexInfo("excludeB", false);
when(this.indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion, exclusionA, exclusionB));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(ImmutableSet.of("excludeA", "excludeB"));
}
@Test
public void testCalculateIndexInclusion_AllIndexesIncluded() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionInclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
}
@Test
public void testCalculateIndexInclusion_AllIndexesExcluded() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusion = createMockIndexInfo("exclude", false);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
}
@Test
public void testCalculateIndexInclusion_NoIndexSubscriptions() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.<IndexInfo>newArrayList());
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
}
@Test
public void testCalculateIndexInclusion_RepoBasedExclusion() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusionA = createMockIndexInfo("includeA", true);
IndexInfo inclusionB = createMockIndexInfo("includeButNotInThisRepo", true);
when(inclusionB.getIndexDefinition().getRepositoryName()).thenReturn("someOtherRepo");
IndexInfo exclusion = createMockIndexInfo("exclude", false);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusionA, inclusionB, exclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(ImmutableSet.of("includeButNotInThisRepo", "exclude"));
}
@Test
public void testCalculateIndexInclusion_ForNonDefaultRepository() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusionA = createMockIndexInfo("inclusionA", true);
IndexInfo exclusion = createMockIndexInfo("excludeA", false);
IndexInfo inclusionB = createMockIndexInfo("inclusionB", true);
when(inclusionB.getIndexDefinition().getRepositoryName()).thenReturn("someOtherRepo");
when(this.indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusionA, exclusion, inclusionB));
indexFilterHook.calculateIndexInclusion("someOtherRepo",
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(ImmutableSet.of("inclusionA", "excludeA"));
}
@Test
public void testCalculateIndexInclusion_RepoBasedInclusion() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusionA = createMockIndexInfo("inclusionA", true);
IndexInfo exclusion = createMockIndexInfo("excludeA", false);
IndexInfo inclusionB = createMockIndexInfo("inclusionB", true);
ArrayList<IndexInfo> infos = Lists.newArrayList(inclusionA, exclusion, inclusionB);
for (IndexInfo info : infos) {
when(info.getIndexDefinition().getRepositoryName()).thenReturn("someOtherRepo");
}
when(this.indexesInfo.getIndexInfos()).thenReturn(infos);
indexFilterHook.calculateIndexInclusion("someOtherRepo",
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionInclusions(ImmutableSet.of("inclusionA","inclusionB"));
}
private IndexInfo createMockIndexInfo(String queueSubscriptionId, boolean include) {
IndexInfo indexInfo = mock(IndexInfo.class, Mockito.RETURNS_DEEP_STUBS);
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
when(indexInfo.getIndexerConf().getRecordFilter()).thenReturn(indexRecordFilter);
doReturn(include).when(indexFilterHook).indexIsApplicable(indexRecordFilter, Table.RECORD.name, oldRecord, newRecord);
when(indexInfo.getIndexDefinition().getQueueSubscriptionId()).thenReturn(queueSubscriptionId);
return indexInfo;
}
@Test
public void testIndexIsApplicable_TrueForOldRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record oldRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, oldRecord)).thenReturn(mock(IndexCase.class));
assertTrue(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, oldRecord, null));
}
@Test
public void testIndexIsApplicable_FalseForOldRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record oldRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, oldRecord)).thenReturn(null);
assertFalse(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, oldRecord, null));
}
@Test
public void testIndexIsApplicable_TrueForNewRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record newRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, newRecord)).thenReturn(mock(IndexCase.class));
assertTrue(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, null, newRecord));
}
@Test
public void testIndexIsApplicable_FalseForNewRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record newRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, newRecord)).thenReturn(null);
assertFalse(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, null, newRecord));
}
}
| cr/indexer/engine/src/test/java/org/lilyproject/indexer/integration/IndexRecordFilterHookTest.java | /*
* Copyright 2012 NGDATA nv
*
* 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.lilyproject.indexer.integration;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.lilyproject.indexer.model.indexerconf.IndexCase;
import org.lilyproject.indexer.model.indexerconf.IndexRecordFilter;
import org.lilyproject.indexer.model.util.IndexInfo;
import org.lilyproject.indexer.model.util.IndexesInfo;
import org.lilyproject.repository.api.FieldTypes;
import org.lilyproject.repository.api.Record;
import org.lilyproject.repository.api.Repository;
import org.lilyproject.repository.api.RepositoryException;
import org.lilyproject.util.hbase.LilyHBaseSchema.Table;
import org.lilyproject.util.hbase.RepoAndTableUtil;
import org.lilyproject.util.repo.RecordEvent;
import org.lilyproject.util.repo.RecordEvent.IndexRecordFilterData;
import org.lilyproject.util.repo.RecordEvent.Type;
import org.mockito.Mockito;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class IndexRecordFilterHookTest {
private Record oldRecord;
private Record newRecord;
private Repository repository;
private FieldTypes fieldTypes;
private IndexesInfo indexesInfo;
private IndexRecordFilterHook indexFilterHook;
@Before
public void setUp() {
oldRecord = mock(Record.class);
newRecord = mock(Record.class);
repository = mock(Repository.class);
fieldTypes = mock(FieldTypes.class);
indexesInfo = mock(IndexesInfo.class);
indexFilterHook = spy(new IndexRecordFilterHook(indexesInfo));
when(repository.getRepositoryName()).thenReturn(RepoAndTableUtil.DEFAULT_REPOSITORY);
}
@Test
public void testBeforeUpdate() throws RepositoryException, InterruptedException {
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.UPDATE);
recordEvent.setTableName(Table.RECORD.name);
indexFilterHook.beforeUpdate(newRecord, oldRecord, repository, fieldTypes, recordEvent);
IndexRecordFilterData idxFilterData = recordEvent.getIndexRecordFilterData();
assertTrue(idxFilterData.getOldRecordExists());
assertTrue(idxFilterData.getNewRecordExists());
verify(indexFilterHook).calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, idxFilterData);
}
@Test
public void testBeforeCreate() throws RepositoryException, InterruptedException {
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.CREATE);
recordEvent.setTableName(Table.RECORD.name);
indexFilterHook.beforeCreate(newRecord, repository, fieldTypes, recordEvent);
IndexRecordFilterData idxFilterData = recordEvent.getIndexRecordFilterData();
assertFalse(idxFilterData.getOldRecordExists());
assertTrue(idxFilterData.getNewRecordExists());
verify(indexFilterHook).calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, null, newRecord, idxFilterData);
}
@Test
public void testBeforeDelete() throws RepositoryException, InterruptedException {
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
RecordEvent recordEvent = new RecordEvent();
recordEvent.setType(Type.DELETE);
recordEvent.setTableName(Table.RECORD.name);
indexFilterHook.beforeDelete(oldRecord, repository, fieldTypes, recordEvent);
IndexRecordFilterData idxFilterData = recordEvent.getIndexRecordFilterData();
assertTrue(idxFilterData.getOldRecordExists());
assertFalse(idxFilterData.getNewRecordExists());
verify(indexFilterHook).calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, null, idxFilterData);
}
@Test
public void testCalculateIndexInclusion_MoreInclusionsThanExclusions() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusionA = createMockIndexInfo("includeA", true);
IndexInfo inclusionB = createMockIndexInfo("includeB", true);
IndexInfo exclusion = createMockIndexInfo("exclude", false);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusionA, inclusionB, exclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionInclusions(ImmutableSet.of("includeA", "includeB"));
}
@Test
public void testCalculateIndexInclusion_MoreExclusionsThanInclusions() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusion = createMockIndexInfo("include", true);
IndexInfo exclusionA = createMockIndexInfo("excludeA", false);
IndexInfo exclusionB = createMockIndexInfo("excludeB", false);
when(this.indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion, exclusionA, exclusionB));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(ImmutableSet.of("excludeA", "excludeB"));
}
@Test
public void testCalculateIndexInclusion_AllIndexesIncluded() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusion = createMockIndexInfo("include", true);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionInclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
}
@Test
public void testCalculateIndexInclusion_AllIndexesExcluded() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
IndexInfo inclusion = createMockIndexInfo("exclude", false);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusion));
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
}
@Test
public void testCalculateIndexInclusion_NoIndexSubscriptions() {
IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
when(indexesInfo.getIndexInfos()).thenReturn(Lists.<IndexInfo>newArrayList());
indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
Table.RECORD.name, oldRecord, newRecord, indexFilterData);
verify(indexFilterData).setSubscriptionExclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
}
private IndexInfo createMockIndexInfo(String queueSubscriptionId, boolean include) {
IndexInfo indexInfo = mock(IndexInfo.class, Mockito.RETURNS_DEEP_STUBS);
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
when(indexInfo.getIndexerConf().getRecordFilter()).thenReturn(indexRecordFilter);
doReturn(include).when(indexFilterHook).indexIsApplicable(indexRecordFilter, Table.RECORD.name, oldRecord, newRecord);
when(indexInfo.getIndexDefinition().getQueueSubscriptionId()).thenReturn(queueSubscriptionId);
return indexInfo;
}
@Test
public void testIndexIsApplicable_TrueForOldRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record oldRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, oldRecord)).thenReturn(mock(IndexCase.class));
assertTrue(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, oldRecord, null));
}
@Test
public void testIndexIsApplicable_FalseForOldRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record oldRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, oldRecord)).thenReturn(null);
assertFalse(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, oldRecord, null));
}
@Test
public void testIndexIsApplicable_TrueForNewRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record newRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, newRecord)).thenReturn(mock(IndexCase.class));
assertTrue(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, null, newRecord));
}
@Test
public void testIndexIsApplicable_FalseForNewRecord() {
IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class);
Record newRecord = mock(Record.class);
when(indexRecordFilter.getIndexCase(Table.RECORD.name, newRecord)).thenReturn(null);
assertFalse(indexFilterHook.indexIsApplicable(indexRecordFilter, Table.RECORD.name, null, newRecord));
}
}
| add tests for repository-based inclusion/exclusion in IndexRecordFilterHook
| cr/indexer/engine/src/test/java/org/lilyproject/indexer/integration/IndexRecordFilterHookTest.java | add tests for repository-based inclusion/exclusion in IndexRecordFilterHook | <ide><path>r/indexer/engine/src/test/java/org/lilyproject/indexer/integration/IndexRecordFilterHookTest.java
<ide> import static org.mockito.Mockito.verify;
<ide> import static org.mockito.Mockito.when;
<ide>
<add>import java.util.ArrayList;
<add>
<ide> public class IndexRecordFilterHookTest {
<ide>
<ide> private Record oldRecord;
<ide> verify(indexFilterData).setSubscriptionExclusions(IndexRecordFilterData.ALL_INDEX_SUBSCRIPTIONS);
<ide> }
<ide>
<add> @Test
<add> public void testCalculateIndexInclusion_RepoBasedExclusion() {
<add> IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
<add> IndexInfo inclusionA = createMockIndexInfo("includeA", true);
<add> IndexInfo inclusionB = createMockIndexInfo("includeButNotInThisRepo", true);
<add> when(inclusionB.getIndexDefinition().getRepositoryName()).thenReturn("someOtherRepo");
<add> IndexInfo exclusion = createMockIndexInfo("exclude", false);
<add>
<add> when(indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusionA, inclusionB, exclusion));
<add>
<add> indexFilterHook.calculateIndexInclusion(RepoAndTableUtil.DEFAULT_REPOSITORY,
<add> Table.RECORD.name, oldRecord, newRecord, indexFilterData);
<add>
<add> verify(indexFilterData).setSubscriptionExclusions(ImmutableSet.of("includeButNotInThisRepo", "exclude"));
<add> }
<add>
<add> @Test
<add> public void testCalculateIndexInclusion_ForNonDefaultRepository() {
<add> IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
<add> IndexInfo inclusionA = createMockIndexInfo("inclusionA", true);
<add> IndexInfo exclusion = createMockIndexInfo("excludeA", false);
<add> IndexInfo inclusionB = createMockIndexInfo("inclusionB", true);
<add> when(inclusionB.getIndexDefinition().getRepositoryName()).thenReturn("someOtherRepo");
<add>
<add> when(this.indexesInfo.getIndexInfos()).thenReturn(Lists.newArrayList(inclusionA, exclusion, inclusionB));
<add>
<add> indexFilterHook.calculateIndexInclusion("someOtherRepo",
<add> Table.RECORD.name, oldRecord, newRecord, indexFilterData);
<add>
<add> verify(indexFilterData).setSubscriptionExclusions(ImmutableSet.of("inclusionA", "excludeA"));
<add> }
<add>
<add> @Test
<add> public void testCalculateIndexInclusion_RepoBasedInclusion() {
<add> IndexRecordFilterData indexFilterData = mock(IndexRecordFilterData.class);
<add> IndexInfo inclusionA = createMockIndexInfo("inclusionA", true);
<add> IndexInfo exclusion = createMockIndexInfo("excludeA", false);
<add> IndexInfo inclusionB = createMockIndexInfo("inclusionB", true);
<add> ArrayList<IndexInfo> infos = Lists.newArrayList(inclusionA, exclusion, inclusionB);
<add> for (IndexInfo info : infos) {
<add> when(info.getIndexDefinition().getRepositoryName()).thenReturn("someOtherRepo");
<add> }
<add> when(this.indexesInfo.getIndexInfos()).thenReturn(infos);
<add>
<add> indexFilterHook.calculateIndexInclusion("someOtherRepo",
<add> Table.RECORD.name, oldRecord, newRecord, indexFilterData);
<add>
<add> verify(indexFilterData).setSubscriptionInclusions(ImmutableSet.of("inclusionA","inclusionB"));
<add> }
<add>
<ide> private IndexInfo createMockIndexInfo(String queueSubscriptionId, boolean include) {
<ide> IndexInfo indexInfo = mock(IndexInfo.class, Mockito.RETURNS_DEEP_STUBS);
<ide> IndexRecordFilter indexRecordFilter = mock(IndexRecordFilter.class); |
|
Java | mit | a40952937bae27591e43d18df8b670a3a0b663da | 0 | nfleet/java-sdk | package fi.cosky.sdk.tests;
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import fi.cosky.sdk.*;
import fi.cosky.sdk.CoordinateData.CoordinateSystem;
public class TestHelper {
private static API apis = null;
static String clientKey = "";
static String clientSecret = "";
static API authenticate() {
String url = "https://api.nfleet.fi";
if (apis == null) {
API api = new API(url);
api.setTimed(true);
if (api.authenticate(clientKey, clientSecret)) {
apis = api;
} else {
System.out.println("Could not authenticate, please check service and credentials");
return null;
}
}
return apis;
}
static UserData getOrCreateUser( API api ) {
try {
ApiData apiData = api.navigate(ApiData.class, api.getRoot());
UserData user = new UserData();
ResponseData createdUser = api.navigate(ResponseData.class, apiData.getLink("create-user"), user);
user = api.navigate(UserData.class, createdUser.getLocation());
return user;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong");
return null;
} catch (IOException e) {
return null;
}
}
static RoutingProblemData createProblem(API api, UserData user) {
try {
RoutingProblemData problem = new RoutingProblemData("exampleProblem");
ResponseData created = api.navigate(ResponseData.class, user.getLink("create-problem"), problem);
problem = api.navigate(RoutingProblemData.class, created.getLocation());
return problem;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong");
return null;
} catch (IOException e) {
return null;
}
}
static RoutingProblemData createProblemWithDemoData(API api, UserData user) {
RoutingProblemData problem = createProblem(api, user);
TestData.CreateDemoData(problem, api);
return problem;
}
static VehicleData getVehicle(API api, UserData user, RoutingProblemData problem) {
try {
TestData.CreateDemoData(problem, api);
VehicleDataSet vehicles = api.navigate(VehicleDataSet.class, problem.getLink("list-vehicles"));
VehicleData vehicle = null;
vehicle = api.navigate(VehicleData.class, vehicles.getItems().get(0).getLink("self"));
return vehicle;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong: " + e.toString());
return null;
} catch (IOException e) {
return null;
}
}
static TaskData getTask(API api, RoutingProblemData problem) {
LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
TimeWindowData twstart = createTimeWindow(7, 20);
ArrayList<TimeWindowData> timewindows = new ArrayList<TimeWindowData>();
timewindows.add(twstart);
task1.setTimeWindows(timewindows);
task2.setTimeWindows(timewindows);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName("testTask");
try {
ResponseData createdTask = api.navigate(ResponseData.class, problem.getLink("create-task"), task);
TaskData td = api.navigate(TaskData.class, createdTask.getLocation());
return td;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong " + e.toString());
return null;
} catch (IOException e) {
return null;
}
}
static TaskUpdateRequest createTaskUpdateRequest(String name) {
LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
List<TimeWindowData> timeWindows = new ArrayList<TimeWindowData>();
TimeWindowData tw = createTimeWindow(7, 20);
timeWindows.add(tw);
task1.setTimeWindows(timeWindows);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
task2.setTimeWindows(timeWindows);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName(name);
return task;
}
static List<TaskUpdateRequest> createListOfTasks(int howMany) {
List<TaskUpdateRequest> tasks = new ArrayList<TaskUpdateRequest>();
for (int i = 0; i < howMany; i++) {
LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
TimeWindowData twstart = createTimeWindow(7, 20);
ArrayList<TimeWindowData> timewindows = new ArrayList<TimeWindowData>();
timewindows.add(twstart);
task1.setTimeWindows(timewindows);
task2.setTimeWindows(timewindows);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName("testTask" + i);
tasks.add(task);
}
return tasks;
}
static VehicleUpdateRequest createVehicleUpdateRequest(String name) {
ArrayList<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(new CapacityData("Weight", 100000));
ArrayList<TimeWindowData> timeWindows = new ArrayList<TimeWindowData>();
timeWindows.add(createTimeWindow(7, 20));
LocationData startLocation = createLocationWithCoordinates(Location.VEHICLE_START);
VehicleUpdateRequest vehicleRequest = new VehicleUpdateRequest(name, capacities, startLocation, startLocation);
vehicleRequest.setVehicleSpeedProfile(SpeedProfile.Max80Kmh);
vehicleRequest.setVehicleSpeedFactor(0.7);
vehicleRequest.setTimeWindows(timeWindows);
return vehicleRequest;
}
static LocationData createLocationWithCoordinates(Location name) {
CoordinateData coordinates = new CoordinateData();
switch (name){
case TASK_PICKUP: {
coordinates.setLatitude(62.244958);
coordinates.setLongitude(25.747143);
break;
}
case TASK_DELIVERY: {
coordinates.setLatitude(62.244589);
coordinates.setLongitude(25.74892);
break;
}
case VEHICLE_START:
default: {
coordinates.setLatitude(62.247906);
coordinates.setLongitude(25.867395);
break;
}
}
coordinates.setSystem(CoordinateSystem.Euclidian);
LocationData data = new LocationData();
data.setCoordinatesData(coordinates);
return data;
}
static LocationData createLocationWithAddress() {
AddressData address = new AddressData();
address.setCity("Jyvskyl");
address.setCountry("Finland");
address.setPostalCode("40100");
address.setStreet("Mattilanniemi 2");
LocationData data = new LocationData();
data.setAddress(address);
return data;
}
static VehicleData createAndGetVehicle(API api, RoutingProblemData problem, VehicleUpdateRequest request) {
try {
ResponseData result = api.navigate(ResponseData.class, problem.getLink("create-vehicle"), request);
VehicleData vehicle = api.navigate(VehicleData.class, result.getLocation());
return vehicle;
}
catch (Exception e) {
System.out.println("Something went wrong. Unable to create a vehicle.");
}
return null;
}
static TaskData createAndGetTask(API api, RoutingProblemData problem, TaskUpdateRequest request) {
try {
ResponseData result = api.navigate(ResponseData.class, problem.getLink("create-task"), request);
TaskData task = api.navigate(TaskData.class, result.getLocation());
return task;
}
catch (Exception e) {
System.out.println("Something went wrong. Unable to create a task.");
}
return null;
}
enum Location{ VEHICLE_START, TASK_PICKUP, TASK_DELIVERY};
static TimeWindowData createTimeWindow(int start, int end) {
Date startD = new Date();
startD.setHours(start);
Date endD = new Date();
endD.setHours(end);
TimeWindowData twd = new TimeWindowData(startD, endD);
return twd;
}
}
| fi/cosky/sdk/tests/TestHelper.java | package fi.cosky.sdk.tests;
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import fi.cosky.sdk.*;
import fi.cosky.sdk.CoordinateData.CoordinateSystem;
public class TestHelper {
private static API apis = null;
static String clientKey = "";
static String clientSecret = "";
static API authenticate() {
String url = "https://api.nfleet.fi";
if (apis == null) {
API api = new API(url);
api.setTimed(true);
if (api.authenticate(clientKey, clientSecret)) {
apis = api;
} else {
System.out.println("Could not authenticate, please check service and credentials");
return null;
}
}
return apis;
}
static UserData getOrCreateUser( API api ) {
try {
ApiData apiData = api.navigate(ApiData.class, api.getRoot());
UserDataSet users = api.navigate(UserDataSet.class, apiData.getLink("list-users"));
UserData user = null;
if ( users.getItems() != null && users.getItems().size() < 1) {
user = new UserData();
ResponseData createdUser = api.navigate(ResponseData.class, apiData.getLink("create-user"), user);
user = api.navigate(UserData.class, createdUser.getLocation());
} else {
user = api.navigate(UserData.class, users.getItems().get(users.getItems().size()-1).getLink("self"));
}
return user;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong");
return null;
} catch (IOException e) {
return null;
}
}
static RoutingProblemData createProblem(API api, UserData user) {
try {
RoutingProblemData problem = new RoutingProblemData("exampleProblem");
RoutingProblemDataSet problems = api.navigate(RoutingProblemDataSet.class, user.getLink("list-problems"));
ResponseData created = api.navigate(ResponseData.class, user.getLink("create-problem"), problem);
problem = api.navigate(RoutingProblemData.class, created.getLocation());
return problem;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong");
return null;
} catch (IOException e) {
return null;
}
}
static RoutingProblemData createProblemWithDemoData(API api, UserData user) {
RoutingProblemData problem = createProblem(api, user);
TestData.CreateDemoData(problem, api);
return problem;
}
static VehicleData getVehicle(API api, UserData user, RoutingProblemData problem) {
try {
TestData.CreateDemoData(problem, api);
VehicleDataSet vehicles = api.navigate(VehicleDataSet.class, problem.getLink("list-vehicles"));
VehicleData vehicle = null;
vehicle = api.navigate(VehicleData.class, vehicles.getItems().get(0).getLink("self"));
return vehicle;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong: " + e.toString());
return null;
} catch (IOException e) {
return null;
}
}
static TaskData getTask(API api, RoutingProblemData problem) {
LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
TimeWindowData twstart = createTimeWindow(7, 20);
ArrayList<TimeWindowData> timewindows = new ArrayList<TimeWindowData>();
timewindows.add(twstart);
task1.setTimeWindows(timewindows);
task2.setTimeWindows(timewindows);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName("testTask");
try {
ResponseData createdTask = api.navigate(ResponseData.class, problem.getLink("create-task"), task);
TaskData td = api.navigate(TaskData.class, createdTask.getLocation());
return td;
} catch (NFleetRequestException e) {
System.out.println("Something went wrong " + e.toString());
return null;
} catch (IOException e) {
return null;
}
}
static TaskUpdateRequest createTaskUpdateRequest(String name) {
LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
List<TimeWindowData> timeWindows = new ArrayList<TimeWindowData>();
TimeWindowData tw = createTimeWindow(7, 20);
timeWindows.add(tw);
task1.setTimeWindows(timeWindows);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
task2.setTimeWindows(timeWindows);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName(name);
return task;
}
static List<TaskUpdateRequest> createListOfTasks(int howMany) {
List<TaskUpdateRequest> tasks = new ArrayList<TaskUpdateRequest>();
for (int i = 0; i < howMany; i++) {
LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
CapacityData capacity = new CapacityData("Weight", 20);
List<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(capacity);
TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
TimeWindowData twstart = createTimeWindow(7, 20);
ArrayList<TimeWindowData> timewindows = new ArrayList<TimeWindowData>();
timewindows.add(twstart);
task1.setTimeWindows(timewindows);
task2.setTimeWindows(timewindows);
List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
both.add(task1);
both.add(task2);
TaskUpdateRequest task = new TaskUpdateRequest(both);
task.setName("testTask" + i);
tasks.add(task);
}
return tasks;
}
static VehicleUpdateRequest createVehicleUpdateRequest(String name) {
ArrayList<CapacityData> capacities = new ArrayList<CapacityData>();
capacities.add(new CapacityData("Weight", 100000));
ArrayList<TimeWindowData> timeWindows = new ArrayList<TimeWindowData>();
timeWindows.add(createTimeWindow(7, 20));
LocationData startLocation = createLocationWithCoordinates(Location.VEHICLE_START);
VehicleUpdateRequest vehicleRequest = new VehicleUpdateRequest(name, capacities, startLocation, startLocation);
vehicleRequest.setVehicleSpeedProfile(SpeedProfile.Max80Kmh);
vehicleRequest.setVehicleSpeedFactor(0.7);
vehicleRequest.setTimeWindows(timeWindows);
return vehicleRequest;
}
static LocationData createLocationWithCoordinates(Location name) {
CoordinateData coordinates = new CoordinateData();
switch (name){
case TASK_PICKUP: {
coordinates.setLatitude(62.244958);
coordinates.setLongitude(25.747143);
break;
}
case TASK_DELIVERY: {
coordinates.setLatitude(62.244589);
coordinates.setLongitude(25.74892);
break;
}
case VEHICLE_START:
default: {
coordinates.setLatitude(62.247906);
coordinates.setLongitude(25.867395);
break;
}
}
coordinates.setSystem(CoordinateSystem.Euclidian);
LocationData data = new LocationData();
data.setCoordinatesData(coordinates);
return data;
}
static LocationData createLocationWithAddress() {
AddressData address = new AddressData();
address.setCity("Jyvskyl");
address.setCountry("Finland");
address.setPostalCode("40100");
address.setStreet("Mattilanniemi 2");
LocationData data = new LocationData();
data.setAddress(address);
return data;
}
static VehicleData createAndGetVehicle(API api, RoutingProblemData problem, VehicleUpdateRequest request) {
try {
ResponseData result = api.navigate(ResponseData.class, problem.getLink("create-vehicle"), request);
VehicleData vehicle = api.navigate(VehicleData.class, result.getLocation());
return vehicle;
}
catch (Exception e) {
System.out.println("Something went wrong. Unable to create a vehicle.");
}
return null;
}
static TaskData createAndGetTask(API api, RoutingProblemData problem, TaskUpdateRequest request) {
try {
ResponseData result = api.navigate(ResponseData.class, problem.getLink("create-task"), request);
TaskData task = api.navigate(TaskData.class, result.getLocation());
return task;
}
catch (Exception e) {
System.out.println("Something went wrong. Unable to create a task.");
}
return null;
}
enum Location{ VEHICLE_START, TASK_PICKUP, TASK_DELIVERY};
static TimeWindowData createTimeWindow(int start, int end) {
Date startD = new Date();
startD.setHours(start);
Date endD = new Date();
endD.setHours(end);
TimeWindowData twd = new TimeWindowData(startD, endD);
return twd;
}
}
| Made it so that tests create new user every time.
| fi/cosky/sdk/tests/TestHelper.java | Made it so that tests create new user every time. | <ide><path>i/cosky/sdk/tests/TestHelper.java
<ide> static UserData getOrCreateUser( API api ) {
<ide> try {
<ide> ApiData apiData = api.navigate(ApiData.class, api.getRoot());
<del> UserDataSet users = api.navigate(UserDataSet.class, apiData.getLink("list-users"));
<del> UserData user = null;
<del> if ( users.getItems() != null && users.getItems().size() < 1) {
<del> user = new UserData();
<del> ResponseData createdUser = api.navigate(ResponseData.class, apiData.getLink("create-user"), user);
<del> user = api.navigate(UserData.class, createdUser.getLocation());
<del> } else {
<del> user = api.navigate(UserData.class, users.getItems().get(users.getItems().size()-1).getLink("self"));
<del> }
<add> UserData user = new UserData();
<add> ResponseData createdUser = api.navigate(ResponseData.class, apiData.getLink("create-user"), user);
<add> user = api.navigate(UserData.class, createdUser.getLocation());
<ide> return user;
<ide> } catch (NFleetRequestException e) {
<ide> System.out.println("Something went wrong");
<ide> static RoutingProblemData createProblem(API api, UserData user) {
<ide> try {
<ide> RoutingProblemData problem = new RoutingProblemData("exampleProblem");
<del> RoutingProblemDataSet problems = api.navigate(RoutingProblemDataSet.class, user.getLink("list-problems"));
<ide> ResponseData created = api.navigate(ResponseData.class, user.getLink("create-problem"), problem);
<ide> problem = api.navigate(RoutingProblemData.class, created.getLocation());
<ide> return problem; |
|
Java | apache-2.0 | d9c71ce79292454e55ec4d212e521efc470a9935 | 0 | mtransitapps/ca-niagara-region-transit-bus-parser | package org.mtransit.parser.ca_niagara_region_transit_bus;
import static org.mtransit.commons.RegexUtils.DIGITS;
import static org.mtransit.commons.StringUtils.EMPTY;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mtransit.commons.CharUtils;
import org.mtransit.commons.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.gtfs.data.GAgency;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.mt.data.MAgency;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// https://niagaraopendata.ca/dataset/niagara-region-transit-gtfs
// https://maps.niagararegion.ca/googletransit/NiagaraRegionTransit.zip
public class NiagaraRegionTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(@NotNull String[] args) {
new NiagaraRegionTransitBusAgencyTools().start(args);
}
@Nullable
@Override
public List<Locale> getSupportedLanguages() {
return LANG_EN;
}
@Override
public boolean defaultExcludeEnabled() {
return true;
}
@NotNull
@Override
public String getAgencyName() {
return "Niagara Region Transit";
}
private static final String NIAGARA_REGION_TRANSIT = "Niagara Region Transit";
private static final String EXCLUDE_STC_ROUTE_IDS_STARTS_WITH = "STC_";
@Override
public boolean excludeAgency(@NotNull GAgency gAgency) {
//noinspection deprecation
final String agencyId = gAgency.getAgencyId();
if (!agencyId.contains(NIAGARA_REGION_TRANSIT)
&& !agencyId.contains("AllNRT_")
&& !agencyId.equals("1")) {
return EXCLUDE;
}
return super.excludeAgency(gAgency);
}
@Override
public boolean excludeRoute(@NotNull GRoute gRoute) {
//noinspection deprecation
final String agencyId = gRoute.getAgencyIdOrDefault();
if (!agencyId.contains(NIAGARA_REGION_TRANSIT)
&& !agencyId.contains("AllNRT_")
&& !agencyId.equals("1")) {
return EXCLUDE;
}
if (agencyId.contains("AllNRT_") || agencyId.equals("1")) {
if (!CharUtils.isDigitsOnly(gRoute.getRouteShortName())) {
return true; // exclude
}
final int rsn = Integer.parseInt(gRoute.getRouteShortName());
if (rsn > 100) {
return EXCLUDE;
}
}
//noinspection deprecation
final String routeId = gRoute.getRouteId();
if (routeId.startsWith(EXCLUDE_STC_ROUTE_IDS_STARTS_WITH)) {
return EXCLUDE;
}
return super.excludeRoute(gRoute);
}
@NotNull
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public boolean defaultRouteIdEnabled() {
return true;
}
@Override
public boolean useRouteShortNameForRouteId() {
return true;
}
@Override
public boolean defaultRouteLongNameEnabled() {
return true;
}
private static final Pattern STARTS_WITH_CT = Pattern.compile("(^(NRT - ))", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_CT = Pattern.compile("( (nf|sc|we)$)", Pattern.CASE_INSENSITIVE);
@NotNull
@Override
public String cleanRouteLongName(@NotNull String routeLongName) {
routeLongName = STARTS_WITH_CT.matcher(routeLongName).replaceAll(EMPTY);
routeLongName = ENDS_WITH_CT.matcher(routeLongName).replaceAll(EMPTY);
//noinspection deprecation
routeLongName = CleanUtils.removePoints(routeLongName);
return routeLongName;
}
private static final String AGENCY_COLOR_GREEN = "6CB33F"; // GREEN (from PDF)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public boolean defaultAgencyColorEnabled() {
return true;
}
@NotNull
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@SuppressWarnings("DuplicateBranchesInSwitch")
@Nullable
@Override
public String provideMissingRouteColor(@NotNull GRoute gRoute) {
final Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName());
if (matcher.find()) {
final int rsn = Integer.parseInt(matcher.group());
switch (rsn) {
// @formatter:off
case 22: return "766A24";
case 25: return "00AAA0"; // Welland Transit?
case 40: return "1B5C28";
case 45: return "1B5C28";
case 50: return "F1471C";
case 55: return "F1471C";
case 60: return "1378C7";
case 65: return "1378C7";
case 70: return "62B92C";
case 75: return "62B92C";
// @formatter:on
}
}
throw new MTLog.Fatal("Unexpected route color for %s!", gRoute);
}
private static final Pattern STARTS_WITH_NRT_A00_ = Pattern.compile( //
"((^)((allnrt|nrt|)_([a-z]{1,3})?[\\d]{2,4}(_)?([A-Z]{3}(stop))?(stop)?)(NFT)?)", //
Pattern.CASE_INSENSITIVE);
@NotNull
@Override
public String cleanStopOriginalId(@NotNull String gStopId) {
gStopId = STARTS_WITH_NRT_A00_.matcher(gStopId).replaceAll(EMPTY);
return gStopId;
}
@Override
public boolean directionFinderEnabled() {
return true;
}
private static final Pattern STARTS_WITH_RSN = Pattern.compile("((^)[\\d]{2}([a-z] | ))", Pattern.CASE_INSENSITIVE);
private static final String STARTS_WITH_RSN_REPLACEMENT = "$3";
private static final Pattern IMT_ = Pattern.compile("((^|\\W)(imt -|imt)(\\W|$))", Pattern.CASE_INSENSITIVE); // Inter-Municipal Transit
private static final String ST_CATHARINES = "St Catharines";
private static final Pattern ST_CATHARINES_ = Pattern.compile("((^|\\W)(" //
+ "st\\. catharines" + "|" //
+ "st\\. catharine" + "|" //
+ "st\\. catharin" + "|" //
+ "st\\. cathari" + "|" //
+ "st\\. cathar" + "|" //
+ "st\\. catha" + "|" //
+ "st\\. cath" + "|" //
+ "st\\. cat" + "|" //
+ "st\\. ca" + "|" //
+ "st\\. c" + "|" //
+ "st\\. " //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String ST_CATHARINES_REPLACEMENT = "$2" + ST_CATHARINES + "$4";
private static final String NIAGARA_FALLS = "Niagara Falls";
private static final Pattern NIAGARA_FALLS_ = Pattern.compile("((^|\\W)(" //
+ "niagara falls" + "|" //
+ "niagara fall" + "|" //
+ "niag" + "|" //
+ "nia\\. falls" + "|" //
+ "falls" //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String NIAGARA_FALLS_REPLACEMENT = "$2" + NIAGARA_FALLS + "$4";
private static final String OUTLET_MALL = "Outlet Mall";
private static final Pattern OUTLET_MALL_ = Pattern.compile("((^|\\W)(" //
+ "outlet mall" + "|" //
+ "outlet m" //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String OUTLET_MALL_REPLACEMENT = "$2" + OUTLET_MALL + "$4";
private static final String WELLAND = "Welland";
private static final Pattern WELLAND_ = Pattern.compile("((^|\\W)(" //
+ "welland" + "|" //
+ "wellan" //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String WELLAND_REPLACEMENT = "$2" + WELLAND + "$4";
private static final Pattern NOTL_ = Pattern.compile("((^|\\W)(" //
+ "notl"
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String NOTL_REPLACEMENT_ = "$2" + "NOTL" + "$4";
private static final Pattern AND_NO_SPACE = Pattern.compile("(([\\S])\\s?([&@])\\s?([\\S]))", Pattern.CASE_INSENSITIVE);
private static final String AND_NO_SPACE_REPLACEMENT = "$2 $3 $4";
@NotNull
@Override
public String cleanTripHeadsign(@NotNull String tripHeadsign) {
tripHeadsign = AND_NO_SPACE.matcher(tripHeadsign).replaceAll(AND_NO_SPACE_REPLACEMENT);
tripHeadsign = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, tripHeadsign, getIgnoredWords());
tripHeadsign = STARTS_WITH_RSN.matcher(tripHeadsign).replaceAll(STARTS_WITH_RSN_REPLACEMENT);
tripHeadsign = IMT_.matcher(tripHeadsign).replaceAll(EMPTY);
tripHeadsign = ST_CATHARINES_.matcher(tripHeadsign).replaceAll(ST_CATHARINES_REPLACEMENT);
tripHeadsign = NIAGARA_FALLS_.matcher(tripHeadsign).replaceAll(NIAGARA_FALLS_REPLACEMENT);
tripHeadsign = NOTL_.matcher(tripHeadsign).replaceAll(NOTL_REPLACEMENT_);
tripHeadsign = OUTLET_MALL_.matcher(tripHeadsign).replaceAll(OUTLET_MALL_REPLACEMENT);
tripHeadsign = WELLAND_.matcher(tripHeadsign).replaceAll(WELLAND_REPLACEMENT);
tripHeadsign = CleanUtils.cleanBounds(tripHeadsign);
tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private String[] getIgnoredWords() {
return new String[]{
"NE", "NW", "SE", "SW",
"GO", "NF", "NOTL",
};
}
@NotNull
@Override
public String cleanStopName(@NotNull String gStopName) {
gStopName = AND_NO_SPACE.matcher(gStopName).replaceAll(AND_NO_SPACE_REPLACEMENT);
gStopName = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, gStopName, getIgnoredWords());
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.cleanBounds(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@NotNull
@Override
public String getStopCode(@NotNull GStop gStop) {
if (ZERO_0.equals(gStop.getStopCode())) {
return EMPTY; // no stop code
}
return super.getStopCode(gStop);
}
private static final String ZERO_0 = "0";
@Override
public int getStopId(@NotNull GStop gStop) {
//noinspection deprecation
final String stopId1 = gStop.getStopId();
//noinspection ConstantConditions
if (true) {
String stopId = stopId1;
stopId = STARTS_WITH_NRT_A00_.matcher(stopId).replaceAll(EMPTY);
if (stopId.isEmpty()) {
throw new MTLog.Fatal("Unexpected stop ID (%d) %s!", stopId, gStop.toStringPlus());
}
if (CharUtils.isDigitsOnly(stopId)) {
return Integer.parseInt(stopId);
}
throw new MTLog.Fatal("Unexpected stop ID %s!", gStop.toStringPlus());
}
String stopCode = gStop.getStopCode();
if (stopCode == null || stopCode.length() == 0 || ZERO_0.equals(stopCode)) {
stopCode = stopId1;
}
stopCode = STARTS_WITH_NRT_A00_.matcher(stopCode).replaceAll(EMPTY);
if (stopCode.isEmpty()) {
throw new MTLog.Fatal("Unexpected empty stop ID %s!", gStop.toStringPlus());
}
if (CharUtils.isDigitsOnly(stopCode)) {
return Integer.parseInt(stopCode); // using stop code as stop ID
}
switch (stopCode) {
case "DTT":
return 100_000;
case "NFT":
return 100_001;
case "PEN":
return 100_002;
case "SWM":
return 100_003;
case "WEL":
return 100004;
case "BRU":
return 100_006;
case "FVM":
return 100_008;
case "GDC":
return 100_020;
case "WLC":
return 100_021;
case "CTO":
return 100_035;
case "OUT":
return 100_044;
case "MCC":
return 100_045;
}
switch (stopCode) {
case "NiagSqua":
return 200_000;
case "Concentrix":
return 200_001;
case "FortErie":
return 200_002;
}
if (stopCode.equals("PCH")) {
return 9_000_016;
}
throw new MTLog.Fatal("Unexpected stop ID %s!", gStop.toStringPlus());
}
}
| src/main/java/org/mtransit/parser/ca_niagara_region_transit_bus/NiagaraRegionTransitBusAgencyTools.java | package org.mtransit.parser.ca_niagara_region_transit_bus;
import static org.mtransit.commons.RegexUtils.DIGITS;
import static org.mtransit.commons.StringUtils.EMPTY;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mtransit.commons.CharUtils;
import org.mtransit.commons.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.gtfs.data.GAgency;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.mt.data.MAgency;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// https://niagaraopendata.ca/dataset/niagara-region-transit-gtfs
// https://maps.niagararegion.ca/googletransit/NiagaraRegionTransit.zip
// https://niagaraopendata.ca/dataset/1a1b885e-1a86-415d-99aa-6803a2d8f178/resource/f7dbcaed-f31a-435e-8146-b0efff0b8eb8/download/gtfs.zip
public class NiagaraRegionTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(@NotNull String[] args) {
new NiagaraRegionTransitBusAgencyTools().start(args);
}
@Nullable
@Override
public List<Locale> getSupportedLanguages() {
return LANG_EN;
}
@Override
public boolean defaultExcludeEnabled() {
return true;
}
@NotNull
@Override
public String getAgencyName() {
return "Niagara Region Transit";
}
private static final String NIAGARA_REGION_TRANSIT = "Niagara Region Transit";
private static final String EXCLUDE_STC_ROUTE_IDS_STARTS_WITH = "STC_";
@Override
public boolean excludeAgency(@NotNull GAgency gAgency) {
//noinspection deprecation
final String agencyId = gAgency.getAgencyId();
if (!agencyId.contains(NIAGARA_REGION_TRANSIT)
&& !agencyId.contains("AllNRT_")
&& !agencyId.equals("1")) {
return EXCLUDE;
}
return super.excludeAgency(gAgency);
}
@Override
public boolean excludeRoute(@NotNull GRoute gRoute) {
//noinspection deprecation
final String agencyId = gRoute.getAgencyIdOrDefault();
if (!agencyId.contains(NIAGARA_REGION_TRANSIT)
&& !agencyId.contains("AllNRT_")
&& !agencyId.equals("1")) {
return EXCLUDE;
}
if (agencyId.contains("AllNRT_") || agencyId.equals("1")) {
if (!CharUtils.isDigitsOnly(gRoute.getRouteShortName())) {
return true; // exclude
}
final int rsn = Integer.parseInt(gRoute.getRouteShortName());
if (rsn > 100) {
return EXCLUDE;
}
}
//noinspection deprecation
final String routeId = gRoute.getRouteId();
if (routeId.startsWith(EXCLUDE_STC_ROUTE_IDS_STARTS_WITH)) {
return EXCLUDE;
}
return super.excludeRoute(gRoute);
}
@NotNull
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public boolean defaultRouteIdEnabled() {
return true;
}
@Override
public boolean useRouteShortNameForRouteId() {
return true;
}
@Override
public boolean defaultRouteLongNameEnabled() {
return true;
}
private static final Pattern STARTS_WITH_CT = Pattern.compile("(^(NRT - ))", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_CT = Pattern.compile("( (nf|sc|we)$)", Pattern.CASE_INSENSITIVE);
@NotNull
@Override
public String cleanRouteLongName(@NotNull String routeLongName) {
routeLongName = STARTS_WITH_CT.matcher(routeLongName).replaceAll(EMPTY);
routeLongName = ENDS_WITH_CT.matcher(routeLongName).replaceAll(EMPTY);
//noinspection deprecation
routeLongName = CleanUtils.removePoints(routeLongName);
return routeLongName;
}
private static final String AGENCY_COLOR_GREEN = "6CB33F"; // GREEN (from PDF)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public boolean defaultAgencyColorEnabled() {
return true;
}
@NotNull
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@SuppressWarnings("DuplicateBranchesInSwitch")
@Nullable
@Override
public String provideMissingRouteColor(@NotNull GRoute gRoute) {
final Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName());
if (matcher.find()) {
final int rsn = Integer.parseInt(matcher.group());
switch (rsn) {
// @formatter:off
case 22: return "766A24";
case 25: return "00AAA0"; // Welland Transit?
case 40: return "1B5C28";
case 45: return "1B5C28";
case 50: return "F1471C";
case 55: return "F1471C";
case 60: return "1378C7";
case 65: return "1378C7";
case 70: return "62B92C";
case 75: return "62B92C";
// @formatter:on
}
}
throw new MTLog.Fatal("Unexpected route color for %s!", gRoute);
}
private static final Pattern STARTS_WITH_NRT_A00_ = Pattern.compile( //
"((^)((allnrt|nrt|)_([a-z]{1,3})?[\\d]{2,4}(_)?([A-Z]{3}(stop))?(stop)?)(NFT)?)", //
Pattern.CASE_INSENSITIVE);
@NotNull
@Override
public String cleanStopOriginalId(@NotNull String gStopId) {
gStopId = STARTS_WITH_NRT_A00_.matcher(gStopId).replaceAll(EMPTY);
return gStopId;
}
@Override
public boolean directionFinderEnabled() {
return true;
}
private static final Pattern STARTS_WITH_RSN = Pattern.compile("((^)[\\d]{2}([a-z] | ))", Pattern.CASE_INSENSITIVE);
private static final String STARTS_WITH_RSN_REPLACEMENT = "$3";
private static final Pattern IMT_ = Pattern.compile("((^|\\W)(imt -|imt)(\\W|$))", Pattern.CASE_INSENSITIVE); // Inter-Municipal Transit
private static final String ST_CATHARINES = "St Catharines";
private static final Pattern ST_CATHARINES_ = Pattern.compile("((^|\\W)(" //
+ "st\\. catharines" + "|" //
+ "st\\. catharine" + "|" //
+ "st\\. catharin" + "|" //
+ "st\\. cathari" + "|" //
+ "st\\. cathar" + "|" //
+ "st\\. catha" + "|" //
+ "st\\. cath" + "|" //
+ "st\\. cat" + "|" //
+ "st\\. ca" + "|" //
+ "st\\. c" + "|" //
+ "st\\. " //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String ST_CATHARINES_REPLACEMENT = "$2" + ST_CATHARINES + "$4";
private static final String NIAGARA_FALLS = "Niagara Falls";
private static final Pattern NIAGARA_FALLS_ = Pattern.compile("((^|\\W)(" //
+ "niagara falls" + "|" //
+ "niagara fall" + "|" //
+ "niag" + "|" //
+ "nia\\. falls" + "|" //
+ "falls" //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String NIAGARA_FALLS_REPLACEMENT = "$2" + NIAGARA_FALLS + "$4";
private static final String OUTLET_MALL = "Outlet Mall";
private static final Pattern OUTLET_MALL_ = Pattern.compile("((^|\\W)(" //
+ "outlet mall" + "|" //
+ "outlet m" //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String OUTLET_MALL_REPLACEMENT = "$2" + OUTLET_MALL + "$4";
private static final String WELLAND = "Welland";
private static final Pattern WELLAND_ = Pattern.compile("((^|\\W)(" //
+ "welland" + "|" //
+ "wellan" //
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String WELLAND_REPLACEMENT = "$2" + WELLAND + "$4";
private static final Pattern NOTL_ = Pattern.compile("((^|\\W)(" //
+ "notl"
+ ")(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String NOTL_REPLACEMENT_ = "$2" + "NOTL" + "$4";
private static final Pattern AND_NO_SPACE = Pattern.compile("(([\\S])\\s?([&@])\\s?([\\S]))", Pattern.CASE_INSENSITIVE);
private static final String AND_NO_SPACE_REPLACEMENT = "$2 $3 $4";
@NotNull
@Override
public String cleanTripHeadsign(@NotNull String tripHeadsign) {
tripHeadsign = AND_NO_SPACE.matcher(tripHeadsign).replaceAll(AND_NO_SPACE_REPLACEMENT);
tripHeadsign = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, tripHeadsign, getIgnoredWords());
tripHeadsign = STARTS_WITH_RSN.matcher(tripHeadsign).replaceAll(STARTS_WITH_RSN_REPLACEMENT);
tripHeadsign = IMT_.matcher(tripHeadsign).replaceAll(EMPTY);
tripHeadsign = ST_CATHARINES_.matcher(tripHeadsign).replaceAll(ST_CATHARINES_REPLACEMENT);
tripHeadsign = NIAGARA_FALLS_.matcher(tripHeadsign).replaceAll(NIAGARA_FALLS_REPLACEMENT);
tripHeadsign = NOTL_.matcher(tripHeadsign).replaceAll(NOTL_REPLACEMENT_);
tripHeadsign = OUTLET_MALL_.matcher(tripHeadsign).replaceAll(OUTLET_MALL_REPLACEMENT);
tripHeadsign = WELLAND_.matcher(tripHeadsign).replaceAll(WELLAND_REPLACEMENT);
tripHeadsign = CleanUtils.cleanBounds(tripHeadsign);
tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private String[] getIgnoredWords() {
return new String[]{
"NE", "NW", "SE", "SW",
"GO", "NF", "NOTL",
};
}
@NotNull
@Override
public String cleanStopName(@NotNull String gStopName) {
gStopName = AND_NO_SPACE.matcher(gStopName).replaceAll(AND_NO_SPACE_REPLACEMENT);
gStopName = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, gStopName, getIgnoredWords());
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.cleanBounds(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@NotNull
@Override
public String getStopCode(@NotNull GStop gStop) {
if (ZERO_0.equals(gStop.getStopCode())) {
return EMPTY; // no stop code
}
return super.getStopCode(gStop);
}
private static final String ZERO_0 = "0";
@Override
public int getStopId(@NotNull GStop gStop) {
//noinspection deprecation
final String stopId1 = gStop.getStopId();
//noinspection ConstantConditions
if (true) {
String stopId = stopId1;
stopId = STARTS_WITH_NRT_A00_.matcher(stopId).replaceAll(EMPTY);
if (stopId.isEmpty()) {
throw new MTLog.Fatal("Unexpected stop ID (%d) %s!", stopId, gStop.toStringPlus());
}
if (CharUtils.isDigitsOnly(stopId)) {
return Integer.parseInt(stopId);
}
throw new MTLog.Fatal("Unexpected stop ID %s!", gStop.toStringPlus());
}
String stopCode = gStop.getStopCode();
if (stopCode == null || stopCode.length() == 0 || ZERO_0.equals(stopCode)) {
stopCode = stopId1;
}
stopCode = STARTS_WITH_NRT_A00_.matcher(stopCode).replaceAll(EMPTY);
if (stopCode.isEmpty()) {
throw new MTLog.Fatal("Unexpected empty stop ID %s!", gStop.toStringPlus());
}
if (CharUtils.isDigitsOnly(stopCode)) {
return Integer.parseInt(stopCode); // using stop code as stop ID
}
switch (stopCode) {
case "DTT":
return 100_000;
case "NFT":
return 100_001;
case "PEN":
return 100_002;
case "SWM":
return 100_003;
case "WEL":
return 100004;
case "BRU":
return 100_006;
case "FVM":
return 100_008;
case "GDC":
return 100_020;
case "WLC":
return 100_021;
case "CTO":
return 100_035;
case "OUT":
return 100_044;
case "MCC":
return 100_045;
}
switch (stopCode) {
case "NiagSqua":
return 200_000;
case "Concentrix":
return 200_001;
case "FortErie":
return 200_002;
}
if (stopCode.equals("PCH")) {
return 9_000_016;
}
throw new MTLog.Fatal("Unexpected stop ID %s!", gStop.toStringPlus());
}
}
| Compatibility with latest update
| src/main/java/org/mtransit/parser/ca_niagara_region_transit_bus/NiagaraRegionTransitBusAgencyTools.java | Compatibility with latest update | <ide><path>rc/main/java/org/mtransit/parser/ca_niagara_region_transit_bus/NiagaraRegionTransitBusAgencyTools.java
<ide>
<ide> // https://niagaraopendata.ca/dataset/niagara-region-transit-gtfs
<ide> // https://maps.niagararegion.ca/googletransit/NiagaraRegionTransit.zip
<del>// https://niagaraopendata.ca/dataset/1a1b885e-1a86-415d-99aa-6803a2d8f178/resource/f7dbcaed-f31a-435e-8146-b0efff0b8eb8/download/gtfs.zip
<ide> public class NiagaraRegionTransitBusAgencyTools extends DefaultAgencyTools {
<ide>
<ide> public static void main(@NotNull String[] args) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.