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 | apache-2.0 | error: pathspec 'src/main/java/tech/aroma/banana/data/memory/MessageRepositoryInMemory.java' did not match any file(s) known to git
| 64194edeacb7472b992e920399122895cd432231 | 1 | RedRoma/aroma-data-operations,AromaTech/banana-data-operations,RedRoma/banana-data-operations,RedRoma/aroma-data-operations | /*
* Copyright 2016 Aroma Tech.
*
* 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 tech.aroma.banana.data.memory;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sir.wellington.alchemy.collections.lists.Lists;
import sir.wellington.alchemy.collections.maps.Maps;
import tech.aroma.banana.data.MessageRepository;
import tech.aroma.banana.thrift.Message;
import tech.aroma.banana.thrift.exceptions.InvalidArgumentException;
import tech.aroma.banana.thrift.exceptions.MessageDoesNotExistException;
import static tech.aroma.banana.data.assertions.DataAssertions.isNullOrEmpty;
import static tech.aroma.banana.data.assertions.DataAssertions.validMessage;
import static tech.sirwellington.alchemy.arguments.Arguments.checkThat;
import static tech.sirwellington.alchemy.arguments.assertions.CollectionAssertions.keyInMap;
import static tech.sirwellington.alchemy.arguments.assertions.StringAssertions.nonEmptyString;
/**
*
* @author SirWellington
*/
final class MessageRepositoryInMemory implements MessageRepository
{
private final static Logger LOG = LoggerFactory.getLogger(MessageRepositoryInMemory.class);
private final Map<String, Message> messages = Maps.createSynchronized();
private final Map<String, List<String>> messagesByHostname = Maps.createSynchronized();
private final Map<String, List<String>> messagesByApplication = Maps.createSynchronized();
private final Map<String, List<String>> messagesByTitle = Maps.createSynchronized();
@Override
public void saveMessage(Message message) throws TException
{
checkThat(message)
.throwing(InvalidArgumentException.class)
.is(validMessage());
String messageId = message.messageId;
messages.put(messageId, message);
if(!isNullOrEmpty(message.hostname))
{
String hostname = message.hostname;
List<String> list = messagesByHostname.getOrDefault(hostname, Lists.create());
list.add(messageId);
messagesByHostname.put(hostname, list);
}
if(!isNullOrEmpty(message.title))
{
String title = message.title;
List<String> list = messagesByTitle.getOrDefault(title, Lists.create());
list.add(messageId);
messagesByTitle.put(title, list);
}
if(!isNullOrEmpty(message.applicationId))
{
String appId = message.applicationId;
List<String> list = messagesByApplication.getOrDefault(appId, Lists.create());
list.add(messageId);
messagesByApplication.put(appId, list);
}
}
@Override
public Message getMessage(String messageId) throws TException
{
checkMessageId(messageId);
return messages.get(messageId);
}
@Override
public void deleteMessage(String messageId) throws TException
{
checkThat(messageId)
.throwing(InvalidArgumentException.class)
.is(nonEmptyString());
Message deletedMessage = messages.remove(messageId);
if(deletedMessage == null)
{
return;
}
Predicate<String> doesNotMatchMessage = id -> !Objects.equals(id, messageId);
String applicationId = deletedMessage.applicationId;
String hostname = deletedMessage.hostname;
String title = deletedMessage.title;
if (!isNullOrEmpty(applicationId))
{
List<String> list = messagesByApplication.getOrDefault(applicationId, Lists.emptyList());
list = list.stream()
.filter(doesNotMatchMessage)
.collect(Collectors.toList());
messagesByApplication.put(applicationId, list);
}
if (!isNullOrEmpty(hostname))
{
List<String> list = messagesByHostname.getOrDefault(hostname, Lists.emptyList());
list = list.stream()
.filter(doesNotMatchMessage)
.collect(Collectors.toList());
messagesByHostname.put(hostname, list);
}
if (!isNullOrEmpty(title))
{
List<String> list = messagesByTitle.getOrDefault(title, Lists.emptyList());
list = list.stream()
.filter(doesNotMatchMessage)
.collect(Collectors.toList());
messagesByTitle.put(title, list);
}
}
@Override
public boolean containsMessage(String messageId) throws TException
{
checkThat(messageId)
.usingMessage("messageId cannot be empty")
.is(nonEmptyString())
.is(nonEmptyString());
return messages.containsKey(messageId);
}
@Override
public List<Message> getByHostname(String hostname) throws TException
{
checkThat(hostname)
.usingMessage("hostname cannot be empty")
.throwing(InvalidArgumentException.class)
.is(nonEmptyString());
return messagesByHostname.getOrDefault(hostname, Lists.emptyList())
.stream()
.map(id -> messages.get(id))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public List<Message> getByApplication(String applicationId) throws TException
{
checkThat(applicationId)
.usingMessage("applicationId cannot be empty")
.throwing(InvalidArgumentException.class)
.is(nonEmptyString());
return messagesByApplication.getOrDefault(applicationId, Lists.emptyList())
.stream()
.map(id -> messages.get(id))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public List<Message> getByTitle(String applicationId, String title) throws TException
{
checkThat(applicationId, title)
.throwing(InvalidArgumentException.class)
.are(nonEmptyString());
return messagesByTitle.getOrDefault(title, Lists.emptyList())
.stream()
.map(id -> messages.get(id))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public long getCountByApplication(String applicationId) throws TException
{
checkThat(applicationId)
.throwing(InvalidArgumentException.class)
.is(nonEmptyString());
return messagesByApplication.getOrDefault(applicationId, Lists.emptyList()).size();
}
private void checkMessageId(String messageId) throws TException
{
checkThat(messageId)
.throwing(InvalidArgumentException.class)
.usingMessage("missing messageId")
.is(nonEmptyString())
.throwing(MessageDoesNotExistException.class)
.is(keyInMap(messages));
}
}
| src/main/java/tech/aroma/banana/data/memory/MessageRepositoryInMemory.java | Adding MessageRepositoryInMemory | src/main/java/tech/aroma/banana/data/memory/MessageRepositoryInMemory.java | Adding MessageRepositoryInMemory | <ide><path>rc/main/java/tech/aroma/banana/data/memory/MessageRepositoryInMemory.java
<add>/*
<add> * Copyright 2016 Aroma Tech.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>
<add>package tech.aroma.banana.data.memory;
<add>
<add>
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Objects;
<add>import java.util.function.Predicate;
<add>import java.util.stream.Collectors;
<add>import org.apache.thrift.TException;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<add>import sir.wellington.alchemy.collections.lists.Lists;
<add>import sir.wellington.alchemy.collections.maps.Maps;
<add>import tech.aroma.banana.data.MessageRepository;
<add>import tech.aroma.banana.thrift.Message;
<add>import tech.aroma.banana.thrift.exceptions.InvalidArgumentException;
<add>import tech.aroma.banana.thrift.exceptions.MessageDoesNotExistException;
<add>
<add>import static tech.aroma.banana.data.assertions.DataAssertions.isNullOrEmpty;
<add>import static tech.aroma.banana.data.assertions.DataAssertions.validMessage;
<add>import static tech.sirwellington.alchemy.arguments.Arguments.checkThat;
<add>import static tech.sirwellington.alchemy.arguments.assertions.CollectionAssertions.keyInMap;
<add>import static tech.sirwellington.alchemy.arguments.assertions.StringAssertions.nonEmptyString;
<add>
<add>/**
<add> *
<add> * @author SirWellington
<add> */
<add>final class MessageRepositoryInMemory implements MessageRepository
<add>{
<add> private final static Logger LOG = LoggerFactory.getLogger(MessageRepositoryInMemory.class);
<add>
<add> private final Map<String, Message> messages = Maps.createSynchronized();
<add> private final Map<String, List<String>> messagesByHostname = Maps.createSynchronized();
<add> private final Map<String, List<String>> messagesByApplication = Maps.createSynchronized();
<add> private final Map<String, List<String>> messagesByTitle = Maps.createSynchronized();
<add>
<add>
<add> @Override
<add> public void saveMessage(Message message) throws TException
<add> {
<add> checkThat(message)
<add> .throwing(InvalidArgumentException.class)
<add> .is(validMessage());
<add>
<add> String messageId = message.messageId;
<add> messages.put(messageId, message);
<add>
<add> if(!isNullOrEmpty(message.hostname))
<add> {
<add> String hostname = message.hostname;
<add> List<String> list = messagesByHostname.getOrDefault(hostname, Lists.create());
<add> list.add(messageId);
<add> messagesByHostname.put(hostname, list);
<add> }
<add>
<add> if(!isNullOrEmpty(message.title))
<add> {
<add> String title = message.title;
<add> List<String> list = messagesByTitle.getOrDefault(title, Lists.create());
<add> list.add(messageId);
<add> messagesByTitle.put(title, list);
<add> }
<add>
<add> if(!isNullOrEmpty(message.applicationId))
<add> {
<add> String appId = message.applicationId;
<add> List<String> list = messagesByApplication.getOrDefault(appId, Lists.create());
<add> list.add(messageId);
<add> messagesByApplication.put(appId, list);
<add> }
<add>
<add> }
<add>
<add> @Override
<add> public Message getMessage(String messageId) throws TException
<add> {
<add> checkMessageId(messageId);
<add>
<add> return messages.get(messageId);
<add> }
<add>
<add> @Override
<add> public void deleteMessage(String messageId) throws TException
<add> {
<add> checkThat(messageId)
<add> .throwing(InvalidArgumentException.class)
<add> .is(nonEmptyString());
<add>
<add> Message deletedMessage = messages.remove(messageId);
<add>
<add> if(deletedMessage == null)
<add> {
<add> return;
<add> }
<add>
<add> Predicate<String> doesNotMatchMessage = id -> !Objects.equals(id, messageId);
<add>
<add> String applicationId = deletedMessage.applicationId;
<add> String hostname = deletedMessage.hostname;
<add> String title = deletedMessage.title;
<add>
<add> if (!isNullOrEmpty(applicationId))
<add> {
<add> List<String> list = messagesByApplication.getOrDefault(applicationId, Lists.emptyList());
<add> list = list.stream()
<add> .filter(doesNotMatchMessage)
<add> .collect(Collectors.toList());
<add> messagesByApplication.put(applicationId, list);
<add> }
<add>
<add> if (!isNullOrEmpty(hostname))
<add> {
<add> List<String> list = messagesByHostname.getOrDefault(hostname, Lists.emptyList());
<add> list = list.stream()
<add> .filter(doesNotMatchMessage)
<add> .collect(Collectors.toList());
<add> messagesByHostname.put(hostname, list);
<add> }
<add>
<add> if (!isNullOrEmpty(title))
<add> {
<add> List<String> list = messagesByTitle.getOrDefault(title, Lists.emptyList());
<add> list = list.stream()
<add> .filter(doesNotMatchMessage)
<add> .collect(Collectors.toList());
<add> messagesByTitle.put(title, list);
<add> }
<add> }
<add>
<add> @Override
<add> public boolean containsMessage(String messageId) throws TException
<add> {
<add> checkThat(messageId)
<add> .usingMessage("messageId cannot be empty")
<add> .is(nonEmptyString())
<add> .is(nonEmptyString());
<add>
<add> return messages.containsKey(messageId);
<add> }
<add>
<add> @Override
<add> public List<Message> getByHostname(String hostname) throws TException
<add> {
<add> checkThat(hostname)
<add> .usingMessage("hostname cannot be empty")
<add> .throwing(InvalidArgumentException.class)
<add> .is(nonEmptyString());
<add>
<add> return messagesByHostname.getOrDefault(hostname, Lists.emptyList())
<add> .stream()
<add> .map(id -> messages.get(id))
<add> .filter(Objects::nonNull)
<add> .collect(Collectors.toList());
<add> }
<add>
<add> @Override
<add> public List<Message> getByApplication(String applicationId) throws TException
<add> {
<add> checkThat(applicationId)
<add> .usingMessage("applicationId cannot be empty")
<add> .throwing(InvalidArgumentException.class)
<add> .is(nonEmptyString());
<add>
<add> return messagesByApplication.getOrDefault(applicationId, Lists.emptyList())
<add> .stream()
<add> .map(id -> messages.get(id))
<add> .filter(Objects::nonNull)
<add> .collect(Collectors.toList());
<add> }
<add>
<add> @Override
<add> public List<Message> getByTitle(String applicationId, String title) throws TException
<add> {
<add> checkThat(applicationId, title)
<add> .throwing(InvalidArgumentException.class)
<add> .are(nonEmptyString());
<add>
<add> return messagesByTitle.getOrDefault(title, Lists.emptyList())
<add> .stream()
<add> .map(id -> messages.get(id))
<add> .filter(Objects::nonNull)
<add> .collect(Collectors.toList());
<add> }
<add>
<add> @Override
<add> public long getCountByApplication(String applicationId) throws TException
<add> {
<add> checkThat(applicationId)
<add> .throwing(InvalidArgumentException.class)
<add> .is(nonEmptyString());
<add>
<add> return messagesByApplication.getOrDefault(applicationId, Lists.emptyList()).size();
<add> }
<add>
<add> private void checkMessageId(String messageId) throws TException
<add> {
<add> checkThat(messageId)
<add> .throwing(InvalidArgumentException.class)
<add> .usingMessage("missing messageId")
<add> .is(nonEmptyString())
<add> .throwing(MessageDoesNotExistException.class)
<add> .is(keyInMap(messages));
<add> }
<add>
<add>} |
|
Java | bsd-3-clause | 14ef5feaffa8e57cb401810ebb8df0f8a4f14976 | 0 | nish5887/blueprints | package org.apache.usergrid.drivers.blueprints;
import com.fasterxml.jackson.databind.JsonNode;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.VertexQuery;
import org.apache.usergrid.java.client.Client;
import org.apache.usergrid.java.client.model.UsergridEntity;
import org.apache.usergrid.java.client.response.ApiResponse;
import java.util.*;
/**
* Created by ApigeeCorporation on 6/29/15.
*/
public class UsergridVertex extends UsergridEntity implements Vertex {
private static String CONNECTING = "connecting";
private static String defaultType;
private static String METADATA = "metadata";
private static String CONNECTIONS = "connections";
public static final String SLASH = "/";
public static String STRING_NAME = "name";
public static String STRING_TYPE = "type";
public static String STRING_UUID = "uuid";
public UsergridVertex(String defaultType) {
super.setType(defaultType);
}
public static void setDefaultType(String defaultType) {
UsergridVertex.defaultType = defaultType;
}
/**
* This gets edges that are connected to the vertex in a
* particular direction specified, and having a specific label
*
* @param direction Direction of the edges to retrieve.
* @param labels Names of the edges to retrieve.
* @return Returns an Iterable of edges.
*/
public Iterable<Edge> getEdges(Direction direction, String... labels) {
/**
1) Check if the vertex exists.
2) Get the UUIDs of edges that are connected to the
particular vertex in a particular direction and with a particular label
3) Return an iterable of edges
*/
ValidationUtils.validateNotNull(direction, IllegalArgumentException.class, "Direction for getEdges cannot be null");
ValidationUtils.validateStringNotEmpty(labels.toString(), RuntimeException.class, "Label for edge in getEdges cannot be empty");
String srcType = this.getType();
String srcId = this.getUuid().toString();
List<Edge> edgesSet1 = new ArrayList<Edge>();
ApiResponse response = UsergridGraph.client.queryEdgesForVertex(srcType, srcId);
UsergridGraph.ValidateResponseErrors(response);
//Gets the vertex for which edges are to be found
UsergridEntity trgEntity = response.getFirstEntity();
switch (direction) {
case OUT:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
//Returns empty list if there are no edges
return new ArrayList<Edge>();
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTIONS, labels);
return edgesSet1;
case IN:
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Edge>();
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTING, labels);
return edgesSet1;
case BOTH:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Edge>();
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTING, labels);
return edgesSet1;
} else if (!checkHasEdges(trgEntity, CONNECTING)) {
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTIONS, labels);
return edgesSet1;
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTING, labels);
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTIONS, labels);
return edgesSet1;
}
return new ArrayList<Edge>();
}
private boolean checkHasEdges(UsergridEntity trgUUID, String conn) {
if (trgUUID.getProperties().get(METADATA).findValue(conn) == null)
return false;
else
return true;
}
private void IterarteOverEdges(UsergridEntity trgUUID, String srcType, String srcId, List<Edge> edges, String conn, String... labels) {
List<String> connections = new ArrayList<String>();
//If labels are specified
if(labels.length != 0){
for (String label : labels){
connections.add(label);
}
}else {
//When labels are not specified
Iterator<String> conn1 = trgUUID.getProperties().get(METADATA).findValue(conn).fieldNames();
while(conn1.hasNext()){
connections.add(conn1.next());
}
}
Direction direction = null;
for (int conLen = 0 ; conLen < connections.size();conLen++){
ApiResponse resp = new ApiResponse();
if (conn == CONNECTIONS) {
resp = UsergridGraph.client.queryConnection(srcType, srcId, connections.get(conLen));
direction = Direction.OUT;
} else {
resp = UsergridGraph.client.queryConnection(srcType, srcId, CONNECTING, connections.get(conLen));
direction = Direction.IN;
}
List<UsergridEntity> entities = resp.getEntities();
getAllEdgesForVertex(entities, connections.get(conLen), edges, direction);
}
}
private List<Edge> getAllEdgesForVertex(List<UsergridEntity> entities, String name, List<Edge> edges, Direction dir) {
for (int i = 0; i < entities.size(); i++) {
UsergridEntity e = entities.get(i);
String vertex;
if(e.getStringProperty(STRING_NAME) != null )
vertex = e.getType() + SLASH + e.getStringProperty(STRING_NAME);
else
vertex = e.getType() + SLASH + e.getUuid().toString();
Edge e1 = null;
if (dir == Direction.OUT)
e1 = new UsergridEdge(this.getId().toString(), vertex, name);
else if (dir == Direction.IN)
e1 = new UsergridEdge(vertex, this.getId().toString(), name);
edges.add(e1);
}
return edges;
}
private void IterarteOverVertices(UsergridEntity trgEntity, String srcType, String srcId, List<Vertex> vertexSet, String conn, String... labels) {
List<String> connections = new ArrayList<String>();
//If labels are specified
if(labels.length != 0){
for (String label : labels){
connections.add(label);
}
}else {
//When labels are not specified, Example of conn1 is 'likes', 'hates' and other such verbs associated with the vertex
Iterator<String> conn1 = trgEntity.getProperties().get(METADATA).findValue(conn).fieldNames();
while(conn1.hasNext()){
connections.add(conn1.next());
}
}
for (int conLen = 0 ; conLen < connections.size();conLen++){
ApiResponse resp = new ApiResponse();
if (conn == CONNECTIONS) {
resp = UsergridGraph.client.queryConnection(srcType, srcId, connections.get(conLen));
} else {
resp = UsergridGraph.client.queryConnection(srcType, srcId, CONNECTING, connections.get(conLen));
}
List<UsergridEntity> entities = resp.getEntities();
getAllVerticesForVertex(entities, vertexSet);
}
}
private List<Vertex> getAllVerticesForVertex(List<UsergridEntity> entities, List<Vertex> vertices){
for (int i = 0; i < entities.size(); i++) {
UsergridVertex v1 = UsergridGraph.CreateVertexFromEntity(entities.get(i));
vertices.add(v1);
}
return vertices;
}
/**
* This gets all the adjacent vertices connected to the vertex by an edge specified by a particular direction and label
*
* @param direction Direction of the vertices to retrieve.
* @param labels names of the vertices to retrieve.
* @return Returns and Iterable of vertices.
*/
public Iterable<Vertex> getVertices(Direction direction, String... labels) {
/**
1) Check if the vertex exists
2) Get the UUIDs of edges that are connected to the
particular vertex in a particular direction and with a particular label
3)Get the vertices at the other end of the edge
4) Return an iterable of vertices
*/
ValidationUtils.validateNotNull(direction, IllegalArgumentException.class, "Direction for getEdges cannot be null");
ValidationUtils.validateStringNotEmpty(labels.toString(), RuntimeException.class, "Label for edge in getEdges cannot be empty");
String srcType = this.getType().toString();
String srcId = this.getUuid().toString();
List<Vertex> vertexSet = new ArrayList<Vertex>();
ApiResponse response = UsergridGraph.client.queryEdgesForVertex(srcType, srcId);
UsergridGraph.ValidateResponseErrors(response);
//Gets the vertex for which edges are to be found
UsergridEntity trgEntity = response.getFirstEntity();
switch (direction) {
case OUT:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
//Returns empty list if there are no adjacent vertices
return new ArrayList<Vertex>();
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTIONS, labels);
return vertexSet;
case IN:
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Vertex>();
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTING, labels);
return vertexSet;
case BOTH:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Vertex>();
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTING, labels);
return vertexSet;
} else if (!checkHasEdges(trgEntity, CONNECTING)) {
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTIONS, labels);
return vertexSet;
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTING, labels);
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTIONS, labels);
return vertexSet;
}
return new ArrayList<Vertex>();
}
/**
* Not supported for Usergrid
*
* Generate a query object that can be
* used to filter which connections/entities are retrieved that are incident/adjacent to this entity.
*
* @return
*/
public VertexQuery query() {
throw new UnsupportedOperationException("Not supported for Usergrid");
}
/**
* Adds an edge to the vertex, with the target vertex specified
*
* @param label Name of the edge to be added.
* @param inVertex connecting edge.
* @return Returns the new edge formed.
*/
public Edge addEdge(String label, Vertex inVertex) {
/**
1) Check if the target vertex exists
2) Use the following to add an edge - connectEntities( String connectingEntityType,String
connectingEntityId, String connectionType, String connectedEntityId) in org.apache.usergrid.java.client
3) Return the newly created edge
*/
ValidationUtils.validateNotNull(label,IllegalArgumentException.class,"Label for edge cannot be null");
ValidationUtils.validateNotNull(inVertex, IllegalArgumentException.class, "Target vertex cannot be null");
ValidationUtils.validateStringNotEmpty(label, RuntimeException.class, "Label of edge cannot be emoty");
UsergridEdge e = new UsergridEdge(this.getId().toString(), inVertex.getId().toString(), label);
ApiResponse response = UsergridGraph.client.connectEntities(this, (UsergridVertex) inVertex, label);
UsergridGraph.ValidateResponseErrors(response);
return e;
}
/**
* Get a particular property of a vertex specified by a key
*
* @param key The property to retrieve for a vertex.
* @return Returns the value of the property.
*/
public <T> T getProperty(String key) {
/**
1) Check if the vertex exists
2) Use the getEntityProperty(String name, float/String/long/int/boolean/JsonNode value) in
org.apache.usergrid.java.client.entities
3) If any other type throw an error
*/
//TODO: Check if vertex exists?
ValidationUtils.validateNotNull(key, IllegalArgumentException.class, "Property key cannot be null");
ValidationUtils.validateStringNotEmpty(key, RuntimeException.class, "Property key cannot be empty");
T propertyValue = (T) super.getEntityProperty(key);
//TODO: Check if property exists
return propertyValue;
}
/**
* This gets all the property keys for a particular vertex
*
* @return Returns a Set of properties for the vertex.
*/
public Set<String> getPropertyKeys() {
//TODO: Check if vertex exists?
Set<String> allKeys = super.getProperties().keySet();
return allKeys;
}
/**
* This sets a particular value of a property using the specified key in the local object
*
* @param key Name of the property.
* @param value Value of the property.
*/
public void setLocalProperty(String key, Object value) {
ValidationUtils.validateNotNull(key, IllegalArgumentException.class, "Key for the property cannot be null");
ValidationUtils.validateStringNotEmpty(key, RuntimeException.class, "Key of the property cannot be empty");
if (value instanceof String) {
super.setProperty(key, (String) value);
} else if (value instanceof JsonNode) {
super.setProperty(key, (JsonNode) value);
} else if (value instanceof Integer) {
super.setProperty(key, (Integer) value);
} else if (value instanceof Float) {
super.setProperty(key, (Float) value);
} else if (value instanceof Boolean) {
super.setProperty(key, (Boolean) value);
} else if (value instanceof Long) {
super.setProperty(key, (Long) value);
} else if (value.equals(null)){
super.setProperty(key,(String) null);
}
else {
throw new IllegalArgumentException("Supplied ID class of " + String.valueOf(value.getClass()) + " is not supported");
}
}
public void setProperty(String key, Object value) {
if (key.equals(STRING_TYPE)) {
if (value.equals(this.getType())) {
} else {
String oldType = this.getType();
String newType = value.toString();
UsergridVertex v = new UsergridVertex(newType);
Map allProperties = this.properties;
Iterable allOUTEdges = this.getEdges(Direction.OUT);
Iterable allINEdges = this.getEdges(Direction.IN);
v.properties = allProperties;
v.setLocalProperty(STRING_TYPE, newType);
ApiResponse responseDelete = UsergridGraph.client.deleteEntity(oldType, this.getUuid().toString());
ApiResponse response = UsergridGraph.client.createEntity(v);
UsergridGraph.ValidateResponseErrors(response);
ValidationUtils.validateDuplicate(response, RuntimeException.class, "Entity with the name specified already exists in Usergrid");
String uuid = response.getFirstEntity().getStringProperty(STRING_UUID);
v.setUuid(UUID.fromString(uuid));
if (allOUTEdges != null) {
for (Object outEdge : allOUTEdges) {
//TODO:Create outGoing Edges for the Vertex
String[] parts = ((UsergridEdge) outEdge).getId().toString().split(SLASH);
String sourceName = parts[1];
String connectionType = parts[2];
String target = parts[3] + SLASH + parts[4];
ApiResponse responseOutEdge = UsergridGraph.client.connectEntities(v.getType(), sourceName, connectionType, target);
UsergridGraph.ValidateResponseErrors(responseOutEdge);
ValidationUtils.validateDuplicate(responseOutEdge, RuntimeException.class, "Entity with the name specified already exists in Usergrid");
}
}
if (allINEdges != null) {
for (Object inEdge : allINEdges) {
//TODO: Create incomingEdges for the Vertex
String[] parts = ((UsergridEdge) inEdge).getId().toString().split(SLASH);
String sourceType = parts[0];
String sourceName = parts[1];
String connectionType = parts[2];
ApiResponse responseInEdge = UsergridGraph.client.connectEntities(sourceType, sourceName, connectionType, v.getId().toString());
UsergridGraph.ValidateResponseErrors(responseInEdge);
ValidationUtils.validateDuplicate(responseInEdge, RuntimeException.class, "Entity with the name specified already exists in Usergrid");
}
}
}
} else if (value.equals(null)&&this.getProperty(key).equals(null)) {
throw new IllegalArgumentException("Value for property that does not exist cannot be null");
}
else {
setLocalProperty(key, value);
super.save();
}
}
/**
* Remove a particular property as specified by the key
*
* @param key Name of the property to delete.
* @return Returns the value of the property removed.
*/
public <T> T removeProperty(String key) {
T oldValue = this.getProperty(key);
super.setProperty(key, (String) null);
return oldValue;
}
/**
* Removes or deletes the vertex or entity
*/
public void remove() {
super.delete();
}
/**
* This gets the ID of the vertex
*
* @return Returns the ID of the vertex.
*/
public Object getId() {
String ObjectType = this.getType();
UUID ObjectUUID = this.getUuid();
String id;
if (this.getProperty(STRING_NAME) != null) {
id = ObjectType + SLASH + this.getProperty(STRING_NAME);
} else {
id = ObjectType + SLASH + ObjectUUID;
}
return id;
}
/**
* This compares the vertex with another vertex by UUID and type
* @param o The object tobe compared
* @return Returns a Boolean whether the vertices are equal or not
*/
@Override
public boolean equals(Object o) {
if (o instanceof UsergridVertex){
UsergridVertex v = (UsergridVertex)o;
boolean flag;
if ((this.getUuid().equals(v.getUuid()))&&(this.getType().equals(v.getType()))){flag = true;}
else {flag = false;}
return flag;
}
else if (o instanceof Vertex) {
Vertex v = (Vertex) o;
boolean flag;
if ((this.getProperty(STRING_UUID).equals(v.getProperty(STRING_UUID))) && (this.getProperty(STRING_TYPE).equals(v.getProperty(STRING_TYPE)))) {
flag = true;
} else {
flag = false;
}
return flag;
}
throw new IllegalArgumentException("Couldn't compare class '" + o.getClass() + "'");
}
/**
* This gives the hashCode of the ID of the vertex
* @return Returns the hasCode of the ID of the vertex as an Integer
*/
@Override
public int hashCode(){
int hashCode = this.getId().hashCode();
return hashCode;
}
}
| blueprints-usergrid-graph/src/main/java/org/apache/usergrid/drivers/blueprints/UsergridVertex.java | package org.apache.usergrid.drivers.blueprints;
import com.fasterxml.jackson.databind.JsonNode;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.VertexQuery;
import org.apache.usergrid.java.client.Client;
import org.apache.usergrid.java.client.model.UsergridEntity;
import org.apache.usergrid.java.client.response.ApiResponse;
import java.util.*;
/**
* Created by ApigeeCorporation on 6/29/15.
*/
public class UsergridVertex extends UsergridEntity implements Vertex {
private static String CONNECTING = "connecting";
private static String defaultType;
private static String METADATA = "metadata";
private static String CONNECTIONS = "connections";
public static final String SLASH = "/";
public static String STRING_NAME = "name";
public static String STRING_TYPE = "type";
public static String STRING_UUID = "uuid";
public UsergridVertex(String defaultType) {
super.setType(defaultType);
}
public static void setDefaultType(String defaultType) {
UsergridVertex.defaultType = defaultType;
}
/**
* This gets edges that are connected to the vertex in a
* particular direction specified, and having a specific label
*
* @param direction Direction of the edges to retrieve.
* @param labels Names of the edges to retrieve.
* @return Returns an Iterable of edges.
*/
public Iterable<Edge> getEdges(Direction direction, String... labels) {
/**
1) Check if the vertex exists.
2) Get the UUIDs of edges that are connected to the
particular vertex in a particular direction and with a particular label
3) Return an iterable of edges
*/
ValidationUtils.validateNotNull(direction, IllegalArgumentException.class, "Direction for getEdges cannot be null");
ValidationUtils.validateStringNotEmpty(labels.toString(), RuntimeException.class, "Label for edge in getEdges cannot be empty");
String srcType = this.getType();
String srcId = this.getUuid().toString();
List<Edge> edgesSet1 = new ArrayList<Edge>();
ApiResponse response = UsergridGraph.client.queryEdgesForVertex(srcType, srcId);
UsergridGraph.ValidateResponseErrors(response);
//Gets the vertex for which edges are to be found
UsergridEntity trgEntity = response.getFirstEntity();
switch (direction) {
case OUT:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
//Returns empty list if there are no edges
return new ArrayList<Edge>();
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTIONS, labels);
return edgesSet1;
case IN:
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Edge>();
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTING, labels);
return edgesSet1;
case BOTH:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Edge>();
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTING, labels);
return edgesSet1;
} else if (!checkHasEdges(trgEntity, CONNECTING)) {
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTIONS, labels);
return edgesSet1;
}
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTING, labels);
IterarteOverEdges(trgEntity, srcType, srcId, edgesSet1, CONNECTIONS, labels);
return edgesSet1;
}
return new ArrayList<Edge>();
}
private boolean checkHasEdges(UsergridEntity trgUUID, String conn) {
if (trgUUID.getProperties().get(METADATA).findValue(conn) == null)
return false;
else
return true;
}
private void IterarteOverEdges(UsergridEntity trgUUID, String srcType, String srcId, List<Edge> edges, String conn, String... labels) {
List<String> connections = new ArrayList<String>();
//If labels are specified
if(labels.length != 0){
for (String label : labels){
connections.add(label);
}
}else {
//When labels are not specified
Iterator<String> conn1 = trgUUID.getProperties().get(METADATA).findValue(conn).fieldNames();
while(conn1.hasNext()){
connections.add(conn1.next());
}
}
Direction direction = null;
for (int conLen = 0 ; conLen < connections.size();conLen++){
ApiResponse resp = new ApiResponse();
if (conn == CONNECTIONS) {
resp = UsergridGraph.client.queryConnection(srcType, srcId, connections.get(conLen));
direction = Direction.OUT;
} else {
resp = UsergridGraph.client.queryConnection(srcType, srcId, CONNECTING, connections.get(conLen));
direction = Direction.IN;
}
List<UsergridEntity> entities = resp.getEntities();
getAllEdgesForVertex(entities, connections.get(conLen), edges, direction);
}
}
private List<Edge> getAllEdgesForVertex(List<UsergridEntity> entities, String name, List<Edge> edges, Direction dir) {
for (int i = 0; i < entities.size(); i++) {
UsergridEntity e = entities.get(i);
String vertex;
if(e.getStringProperty(STRING_NAME) != null )
vertex = e.getType() + SLASH + e.getStringProperty(STRING_NAME);
else
vertex = e.getType() + SLASH + e.getUuid().toString();
Edge e1 = null;
if (dir == Direction.OUT)
e1 = new UsergridEdge(this.getId().toString(), vertex, name);
else if (dir == Direction.IN)
e1 = new UsergridEdge(vertex, this.getId().toString(), name);
edges.add(e1);
}
return edges;
}
private void IterarteOverVertices(UsergridEntity trgEntity, String srcType, String srcId, List<Vertex> vertexSet, String conn, String... labels) {
List<String> connections = new ArrayList<String>();
//If labels are specified
if(labels.length != 0){
for (String label : labels){
connections.add(label);
}
}else {
//When labels are not specified, Example of conn1 is 'likes', 'hates' and other such verbs associated with the vertex
Iterator<String> conn1 = trgEntity.getProperties().get(METADATA).findValue(conn).fieldNames();
while(conn1.hasNext()){
connections.add(conn1.next());
}
}
for (int conLen = 0 ; conLen < connections.size();conLen++){
ApiResponse resp = new ApiResponse();
if (conn == CONNECTIONS) {
resp = UsergridGraph.client.queryConnection(srcType, srcId, connections.get(conLen));
} else {
resp = UsergridGraph.client.queryConnection(srcType, srcId, CONNECTING, connections.get(conLen));
}
List<UsergridEntity> entities = resp.getEntities();
getAllVerticesForVertex(entities, vertexSet);
}
}
private List<Vertex> getAllVerticesForVertex(List<UsergridEntity> entities, List<Vertex> vertices){
for (int i = 0; i < entities.size(); i++) {
UsergridVertex v1 = UsergridGraph.CreateVertexFromEntity(entities.get(i));
vertices.add(v1);
}
return vertices;
}
/**
* This gets all the adjacent vertices connected to the vertex by an edge specified by a particular direction and label
*
* @param direction Direction of the vertices to retrieve.
* @param labels names of the vertices to retrieve.
* @return Returns and Iterable of vertices.
*/
public Iterable<Vertex> getVertices(Direction direction, String... labels) {
/**
1) Check if the vertex exists
2) Get the UUIDs of edges that are connected to the
particular vertex in a particular direction and with a particular label
3)Get the vertices at the other end of the edge
4) Return an iterable of vertices
*/
ValidationUtils.validateNotNull(direction, IllegalArgumentException.class, "Direction for getEdges cannot be null");
ValidationUtils.validateStringNotEmpty(labels.toString(), RuntimeException.class, "Label for edge in getEdges cannot be empty");
String srcType = this.getType().toString();
String srcId = this.getUuid().toString();
List<Vertex> vertexSet = new ArrayList<Vertex>();
ApiResponse response = UsergridGraph.client.queryEdgesForVertex(srcType, srcId);
UsergridGraph.ValidateResponseErrors(response);
//Gets the vertex for which edges are to be found
UsergridEntity trgEntity = response.getFirstEntity();
switch (direction) {
case OUT:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
//Returns empty list if there are no adjacent vertices
return new ArrayList<Vertex>();
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTIONS, labels);
return vertexSet;
case IN:
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Vertex>();
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTING, labels);
return vertexSet;
case BOTH:
if (!checkHasEdges(trgEntity, CONNECTIONS)) {
if (!checkHasEdges(trgEntity, CONNECTING)) {
return new ArrayList<Vertex>();
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTING, labels);
return vertexSet;
} else if (!checkHasEdges(trgEntity, CONNECTING)) {
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTIONS, labels);
return vertexSet;
}
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTING, labels);
IterarteOverVertices(trgEntity, srcType, srcId, vertexSet, CONNECTIONS, labels);
return vertexSet;
}
return new ArrayList<Vertex>();
}
/**
* Not supported for Usergrid
*
* Generate a query object that can be
* used to filter which connections/entities are retrieved that are incident/adjacent to this entity.
*
* @return
*/
public VertexQuery query() {
throw new UnsupportedOperationException("Not supported for Usergrid");
}
/**
* Adds an edge to the vertex, with the target vertex specified
*
* @param label Name of the edge to be added.
* @param inVertex connecting edge.
* @return Returns the new edge formed.
*/
public Edge addEdge(String label, Vertex inVertex) {
/**
1) Check if the target vertex exists
2) Use the following to add an edge - connectEntities( String connectingEntityType,String
connectingEntityId, String connectionType, String connectedEntityId) in org.apache.usergrid.java.client
3) Return the newly created edge
*/
ValidationUtils.validateNotNull(label,IllegalArgumentException.class,"Label for edge cannot be null");
ValidationUtils.validateNotNull(inVertex, IllegalArgumentException.class, "Target vertex cannot be null");
ValidationUtils.validateStringNotEmpty(label, RuntimeException.class, "Label of edge cannot be emoty");
UsergridEdge e = new UsergridEdge(this.getId().toString(), inVertex.getId().toString(), label);
ApiResponse response = UsergridGraph.client.connectEntities(this, (UsergridVertex) inVertex, label);
UsergridGraph.ValidateResponseErrors(response);
return e;
}
/**
* Get a particular property of a vertex specified by a key
*
* @param key The property to retrieve for a vertex.
* @return Returns the value of the property.
*/
public <T> T getProperty(String key) {
/**
1) Check if the vertex exists
2) Use the getEntityProperty(String name, float/String/long/int/boolean/JsonNode value) in
org.apache.usergrid.java.client.entities
3) If any other type throw an error
*/
//TODO: Check if vertex exists?
ValidationUtils.validateNotNull(key, IllegalArgumentException.class, "Property key cannot be null");
ValidationUtils.validateStringNotEmpty(key, RuntimeException.class, "Property key cannot be empty");
T propertyValue = (T) super.getEntityProperty(key);
//TODO: Check if property exists
return propertyValue;
}
/**
* This gets all the property keys for a particular vertex
*
* @return Returns a Set of properties for the vertex.
*/
public Set<String> getPropertyKeys() {
//TODO: Check if vertex exists?
Set<String> allKeys = super.getProperties().keySet();
return allKeys;
}
/**
* This sets a particular value of a property using the specified key in the local object
*
* @param key Name of the property.
* @param value Value of the property.
*/
public void setLocalProperty(String key, Object value) {
ValidationUtils.validateNotNull(key, IllegalArgumentException.class, "Key for the property cannot be null");
ValidationUtils.validateStringNotEmpty(key, RuntimeException.class, "Key of the property cannot be empty");
if (value instanceof String) {
super.setProperty(key, (String) value);
} else if (value instanceof JsonNode) {
super.setProperty(key, (JsonNode) value);
} else if (value instanceof Integer) {
super.setProperty(key, (Integer) value);
} else if (value instanceof Float) {
super.setProperty(key, (Float) value);
} else if (value instanceof Boolean) {
super.setProperty(key, (Boolean) value);
} else if (value instanceof Long) {
super.setProperty(key, (Long) value);
} else if (value.equals(null)){
super.setProperty(key,(String) null);
}
else {
throw new IllegalArgumentException("Supplied ID class of " + String.valueOf(value.getClass()) + " is not supported");
}
}
public void setProperty(String key, Object value) {
if (key.equals(STRING_TYPE)) {
if (value.equals(this.getType())) {
} else {
String oldType = this.getType();
String newType = value.toString();
UsergridVertex v = new UsergridVertex(newType);
Map allProperties = this.properties;
Iterable allOUTEdges = this.getEdges(Direction.OUT);
Iterable allINEdges = this.getEdges(Direction.IN);
v.properties = allProperties;
v.setLocalProperty(STRING_TYPE, newType);
ApiResponse responseDelete = UsergridGraph.client.deleteEntity(oldType, this.getUuid().toString());
ApiResponse response = UsergridGraph.client.createEntity(v);
UsergridGraph.ValidateResponseErrors(response);
ValidationUtils.validateDuplicate(response, RuntimeException.class, "Entity with the name specified already exists in Usergrid");
String uuid = response.getFirstEntity().getStringProperty(STRING_UUID);
v.setUuid(UUID.fromString(uuid));
if (allOUTEdges != null) {
for (Object outEdge : allOUTEdges) {
//TODO:Create outGoing Edges for the Vertex
String[] parts = ((UsergridEdge) outEdge).getId().toString().split(SLASH);
String sourceName = parts[1];
String connectionType = parts[2];
String target = parts[3] + SLASH + parts[4];
ApiResponse responseOutEdge = UsergridGraph.client.connectEntities(v.getType(), sourceName, connectionType, target);
UsergridGraph.ValidateResponseErrors(responseOutEdge);
ValidationUtils.validateDuplicate(responseOutEdge, RuntimeException.class, "Entity with the name specified already exists in Usergrid");
}
}
if (allINEdges != null) {
for (Object inEdge : allINEdges) {
//TODO: Create incomingEdges for the Vertex
String[] parts = ((UsergridEdge) inEdge).getId().toString().split(SLASH);
String sourceType = parts[0];
String sourceName = parts[1];
String connectionType = parts[2];
ApiResponse responseInEdge = UsergridGraph.client.connectEntities(sourceType, sourceName, connectionType, v.getId().toString());
UsergridGraph.ValidateResponseErrors(responseInEdge);
ValidationUtils.validateDuplicate(responseInEdge, RuntimeException.class, "Entity with the name specified already exists in Usergrid");
}
}
}
} else {
setLocalProperty(key, value);
super.save();
}
}
/**
* Remove a particular property as specified by the key
*
* @param key Name of the property to delete.
* @return Returns the value of the property removed.
*/
public <T> T removeProperty(String key) {
T oldValue = this.getProperty(key);
super.setProperty(key, (String) null);
return oldValue;
}
/**
* Removes or deletes the vertex or entity
*/
public void remove() {
super.delete();
}
/**
* This gets the ID of the vertex
*
* @return Returns the ID of the vertex.
*/
public Object getId() {
String ObjectType = this.getType();
UUID ObjectUUID = this.getUuid();
String id;
if (this.getProperty(STRING_NAME) != null) {
id = ObjectType + SLASH + this.getProperty(STRING_NAME);
} else {
id = ObjectType + SLASH + ObjectUUID;
}
return id;
}
/**
* This compares the vertex with another vertex by UUID and type
* @param o The object tobe compared
* @return Returns a Boolean whether the vertices are equal or not
*/
@Override
public boolean equals(Object o) {
if (o instanceof UsergridVertex){
UsergridVertex v = (UsergridVertex)o;
boolean flag;
if ((this.getUuid().equals(v.getUuid()))&&(this.getType().equals(v.getType()))){flag = true;}
else {flag = false;}
return flag;
}
else if (o instanceof Vertex) {
Vertex v = (Vertex) o;
boolean flag;
if ((this.getProperty(STRING_UUID).equals(v.getProperty(STRING_UUID))) && (this.getProperty(STRING_TYPE).equals(v.getProperty(STRING_TYPE)))) {
flag = true;
} else {
flag = false;
}
return flag;
}
throw new IllegalArgumentException("Couldn't compare class '" + o.getClass() + "'");
}
/**
* This gives the hashCode of the ID of the vertex
* @return Returns the hasCode of the ID of the vertex as an Integer
*/
@Override
public int hashCode(){
int hashCode = this.getId().hashCode();
return hashCode;
}
}
| Support for null value of property that did not exist before
| blueprints-usergrid-graph/src/main/java/org/apache/usergrid/drivers/blueprints/UsergridVertex.java | Support for null value of property that did not exist before | <ide><path>lueprints-usergrid-graph/src/main/java/org/apache/usergrid/drivers/blueprints/UsergridVertex.java
<ide> }
<ide> }
<ide> }
<del> } else {
<add> } else if (value.equals(null)&&this.getProperty(key).equals(null)) {
<add> throw new IllegalArgumentException("Value for property that does not exist cannot be null");
<add> }
<add> else {
<ide> setLocalProperty(key, value);
<ide> super.save();
<ide> } |
|
JavaScript | mit | cfeba8fe95cfba2ae4087962792fd304c78bd3e3 | 0 | mmig/mmir-lib | /*
* Copyright (C) 2012-2013 DFKI GmbH
* Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
* German Research Center for Artificial Intelligence
* http://www.dfki.de
*
* 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.
*/
define(['jquery', 'constants', 'commonUtils', 'configurationManager', 'dictionary', 'logger', 'module'],
/**
* The MediaManager gives access to audio in- and output functionality.
*
* Depending on its configuration, the MediaManager loads different implementation modules
* (<em>plugins</em>) that realize the interface-functions differently.
*
* See directory <code>mmirf/env/media</code> for available plugins.
*
* This "class" is a singleton - so that only one instance is in use.<br>
*
* @class
* @name MediaManager
* @exports MediaManager as mmir.MediaManager
* @static
*
* @depends jQuery.extend
* @depends jQuery.Deferred
*
* TODO remove / change dependency on forBrowser: constants.isBrowserEnv()!!!
*/
function(
jQuery, constants, commonUtils, configurationManager, Dictionary, Logger, module
){
//next 2 comments are needed by JSDoc so that all functions etc. can
// be mapped to the correct class description
/** @scope mmir.MediaManager.prototype */
/**
* #@+
* @memberOf mmir.MediaManager.prototype
*/
var instance = null;
//default configuration for env-settings "browser" and "cordova":
//
// -> may be overwritten by settings in the configuration file.
// e.g. adding the following JSON data to config/configuration.json:
//
// "mediaManager": {
// "plugins": {
// "browser": ["html5AudioOutput.js",
// "html5AudioInput.js",
// "maryTextToSpeech.js"
// ],
// "cordova": ["cordovaAudioOutput.js",
// "nuanceAudioInput.js",
// "nativeTextToSpeech.js"
// ]
// }
// }
var pluginsToLoad = {
'browser': ['html5AudioOutput.js',
'html5AudioInput.js',
'maryTextToSpeech.js'
],
'cordova': ['cordovaAudioOutput.js',
'nuanceAudioInput.js',
'nativeTextToSpeech.js'
]
};
var loadPlugin = function loadPlugin (filePath, successCallback, failureCallback){
try {
commonUtils.loadScript(constants.getMediaPluginPath() + filePath, function(){
if (typeof newMediaPlugin !== 'undefined' && newMediaPlugin){
newMediaPlugin.initialize(function(exportedFunctions){
jQuery.extend(true,instance,exportedFunctions);
newMediaPlugin = null;
if (successCallback) successCallback();
}, instance);
}
else {
console.error('Error loading MediaPlugin '+filePath + ' - no newMediaPlugin set!');
if (failureCallback) failureCallback();
}
});
//DISABLED @russa: currently disabled, since debugging eval'ed code is problematic
// NOTE support for code-naming feature (see below) is currently somewhat broken in FireFox (e.g. location in error-stack is not done correctly)
// //NOTE: this new loading-mechanism avoids global VARIABLES by
// // * loading the script as text
// // * evaluating the script-text (i.e. executing the JavaScript) within an local context
// // * uses code-naming feature for eval'ed code: //@ sourceURL=...
// //i.e. eval(..) is used ...
// var targetPath = constants.getMediaPluginPath()+filePath;
// $.ajax({
// async: true,
// dataType: "text",
// url: targetPath,
// success: function(data){
//
// //add "dummy-export-code" to script-text
// // -> for "retrieving" the media-plugin implementation as return value from eval(..)
// var LOAD_MODULE_TEMPLATE_POSTFIX = 'var dummy = newMediaPlugin; dummy';
// //use eval code naming feature...
// var codeId = ' sourceURL=' + constants.getMediaPluginPath()+filePath + '\n';
// //... for WebKit:
// var CODE_ID_EXPR1 = '//@';
// // ... and for FireFox:
// var CODE_ID_EXPR2 = '//#';
//
// var newMediaPlugin = eval(data
// + CODE_ID_EXPR1 + codeId
// + CODE_ID_EXPR2 + codeId
// + LOAD_MODULE_TEMPLATE_POSTFIX
// );
//
// if (typeof newMediaPlugin !== 'undefined' && newMediaPlugin){
// newMediaPlugin.initialize(function(exportedFunctions){
// jQuery.extend(true,instance,exportedFunctions);
// newMediaPlugin = null;
// if (successCallback) successCallback();
// }, instance);
// }
// else {
// console.error('Error loading MediaPlugin '+filePath + ' - no newMediaPlugin set!');
// if (failureCallback) failureCallback();
// }
// }
// }).fail(function(jqxhr, settings, err){
// // print out an error message
// var errMsg = err && err.stack? err.stack : err;
// console.error("[" + settings + "] " + JSON.stringify(jqxhr) + " -- " + partial.path + ": "+errMsg); //failure
// });
}catch (e){
console.error('Error loading MediaPlugin '+filePath+': '+e);
if (failureCallback) failureCallback();
}
};
/**
* @constructs MediaManager
* @memberOf MediaManager.prototype
* @private
*/
function constructor(){
//map of listeners for event X
var listener = new Dictionary();
//map of listener-observers (get notified if listener for event X gets added/removed)
var listenerObserver = new Dictionary();
/** exported as addListener() and on() */
var addListenerImpl = function(eventName, eventHandler){
var list = listener.get(eventName);
if(!list){
list = [eventHandler];
listener.put(eventName, list);
}
else {
list.push(eventHandler);
}
//notify listener-observers for this event-type
this._notifyObservers(eventName, 'added', eventHandler);
};
/** exported as removeListener() and off() */
var removeListenerImpl = function(eventName, eventHandler){
var isRemoved = false;
var list = listener.get(eventName);
if(list){
var size = list.length;
for(var i = size - 1; i >= 0; --i){
if(list[i] === eventHandler){
//move all handlers after i by 1 index-position ahead:
for(var j = size - 1; j > i; --j){
list[j-1] = list[j];
}
//remove last array-element
list.splice(size-1, 1);
//notify listener-observers for this event-type
this._notifyObservers(eventName, 'removed', eventHandler);
isRemoved = true;
break;
}
}
}
return isRemoved;
};
/**
* The logger for the MediaManager.
*
* Exported as <code>_log</code> by the MediaManager instance.
*/
var logger = Logger.create(module);//initialize with requirejs-module information
/** @lends MediaManager.prototype */
return {
/**
* A logger for the MediaManager.
*
* This logger MAY be used by media-plugins and / or tools and helpers
* related to the MediaManager.
*
* This logger SHOULD NOT be used by "code" that non-related to the
* MediaManager
*
* @name _log
* @property
* @type mmir.Logger
* @default mmir.Logger (logger instance for mmir.MediaManager)
* @public
*/
_log: logger,
//TODO add API documentation
//... these are the standard audioInput procedures, that should be implemented by a loaded file
///////////////////////////// audio input API: /////////////////////////////
/**
* Start speech recognition with <em>end-of-speech</em> detection:
*
* the recognizer automatically tries to detect when speech has finished and then
* triggers the callback with the result.
*
* @async
*
* @param {Function} [successCallBack] OPTIONAL
* callback function that is triggered when a text result is available.
* The callback signature is:
* <code>callback(textResult)</code>
* @param {Function} [failureCallBack] OPTIONAL
* callback function that is triggered when an error occurred.
* The callback signature is:
* <code>callback(error)</code>
*/
recognize: function(successCallBack, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Input: Speech Recognition is not supported.");
}
else {
console.error("Audio Input: Speech Recognition is not supported.");
}
},
/**
* Start continuous speech recognition:
*
* The recognizer continues until {@link #stopRecord} is called.
*
* <p>
* If <code>isWithIntermediateResults</code> is used, the recognizer may
* invoke the callback with intermediate recognition results.
*
* TODO specify whether stopRecord should return the "gathered" intermediate results, or just the last one
*
* NOTE that not all implementation may support this feature.
*
* @async
*
* @param {Function} [successCallBack] OPTIONAL
* callback function that is triggered when a text result is available.
* The callback signature is:
* <code>callback(textResult)</code>
* @param {Function} [failureCallBack] OPTIONAL
* callback function that is triggered when an error occurred.
* The callback signature is:
* <code>callback(error)</code>
* @param {Boolean} [isWithIntermediateResults] OPTIONAL
* if <code>true</code>, the recognizer will return intermediate results
* by invoking the successCallback
*
* @see #stopRecord
*/
startRecord: function(successCallBack,failureCallBack, isWithIntermediateResults){
if(failureCallBack){
failureCallBack("Audio Input: Speech Recognition (recording) is not supported.");
}
else {
console.error("Audio Input: Speech Recognition (recording) is not supported.");
}
},
/**
* Stops continuous speech recognition:
*
* After {@link #startRecord} was called, invoking this function will stop the recognition
* process and return the result by invoking the <code>succesCallback</code>.
*
* TODO specify whether stopRecord should return the "gathered" intermediate results, or just the last one
*
* @async
*
* @param {Function} [successCallBack] OPTIONAL
* callback function that is triggered when a text result is available.
* The callback signature is:
* <code>callback(textResult)</code>
* @param {Function} [failureCallBack] OPTIONAL
* callback function that is triggered when an error occurred.
* The callback signature is:
* <code>callback(error)</code>
*
* @see #startRecord
*/
stopRecord: function(successCallBack,failureCallBack){
if(failureCallBack){
failureCallBack("Audio Input: Speech Recognition (recording) is not supported.");
}
else {
console.error("Audio Input: Speech Recognition (recording) is not supported.");
}
},
/**
* Cancel currently active speech recognition.
*
* Has no effect, if no recognition is active.
*/
cancelRecognition: function(successCallBack,failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: canceling Recognize Speech is not supported.");
}
else {
console.error("Audio Output: canceling Recognize Speech is not supported.");
}
},
///////////////////////////// audio output API: /////////////////////////////
/**
* Play PCM audio data.
*/
playWAV: function(blob, onPlayedCallback, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: play WAV audio is not supported.");
}
else {
console.error("Audio Output: play WAV audio is not supported.");
}
},
/**
* Play audio file from the specified URL.
*/
playURL: function(url, onPlayedCallback, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: play audio from URL is not supported.");
}
else {
console.error("Audio Output: play audio from URL is not supported.");
}
},
/**
* Get an audio object for the audio file specified by URL.
*
* The audio object exports the following functions:
*
* play
* stop
* release
* enable
* disable
* setVolume
* getDuration
* isPaused
* isEnabled
*
* NOTE: the audio object should only be used, after the <code>onLoadedCallback</code>
* was triggered.
*
* @param {String} url
* @param {Function} [onPlayedCallback] OPTIONAL
* @param {Function} [failureCallBack] OPTIONAL
* @param {Function} [onLoadedCallBack] OPTIONAL
*/
getURLAsAudio: function(url, onPlayedCallback, failureCallBack, onLoadedCallBack){
if(failureCallBack){
failureCallBack("Audio Output: create audio from URL is not supported.");
}
else {
console.error("Audio Output: create audio from URL is not supported.");
}
},
///////////////////////////// text-to-speech API: /////////////////////////////
/**
* Synthesizes ("read out loud") text.
*
* @param {String|Array[String]|PlainObjec} parameter
* if <code>String</code> or <code>Array</code> of <code>String</code>s
* synthesizes the text of the String, for an Array: each entry is interpreted as "sentence";
* after each sentence, a short pause is inserted before synthesizing the
* the next sentence<br>
* for a <code>PlainObject</code>, the following properties should be used:
* <pre>{
* text: string OR string Array, text that should be read aloud
* , pauseLength: OPTIONAL Length of the pauses between sentences in milliseconds
* , forceSingleSentence: OPTIONAL boolean, if true, a string Array will be turned into a single string
* , split: OPTIONAL boolean, if true and the text is a single string, it will be split using a splitter function
* , splitter: OPTIONAL function, replaces the default splitter-function. It takes a simple string as input and gives a string Array as output
* }</pre>
*/
textToSpeech: function(parameter, onPlayedCallback, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: Text To Speech is not supported.");
}
else {
console.error("Audio Output: Text To Speech is not supported.");
}
},
/**
* Cancel current synthesis.
*/
cancelSpeech: function(successCallBack,failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: canceling Text To Speech is not supported.");
}
else {
console.error("Audio Output: canceling Text To Speech is not supported.");
}
},
///////////////////////////// ADDITIONAL (optional) functions: /////////////////////////////
/**
* Set the volume for the speech synthesis (text-to-speech).
*
* @param {Number} newValue
* TODO specify format / range
*/
setTextToSpeechVolume: function(newValue){
console.error("Audio Output: set volume for Text To Speech is not supported.");
}
/**
* Adds the handler-function for the event.
*
* This function calls {@link #_notifyObservers} for the eventName with
* <code>actionType "added"</code>.
*
*
* Event names (and firing events) are specific to the loaded media plugins.
*
* TODO list events that the default media-plugins support
* * "miclevelchanged": fired by AudioInput plugins that support querying the microphone (audio input) levels
*
* A plugin can tigger / fire events using the helper {@link #_fireEvent}
* of the MediaManager.
*
*
* Media plugins may observe registration / removal of listeners
* via {@link #_addListenerObserver} and {@link #_removeListenerObserver}.
* Or get and iterate over listeners via {@link #getListeners}.
*
*
*
*
* @param {String} eventName
* @param {Function} eventHandler
*/
, addListener: addListenerImpl
/**
* Removes the handler-function for the event.
*
* Calls {@link #_notifyObservers} for the eventName with
* <code>actionType "removed"</code>, if the handler
* was actually removed.
*
* @param {String} eventName
* @param {Function} eventHandler
*
* @returns {Boolean}
* <code>true</code> if the handler function was actually
* removed, and <code>false</code> otherwise.
*/
, removeListener: removeListenerImpl
/** @see {@link #addListener} */
, on:addListenerImpl
/** @see {@link #removeListener} */
, off: removeListenerImpl
/**
* Get list of registered listeners / handlers for an event.
*
* @returns {Array[Function]} of event-handlers.
* Empty, if there are no event handlers for eventName
*/
, getListeners: function(eventName){
var list = listener.get(eventName);
if(list && list.length){
//return copy of listener-list
return list.slice(0,list.length);
}
return [];
}
/**
* Check if at least one listener / handler is registered for the event.
*
* @returns {Boolean} <code>true</code> if at least 1 handler is registered
* for eventName; otherwise <code>false</code>.
*/
, hasListeners: function(eventName){
var list = listener.get(eventName);
return list && list.length > 0;
}
/**
* Helper for firing / triggering an event.
* This should only be used by media plugins (that handle the eventName).
*
* @param {String} eventName
* @param {Array} argsArray
* the list of arguments with which the event-handlers
* will be called.
*/
, _fireEvent: function(eventName, argsArray){
var list = listener.get(eventName);
if(list && list.length){
for(var i=0, size = list.length; i < size; ++i){
list[i].apply(this, argsArray);
}
}
}
/** @private */
, _notifyObservers: function(eventName, actionType, eventHandler){//actionType: one of "added" | "removed"
var list = listenerObserver.get(eventName);
if(list && list.length){
for(var i=0, size = list.length; i < size; ++i){
list[i](actionType,eventHandler);
}
}
}
/**
* Add an observer for registration / removal of event-handler.
*
* The observer gets notified,when handlers are registered / removed for the event.
*
* The observer-callback function will be called with the following
* arguments
*
* <code>(eventName, ACTION_TYPE, eventHandler)</code>
* where
* <ul>
* <li>eventName: String the name of the event that should be observed</li>
* <li>ACTION_TYPE: the type of action: "added" if the handler was
* registered for the event, "removed" if the the handler was removed
* </li>
* <li>eventHandler: the handler function that was registered or removed</li>
* </ul>
*
* @param {String} eventName
* @param {Function} observerCallback
*/
, _addListenerObserver: function(eventName, observerCallback){
var list = listenerObserver.get(eventName);
if(!list){
list = [observerCallback];
listenerObserver.put(eventName, list);
}
else {
list.push(observerCallback);
}
}
, _removeListenerObserver: function(eventName, observerCallback){
var isRemoved = false;
var list = listenerObserver.get(eventName);
if(list){
var size = list.length;
for(var i = size - 1; i >= 0; --i){
if(list[i] === observerCallback){
//move all handlers after i by 1 index-position ahead:
for(var j = size - 1; j > i; --j){
list[j-1] = list[j];
}
//remove last array-element
list.splice(size-1, 1);
isRemoved = true;
break;
}
}
}
return isRemoved;
}
};//END: return{...
};//END: constructor(){...
//has 2 default configuarions:
// if isCordovaEnvironment TRUE: use 'cordova' config
// if FALSEy: use 'browser' config
//
// NOTE: this setting/paramater is overwritten, if the configuration has a property 'mediaPlugins' set!!!
function getPluginsToLoad(isCordovaEnvironment){
var env = null;
var pluginArray = [];
if (isCordovaEnvironment) {
env = 'cordova';
} else {
env = 'browser';
}
var dataFromConfig = configurationManager.get('mediaManager.plugins', true);
if (dataFromConfig && dataFromConfig[env]){
pluginArray = pluginArray.concat(dataFromConfig[env]);
} else{
pluginArray = pluginArray.concat(pluginsToLoad[env]);
}
return pluginArray;
}
function loadAllPlugins(pluginArray, successCallback,failureCallback){
if (pluginArray == null || pluginArray.length<1){
if (successCallback) {
successCallback();
}
return;
}
var newPluginName = pluginArray.pop();
loadPlugin(newPluginName, function (){
console.log(newPluginName+' loaded!');
loadAllPlugins(pluginArray,successCallback, failureCallback);},
failureCallback
);
}
var _stub = {
/** @scope MediaManager.prototype */
//TODO add for backwards compatibility?:
// create : function(){ return this.init.apply(this, arguments); },
/**
* Object containing the instance of the class {{#crossLink "audioInput"}}{{/crossLink}}
*
* If <em>listenerList</em> is provided, each listener will be registered after the instance
* is initialized, but before media-plugins (i.e. environment specfific implementations) are
* loaded.
* Each entry in the <em>listenerList</em> must have fields <tt>name</tt> (String) and
* <tt>listener</tt> (Function), where
* <br>
* name: is the name of the event
* <br>
* listener: is the listener implementation (the signature/arguments of the listener function depends
* on the specific event for which the listener will be registered)
*
*
* @method init
* @param {Function} [successCallback] OPTIONAL
* callback that gets triggered after the MediaManager instance has been initialized.
* @param {Function} [failureCallback] OPTIONAL
* a failure callback that gets triggered if an error occurs during initialization.
* @param {Array[Object]} [listenerList] OPTIONAL
* a list of listeners that should be registered, where each entry is an Object
* with properties:
* <pre>
* {
* name: String the event name,
* listener: Function the handler function
* }
* </pre>
* @return {Object}
* an Deferred object that gets resolved, after the {@link mmir.MediaManager}
* has been initialized.
* @public
*
*/
init: function(successCallback, failureCallback, listenerList){
var defer = jQuery.Deferred();
var deferredSuccess = function(){
defer.resolve();
};
var deferredFailure = function(){
defer.reject();
};
if(successCallback){
defer.done(successCallback);
}
if(deferredFailure){
defer.fail(failureCallback);
}
if (instance === null) {
jQuery.extend(true,this,constructor());
instance = this;
if(listenerList){
for(var i=0, size = listenerList.length; i < size; ++i){
instance.addListener(listenerList[i].name, listenerList[i].listener);
}
}
var isCordovaEnvironment = ! constants.isBrowserEnv();//FIXME implement mechanism for configuring this!!
var pluginArray = getPluginsToLoad(isCordovaEnvironment);
loadAllPlugins(pluginArray,deferredSuccess, deferredFailure);
}
else if(listenerList){
for(var i=0, size = listenerList.length; i < size; ++i){
instance.addListener(listenerList[i].name, listenerList[i].listener);
}
}
return defer.promise(this);
},
/**
* Same as {@link #init}.
*
* @deprecated use <code>init()</code> instead.
*
* @method getInstance
* @public
*/
getInstance: function(){
return this.init(null, null);
},
/**
* loads a file. If the file implements a function initialize(f)
* where the function f is called with a set of functions e, then those functions in e
* are added to the visibility of audioInput, and will from now on be applicable by calling
* mmir.MediaManager.<function name>().
*
* @deprecated do not use.
* @method loadFile
* @protected
*
*/
loadFile: function(filePath,successCallback, failureCallback){
if (instance=== null) {
this.init();
}
loadPlugin(filePath,sucessCallback, failureCallback);
}
};
return _stub;
/** #@- */
});//END: define(..., function(){...
| manager/mediaManager.js | /*
* Copyright (C) 2012-2013 DFKI GmbH
* Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
* German Research Center for Artificial Intelligence
* http://www.dfki.de
*
* 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.
*/
define(['jquery', 'constants', 'commonUtils', 'configurationManager', 'dictionary', 'logger', 'module'],
/**
* The MediaManager gives access to audio in- and output functionality.
*
* Depending on its configuration, the MediaManager loads different implementation modules
* (<em>plugins</em>) that realize the interface-functions differently.
*
* See directory <code>mmirf/env/media</code> for available plugins.
*
* This "class" is a singleton - so that only one instance is in use.<br>
*
* @class
* @name MediaManager
* @exports MediaManager as mmir.MediaManager
* @static
*
* @depends jQuery.extend
* @depends jQuery.Deferred
*
* TODO remove / change dependency on forBrowser: constants.isBrowserEnv()!!!
*/
function(
jQuery, constants, commonUtils, configurationManager, Dictionary, Logger, module
){
//next 2 comments are needed by JSDoc so that all functions etc. can
// be mapped to the correct class description
/** @scope mmir.MediaManager.prototype */
/**
* #@+
* @memberOf mmir.MediaManager.prototype
*/
var instance = null;
//default configuration for env-settings "browser" and "cordova":
//
// -> may be overwritten by settings in the configuration file.
// e.g. adding the following JSON data to config/configuration.json:
//
// "mediaManager": {
// "plugins": {
// "browser": ["html5AudioOutput.js",
// "html5AudioInput.js",
// "maryTextToSpeech.js"
// ],
// "cordova": ["cordovaAudioOutput.js",
// "nuanceAudioInput.js",
// "nativeTextToSpeech.js"
// ]
// }
// }
var pluginsToLoad = {
'browser': ['html5AudioOutput.js',
'html5AudioInput.js',
'maryTextToSpeech.js'
],
'cordova': ['cordovaAudioOutput.js',
'nuanceAudioInput.js',
'nativeTextToSpeech.js'
]
};
var loadPlugin = function loadPlugin (filePath, successCallback, failureCallback){
try {
commonUtils.loadScript(constants.getMediaPluginPath() + filePath, function(){
if (typeof newMediaPlugin !== 'undefined' && newMediaPlugin){
newMediaPlugin.initialize(function(exportedFunctions){
jQuery.extend(true,instance,exportedFunctions);
newMediaPlugin = null;
if (successCallback) successCallback();
}, instance);
}
else {
console.error('Error loading MediaPlugin '+filePath + ' - no newMediaPlugin set!');
if (failureCallback) failureCallback();
}
});
//DISABLED @russa: currently disabled, since debugging eval'ed code is problematic
// NOTE support for code-naming feature (see below) is currently somewhat broken in FireFox (e.g. location in error-stack is not done correctly)
// //NOTE: this new loading-mechanism avoids global VARIABLES by
// // * loading the script as text
// // * evaluating the script-text (i.e. executing the JavaScript) within an local context
// // * uses code-naming feature for eval'ed code: //@ sourceURL=...
// //i.e. eval(..) is used ...
// var targetPath = constants.getMediaPluginPath()+filePath;
// $.ajax({
// async: true,
// dataType: "text",
// url: targetPath,
// success: function(data){
//
// //add "dummy-export-code" to script-text
// // -> for "retrieving" the media-plugin implementation as return value from eval(..)
// var LOAD_MODULE_TEMPLATE_POSTFIX = 'var dummy = newMediaPlugin; dummy';
// //use eval code naming feature...
// var codeId = ' sourceURL=' + constants.getMediaPluginPath()+filePath + '\n';
// //... for WebKit:
// var CODE_ID_EXPR1 = '//@';
// // ... and for FireFox:
// var CODE_ID_EXPR2 = '//#';
//
// var newMediaPlugin = eval(data
// + CODE_ID_EXPR1 + codeId
// + CODE_ID_EXPR2 + codeId
// + LOAD_MODULE_TEMPLATE_POSTFIX
// );
//
// if (typeof newMediaPlugin !== 'undefined' && newMediaPlugin){
// newMediaPlugin.initialize(function(exportedFunctions){
// jQuery.extend(true,instance,exportedFunctions);
// newMediaPlugin = null;
// if (successCallback) successCallback();
// }, instance);
// }
// else {
// console.error('Error loading MediaPlugin '+filePath + ' - no newMediaPlugin set!');
// if (failureCallback) failureCallback();
// }
// }
// }).fail(function(jqxhr, settings, err){
// // print out an error message
// var errMsg = err && err.stack? err.stack : err;
// console.error("[" + settings + "] " + JSON.stringify(jqxhr) + " -- " + partial.path + ": "+errMsg); //failure
// });
}catch (e){
console.error('Error loading MediaPlugin '+filePath+': '+e);
if (failureCallback) failureCallback();
}
};
/**
* @constructs MediaManager
* @memberOf MediaManager.prototype
* @private
*/
function constructor(){
var listener = new Dictionary();
var logger = Logger.create(module);
/** @lends MediaManager.prototype */
return {
_log: logger,
//TODO add API documentation
//... these are the standard audioInput procedures, that should be implemented by a loaded file
///////////////////////////// audio input API: /////////////////////////////
/**
* Start speech recognition with <em>end-of-speech</em> detection:
*
* the recognizer automatically tries to detect when speech has finished and then
* triggers the callback with the result.
*
* @async
*
* @param {Function} [successCallBack] OPTIONAL
* callback function that is triggered when a text result is available.
* The callback signature is:
* <code>callback(textResult)</code>
* @param {Function} [failureCallBack] OPTIONAL
* callback function that is triggered when an error occurred.
* The callback signature is:
* <code>callback(error)</code>
*/
recognize: function(successCallBack, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Input: Speech Recognition is not supported.");
}
else {
console.error("Audio Input: Speech Recognition is not supported.");
}
},
/**
* Start continuous speech recognition:
*
* The recognizer continues until {@link #stopRecord} is called.
*
* <p>
* If <code>isWithIntermediateResults</code> is used, the recognizer may
* invoke the callback with intermediate recognition results.
*
* TODO specify whether stopRecord should return the "gathered" intermediate results, or just the last one
*
* NOTE that not all implementation may support this feature.
*
* @async
*
* @param {Function} [successCallBack] OPTIONAL
* callback function that is triggered when a text result is available.
* The callback signature is:
* <code>callback(textResult)</code>
* @param {Function} [failureCallBack] OPTIONAL
* callback function that is triggered when an error occurred.
* The callback signature is:
* <code>callback(error)</code>
* @param {Boolean} [isWithIntermediateResults] OPTIONAL
* if <code>true</code>, the recognizer will return intermediate results
* by invoking the successCallback
*
* @see #stopRecord
*/
startRecord: function(successCallBack,failureCallBack, isWithIntermediateResults){
if(failureCallBack){
failureCallBack("Audio Input: Speech Recognition (recording) is not supported.");
}
else {
console.error("Audio Input: Speech Recognition (recording) is not supported.");
}
},
/**
* Stops continuous speech recognition:
*
* After {@link #startRecord} was called, invoking this function will stop the recognition
* process and return the result by invoking the <code>succesCallback</code>.
*
* TODO specify whether stopRecord should return the "gathered" intermediate results, or just the last one
*
* @async
*
* @param {Function} [successCallBack] OPTIONAL
* callback function that is triggered when a text result is available.
* The callback signature is:
* <code>callback(textResult)</code>
* @param {Function} [failureCallBack] OPTIONAL
* callback function that is triggered when an error occurred.
* The callback signature is:
* <code>callback(error)</code>
*
* @see #startRecord
*/
stopRecord: function(successCallBack,failureCallBack){
if(failureCallBack){
failureCallBack("Audio Input: Speech Recognition (recording) is not supported.");
}
else {
console.error("Audio Input: Speech Recognition (recording) is not supported.");
}
},
/**
* Cancel currently active speech recognition.
*
* Has no effect, if no recognition is active.
*/
cancelRecognition: function(successCallBack,failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: canceling Recognize Speech is not supported.");
}
else {
console.error("Audio Output: canceling Recognize Speech is not supported.");
}
},
///////////////////////////// audio output API: /////////////////////////////
/**
* Play PCM audio data.
*/
playWAV: function(blob, onPlayedCallback, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: play WAV audio is not supported.");
}
else {
console.error("Audio Output: play WAV audio is not supported.");
}
},
/**
* Play audio file from the specified URL.
*/
playURL: function(url, onPlayedCallback, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: play audio from URL is not supported.");
}
else {
console.error("Audio Output: play audio from URL is not supported.");
}
},
/**
* Get an audio object for the audio file specified by URL.
*
* The audio object exports the following functions:
*
* play
* stop
* release
* enable
* disable
* setVolume
* getDuration
* isPaused
* isEnabled
*
* NOTE: the audio object should only be used, after the <code>onLoadedCallback</code>
* was triggered.
*
* @param {String} url
* @param {Function} [onPlayedCallback] OPTIONAL
* @param {Function} [failureCallBack] OPTIONAL
* @param {Function} [onLoadedCallBack] OPTIONAL
*/
getURLAsAudio: function(url, onPlayedCallback, failureCallBack, onLoadedCallBack){
if(failureCallBack){
failureCallBack("Audio Output: create audio from URL is not supported.");
}
else {
console.error("Audio Output: create audio from URL is not supported.");
}
},
///////////////////////////// text-to-speech API: /////////////////////////////
/**
* Synthesizes ("read out loud") text.
*
* @param {String|Array[String]|PlainObjec} parameter
* if <code>String</code> or <code>Array</code> of <code>String</code>s
* synthesizes the text of the String, for an Array: each entry is interpreted as "sentence";
* after each sentence, a short pause is inserted before synthesizing the
* the next sentence<br>
* for a <code>PlainObject</code>, the following properties should be used:
* <pre>{
* text: string OR string Array, text that should be read aloud
* , pauseLength: OPTIONAL Length of the pauses between sentences in milliseconds
* , forceSingleSentence: OPTIONAL boolean, if true, a string Array will be turned into a single string
* , split: OPTIONAL boolean, if true and the text is a single string, it will be split using a splitter function
* , splitter: OPTIONAL function, replaces the default splitter-function. It takes a simple string as input and gives a string Array as output
* }</pre>
*/
textToSpeech: function(parameter, onPlayedCallback, failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: Text To Speech is not supported.");
}
else {
console.error("Audio Output: Text To Speech is not supported.");
}
},
/**
* Cancel current synthesis.
*/
cancelSpeech: function(successCallBack,failureCallBack){
if(failureCallBack){
failureCallBack("Audio Output: canceling Text To Speech is not supported.");
}
else {
console.error("Audio Output: canceling Text To Speech is not supported.");
}
},
///////////////////////////// ADDITIONAL (optional) functions: /////////////////////////////
/**
* Set the volume for the speech synthesis (text-to-speech).
*
* @param {Number} newValue
* TODO specify format / range
*/
setTextToSpeechVolume: function(newValue){
console.error("Audio Output: set volume for Text To Speech is not supported.");
}
/**
* @param {String} eventName
* @param {Function} eventHandler
*/
, addListener: function(eventName, eventHandler){
var list = listener.get(eventName);
if(!list){
list = [eventHandler];
listener.put(eventName, list);
}
else {
list.push(eventHandler);
}
}
/**
* @param {String} eventName
* @param {Function} eventHandler
*/
, removeListener: function(eventName, eventHandler){
var isRemoved = false;
var list = listener.get(eventName);
if(list){
var size = list.length;
for(var i = size - 1; i >= 0; --i){
if(list[i] === eventHandler){
//move all handlers after i by 1 index-position ahead:
for(var j = size - 1; j > i; --j){
list[j-1] = list[j];
}
//remove last array-element
list.splice(size-1, 1);
isRemoved = true;
break;
}
}
}
return isRemoved;
}
/**
* @returns {Array[Function]} of event-handlers; empty, if there are no event handlers for eventName
*/
, getListeners: function(eventName){
var list = listener.get(eventName);
if(list){
return list;
}
return [];
}
};//END: return{...
};//END: constructor(){...
//has 2 default configuarions:
// if isCordovaEnvironment TRUE: use 'cordova' config
// if FALSEy: use 'browser' config
//
// NOTE: this setting/paramater is overwritten, if the configuration has a property 'mediaPlugins' set!!!
function getPluginsToLoad(isCordovaEnvironment){
var env = null;
var pluginArray = [];
if (isCordovaEnvironment) {
env = 'cordova';
} else {
env = 'browser';
}
var dataFromConfig = configurationManager.get('mediaManager.plugins', true);
if (dataFromConfig && dataFromConfig[env]){
pluginArray = pluginArray.concat(dataFromConfig[env]);
} else{
pluginArray = pluginArray.concat(pluginsToLoad[env]);
}
return pluginArray;
}
function loadAllPlugins(pluginArray, successCallback,failureCallback){
if (pluginArray == null || pluginArray.length<1){
if (successCallback) {
successCallback();
}
return;
}
var newPluginName = pluginArray.pop();
loadPlugin(newPluginName, function (){
console.log(newPluginName+' loaded!');
loadAllPlugins(pluginArray,successCallback, failureCallback);},
failureCallback
);
}
var _stub = {
/** @scope MediaManager.prototype */
//TODO add for backwards compatibility?:
// create : function(){ return this.init.apply(this, arguments); },
/**
* Object containing the instance of the class {{#crossLink "audioInput"}}{{/crossLink}}
*
* If <em>listenerList</em> is provided, each listener will be registered after the instance
* is initialized, but before media-plugins (i.e. environment specfific implementations) are
* loaded.
* Each entry in the <em>listenerList</em> must have fields <tt>name</tt> (String) and
* <tt>listener</tt> (Function), where
* <br>
* name: is the name of the event
* <br>
* listener: is the listener implementation (the signature/arguments of the listener function depends
* on the specific event for which the listener will be registered)
*
*
* @method init
* @param {Function} [successCallback] OPTIONAL
* callback that gets triggered after the MediaManager instance has been initialized.
* @param {Function} [failureCallback] OPTIONAL
* a failure callback that gets triggered if an error occurs during initialization.
* @param {Array[Object]} [listenerList] OPTIONAL
* a list of listeners that should be registered, where each entry is an Object
* with properties:
* <pre>
* {
* name: String the event name,
* listener: Function the handler function
* }
* </pre>
* @return {Object}
* an Deferred object that gets resolved, after the {@link mmir.MediaManager}
* has been initialized.
* @public
*
*/
init: function(successCallback, failureCallback, listenerList){
var defer = jQuery.Deferred();
var deferredSuccess = function(){
defer.resolve();
};
var deferredFailure = function(){
defer.reject();
};
if(successCallback){
defer.done(successCallback);
}
if(deferredFailure){
defer.fail(failureCallback);
}
if (instance === null) {
jQuery.extend(true,this,constructor());
instance = this;
if(listenerList){
for(var i=0, size = listenerList.length; i < size; ++i){
instance.addListener(listenerList[i].name, listenerList[i].listener);
}
}
var isCordovaEnvironment = ! constants.isBrowserEnv();//FIXME implement mechanism for configuring this!!
var pluginArray = getPluginsToLoad(isCordovaEnvironment);
loadAllPlugins(pluginArray,deferredSuccess, deferredFailure);
}
else if(listenerList){
for(var i=0, size = listenerList.length; i < size; ++i){
instance.addListener(listenerList[i].name, listenerList[i].listener);
}
}
return defer.promise(this);
},
/**
* Same as {@link #init}.
*
* @deprecated use <code>init()</code> instead.
*
* @method getInstance
* @public
*/
getInstance: function(){
return this.init(null, null);
},
/**
* loads a file. If the file implements a function initialize(f)
* where the function f is called with a set of functions e, then those functions in e
* are added to the visibility of audioInput, and will from now on be applicable by calling
* mmir.MediaManager.<function name>().
*
* @deprecated do not use.
* @method loadFile
* @protected
*
*/
loadFile: function(filePath,successCallback, failureCallback){
if (instance=== null) {
this.init();
}
loadPlugin(filePath,sucessCallback, failureCallback);
}
};
return _stub;
/** #@- */
});//END: define(..., function(){...
| added support for "observering listeners", i.e. observing registration /
removal of event-listeners | manager/mediaManager.js | added support for "observering listeners", i.e. observing registration / removal of event-listeners | <ide><path>anager/mediaManager.js
<ide> */
<ide> function constructor(){
<ide>
<add> //map of listeners for event X
<ide> var listener = new Dictionary();
<del>
<del> var logger = Logger.create(module);
<add> //map of listener-observers (get notified if listener for event X gets added/removed)
<add> var listenerObserver = new Dictionary();
<add>
<add> /** exported as addListener() and on() */
<add> var addListenerImpl = function(eventName, eventHandler){
<add> var list = listener.get(eventName);
<add> if(!list){
<add> list = [eventHandler];
<add> listener.put(eventName, list);
<add> }
<add> else {
<add> list.push(eventHandler);
<add> }
<add>
<add> //notify listener-observers for this event-type
<add> this._notifyObservers(eventName, 'added', eventHandler);
<add> };
<add> /** exported as removeListener() and off() */
<add> var removeListenerImpl = function(eventName, eventHandler){
<add> var isRemoved = false;
<add> var list = listener.get(eventName);
<add> if(list){
<add> var size = list.length;
<add> for(var i = size - 1; i >= 0; --i){
<add> if(list[i] === eventHandler){
<add>
<add> //move all handlers after i by 1 index-position ahead:
<add> for(var j = size - 1; j > i; --j){
<add> list[j-1] = list[j];
<add> }
<add> //remove last array-element
<add> list.splice(size-1, 1);
<add>
<add> //notify listener-observers for this event-type
<add> this._notifyObservers(eventName, 'removed', eventHandler);
<add>
<add> isRemoved = true;
<add> break;
<add> }
<add> }
<add> }
<add> return isRemoved;
<add> };
<add>
<add>
<add> /**
<add> * The logger for the MediaManager.
<add> *
<add> * Exported as <code>_log</code> by the MediaManager instance.
<add> */
<add> var logger = Logger.create(module);//initialize with requirejs-module information
<ide>
<ide> /** @lends MediaManager.prototype */
<ide> return {
<add>
<add> /**
<add> * A logger for the MediaManager.
<add> *
<add> * This logger MAY be used by media-plugins and / or tools and helpers
<add> * related to the MediaManager.
<add> *
<add> * This logger SHOULD NOT be used by "code" that non-related to the
<add> * MediaManager
<add> *
<add> * @name _log
<add> * @property
<add> * @type mmir.Logger
<add> * @default mmir.Logger (logger instance for mmir.MediaManager)
<add> * @public
<add> */
<add> _log: logger,
<ide>
<del> _log: logger,
<del>
<ide> //TODO add API documentation
<ide>
<ide> //... these are the standard audioInput procedures, that should be implemented by a loaded file
<ide> }
<ide>
<ide> /**
<del> * @param {String} eventName
<del> * @param {Function} eventHandler
<del> */
<del> , addListener: function(eventName, eventHandler){
<add> * Adds the handler-function for the event.
<add> *
<add> * This function calls {@link #_notifyObservers} for the eventName with
<add> * <code>actionType "added"</code>.
<add> *
<add> *
<add> * Event names (and firing events) are specific to the loaded media plugins.
<add> *
<add> * TODO list events that the default media-plugins support
<add> * * "miclevelchanged": fired by AudioInput plugins that support querying the microphone (audio input) levels
<add> *
<add> * A plugin can tigger / fire events using the helper {@link #_fireEvent}
<add> * of the MediaManager.
<add> *
<add> *
<add> * Media plugins may observe registration / removal of listeners
<add> * via {@link #_addListenerObserver} and {@link #_removeListenerObserver}.
<add> * Or get and iterate over listeners via {@link #getListeners}.
<add> *
<add> *
<add> *
<add> *
<add> * @param {String} eventName
<add> * @param {Function} eventHandler
<add> */
<add> , addListener: addListenerImpl
<add> /**
<add> * Removes the handler-function for the event.
<add> *
<add> * Calls {@link #_notifyObservers} for the eventName with
<add> * <code>actionType "removed"</code>, if the handler
<add> * was actually removed.
<add> *
<add> * @param {String} eventName
<add> * @param {Function} eventHandler
<add> *
<add> * @returns {Boolean}
<add> * <code>true</code> if the handler function was actually
<add> * removed, and <code>false</code> otherwise.
<add> */
<add> , removeListener: removeListenerImpl
<add> /** @see {@link #addListener} */
<add> , on:addListenerImpl
<add> /** @see {@link #removeListener} */
<add> , off: removeListenerImpl
<add> /**
<add> * Get list of registered listeners / handlers for an event.
<add> *
<add> * @returns {Array[Function]} of event-handlers.
<add> * Empty, if there are no event handlers for eventName
<add> */
<add> , getListeners: function(eventName){
<ide> var list = listener.get(eventName);
<add> if(list && list.length){
<add> //return copy of listener-list
<add> return list.slice(0,list.length);
<add> }
<add> return [];
<add> }
<add> /**
<add> * Check if at least one listener / handler is registered for the event.
<add> *
<add> * @returns {Boolean} <code>true</code> if at least 1 handler is registered
<add> * for eventName; otherwise <code>false</code>.
<add> */
<add> , hasListeners: function(eventName){
<add> var list = listener.get(eventName);
<add> return list && list.length > 0;
<add> }
<add> /**
<add> * Helper for firing / triggering an event.
<add> * This should only be used by media plugins (that handle the eventName).
<add> *
<add> * @param {String} eventName
<add> * @param {Array} argsArray
<add> * the list of arguments with which the event-handlers
<add> * will be called.
<add> */
<add> , _fireEvent: function(eventName, argsArray){
<add> var list = listener.get(eventName);
<add> if(list && list.length){
<add> for(var i=0, size = list.length; i < size; ++i){
<add> list[i].apply(this, argsArray);
<add> }
<add> }
<add> }
<add> /** @private */
<add> , _notifyObservers: function(eventName, actionType, eventHandler){//actionType: one of "added" | "removed"
<add> var list = listenerObserver.get(eventName);
<add> if(list && list.length){
<add> for(var i=0, size = list.length; i < size; ++i){
<add> list[i](actionType,eventHandler);
<add> }
<add> }
<add> }
<add> /**
<add> * Add an observer for registration / removal of event-handler.
<add> *
<add> * The observer gets notified,when handlers are registered / removed for the event.
<add> *
<add> * The observer-callback function will be called with the following
<add> * arguments
<add> *
<add> * <code>(eventName, ACTION_TYPE, eventHandler)</code>
<add> * where
<add> * <ul>
<add> * <li>eventName: String the name of the event that should be observed</li>
<add> * <li>ACTION_TYPE: the type of action: "added" if the handler was
<add> * registered for the event, "removed" if the the handler was removed
<add> * </li>
<add> * <li>eventHandler: the handler function that was registered or removed</li>
<add> * </ul>
<add> *
<add> * @param {String} eventName
<add> * @param {Function} observerCallback
<add> */
<add> , _addListenerObserver: function(eventName, observerCallback){
<add> var list = listenerObserver.get(eventName);
<ide> if(!list){
<del> list = [eventHandler];
<del> listener.put(eventName, list);
<del> }
<del> else {
<del> list.push(eventHandler);
<add> list = [observerCallback];
<add> listenerObserver.put(eventName, list);
<add> }
<add> else {
<add> list.push(observerCallback);
<ide> }
<ide> }
<del> /**
<del> * @param {String} eventName
<del> * @param {Function} eventHandler
<del> */
<del> , removeListener: function(eventName, eventHandler){
<add>
<add> , _removeListenerObserver: function(eventName, observerCallback){
<ide> var isRemoved = false;
<del> var list = listener.get(eventName);
<add> var list = listenerObserver.get(eventName);
<ide> if(list){
<ide> var size = list.length;
<ide> for(var i = size - 1; i >= 0; --i){
<del> if(list[i] === eventHandler){
<add> if(list[i] === observerCallback){
<ide>
<ide> //move all handlers after i by 1 index-position ahead:
<ide> for(var j = size - 1; j > i; --j){
<ide> }
<ide> }
<ide> return isRemoved;
<del> }
<del> /**
<del> * @returns {Array[Function]} of event-handlers; empty, if there are no event handlers for eventName
<del> */
<del> , getListeners: function(eventName){
<del> var list = listener.get(eventName);
<del> if(list){
<del> return list;
<del> }
<del> return [];
<ide> }
<ide>
<ide> };//END: return{... |
|
Java | apache-2.0 | 89fbe746e83397ca6317f7d1811fe60b4b5ac296 | 0 | shibing624/ansj_seg,chaoliu1024/ansj_seg,chaoliu1024/ansj_seg,XYUU/ansj_seg,walletma/ansj_seg,NLPchina/ansj_seg,shibing624/ansj_seg,walletma/ansj_seg,waiteryee1/ansj_seg,waiteryee1/ansj_seg | src/test/java/org/ansj/demo/WapitiModelDemo.java | package org.ansj.demo;
import org.ansj.app.crf.Model;
import org.ansj.app.crf.model.WapitiCRFModel;
import org.ansj.util.MyStaticValue;
public class WapitiModelDemo {
public static void main(String[] args) throws Exception {
Model model = WapitiCRFModel.parseFileToModel("/Users/sunjian/Documents/src/Wapiti/test/model.dat", "/Users/sunjian/Documents/src/Wapiti/test/pattern.txt", 0) ;
}
}
| 删除了wapiti的模型转换方式.替代以直接调用wapitit的模型
| src/test/java/org/ansj/demo/WapitiModelDemo.java | 删除了wapiti的模型转换方式.替代以直接调用wapitit的模型 | <ide><path>rc/test/java/org/ansj/demo/WapitiModelDemo.java
<del>package org.ansj.demo;
<del>
<del>import org.ansj.app.crf.Model;
<del>import org.ansj.app.crf.model.WapitiCRFModel;
<del>import org.ansj.util.MyStaticValue;
<del>
<del>public class WapitiModelDemo {
<del> public static void main(String[] args) throws Exception {
<del>
<del> Model model = WapitiCRFModel.parseFileToModel("/Users/sunjian/Documents/src/Wapiti/test/model.dat", "/Users/sunjian/Documents/src/Wapiti/test/pattern.txt", 0) ;
<del>
<del>
<del> }
<del>} |
||
JavaScript | mit | f25404839ee88e98690ced8054ae7fb4f55a35f8 | 0 | mountsbefore/blog,lidan-cn/blog,mountsbefore/blog,lidan-cn/blog,mountsbefore/blog,lidan-cn/blog | "use strict"
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var db_connect_str = "mongodb://localhost/test"
var mongoose = require('mongoose');
var User = require("./application/model/user");
mongoose.connect(db_connect_str);//;连接数据库
var MongoStore = require('connect-mongo')(session)
var router = express.Router();
var app = express();
app.use(cookieParser("secret"));
app.use(session({
secret: '12345',
name: 'testapp',
cookie: {maxAge: 80000 },
resave: false,
saveUninitialized: true,
store: new MongoStore({ //创建新的mongodb数据库
url:db_connect_str
})
}));
app.use(express.static('public'));
// app.set("views","/")
var userRouter = require("./router/userRouter.js")
app.use(function(req,res,next){
res.setHeader("access-control-allow-origin","*");
next();
})
app.use(userRouter)
var server = app.listen(8080, function () {
var host = server.address().address || "localhost";
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port)
}) | rear/app.js | "use strict"
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var db_connect_str = "mongodb://localhost/test"
var mongoose = require('mongoose');
var User = require("./application/model/user");
var db = mongoose.createConnection(db_connect_str);//;连接数据库
db.on('error',console.error.bind(console,'连接错误:'));
db.once('open', function (callback) {
console.log("open.....")
});
var MongoStore = require('connect-mongo')(session)
var router = express.Router();
var app = express();
app.use(cookieParser("secret"));
// app.use(session({
// secret: '12345',
// name: 'testapp',
// cookie: {maxAge: 80000 },
// resave: false,
// saveUninitialized: true,
// store: new MongoStore({ //创建新的mongodb数据库
// url:db_connect_str
// })
// }));
// app.use(express.static('public'));
// app.set("views","/")
app.get('/', function (req, res) {
console.log("in home....")
res.send('Hello World!');
});
// var userRouter = require("./router/userRouter.js")
// app.use(function(req,res,next){
// res.setHeader("access-control-allow-origin","*");
// next();
// })
// app.use(userRouter)
// app.post("/test",function(req,res){
// console.log(__dirname)
// // res.send("hello world");
// req.session.user = "ssp";
// var user = new User({
// "name":"史少鹏5",
// "password" :"史少鹏5",
// "role":10
// });
// user.save(function(err,data){
// if(err){console.log(err)}
// });
// res.json({"success":"success"})
// });
var server = app.listen(3000, function () {
var host = server.address().address || "localhost";
var port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port)
}) | run app in 8080
| rear/app.js | run app in 8080 | <ide><path>ear/app.js
<ide>
<ide> var User = require("./application/model/user");
<ide>
<del>var db = mongoose.createConnection(db_connect_str);//;连接数据库
<del>
<del>db.on('error',console.error.bind(console,'连接错误:'));
<del>db.once('open', function (callback) {
<del> console.log("open.....")
<del>});
<del>
<add>mongoose.connect(db_connect_str);//;连接数据库
<ide>
<ide> var MongoStore = require('connect-mongo')(session)
<ide> var router = express.Router();
<ide> app.use(cookieParser("secret"));
<ide>
<ide>
<del>// app.use(session({
<del>// secret: '12345',
<del>// name: 'testapp',
<del>// cookie: {maxAge: 80000 },
<del>// resave: false,
<del>// saveUninitialized: true,
<del>// store: new MongoStore({ //创建新的mongodb数据库
<del>// url:db_connect_str
<del>// })
<del>// }));
<add>app.use(session({
<add> secret: '12345',
<add> name: 'testapp',
<add> cookie: {maxAge: 80000 },
<add> resave: false,
<add> saveUninitialized: true,
<add> store: new MongoStore({ //创建新的mongodb数据库
<add> url:db_connect_str
<add> })
<add>}));
<ide>
<del>// app.use(express.static('public'));
<add>app.use(express.static('public'));
<ide> // app.set("views","/")
<del>app.get('/', function (req, res) {
<del> console.log("in home....")
<del> res.send('Hello World!');
<del>});
<add>var userRouter = require("./router/userRouter.js")
<add>
<add>app.use(function(req,res,next){
<add> res.setHeader("access-control-allow-origin","*");
<add> next();
<add>})
<add>app.use(userRouter)
<ide>
<ide>
<del>// var userRouter = require("./router/userRouter.js")
<ide>
<del>// app.use(function(req,res,next){
<del>// res.setHeader("access-control-allow-origin","*");
<del>// next();
<del>// })
<del>// app.use(userRouter)
<del>
<del>// app.post("/test",function(req,res){
<del>// console.log(__dirname)
<del>// // res.send("hello world");
<del>// req.session.user = "ssp";
<del>// var user = new User({
<del>// "name":"史少鹏5",
<del>// "password" :"史少鹏5",
<del>// "role":10
<del>// });
<del>// user.save(function(err,data){
<del>// if(err){console.log(err)}
<del>// });
<del>// res.json({"success":"success"})
<del>// });
<del>
<del>
<del>var server = app.listen(3000, function () {
<add>var server = app.listen(8080, function () {
<ide>
<ide> var host = server.address().address || "localhost";
<ide> var port = server.address().port; |
|
Java | apache-2.0 | fd166b8b35e78075d7be70048bd41f9f6e068692 | 0 | supunucsc/java-sdk,m2fd/java-sdk,watson-developer-cloud/java-sdk,watson-developer-cloud/java-sdk,m2fd/java-sdk,JoshSharpe/java-sdk,watson-developer-cloud/java-sdk,JoshSharpe/java-sdk,JoshSharpe/java-sdk,supunucsc/java-sdk,watson-developer-cloud/java-sdk,supunucsc/java-sdk,m2fd/java-sdk | /**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ibm.watson.developer_cloud.service;
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gson.JsonObject;
import com.ibm.watson.developer_cloud.http.HttpHeaders;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.http.HttpStatus;
import com.ibm.watson.developer_cloud.http.RequestBuilder;
import com.ibm.watson.developer_cloud.http.ResponseConverter;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.http.ServiceCallback;
import com.ibm.watson.developer_cloud.service.exception.BadRequestException;
import com.ibm.watson.developer_cloud.service.exception.ConflictException;
import com.ibm.watson.developer_cloud.service.exception.ForbiddenException;
import com.ibm.watson.developer_cloud.service.exception.InternalServerErrorException;
import com.ibm.watson.developer_cloud.service.exception.NotFoundException;
import com.ibm.watson.developer_cloud.service.exception.RequestTooLargeException;
import com.ibm.watson.developer_cloud.service.exception.ServiceResponseException;
import com.ibm.watson.developer_cloud.service.exception.ServiceUnavailableException;
import com.ibm.watson.developer_cloud.service.exception.TooManyRequestsException;
import com.ibm.watson.developer_cloud.service.exception.UnauthorizedException;
import com.ibm.watson.developer_cloud.service.exception.UnsupportedException;
import com.ibm.watson.developer_cloud.util.CredentialUtils;
import com.ibm.watson.developer_cloud.util.RequestUtils;
import com.ibm.watson.developer_cloud.util.ResponseConverterUtils;
import com.ibm.watson.developer_cloud.util.ResponseUtils;
import jersey.repackaged.jsr166e.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.Response;
/**
* Watson service abstract common functionality of various Watson Services. It handle authentication
* and default url
*
* @see <a href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/"> IBM Watson
* Developer Cloud</a>
*/
public abstract class WatsonService {
private static final String URL = "url";
private static final String PATH_AUTHORIZATION_V1_TOKEN = "/v1/token";
private static final String AUTHORIZATION = "authorization";
private static final String MESSAGE_ERROR_3 = "message";
private static final String MESSAGE_ERROR_2 = "error_message";
private static final String BASIC = "Basic ";
private static final Logger LOG = Logger.getLogger(WatsonService.class.getName());
private String apiKey;
private final OkHttpClient client;
private String endPoint;
private final String name;
private Headers defaultHeaders = null;
private boolean skipAuthentication;
/** The Constant MESSAGE_CODE. */
protected static final String MESSAGE_CODE = "code";
/** The Constant MESSAGE_ERROR. */
protected static final String MESSAGE_ERROR = "error";
/** The Constant VERSION. */
protected static final String VERSION = "version";
/**
* Instantiates a new Watson service.
*
* @param name the service name
*/
public WatsonService(String name) {
this.name = name;
this.apiKey = CredentialUtils.getAPIKey(name);
this.client = configureHttpClient();
String url = CredentialUtils.getAPIUrl(name);
if (url != null && !url.isEmpty()) {
// The VCAP_SERVICES will typically contain a url. If present use it.
setEndPoint(url);
}
}
/**
* Configures the HTTP client.
*
* @return the HTTP client
*/
protected OkHttpClient configureHttpClient() {
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
final CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
builder.cookieJar(new JavaNetCookieJar(cookieManager));
builder.connectTimeout(60, TimeUnit.SECONDS);
builder.writeTimeout(60, TimeUnit.SECONDS);
builder.readTimeout(90, TimeUnit.SECONDS);
return builder.build();
}
/**
* Execute the HTTP request. Okhttp3 compliant.
*
* @param request the HTTP request
*
* @return the HTTP response
*/
private Call createCall(Request request) {
final Request.Builder builder = request.newBuilder();
if (RequestUtils.isRelative(request)) {
builder.url(RequestUtils.replaceEndPoint(request.url().toString(), getEndPoint()));
}
String userAgent = getUserAgent();
if (defaultHeaders != null) {
for (String key : defaultHeaders.names()) {
builder.header(key, defaultHeaders.get(key));
}
if (defaultHeaders.get(HttpHeaders.USER_AGENT) != null) {
userAgent += " " + defaultHeaders.get(HttpHeaders.USER_AGENT);
}
}
builder.header(HttpHeaders.USER_AGENT, userAgent);
setAuthentication(builder);
final Request newRequest = builder.build();
return client.newCall(newRequest);
}
/**
* Creates the service call.
*
* @param <T> the generic type
* @param request the request
* @param converter the converter
* @return the service call
*/
protected final <T> ServiceCall<T> createServiceCall(final Request request, final ResponseConverter<T> converter) {
final Call call = createCall(request);
return new ServiceCall<T>() {
@Override
public T execute() {
try {
Response response = call.execute();
return processServiceCall(converter, response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void enqueue(final ServiceCallback<T> callback) {
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(e);
}
@Override
public void onResponse(Call call, Response response) {
try {
callback.onResponse(processServiceCall(converter, response));
} catch (Exception e) {
callback.onFailure(e);
}
}
});
}
@Override
public CompletableFuture<T> rx() {
final CompletableFuture<T> completableFuture = new CompletableFuture<T>();
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
completableFuture.completeExceptionally(e);
}
@Override
public void onResponse(Call call, Response response) {
try {
completableFuture.complete(processServiceCall(converter, response));
} catch (Exception e) {
completableFuture.completeExceptionally(e);
}
}
});
return completableFuture;
}
};
}
/**
* Gets the API key.
*
*
* @return the API key
*/
protected String getApiKey() {
return apiKey;
}
/**
* Gets the API end point.
*
*
* @return the API end point
*/
public String getEndPoint() {
return endPoint;
}
/**
* Gets an authorization token that can be use to authorize API calls.
*
*
* @return the token
*/
public ServiceCall<String> getToken() {
HttpUrl url = HttpUrl.parse(getEndPoint()).newBuilder().setPathSegment(0, AUTHORIZATION).build();
Request request = RequestBuilder.get(url + PATH_AUTHORIZATION_V1_TOKEN)
.header(HttpHeaders.ACCEPT, HttpMediaType.TEXT_PLAIN).query(URL, getEndPoint()).build();
return createServiceCall(request, ResponseConverterUtils.getString());
}
/**
* Gets the error message from a JSON response
*
* <pre>
* {
* code: 400
* error: 'bad request'
* }
* </pre>
*
* @param response the HTTP response
* @return the error message from the JSON object
*/
private String getErrorMessage(Response response) {
String error = ResponseUtils.getString(response);
try {
final JsonObject jsonObject = ResponseUtils.getJsonObject(error);
if (jsonObject.has(MESSAGE_ERROR)) {
error = jsonObject.get(MESSAGE_ERROR).getAsString();
} else if (jsonObject.has(MESSAGE_ERROR_2)) {
error = jsonObject.get(MESSAGE_ERROR_2).getAsString();
} else if (jsonObject.has(MESSAGE_ERROR_3)) {
error = jsonObject.get(MESSAGE_ERROR_3).getAsString();
}
} catch (final Exception e) {
// Ignore any kind of exception parsing the json and use fallback String version of response
}
return error;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the user agent.
*
*
* @return the user agent
*/
private String getUserAgent() {
return "watson-apis-java-sdk/3.0.0-RC1";
}
/**
* Sets the API key.
*
* @param apiKey the new API key
*/
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
/**
* Sets the authentication. Okhttp3 compliant.
*
* @param builder the new authentication
*/
protected void setAuthentication(Builder builder) {
if (getApiKey() == null) {
if (skipAuthentication) // This may be a proxy or some other component where the developer has
return; // chosen to skip authentication with the service
throw new IllegalArgumentException("apiKey or username and password were not specified");
}
builder.addHeader(HttpHeaders.AUTHORIZATION, apiKey.startsWith(BASIC) ? apiKey : BASIC + apiKey);
}
/**
* Sets the end point.
*
* @param endPoint the new end point
*/
public void setEndPoint(String endPoint) {
if (endPoint != null && !endPoint.isEmpty()) {
if (endPoint.endsWith("/")) {
endPoint = endPoint.substring(0, endPoint.length() - 1);
}
}
this.endPoint = endPoint;
}
/**
* Sets the username and password.
*
* @param username the username
* @param password the password
*/
public void setUsernameAndPassword(String username, String password) {
apiKey = Credentials.basic(username, password);
}
/**
* Set the default headers to be used on every HTTP request.
*
* @param headers name value pairs of headers
*/
public void setDefaultHeaders(Map<String, String> headers) {
if (headers == null) {
defaultHeaders = null;
} else {
defaultHeaders = Headers.of(headers);
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(" [");
if (endPoint != null) {
builder.append("endPoint=");
builder.append(endPoint);
}
builder.append("]");
return builder.toString();
}
/**
* Process service call.
*
* @param <T> the generic type
* @param converter the converter
* @param response the response
* @return the t
*/
protected <T> T processServiceCall(final ResponseConverter<T> converter, Response response) {
if (response.isSuccessful())
return converter.convert(response);
// There was a Client Error 4xx or a Server Error 5xx
// Get the error message and create the exception
final String error = getErrorMessage(response);
LOG.log(Level.SEVERE, response.request().method() + " " + response.request().url().toString() + ", status: "
+ response.code() + ", error: " + error);
switch (response.code()) {
case HttpStatus.BAD_REQUEST: // HTTP 400
throw new BadRequestException(error != null ? error : "Bad Request", response);
case HttpStatus.UNAUTHORIZED: // HTTP 401
throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials", response);
case HttpStatus.FORBIDDEN: // HTTP 403
throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response);
case HttpStatus.NOT_FOUND: // HTTP 404
throw new NotFoundException(error != null ? error : "Not found", response);
case HttpStatus.NOT_ACCEPTABLE: // HTTP 406
throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response);
case HttpStatus.CONFLICT: // HTTP 409
throw new ConflictException(error != null ? error : "", response);
case HttpStatus.REQUEST_TOO_LONG: // HTTP 413
throw new RequestTooLargeException(error != null ? error
: "Request too large: The request entity is larger than the server is able to process", response);
case HttpStatus.UNSUPPORTED_MEDIA_TYPE: // HTTP 415
throw new UnsupportedException(error != null ? error : "Unsupported Media Type", response);
case HttpStatus.TOO_MANY_REQUESTS: // HTTP 429
throw new TooManyRequestsException(error != null ? error : "Too many requests", response);
case HttpStatus.INTERNAL_SERVER_ERROR: // HTTP 500
throw new InternalServerErrorException(error != null ? error : "Internal Server Error", response);
case HttpStatus.SERVICE_UNAVAILABLE: // HTTP 503
throw new ServiceUnavailableException(error != null ? error : "Service Unavailable", response);
default: // other errors
throw new ServiceResponseException(response.code(), error, response);
}
}
/**
* Sets the skip authentication.
*
* @param skipAuthentication the new skip authentication
*/
public void setSkipAuthentication(boolean skipAuthentication) {
this.skipAuthentication = skipAuthentication;
}
}
| src/main/java/com/ibm/watson/developer_cloud/service/WatsonService.java | /**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ibm.watson.developer_cloud.service;
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gson.JsonObject;
import com.ibm.watson.developer_cloud.http.HttpHeaders;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.http.HttpStatus;
import com.ibm.watson.developer_cloud.http.RequestBuilder;
import com.ibm.watson.developer_cloud.http.ResponseConverter;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.http.ServiceCallback;
import com.ibm.watson.developer_cloud.service.exception.BadRequestException;
import com.ibm.watson.developer_cloud.service.exception.ConflictException;
import com.ibm.watson.developer_cloud.service.exception.ForbiddenException;
import com.ibm.watson.developer_cloud.service.exception.InternalServerErrorException;
import com.ibm.watson.developer_cloud.service.exception.NotFoundException;
import com.ibm.watson.developer_cloud.service.exception.RequestTooLargeException;
import com.ibm.watson.developer_cloud.service.exception.ServiceResponseException;
import com.ibm.watson.developer_cloud.service.exception.ServiceUnavailableException;
import com.ibm.watson.developer_cloud.service.exception.TooManyRequestsException;
import com.ibm.watson.developer_cloud.service.exception.UnauthorizedException;
import com.ibm.watson.developer_cloud.service.exception.UnsupportedException;
import com.ibm.watson.developer_cloud.util.CredentialUtils;
import com.ibm.watson.developer_cloud.util.RequestUtils;
import com.ibm.watson.developer_cloud.util.ResponseConverterUtils;
import com.ibm.watson.developer_cloud.util.ResponseUtils;
import jersey.repackaged.jsr166e.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.Response;
/**
* Watson service abstract common functionality of various Watson Services. It handle authentication
* and default url
*
* @see <a href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/"> IBM Watson
* Developer Cloud</a>
*/
public abstract class WatsonService {
private static final String URL = "url";
private static final String PATH_AUTHORIZATION_V1_TOKEN = "/v1/token";
private static final String AUTHORIZATION = "authorization";
private static final String MESSAGE_ERROR_3 = "message";
private static final String MESSAGE_ERROR_2 = "error_message";
private static final String BASIC = "Basic ";
private static final Logger LOG = Logger.getLogger(WatsonService.class.getName());
private String apiKey;
private final OkHttpClient client;
private String endPoint;
private final String name;
private Headers defaultHeaders = null;
private boolean skipAuthentication;
/** The Constant MESSAGE_CODE. */
protected static final String MESSAGE_CODE = "code";
/** The Constant MESSAGE_ERROR. */
protected static final String MESSAGE_ERROR = "error";
/** The Constant VERSION. */
protected static final String VERSION = "version";
/**
* Instantiates a new Watson service.
*
* @param name the service name
*/
public WatsonService(String name) {
this.name = name;
this.apiKey = CredentialUtils.getAPIKey(name);
this.client = configureHttpClient();
String url = CredentialUtils.getAPIUrl(name);
if (url != null && !url.isEmpty()) {
// The VCAP_SERVICES will typically contain a url. If present use it.
setEndPoint(url);
}
}
/**
* Configures the HTTP client.
*
* @return the HTTP client
*/
protected OkHttpClient configureHttpClient() {
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
final CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
builder.cookieJar(new JavaNetCookieJar(cookieManager));
builder.connectTimeout(60, TimeUnit.SECONDS);
builder.writeTimeout(60, TimeUnit.SECONDS);
builder.readTimeout(90, TimeUnit.SECONDS);
return builder.build();
}
/**
* Execute the HTTP request. Okhttp3 compliant.
*
* @param request the HTTP request
*
* @return the HTTP response
*/
private Call createCall(Request request) {
final Request.Builder builder = request.newBuilder();
if (RequestUtils.isRelative(request)) {
builder.url(RequestUtils.replaceEndPoint(request.url().toString(), getEndPoint()));
}
String userAgent = getUserAgent();
if (defaultHeaders != null) {
for (String key : defaultHeaders.names()) {
builder.header(key, defaultHeaders.get(key));
}
if (defaultHeaders.get(HttpHeaders.USER_AGENT) != null) {
userAgent += "; " + defaultHeaders.get(HttpHeaders.USER_AGENT);
}
}
builder.header(HttpHeaders.USER_AGENT, userAgent);
setAuthentication(builder);
final Request newRequest = builder.build();
return client.newCall(newRequest);
}
/**
* Creates the service call.
*
* @param <T> the generic type
* @param request the request
* @param converter the converter
* @return the service call
*/
protected final <T> ServiceCall<T> createServiceCall(final Request request, final ResponseConverter<T> converter) {
final Call call = createCall(request);
return new ServiceCall<T>() {
@Override
public T execute() {
try {
Response response = call.execute();
return processServiceCall(converter, response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void enqueue(final ServiceCallback<T> callback) {
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(e);
}
@Override
public void onResponse(Call call, Response response) {
try {
callback.onResponse(processServiceCall(converter, response));
} catch (Exception e) {
callback.onFailure(e);
}
}
});
}
@Override
public CompletableFuture<T> rx() {
final CompletableFuture<T> completableFuture = new CompletableFuture<T>();
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
completableFuture.completeExceptionally(e);
}
@Override
public void onResponse(Call call, Response response) {
try {
completableFuture.complete(processServiceCall(converter, response));
} catch (Exception e) {
completableFuture.completeExceptionally(e);
}
}
});
return completableFuture;
}
};
}
/**
* Gets the API key.
*
*
* @return the API key
*/
protected String getApiKey() {
return apiKey;
}
/**
* Gets the API end point.
*
*
* @return the API end point
*/
public String getEndPoint() {
return endPoint;
}
/**
* Gets an authorization token that can be use to authorize API calls.
*
*
* @return the token
*/
public ServiceCall<String> getToken() {
HttpUrl url = HttpUrl.parse(getEndPoint()).newBuilder().setPathSegment(0, AUTHORIZATION).build();
Request request = RequestBuilder.get(url + PATH_AUTHORIZATION_V1_TOKEN)
.header(HttpHeaders.ACCEPT, HttpMediaType.TEXT_PLAIN).query(URL, getEndPoint()).build();
return createServiceCall(request, ResponseConverterUtils.getString());
}
/**
* Gets the error message from a JSON response
*
* <pre>
* {
* code: 400
* error: 'bad request'
* }
* </pre>
*
* @param response the HTTP response
* @return the error message from the JSON object
*/
private String getErrorMessage(Response response) {
String error = ResponseUtils.getString(response);
try {
final JsonObject jsonObject = ResponseUtils.getJsonObject(error);
if (jsonObject.has(MESSAGE_ERROR)) {
error = jsonObject.get(MESSAGE_ERROR).getAsString();
} else if (jsonObject.has(MESSAGE_ERROR_2)) {
error = jsonObject.get(MESSAGE_ERROR_2).getAsString();
} else if (jsonObject.has(MESSAGE_ERROR_3)) {
error = jsonObject.get(MESSAGE_ERROR_3).getAsString();
}
} catch (final Exception e) {
// Ignore any kind of exception parsing the json and use fallback String version of response
}
return error;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the user agent.
*
*
* @return the user agent
*/
private String getUserAgent() {
return "watson-apis-java-sdk/3.0.0-RC1";
}
/**
* Sets the API key.
*
* @param apiKey the new API key
*/
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
/**
* Sets the authentication. Okhttp3 compliant.
*
* @param builder the new authentication
*/
protected void setAuthentication(Builder builder) {
if (getApiKey() == null) {
if (skipAuthentication) // This may be a proxy or some other component where the developer has
return; // chosen to skip authentication with the service
throw new IllegalArgumentException("apiKey or username and password were not specified");
}
builder.addHeader(HttpHeaders.AUTHORIZATION, apiKey.startsWith(BASIC) ? apiKey : BASIC + apiKey);
}
/**
* Sets the end point.
*
* @param endPoint the new end point
*/
public void setEndPoint(String endPoint) {
if (endPoint != null && !endPoint.isEmpty()) {
if (endPoint.endsWith("/")) {
endPoint = endPoint.substring(0, endPoint.length() - 1);
}
}
this.endPoint = endPoint;
}
/**
* Sets the username and password.
*
* @param username the username
* @param password the password
*/
public void setUsernameAndPassword(String username, String password) {
apiKey = Credentials.basic(username, password);
}
/**
* Set the default headers to be used on every HTTP request.
*
* @param headers name value pairs of headers
*/
public void setDefaultHeaders(Map<String, String> headers) {
if (headers == null) {
defaultHeaders = null;
} else {
defaultHeaders = Headers.of(headers);
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(" [");
if (endPoint != null) {
builder.append("endPoint=");
builder.append(endPoint);
}
builder.append("]");
return builder.toString();
}
/**
* Process service call.
*
* @param <T> the generic type
* @param converter the converter
* @param response the response
* @return the t
*/
protected <T> T processServiceCall(final ResponseConverter<T> converter, Response response) {
if (response.isSuccessful())
return converter.convert(response);
// There was a Client Error 4xx or a Server Error 5xx
// Get the error message and create the exception
final String error = getErrorMessage(response);
LOG.log(Level.SEVERE, response.request().method() + " " + response.request().url().toString() + ", status: "
+ response.code() + ", error: " + error);
switch (response.code()) {
case HttpStatus.BAD_REQUEST: // HTTP 400
throw new BadRequestException(error != null ? error : "Bad Request", response);
case HttpStatus.UNAUTHORIZED: // HTTP 401
throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials", response);
case HttpStatus.FORBIDDEN: // HTTP 403
throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response);
case HttpStatus.NOT_FOUND: // HTTP 404
throw new NotFoundException(error != null ? error : "Not found", response);
case HttpStatus.NOT_ACCEPTABLE: // HTTP 406
throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response);
case HttpStatus.CONFLICT: // HTTP 409
throw new ConflictException(error != null ? error : "", response);
case HttpStatus.REQUEST_TOO_LONG: // HTTP 413
throw new RequestTooLargeException(error != null ? error
: "Request too large: The request entity is larger than the server is able to process", response);
case HttpStatus.UNSUPPORTED_MEDIA_TYPE: // HTTP 415
throw new UnsupportedException(error != null ? error : "Unsupported Media Type", response);
case HttpStatus.TOO_MANY_REQUESTS: // HTTP 429
throw new TooManyRequestsException(error != null ? error : "Too many requests", response);
case HttpStatus.INTERNAL_SERVER_ERROR: // HTTP 500
throw new InternalServerErrorException(error != null ? error : "Internal Server Error", response);
case HttpStatus.SERVICE_UNAVAILABLE: // HTTP 503
throw new ServiceUnavailableException(error != null ? error : "Service Unavailable", response);
default: // other errors
throw new ServiceResponseException(response.code(), error, response);
}
}
/**
* Sets the skip authentication.
*
* @param skipAuthentication the new skip authentication
*/
public void setSkipAuthentication(boolean skipAuthentication) {
this.skipAuthentication = skipAuthentication;
}
}
| remove semicolon from user agent
| src/main/java/com/ibm/watson/developer_cloud/service/WatsonService.java | remove semicolon from user agent | <ide><path>rc/main/java/com/ibm/watson/developer_cloud/service/WatsonService.java
<ide> builder.header(key, defaultHeaders.get(key));
<ide> }
<ide> if (defaultHeaders.get(HttpHeaders.USER_AGENT) != null) {
<del> userAgent += "; " + defaultHeaders.get(HttpHeaders.USER_AGENT);
<add> userAgent += " " + defaultHeaders.get(HttpHeaders.USER_AGENT);
<ide> }
<ide>
<ide> } |
|
Java | mit | 2e50c3052f1aa2c167ab5a02001addb43037ae1d | 0 | Bipshark/TDA367,Bipshark/TDA367 | package edu.chalmers.sankoss.desktop.mvc.waiting;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import edu.chalmers.sankoss.core.core.CorePlayer;
import edu.chalmers.sankoss.desktop.mvc.AbstractRenderer;
import edu.chalmers.sankoss.desktop.utils.Common;
import java.beans.PropertyChangeEvent;
/**
* AbstractRenderer for WaitingScreen.
* Will only draw a label and two buttons.
*
* @author Mikael Malmqvist
* @modified Niklas Tegnander
* @date 5/5/14
*/
public class WaitingRenderer extends AbstractRenderer<WaitingModel> {
private Label lblWaiting = new Label("Loading...", Common.getSkin());
private TextButton btnBack = new TextButton("Back", Common.getSkin());
private TextButton btnStart = new TextButton("Start", Common.getSkin());
public WaitingRenderer(WaitingModel model) {
super(model);
getTable().pad(8f);
getTable().add(lblWaiting).expand().colspan(2);
getTable().row();
getTable().add(btnBack.pad(8f)).left().bottom().width(160f);
getTable().add(btnStart.pad(8f)).right().bottom().width(160f);
//getTable().debug();
btnStart.setDisabled(true);
getStage().addActor(getTable());
}
public TextButton getBtnBack() {
return btnBack;
}
public TextButton getBtnStart() {
return btnStart;
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0.663f, 0.663f, 0.663f, 1);
getStage().act();
getStage().draw();
Table.drawDebug(getStage());
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("reset")) {
lblWaiting.setText("Loading...");
btnStart.setText("Start");
btnStart.setDisabled(true);
}
if (evt.getPropertyName().equals("hosting")) {
boolean msg = (boolean) evt.getNewValue();
if (msg) {
lblWaiting.setText("Waiting for players to join...");
} else {
lblWaiting.setText("Waiting for the host to start the game...");
}
}
if (getModel().isHosting()) {
if (evt.getPropertyName().equals("player_joined")) {
CorePlayer msg = (CorePlayer) evt.getNewValue();
btnStart.setDisabled(false);
lblWaiting.setText(msg.getName() + " has joined the room!");
} else if (evt.getPropertyName().equals("player_left")) {
btnStart.setDisabled(true);
lblWaiting.setText("Player left. Waiting for players to join...");
}
}
}
}
| desktop/src/main/java/edu/chalmers/sankoss/desktop/mvc/waiting/WaitingRenderer.java | package edu.chalmers.sankoss.desktop.mvc.waiting;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import edu.chalmers.sankoss.core.core.CorePlayer;
import edu.chalmers.sankoss.desktop.mvc.AbstractRenderer;
import edu.chalmers.sankoss.desktop.utils.Common;
import java.beans.PropertyChangeEvent;
/**
* AbstractRenderer for WaitingScreen.
* Will only draw a label and two buttons.
*
* @author Mikael Malmqvist
* @modified Niklas Tegnander
* @date 5/5/14
*/
public class WaitingRenderer extends AbstractRenderer<WaitingModel> {
private Label lblWaiting = new Label("Loading...", Common.getSkin());
private TextButton btnBack = new TextButton("Back", Common.getSkin());
private TextButton btnStart = new TextButton("Start", Common.getSkin());
public WaitingRenderer(WaitingModel model) {
super(model);
getTable().pad(8f);
getTable().add(lblWaiting).expand().colspan(2);
getTable().row();
getTable().add(btnBack);
getTable().add(btnStart);
//getTable().debug();
btnStart.setDisabled(true);
getStage().addActor(getTable());
}
public TextButton getBtnBack() {
return btnBack;
}
public TextButton getBtnStart() {
return btnStart;
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0.663f, 0.663f, 0.663f, 1);
getStage().act();
getStage().draw();
Table.drawDebug(getStage());
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("reset")) {
lblWaiting.setText("Loading...");
btnStart.setText("Start");
btnStart.setDisabled(true);
}
if (evt.getPropertyName().equals("hosting")) {
boolean msg = (boolean) evt.getNewValue();
if (msg) {
lblWaiting.setText("Waiting for players to join...");
} else {
lblWaiting.setText("Waiting for the host to start the game...");
}
}
if (getModel().isHosting()) {
if (evt.getPropertyName().equals("player_joined")) {
CorePlayer msg = (CorePlayer) evt.getNewValue();
btnStart.setDisabled(false);
lblWaiting.setText(msg.getName() + " has joined the room!");
} else if (evt.getPropertyName().equals("player_left")) {
btnStart.setDisabled(true);
lblWaiting.setText("Player left. Waiting for players to join...");
}
}
}
}
| Made buttons in waitingRenderer bigger
| desktop/src/main/java/edu/chalmers/sankoss/desktop/mvc/waiting/WaitingRenderer.java | Made buttons in waitingRenderer bigger | <ide><path>esktop/src/main/java/edu/chalmers/sankoss/desktop/mvc/waiting/WaitingRenderer.java
<ide>
<ide> getTable().add(lblWaiting).expand().colspan(2);
<ide> getTable().row();
<del> getTable().add(btnBack);
<del> getTable().add(btnStart);
<add> getTable().add(btnBack.pad(8f)).left().bottom().width(160f);
<add> getTable().add(btnStart.pad(8f)).right().bottom().width(160f);
<ide> //getTable().debug();
<ide>
<ide> btnStart.setDisabled(true); |
|
Java | apache-2.0 | e09fa9e1fcc03f48fe1be4e29fe09eb1637ee4a8 | 0 | jbfromlbc/insightcmislab2014 | package org.foo;
import java.math.BigInteger;
import javax.servlet.http.HttpServletRequest;
import org.apache.chemistry.opencmis.commons.data.ExtensionsData;
import org.apache.chemistry.opencmis.commons.data.ObjectInFolderList;
import org.apache.chemistry.opencmis.commons.enums.IncludeRelationships;
import org.apache.chemistry.opencmis.commons.server.CallContext;
import org.apache.chemistry.opencmis.commons.server.CmisService;
import org.apache.chemistry.opencmis.server.support.wrapper.AbstractCmisServiceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Example of a minimal Cmis Custom Service Wrapper (logging example)
*
* Add the following ** to the repo.properties to have framework hook into chain
* The number at the key is the position in the wrapper stack. Lower numbers are
* outer wrappers, higher numbers are inner wrappers.
*
* ** add the following line to your repo.properties file in your servers war
* servicewrapper.1=org.apache.chemistry.opencmis.server.support.CmisCustomLoggingServiceWrapper
*
* See the frameworks SimpleLoggingCmisServiceWrapper for a more generic and
* complete example
*
*/
public class CmisCustomLoggingServiceWrapper extends AbstractCmisServiceWrapper {
// slf4j example
private static final Logger LOG = LoggerFactory.getLogger(CmisCustomLoggingServiceWrapper.class);
// provide constructor
public CmisCustomLoggingServiceWrapper(CmisService service) {
super(service);
}
/**
* slf logging version with dual output to console and slf
*/
protected void slflog(String operation, String repositoryId) {
if (repositoryId == null) {
repositoryId = "<none>";
}
HttpServletRequest request = (HttpServletRequest) getCallContext().get(CallContext.HTTP_SERVLET_REQUEST);
String userAgent = request.getHeader("User-Agent");
if (userAgent == null) {
userAgent = "<unknown>";
}
String binding = getCallContext().getBinding();
LOG.info("Operation: {}, Repository ID: {}, Binding: {}, User Agent: {}", operation, repositoryId, binding,
userAgent);
}
@Override
public ObjectInFolderList getChildren(String repositoryId, String folderId, String filter, String orderBy,
Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
Boolean includePathSegment, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {
slflog("getChildren ", repositoryId);
long startTime = System.currentTimeMillis();
CallContext sharedContext = this.getCallContext();
// Get the native domain object from the call context if one is shared by the vendor (example only)
// Your CMIS vendor's documentation must expose the name of any shared objects they place here for extensions.
// Object objShared = sharedContext.get("shared_key_name_from_vendor");
ObjectInFolderList retVal = getWrappedService().getChildren(repositoryId, folderId, filter, orderBy, includeAllowableActions,
includeRelationships, renditionFilter, includePathSegment, maxItems, skipCount, extension);
// dual log output in case logger not configured
LOG.info("[CmisCustomServiceWrapper] Exiting method getChildren. time (ms):" + (System.currentTimeMillis() - startTime));
//System.out.println("[CmisCustomServiceWrapper] Exiting method getChildren. time (ms):" + (System.currentTimeMillis() - startTime));
return retVal;
}
}
| src/main/java/org/foo/CmisCustomLoggingServiceWrapper.java | package org.foo;
import java.math.BigInteger;
import javax.servlet.http.HttpServletRequest;
import org.apache.chemistry.opencmis.commons.data.ExtensionsData;
import org.apache.chemistry.opencmis.commons.data.ObjectInFolderList;
import org.apache.chemistry.opencmis.commons.enums.IncludeRelationships;
import org.apache.chemistry.opencmis.commons.server.CallContext;
import org.apache.chemistry.opencmis.commons.server.CmisService;
import org.apache.chemistry.opencmis.server.support.wrapper.AbstractCmisServiceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Example of a minimal Cmis Custom Service Wrapper (logging example)
*
* Add the following ** to the repo.properties to have framework hook into chain
* The number at the key is the position in the wrapper stack. Lower numbers are
* outer wrappers, higher numbers are inner wrappers.
*
* ** add the following line to your repo.properties file in your servers war
* servicewrapper.1=org.apache.chemistry.opencmis.server.support.CmisCustomLoggingServiceWrapper
*
* See the frameworks SimpleLoggingCmisServiceWrapper for a more generic and
* complete example
*
*/
public class CmisCustomLoggingServiceWrapper extends AbstractCmisServiceWrapper {
// slf4j example
private static final Logger LOG = LoggerFactory.getLogger(CmisCustomLoggingServiceWrapper.class);
// provide constructor
public CmisCustomLoggingServiceWrapper(CmisService service) {
super(service);
}
/**
* slf logging version with dual output to console and slf
*/
protected void slflog(String operation, String repositoryId) {
if (repositoryId == null) {
repositoryId = "<none>";
}
HttpServletRequest request = (HttpServletRequest) getCallContext().get(CallContext.HTTP_SERVLET_REQUEST);
String userAgent = request.getHeader("User-Agent");
if (userAgent == null) {
userAgent = "<unknown>";
}
String binding = getCallContext().getBinding();
LOG.info("Operation: {}, Repository ID: {}, Binding: {}, User Agent: {}", operation, repositoryId, binding,
userAgent);
}
@Override
public ObjectInFolderList getChildren(String repositoryId, String folderId, String filter, String orderBy,
Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
Boolean includePathSegment, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {
slflog("getChildren override from customer Chameleon module --------------", repositoryId);
long startTime = System.currentTimeMillis();
CallContext sharedContext = this.getCallContext();
// Get the native domain object from the call context if one is shared by the vendor (example only)
// Your CMIS vendor's documentation must expose the name of any shared objects they place here for extensions.
// Object objShared = sharedContext.get("shared_key_name_from_vendor");
ObjectInFolderList retVal = getWrappedService().getChildren(repositoryId, folderId, filter, orderBy, includeAllowableActions,
includeRelationships, renditionFilter, includePathSegment, maxItems, skipCount, extension);
// dual log output in case logger not configured
LOG.info("[CmisCustomServiceWrapper] Exiting method getChildren. time (ms):" + (System.currentTimeMillis() - startTime));
//System.out.println("[CmisCustomServiceWrapper] Exiting method getChildren. time (ms):" + (System.currentTimeMillis() - startTime));
return retVal;
}
}
| clean up getChildren log | src/main/java/org/foo/CmisCustomLoggingServiceWrapper.java | clean up getChildren log | <ide><path>rc/main/java/org/foo/CmisCustomLoggingServiceWrapper.java
<ide> Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
<ide> Boolean includePathSegment, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {
<ide>
<del> slflog("getChildren override from customer Chameleon module --------------", repositoryId);
<add> slflog("getChildren ", repositoryId);
<ide> long startTime = System.currentTimeMillis();
<ide>
<ide> CallContext sharedContext = this.getCallContext(); |
|
Java | mit | 49969fb5fc9a66da721767fb71120c4c5092f0f5 | 0 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
import java.util.Arrays;
/**
* https://leetcode.com/problems/matchsticks-to-square/
*/
public class Problem473 {
public boolean makesquare(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
int length = sum / 4;
int remainder = sum % 4;
if (remainder != 0 || nums.length < 4) {
return false;
}
Arrays.sort(nums);
reverse(nums);
return makeSquare(nums, 0, length, length, length, length);
}
private static void reverse(int[] nums) {
int i = 0, j = nums.length - 1;
while (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++; j--;
}
}
private static boolean makeSquare(int[] nums, int idx, int length1, int length2, int length3,
int length4) {
if (length1 < 0 || length2 < 0 || length3 < 0 || length4 < 0) {
return false;
}
if (idx == nums.length) {
if (length1 == 0 && length2 == 0 && length3 == 0 && length4 == 0) {
return true;
}
return false;
}
return makeSquare(nums, idx + 1, length1 - nums[idx], length2, length3, length4) ||
makeSquare(nums, idx + 1, length1, length2 - nums[idx], length3, length4) ||
makeSquare(nums, idx + 1, length1, length2, length3 - nums[idx], length4) ||
makeSquare(nums, idx + 1, length1, length2, length3, length4 - nums[idx]);
}
}
| src/main/java/leetcode/Problem473.java | package leetcode;
/**
* https://leetcode.com/problems/matchsticks-to-square/
*/
public class Problem473 {
public boolean makesquare(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
int length = sum / 4;
int remainder = sum % 4;
if (remainder != 0) {
return false;
}
return true;
}
private static boolean makeSquare(int[] nums, int length) {
if (length < 0) {
return false;
}
if (length == 0) {
return true;
}
boolean valid = false;
for (int i = 0; i < nums.length; i++) {
valid |= makeSquare(nums, length - nums[i]);
}
return valid;
}
public static void main(String[] args) {
Problem473 prob = new Problem473();
System.out.println(prob.makesquare(new int[]{1, 1, 2, 2, 2})); // true
System.out.println(prob.makesquare(new int[]{3, 3, 3, 3, 4})); // false
System.out.println(prob.makesquare(new int[]{3, 3, 3, 3, 3})); // false
System.out.println(prob.makesquare(new int[]{1, 1, 1, 1, 1, 1, 1, 1})); // true
System.out.println(prob.makesquare(new int[]{3, 5, 4, 4, 6, 2, 1, 1, 1, 5})); // true
}
}
| Solve problem 473
| src/main/java/leetcode/Problem473.java | Solve problem 473 | <ide><path>rc/main/java/leetcode/Problem473.java
<ide> package leetcode;
<add>
<add>import java.util.Arrays;
<ide>
<ide> /**
<ide> * https://leetcode.com/problems/matchsticks-to-square/
<ide> }
<ide> int length = sum / 4;
<ide> int remainder = sum % 4;
<del> if (remainder != 0) {
<add> if (remainder != 0 || nums.length < 4) {
<ide> return false;
<ide> }
<del>
<del> return true;
<add> Arrays.sort(nums);
<add> reverse(nums);
<add> return makeSquare(nums, 0, length, length, length, length);
<ide> }
<ide>
<del> private static boolean makeSquare(int[] nums, int length) {
<del> if (length < 0) {
<add> private static void reverse(int[] nums) {
<add> int i = 0, j = nums.length - 1;
<add> while (i < j) {
<add> int temp = nums[i];
<add> nums[i] = nums[j];
<add> nums[j] = temp;
<add> i++; j--;
<add> }
<add> }
<add>
<add> private static boolean makeSquare(int[] nums, int idx, int length1, int length2, int length3,
<add> int length4) {
<add> if (length1 < 0 || length2 < 0 || length3 < 0 || length4 < 0) {
<ide> return false;
<ide> }
<del> if (length == 0) {
<del> return true;
<add> if (idx == nums.length) {
<add> if (length1 == 0 && length2 == 0 && length3 == 0 && length4 == 0) {
<add> return true;
<add> }
<add> return false;
<ide> }
<del> boolean valid = false;
<del> for (int i = 0; i < nums.length; i++) {
<del> valid |= makeSquare(nums, length - nums[i]);
<del> }
<del> return valid;
<del> }
<del>
<del> public static void main(String[] args) {
<del> Problem473 prob = new Problem473();
<del> System.out.println(prob.makesquare(new int[]{1, 1, 2, 2, 2})); // true
<del> System.out.println(prob.makesquare(new int[]{3, 3, 3, 3, 4})); // false
<del> System.out.println(prob.makesquare(new int[]{3, 3, 3, 3, 3})); // false
<del> System.out.println(prob.makesquare(new int[]{1, 1, 1, 1, 1, 1, 1, 1})); // true
<del> System.out.println(prob.makesquare(new int[]{3, 5, 4, 4, 6, 2, 1, 1, 1, 5})); // true
<add> return makeSquare(nums, idx + 1, length1 - nums[idx], length2, length3, length4) ||
<add> makeSquare(nums, idx + 1, length1, length2 - nums[idx], length3, length4) ||
<add> makeSquare(nums, idx + 1, length1, length2, length3 - nums[idx], length4) ||
<add> makeSquare(nums, idx + 1, length1, length2, length3, length4 - nums[idx]);
<ide> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/jdk15/org/testng/internal/remote/SocketLinkedBlockingQueue.java' did not match any file(s) known to git
| 93a14781814bcd3a907100f07fde77f2378ec0e5 | 1 | ludovicc/testng-debian,ludovicc/testng-debian,ludovicc/testng-debian | /*
* @(#)LinkedBlockingQueue.java
*
* Copyright 1999-2004 by Taleo Corporation,
* 330 St-Vallier East, Suite 400, Quebec city, Quebec, G1K 9C5, CANADA
* All rights reserved
*/
package org.testng.internal.remote;
import java.net.Socket;
public class SocketLinkedBlockingQueue extends java.util.concurrent.LinkedBlockingQueue<Socket>
{
// wrapper
}
| src/jdk15/org/testng/internal/remote/SocketLinkedBlockingQueue.java | Container class specific to JDK15
git-svn-id: 0fb7d80ee932ae2a080de675cb20a4788b2d07b0@177 1a8b0fc8-9519-0410-aeec-afd8fd7729cf
| src/jdk15/org/testng/internal/remote/SocketLinkedBlockingQueue.java | Container class specific to JDK15 | <ide><path>rc/jdk15/org/testng/internal/remote/SocketLinkedBlockingQueue.java
<add>/*
<add> * @(#)LinkedBlockingQueue.java
<add> *
<add> * Copyright 1999-2004 by Taleo Corporation,
<add> * 330 St-Vallier East, Suite 400, Quebec city, Quebec, G1K 9C5, CANADA
<add> * All rights reserved
<add> */
<add>package org.testng.internal.remote;
<add>
<add>import java.net.Socket;
<add>
<add>public class SocketLinkedBlockingQueue extends java.util.concurrent.LinkedBlockingQueue<Socket>
<add>{
<add> // wrapper
<add>} |
|
Java | apache-2.0 | bac485927250621c7edb192ff38e2047176a4586 | 0 | yelshater/hadoop-2.3.0,yelshater/hadoop-2.3.0,yelshater/hadoop-2.3.0,yelshater/hadoop-2.3.0,yelshater/hadoop-2.3.0 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.v2.app.rm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.split.JobSplit.TaskSplitMetaInfo;
import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId;
import org.apache.hadoop.mapreduce.v2.app.AppContext;
import org.apache.hadoop.mapreduce.v2.app.client.ClientService;
import org.apache.hadoop.util.file.LogMessageFileWriter;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceBlacklistRequest;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.proto.YarnProtos.SplitMessage;
import org.apache.hadoop.yarn.proto.YarnProtos.SplitMessage.Builder;
/**
* Keeps the data structures to send container requests to RM.
*/
public abstract class RMContainerRequestor extends RMCommunicator {
private static final Log LOG = LogFactory.getLog(RMContainerRequestor.class);
private int lastResponseID;
private Resource availableResources;
private final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
//Key -> Priority
//Value -> Map
//Key->ResourceName (e.g., hostname, rackname, *)
//Value->Map
//Key->Resource Capability
//Value->ResourceRequest
private final Map<Priority, Map<String, Map<Resource, ResourceRequest>>>
remoteRequestsTable =
new TreeMap<Priority, Map<String, Map<Resource, ResourceRequest>>>();
// use custom comparator to make sure ResourceRequest objects differing only in
// numContainers dont end up as duplicates
private final Set<ResourceRequest> ask = new TreeSet<ResourceRequest>(
new org.apache.hadoop.yarn.api.records.ResourceRequest.ResourceRequestComparator());
private final Set<ContainerId> release = new TreeSet<ContainerId>();
private boolean nodeBlacklistingEnabled;
private int blacklistDisablePercent;
private AtomicBoolean ignoreBlacklisting = new AtomicBoolean(false);
private int blacklistedNodeCount = 0;
private int lastClusterNmCount = 0;
private int clusterNmCount = 0;
private int maxTaskFailuresPerNode;
private final Map<String, Integer> nodeFailures = new HashMap<String, Integer>();
private final Set<String> blacklistedNodes = Collections
.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Set<String> blacklistAdditions = Collections
.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Set<String> blacklistRemovals = Collections
.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
public RMContainerRequestor(ClientService clientService, AppContext context) {
super(clientService, context);
}
static class ContainerRequest {
final TaskAttemptId attemptID;
final Resource capability;
final String[] hosts;
final String[] racks;
//final boolean earlierAttemptFailed;
final Priority priority;
private static final Priority PRIORITY_MAP;
static {
PRIORITY_MAP = RecordFactoryProvider.getRecordFactory(null).newRecordInstance(Priority.class);
PRIORITY_MAP.setPriority(20);
}
/***
* @author Yehia Elshater
*/
TaskSplitMetaInfo metaInfo;
SplitMessage splitMessage;
public ContainerRequest(ContainerRequestEvent event, Priority priority) {
this(event.getAttemptID(), event.getCapability(), event.getHosts(),
event.getRacks(), priority, event.getTaskSplitMetaInfo());
LogMessageFileWriter.writeLogMessage("First ContainerRequest Constructor" );
}
/***
* @author Yehia Elshater
*/
public ContainerRequest(TaskAttemptId attemptID,
Resource capability, String[] hosts, String[] racks,
Priority priority, TaskSplitMetaInfo metaInfo) {
this(attemptID,capability, hosts, racks, priority);
LogMessageFileWriter.writeLogMessage("Third ContainerRequest Constructor 1" );
this.metaInfo = metaInfo;
StringBuffer sb = new StringBuffer();
Builder sm = SplitMessage.newBuilder();
LogMessageFileWriter.writeLogMessage("Checking this this.metaInfo");
try {
if (metaInfo!=null) {
if (metaInfo.getSplitIndex()!=null && !metaInfo.getSplitIndex().getSplitLocation().isEmpty()) {
LogMessageFileWriter.writeLogMessage("After metaInfo.getSplitIndex()!=null && !metaInfo.getSplitIndex().getSplitLocation().isEmpty()");
String loc = metaInfo.getSplitIndex().getSplitLocation();
Path p = new Path(loc.substring(0, loc.lastIndexOf(':')));
sb.append(p.getParent().getName()).append("-").append(p.getName()); //parentfolder-filename
sm.setFileName(sb.toString());
sm.setFilePath(p.toString());
sb.setLength(0);
sm.setStartOffset(metaInfo.getStartOffset());
sm.setInputLength(metaInfo.getInputDataLength());
for (String host : metaInfo.getLocations()) {
sm.addSplitHosts(host);
}
this.splitMessage = sm.build();
}
LogMessageFileWriter.writeLogMessage("setting splitMessage");
}
else {
LogMessageFileWriter.writeLogMessage("metaInfo is null");
}
}
catch (Exception x ) {
LogMessageFileWriter.writeLogMessage(x.getMessage());
}
}
public ContainerRequest(TaskAttemptId attemptID,
Resource capability, String[] hosts, String[] racks,
Priority priority) {
LogMessageFileWriter.writeLogMessage("Second ContainerRequest Constructor 1" );
this.attemptID = attemptID;
this.capability = capability;
this.hosts = hosts;
this.racks = racks;
this.priority = priority;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("AttemptId[").append(attemptID).append("]");
sb.append("Capability[").append(capability).append("]");
sb.append("Priority[").append(priority).append("]");
if (splitMessage!=null && splitMessage.isInitialized()) {
sb.append("SplitName[").append(splitMessage.getFileName()).append("]");
}
return sb.toString();
}
/***
*
* @author Yehia Elshater
* @return
*/
public SplitMessage getSplitMessage () {
return splitMessage;
}
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
super.serviceInit(conf);
nodeBlacklistingEnabled =
conf.getBoolean(MRJobConfig.MR_AM_JOB_NODE_BLACKLISTING_ENABLE, true);
LOG.info("nodeBlacklistingEnabled:" + nodeBlacklistingEnabled);
maxTaskFailuresPerNode =
conf.getInt(MRJobConfig.MAX_TASK_FAILURES_PER_TRACKER, 3);
blacklistDisablePercent =
conf.getInt(
MRJobConfig.MR_AM_IGNORE_BLACKLISTING_BLACKLISTED_NODE_PERECENT,
MRJobConfig.DEFAULT_MR_AM_IGNORE_BLACKLISTING_BLACKLISTED_NODE_PERCENT);
LOG.info("maxTaskFailuresPerNode is " + maxTaskFailuresPerNode);
if (blacklistDisablePercent < -1 || blacklistDisablePercent > 100) {
throw new YarnRuntimeException("Invalid blacklistDisablePercent: "
+ blacklistDisablePercent
+ ". Should be an integer between 0 and 100 or -1 to disabled");
}
LOG.info("blacklistDisablePercent is " + blacklistDisablePercent);
}
protected AllocateResponse makeRemoteRequest() throws IOException {
ResourceBlacklistRequest blacklistRequest =
ResourceBlacklistRequest.newInstance(new ArrayList<String>(blacklistAdditions),
new ArrayList<String>(blacklistRemovals));
AllocateRequest allocateRequest =
AllocateRequest.newInstance(lastResponseID,
super.getApplicationProgress(), new ArrayList<ResourceRequest>(ask),
new ArrayList<ContainerId>(release), blacklistRequest);
AllocateResponse allocateResponse;
try {
allocateResponse = scheduler.allocate(allocateRequest);
} catch (YarnException e) {
throw new IOException(e);
}
lastResponseID = allocateResponse.getResponseId();
availableResources = allocateResponse.getAvailableResources();
lastClusterNmCount = clusterNmCount;
clusterNmCount = allocateResponse.getNumClusterNodes();
if (ask.size() > 0 || release.size() > 0) {
LOG.info("getResources() for " + applicationId + ":" + " ask="
+ ask.size() + " release= " + release.size() + " newContainers="
+ allocateResponse.getAllocatedContainers().size()
+ " finishedContainers="
+ allocateResponse.getCompletedContainersStatuses().size()
+ " resourcelimit=" + availableResources + " knownNMs="
+ clusterNmCount);
}
ask.clear();
release.clear();
if (blacklistAdditions.size() > 0 || blacklistRemovals.size() > 0) {
LOG.info("Update the blacklist for " + applicationId +
": blacklistAdditions=" + blacklistAdditions.size() +
" blacklistRemovals=" + blacklistRemovals.size());
}
blacklistAdditions.clear();
blacklistRemovals.clear();
return allocateResponse;
}
// May be incorrect if there's multiple NodeManagers running on a single host.
// knownNodeCount is based on node managers, not hosts. blacklisting is
// currently based on hosts.
protected void computeIgnoreBlacklisting() {
if (!nodeBlacklistingEnabled) {
return;
}
if (blacklistDisablePercent != -1
&& (blacklistedNodeCount != blacklistedNodes.size() ||
clusterNmCount != lastClusterNmCount)) {
blacklistedNodeCount = blacklistedNodes.size();
if (clusterNmCount == 0) {
LOG.info("KnownNode Count at 0. Not computing ignoreBlacklisting");
return;
}
int val = (int) ((float) blacklistedNodes.size() / clusterNmCount * 100);
if (val >= blacklistDisablePercent) {
if (ignoreBlacklisting.compareAndSet(false, true)) {
LOG.info("Ignore blacklisting set to true. Known: " + clusterNmCount
+ ", Blacklisted: " + blacklistedNodeCount + ", " + val + "%");
// notify RM to ignore all the blacklisted nodes
blacklistAdditions.clear();
blacklistRemovals.addAll(blacklistedNodes);
}
} else {
if (ignoreBlacklisting.compareAndSet(true, false)) {
LOG.info("Ignore blacklisting set to false. Known: " + clusterNmCount
+ ", Blacklisted: " + blacklistedNodeCount + ", " + val + "%");
// notify RM of all the blacklisted nodes
blacklistAdditions.addAll(blacklistedNodes);
blacklistRemovals.clear();
}
}
}
}
protected void containerFailedOnHost(String hostName) {
if (!nodeBlacklistingEnabled) {
return;
}
if (blacklistedNodes.contains(hostName)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Host " + hostName + " is already blacklisted.");
}
return; //already blacklisted
}
Integer failures = nodeFailures.remove(hostName);
failures = failures == null ? Integer.valueOf(0) : failures;
failures++;
LOG.info(failures + " failures on node " + hostName);
if (failures >= maxTaskFailuresPerNode) {
blacklistedNodes.add(hostName);
if (!ignoreBlacklisting.get()) {
blacklistAdditions.add(hostName);
}
//Even if blacklisting is ignored, continue to remove the host from
// the request table. The RM may have additional nodes it can allocate on.
LOG.info("Blacklisted host " + hostName);
//remove all the requests corresponding to this hostname
for (Map<String, Map<Resource, ResourceRequest>> remoteRequests
: remoteRequestsTable.values()){
//remove from host if no pending allocations
boolean foundAll = true;
Map<Resource, ResourceRequest> reqMap = remoteRequests.get(hostName);
if (reqMap != null) {
for (ResourceRequest req : reqMap.values()) {
if (!ask.remove(req)) {
foundAll = false;
// if ask already sent to RM, we can try and overwrite it if possible.
// send a new ask to RM with numContainers
// specified for the blacklisted host to be 0.
ResourceRequest zeroedRequest =
ResourceRequest.newInstance(req.getPriority(),
req.getResourceName(), req.getCapability(),
req.getNumContainers(), req.getRelaxLocality());
zeroedRequest.setNumContainers(0);
// to be sent to RM on next heartbeat
addResourceRequestToAsk(zeroedRequest);
}
}
// if all requests were still in ask queue
// we can remove this request
if (foundAll) {
remoteRequests.remove(hostName);
}
}
// TODO handling of rack blacklisting
// Removing from rack should be dependent on no. of failures within the rack
// Blacklisting a rack on the basis of a single node's blacklisting
// may be overly aggressive.
// Node failures could be co-related with other failures on the same rack
// but we probably need a better approach at trying to decide how and when
// to blacklist a rack
}
} else {
nodeFailures.put(hostName, failures);
}
}
protected Resource getAvailableResources() {
return availableResources;
}
protected void addContainerReq(ContainerRequest req) {
// Create resource requests
for (String host : req.hosts) {
// Data-local
if (!isNodeBlacklisted(host)) {
addResourceRequest(req.priority, host, req.capability,req.getSplitMessage());
}
}
// Nothing Rack-local for now
for (String rack : req.racks) {
addResourceRequest(req.priority, rack, req.capability,req.getSplitMessage());
}
// Off-switch
addResourceRequest(req.priority, ResourceRequest.ANY, req.capability,req.getSplitMessage());
}
protected void decContainerReq(ContainerRequest req) {
// Update resource requests
for (String hostName : req.hosts) {
decResourceRequest(req.priority, hostName, req.capability);
}
for (String rack : req.racks) {
decResourceRequest(req.priority, rack, req.capability);
}
decResourceRequest(req.priority, ResourceRequest.ANY, req.capability);
}
/***
* Adding splitName as a new parameter to this method.
* @author Yehia Elshater
* @param priority
* @param resourceName
* @param capability
*/
private void addResourceRequest(Priority priority, String resourceName,
Resource capability, SplitMessage splitMessage) {
Map<String, Map<Resource, ResourceRequest>> remoteRequests =
this.remoteRequestsTable.get(priority);
if (remoteRequests == null) {
remoteRequests = new HashMap<String, Map<Resource, ResourceRequest>>();
this.remoteRequestsTable.put(priority, remoteRequests);
if (LOG.isDebugEnabled()) {
LOG.debug("Added priority=" + priority);
}
}
Map<Resource, ResourceRequest> reqMap = remoteRequests.get(resourceName);
if (reqMap == null) {
reqMap = new HashMap<Resource, ResourceRequest>();
remoteRequests.put(resourceName, reqMap);
}
ResourceRequest remoteRequest = reqMap.get(capability);
if (remoteRequest == null) {
remoteRequest = recordFactory.newRecordInstance(ResourceRequest.class);
remoteRequest.setPriority(priority);
remoteRequest.setResourceName(resourceName);
remoteRequest.setCapability(capability);
remoteRequest.setNumContainers(0);
List<SplitMessage> splitMessages = new ArrayList<SplitMessage>();
splitMessages.add(splitMessage);
remoteRequest.setSplitMessages(splitMessages);
reqMap.put(capability, remoteRequest);
}
remoteRequest.setNumContainers(remoteRequest.getNumContainers() + 1);
// Note this down for next interaction with ResourceManager
addResourceRequestToAsk(remoteRequest);
if (LOG.isDebugEnabled()) {
LOG.debug("addResourceRequest:" + " applicationId="
+ applicationId.getId() + " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ remoteRequest.getNumContainers() + " #asks=" + ask.size());
}
}
private void decResourceRequest(Priority priority, String resourceName,
Resource capability) {
Map<String, Map<Resource, ResourceRequest>> remoteRequests =
this.remoteRequestsTable.get(priority);
Map<Resource, ResourceRequest> reqMap = remoteRequests.get(resourceName);
if (reqMap == null) {
// as we modify the resource requests by filtering out blacklisted hosts
// when they are added, this value may be null when being
// decremented
if (LOG.isDebugEnabled()) {
LOG.debug("Not decrementing resource as " + resourceName
+ " is not present in request table");
}
return;
}
ResourceRequest remoteRequest = reqMap.get(capability);
if (LOG.isDebugEnabled()) {
LOG.debug("BEFORE decResourceRequest:" + " applicationId="
+ applicationId.getId() + " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ remoteRequest.getNumContainers() + " #asks=" + ask.size());
}
if(remoteRequest.getNumContainers() > 0) {
// based on blacklisting comments above we can end up decrementing more
// than requested. so guard for that.
remoteRequest.setNumContainers(remoteRequest.getNumContainers() -1);
}
if (remoteRequest.getNumContainers() == 0) {
reqMap.remove(capability);
if (reqMap.size() == 0) {
remoteRequests.remove(resourceName);
}
if (remoteRequests.size() == 0) {
remoteRequestsTable.remove(priority);
}
}
// send the updated resource request to RM
// send 0 container count requests also to cancel previous requests
addResourceRequestToAsk(remoteRequest);
if (LOG.isDebugEnabled()) {
LOG.info("AFTER decResourceRequest:" + " applicationId="
+ applicationId.getId() + " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ remoteRequest.getNumContainers() + " #asks=" + ask.size());
}
}
private void addResourceRequestToAsk(ResourceRequest remoteRequest) {
// because objects inside the resource map can be deleted ask can end up
// containing an object that matches new resource object but with different
// numContainers. So exisintg values must be replaced explicitly
if(ask.contains(remoteRequest)) {
ask.remove(remoteRequest);
}
ask.add(remoteRequest);
}
protected void release(ContainerId containerId) {
release.add(containerId);
}
protected boolean isNodeBlacklisted(String hostname) {
if (!nodeBlacklistingEnabled || ignoreBlacklisting.get()) {
return false;
}
return blacklistedNodes.contains(hostname);
}
protected ContainerRequest getFilteredContainerRequest(ContainerRequest orig) {
ArrayList<String> newHosts = new ArrayList<String>();
for (String host : orig.hosts) {
if (!isNodeBlacklisted(host)) {
newHosts.add(host);
}
}
String[] hosts = newHosts.toArray(new String[newHosts.size()]);
ContainerRequest newReq = new ContainerRequest(orig.attemptID, orig.capability,
hosts, orig.racks, orig.priority);
return newReq;
}
public Set<String> getBlacklistedNodes() {
return blacklistedNodes;
}
}
| hadoop-mapreduce-client-app-2.3.0-cdh5.1.0/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/RMContainerRequestor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.v2.app.rm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId;
import org.apache.hadoop.mapreduce.v2.app.AppContext;
import org.apache.hadoop.mapreduce.v2.app.client.ClientService;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceBlacklistRequest;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
/**
* Keeps the data structures to send container requests to RM.
*/
public abstract class RMContainerRequestor extends RMCommunicator {
private static final Log LOG = LogFactory.getLog(RMContainerRequestor.class);
private int lastResponseID;
private Resource availableResources;
private final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
//Key -> Priority
//Value -> Map
//Key->ResourceName (e.g., hostname, rackname, *)
//Value->Map
//Key->Resource Capability
//Value->ResourceRequest
private final Map<Priority, Map<String, Map<Resource, ResourceRequest>>>
remoteRequestsTable =
new TreeMap<Priority, Map<String, Map<Resource, ResourceRequest>>>();
// use custom comparator to make sure ResourceRequest objects differing only in
// numContainers dont end up as duplicates
private final Set<ResourceRequest> ask = new TreeSet<ResourceRequest>(
new org.apache.hadoop.yarn.api.records.ResourceRequest.ResourceRequestComparator());
private final Set<ContainerId> release = new TreeSet<ContainerId>();
private boolean nodeBlacklistingEnabled;
private int blacklistDisablePercent;
private AtomicBoolean ignoreBlacklisting = new AtomicBoolean(false);
private int blacklistedNodeCount = 0;
private int lastClusterNmCount = 0;
private int clusterNmCount = 0;
private int maxTaskFailuresPerNode;
private final Map<String, Integer> nodeFailures = new HashMap<String, Integer>();
private final Set<String> blacklistedNodes = Collections
.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Set<String> blacklistAdditions = Collections
.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Set<String> blacklistRemovals = Collections
.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
public RMContainerRequestor(ClientService clientService, AppContext context) {
super(clientService, context);
}
static class ContainerRequest {
final TaskAttemptId attemptID;
final Resource capability;
final String[] hosts;
final String[] racks;
//final boolean earlierAttemptFailed;
final Priority priority;
public ContainerRequest(ContainerRequestEvent event, Priority priority) {
this(event.getAttemptID(), event.getCapability(), event.getHosts(),
event.getRacks(), priority);
}
public ContainerRequest(TaskAttemptId attemptID,
Resource capability, String[] hosts, String[] racks,
Priority priority) {
this.attemptID = attemptID;
this.capability = capability;
this.hosts = hosts;
this.racks = racks;
this.priority = priority;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("AttemptId[").append(attemptID).append("]");
sb.append("Capability[").append(capability).append("]");
sb.append("Priority[").append(priority).append("]");
return sb.toString();
}
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
super.serviceInit(conf);
nodeBlacklistingEnabled =
conf.getBoolean(MRJobConfig.MR_AM_JOB_NODE_BLACKLISTING_ENABLE, true);
LOG.info("nodeBlacklistingEnabled:" + nodeBlacklistingEnabled);
maxTaskFailuresPerNode =
conf.getInt(MRJobConfig.MAX_TASK_FAILURES_PER_TRACKER, 3);
blacklistDisablePercent =
conf.getInt(
MRJobConfig.MR_AM_IGNORE_BLACKLISTING_BLACKLISTED_NODE_PERECENT,
MRJobConfig.DEFAULT_MR_AM_IGNORE_BLACKLISTING_BLACKLISTED_NODE_PERCENT);
LOG.info("maxTaskFailuresPerNode is " + maxTaskFailuresPerNode);
if (blacklistDisablePercent < -1 || blacklistDisablePercent > 100) {
throw new YarnRuntimeException("Invalid blacklistDisablePercent: "
+ blacklistDisablePercent
+ ". Should be an integer between 0 and 100 or -1 to disabled");
}
LOG.info("blacklistDisablePercent is " + blacklistDisablePercent);
}
protected AllocateResponse makeRemoteRequest() throws IOException {
ResourceBlacklistRequest blacklistRequest =
ResourceBlacklistRequest.newInstance(new ArrayList<String>(blacklistAdditions),
new ArrayList<String>(blacklistRemovals));
AllocateRequest allocateRequest =
AllocateRequest.newInstance(lastResponseID,
super.getApplicationProgress(), new ArrayList<ResourceRequest>(ask),
new ArrayList<ContainerId>(release), blacklistRequest);
AllocateResponse allocateResponse;
try {
allocateResponse = scheduler.allocate(allocateRequest);
} catch (YarnException e) {
throw new IOException(e);
}
lastResponseID = allocateResponse.getResponseId();
availableResources = allocateResponse.getAvailableResources();
lastClusterNmCount = clusterNmCount;
clusterNmCount = allocateResponse.getNumClusterNodes();
if (ask.size() > 0 || release.size() > 0) {
LOG.info("getResources() for " + applicationId + ":" + " ask="
+ ask.size() + " release= " + release.size() + " newContainers="
+ allocateResponse.getAllocatedContainers().size()
+ " finishedContainers="
+ allocateResponse.getCompletedContainersStatuses().size()
+ " resourcelimit=" + availableResources + " knownNMs="
+ clusterNmCount);
}
ask.clear();
release.clear();
if (blacklistAdditions.size() > 0 || blacklistRemovals.size() > 0) {
LOG.info("Update the blacklist for " + applicationId +
": blacklistAdditions=" + blacklistAdditions.size() +
" blacklistRemovals=" + blacklistRemovals.size());
}
blacklistAdditions.clear();
blacklistRemovals.clear();
return allocateResponse;
}
// May be incorrect if there's multiple NodeManagers running on a single host.
// knownNodeCount is based on node managers, not hosts. blacklisting is
// currently based on hosts.
protected void computeIgnoreBlacklisting() {
if (!nodeBlacklistingEnabled) {
return;
}
if (blacklistDisablePercent != -1
&& (blacklistedNodeCount != blacklistedNodes.size() ||
clusterNmCount != lastClusterNmCount)) {
blacklistedNodeCount = blacklistedNodes.size();
if (clusterNmCount == 0) {
LOG.info("KnownNode Count at 0. Not computing ignoreBlacklisting");
return;
}
int val = (int) ((float) blacklistedNodes.size() / clusterNmCount * 100);
if (val >= blacklistDisablePercent) {
if (ignoreBlacklisting.compareAndSet(false, true)) {
LOG.info("Ignore blacklisting set to true. Known: " + clusterNmCount
+ ", Blacklisted: " + blacklistedNodeCount + ", " + val + "%");
// notify RM to ignore all the blacklisted nodes
blacklistAdditions.clear();
blacklistRemovals.addAll(blacklistedNodes);
}
} else {
if (ignoreBlacklisting.compareAndSet(true, false)) {
LOG.info("Ignore blacklisting set to false. Known: " + clusterNmCount
+ ", Blacklisted: " + blacklistedNodeCount + ", " + val + "%");
// notify RM of all the blacklisted nodes
blacklistAdditions.addAll(blacklistedNodes);
blacklistRemovals.clear();
}
}
}
}
protected void containerFailedOnHost(String hostName) {
if (!nodeBlacklistingEnabled) {
return;
}
if (blacklistedNodes.contains(hostName)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Host " + hostName + " is already blacklisted.");
}
return; //already blacklisted
}
Integer failures = nodeFailures.remove(hostName);
failures = failures == null ? Integer.valueOf(0) : failures;
failures++;
LOG.info(failures + " failures on node " + hostName);
if (failures >= maxTaskFailuresPerNode) {
blacklistedNodes.add(hostName);
if (!ignoreBlacklisting.get()) {
blacklistAdditions.add(hostName);
}
//Even if blacklisting is ignored, continue to remove the host from
// the request table. The RM may have additional nodes it can allocate on.
LOG.info("Blacklisted host " + hostName);
//remove all the requests corresponding to this hostname
for (Map<String, Map<Resource, ResourceRequest>> remoteRequests
: remoteRequestsTable.values()){
//remove from host if no pending allocations
boolean foundAll = true;
Map<Resource, ResourceRequest> reqMap = remoteRequests.get(hostName);
if (reqMap != null) {
for (ResourceRequest req : reqMap.values()) {
if (!ask.remove(req)) {
foundAll = false;
// if ask already sent to RM, we can try and overwrite it if possible.
// send a new ask to RM with numContainers
// specified for the blacklisted host to be 0.
ResourceRequest zeroedRequest =
ResourceRequest.newInstance(req.getPriority(),
req.getResourceName(), req.getCapability(),
req.getNumContainers(), req.getRelaxLocality());
zeroedRequest.setNumContainers(0);
// to be sent to RM on next heartbeat
addResourceRequestToAsk(zeroedRequest);
}
}
// if all requests were still in ask queue
// we can remove this request
if (foundAll) {
remoteRequests.remove(hostName);
}
}
// TODO handling of rack blacklisting
// Removing from rack should be dependent on no. of failures within the rack
// Blacklisting a rack on the basis of a single node's blacklisting
// may be overly aggressive.
// Node failures could be co-related with other failures on the same rack
// but we probably need a better approach at trying to decide how and when
// to blacklist a rack
}
} else {
nodeFailures.put(hostName, failures);
}
}
protected Resource getAvailableResources() {
return availableResources;
}
protected void addContainerReq(ContainerRequest req) {
// Create resource requests
for (String host : req.hosts) {
// Data-local
if (!isNodeBlacklisted(host)) {
addResourceRequest(req.priority, host, req.capability);
}
}
// Nothing Rack-local for now
for (String rack : req.racks) {
addResourceRequest(req.priority, rack, req.capability);
}
// Off-switch
addResourceRequest(req.priority, ResourceRequest.ANY, req.capability);
}
protected void decContainerReq(ContainerRequest req) {
// Update resource requests
for (String hostName : req.hosts) {
decResourceRequest(req.priority, hostName, req.capability);
}
for (String rack : req.racks) {
decResourceRequest(req.priority, rack, req.capability);
}
decResourceRequest(req.priority, ResourceRequest.ANY, req.capability);
}
private void addResourceRequest(Priority priority, String resourceName,
Resource capability) {
Map<String, Map<Resource, ResourceRequest>> remoteRequests =
this.remoteRequestsTable.get(priority);
if (remoteRequests == null) {
remoteRequests = new HashMap<String, Map<Resource, ResourceRequest>>();
this.remoteRequestsTable.put(priority, remoteRequests);
if (LOG.isDebugEnabled()) {
LOG.debug("Added priority=" + priority);
}
}
Map<Resource, ResourceRequest> reqMap = remoteRequests.get(resourceName);
if (reqMap == null) {
reqMap = new HashMap<Resource, ResourceRequest>();
remoteRequests.put(resourceName, reqMap);
}
ResourceRequest remoteRequest = reqMap.get(capability);
if (remoteRequest == null) {
remoteRequest = recordFactory.newRecordInstance(ResourceRequest.class);
remoteRequest.setPriority(priority);
remoteRequest.setResourceName(resourceName);
remoteRequest.setCapability(capability);
remoteRequest.setNumContainers(0);
reqMap.put(capability, remoteRequest);
}
remoteRequest.setNumContainers(remoteRequest.getNumContainers() + 1);
// Note this down for next interaction with ResourceManager
addResourceRequestToAsk(remoteRequest);
if (LOG.isDebugEnabled()) {
LOG.debug("addResourceRequest:" + " applicationId="
+ applicationId.getId() + " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ remoteRequest.getNumContainers() + " #asks=" + ask.size());
}
}
private void decResourceRequest(Priority priority, String resourceName,
Resource capability) {
Map<String, Map<Resource, ResourceRequest>> remoteRequests =
this.remoteRequestsTable.get(priority);
Map<Resource, ResourceRequest> reqMap = remoteRequests.get(resourceName);
if (reqMap == null) {
// as we modify the resource requests by filtering out blacklisted hosts
// when they are added, this value may be null when being
// decremented
if (LOG.isDebugEnabled()) {
LOG.debug("Not decrementing resource as " + resourceName
+ " is not present in request table");
}
return;
}
ResourceRequest remoteRequest = reqMap.get(capability);
if (LOG.isDebugEnabled()) {
LOG.debug("BEFORE decResourceRequest:" + " applicationId="
+ applicationId.getId() + " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ remoteRequest.getNumContainers() + " #asks=" + ask.size());
}
if(remoteRequest.getNumContainers() > 0) {
// based on blacklisting comments above we can end up decrementing more
// than requested. so guard for that.
remoteRequest.setNumContainers(remoteRequest.getNumContainers() -1);
}
if (remoteRequest.getNumContainers() == 0) {
reqMap.remove(capability);
if (reqMap.size() == 0) {
remoteRequests.remove(resourceName);
}
if (remoteRequests.size() == 0) {
remoteRequestsTable.remove(priority);
}
}
// send the updated resource request to RM
// send 0 container count requests also to cancel previous requests
addResourceRequestToAsk(remoteRequest);
if (LOG.isDebugEnabled()) {
LOG.info("AFTER decResourceRequest:" + " applicationId="
+ applicationId.getId() + " priority=" + priority.getPriority()
+ " resourceName=" + resourceName + " numContainers="
+ remoteRequest.getNumContainers() + " #asks=" + ask.size());
}
}
private void addResourceRequestToAsk(ResourceRequest remoteRequest) {
// because objects inside the resource map can be deleted ask can end up
// containing an object that matches new resource object but with different
// numContainers. So exisintg values must be replaced explicitly
if(ask.contains(remoteRequest)) {
ask.remove(remoteRequest);
}
ask.add(remoteRequest);
}
protected void release(ContainerId containerId) {
release.add(containerId);
}
protected boolean isNodeBlacklisted(String hostname) {
if (!nodeBlacklistingEnabled || ignoreBlacklisting.get()) {
return false;
}
return blacklistedNodes.contains(hostname);
}
protected ContainerRequest getFilteredContainerRequest(ContainerRequest orig) {
ArrayList<String> newHosts = new ArrayList<String>();
for (String host : orig.hosts) {
if (!isNodeBlacklisted(host)) {
newHosts.add(host);
}
}
String[] hosts = newHosts.toArray(new String[newHosts.size()]);
ContainerRequest newReq = new ContainerRequest(orig.attemptID, orig.capability,
hosts, orig.racks, orig.priority);
return newReq;
}
public Set<String> getBlacklistedNodes() {
return blacklistedNodes;
}
}
| Creating a new protocol message called SplitMessage that holds the required split meta-data. This is the main protocol between RM and AM to send and receive the blocks' meta-data info in each message
| hadoop-mapreduce-client-app-2.3.0-cdh5.1.0/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/RMContainerRequestor.java | Creating a new protocol message called SplitMessage that holds the required split meta-data. This is the main protocol between RM and AM to send and receive the blocks' meta-data info in each message | <ide><path>adoop-mapreduce-client-app-2.3.0-cdh5.1.0/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/RMContainerRequestor.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.TreeMap;
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> import org.apache.hadoop.conf.Configuration;
<add>import org.apache.hadoop.fs.Path;
<ide> import org.apache.hadoop.mapreduce.MRJobConfig;
<add>import org.apache.hadoop.mapreduce.split.JobSplit.TaskSplitMetaInfo;
<ide> import org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId;
<ide> import org.apache.hadoop.mapreduce.v2.app.AppContext;
<ide> import org.apache.hadoop.mapreduce.v2.app.client.ClientService;
<add>import org.apache.hadoop.util.file.LogMessageFileWriter;
<ide> import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
<ide> import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
<ide> import org.apache.hadoop.yarn.api.records.ContainerId;
<ide> import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
<ide> import org.apache.hadoop.yarn.factories.RecordFactory;
<ide> import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
<add>import org.apache.hadoop.yarn.proto.YarnProtos.SplitMessage;
<add>import org.apache.hadoop.yarn.proto.YarnProtos.SplitMessage.Builder;
<ide>
<ide>
<ide> /**
<ide> final String[] racks;
<ide> //final boolean earlierAttemptFailed;
<ide> final Priority priority;
<del>
<del> public ContainerRequest(ContainerRequestEvent event, Priority priority) {
<del> this(event.getAttemptID(), event.getCapability(), event.getHosts(),
<del> event.getRacks(), priority);
<del> }
<del>
<add> private static final Priority PRIORITY_MAP;
<add>
<add> static {
<add> PRIORITY_MAP = RecordFactoryProvider.getRecordFactory(null).newRecordInstance(Priority.class);
<add> PRIORITY_MAP.setPriority(20);
<add> }
<add>
<add> /***
<add> * @author Yehia Elshater
<add> */
<add> TaskSplitMetaInfo metaInfo;
<add> SplitMessage splitMessage;
<add> public ContainerRequest(ContainerRequestEvent event, Priority priority) {
<add> this(event.getAttemptID(), event.getCapability(), event.getHosts(),
<add> event.getRacks(), priority, event.getTaskSplitMetaInfo());
<add> LogMessageFileWriter.writeLogMessage("First ContainerRequest Constructor" );
<add> }
<add>
<add> /***
<add> * @author Yehia Elshater
<add> */
<add> public ContainerRequest(TaskAttemptId attemptID,
<add> Resource capability, String[] hosts, String[] racks,
<add> Priority priority, TaskSplitMetaInfo metaInfo) {
<add>
<add> this(attemptID,capability, hosts, racks, priority);
<add> LogMessageFileWriter.writeLogMessage("Third ContainerRequest Constructor 1" );
<add> this.metaInfo = metaInfo;
<add> StringBuffer sb = new StringBuffer();
<add> Builder sm = SplitMessage.newBuilder();
<add> LogMessageFileWriter.writeLogMessage("Checking this this.metaInfo");
<add>
<add> try {
<add> if (metaInfo!=null) {
<add> if (metaInfo.getSplitIndex()!=null && !metaInfo.getSplitIndex().getSplitLocation().isEmpty()) {
<add> LogMessageFileWriter.writeLogMessage("After metaInfo.getSplitIndex()!=null && !metaInfo.getSplitIndex().getSplitLocation().isEmpty()");
<add> String loc = metaInfo.getSplitIndex().getSplitLocation();
<add> Path p = new Path(loc.substring(0, loc.lastIndexOf(':')));
<add> sb.append(p.getParent().getName()).append("-").append(p.getName()); //parentfolder-filename
<add> sm.setFileName(sb.toString());
<add> sm.setFilePath(p.toString());
<add> sb.setLength(0);
<add> sm.setStartOffset(metaInfo.getStartOffset());
<add> sm.setInputLength(metaInfo.getInputDataLength());
<add> for (String host : metaInfo.getLocations()) {
<add> sm.addSplitHosts(host);
<add> }
<add> this.splitMessage = sm.build();
<add> }
<add> LogMessageFileWriter.writeLogMessage("setting splitMessage");
<add> }
<add> else {
<add> LogMessageFileWriter.writeLogMessage("metaInfo is null");
<add> }
<add> }
<add> catch (Exception x ) {
<add> LogMessageFileWriter.writeLogMessage(x.getMessage());
<add> }
<add> }
<ide> public ContainerRequest(TaskAttemptId attemptID,
<ide> Resource capability, String[] hosts, String[] racks,
<ide> Priority priority) {
<add> LogMessageFileWriter.writeLogMessage("Second ContainerRequest Constructor 1" );
<ide> this.attemptID = attemptID;
<ide> this.capability = capability;
<ide> this.hosts = hosts;
<ide> this.racks = racks;
<ide> this.priority = priority;
<add>
<ide> }
<ide>
<ide> public String toString() {
<ide> sb.append("AttemptId[").append(attemptID).append("]");
<ide> sb.append("Capability[").append(capability).append("]");
<ide> sb.append("Priority[").append(priority).append("]");
<add> if (splitMessage!=null && splitMessage.isInitialized()) {
<add> sb.append("SplitName[").append(splitMessage.getFileName()).append("]");
<add> }
<add>
<ide> return sb.toString();
<add> }
<add>
<add> /***
<add> *
<add> * @author Yehia Elshater
<add> * @return
<add> */
<add> public SplitMessage getSplitMessage () {
<add> return splitMessage;
<ide> }
<ide> }
<ide>
<ide> for (String host : req.hosts) {
<ide> // Data-local
<ide> if (!isNodeBlacklisted(host)) {
<del> addResourceRequest(req.priority, host, req.capability);
<add> addResourceRequest(req.priority, host, req.capability,req.getSplitMessage());
<ide> }
<ide> }
<ide>
<ide> // Nothing Rack-local for now
<ide> for (String rack : req.racks) {
<del> addResourceRequest(req.priority, rack, req.capability);
<add> addResourceRequest(req.priority, rack, req.capability,req.getSplitMessage());
<ide> }
<ide>
<ide> // Off-switch
<del> addResourceRequest(req.priority, ResourceRequest.ANY, req.capability);
<add> addResourceRequest(req.priority, ResourceRequest.ANY, req.capability,req.getSplitMessage());
<ide> }
<ide>
<ide> protected void decContainerReq(ContainerRequest req) {
<ide> decResourceRequest(req.priority, ResourceRequest.ANY, req.capability);
<ide> }
<ide>
<add> /***
<add> * Adding splitName as a new parameter to this method.
<add> * @author Yehia Elshater
<add> * @param priority
<add> * @param resourceName
<add> * @param capability
<add> */
<ide> private void addResourceRequest(Priority priority, String resourceName,
<del> Resource capability) {
<add> Resource capability, SplitMessage splitMessage) {
<ide> Map<String, Map<Resource, ResourceRequest>> remoteRequests =
<ide> this.remoteRequestsTable.get(priority);
<ide> if (remoteRequests == null) {
<ide> remoteRequest.setResourceName(resourceName);
<ide> remoteRequest.setCapability(capability);
<ide> remoteRequest.setNumContainers(0);
<add> List<SplitMessage> splitMessages = new ArrayList<SplitMessage>();
<add> splitMessages.add(splitMessage);
<add> remoteRequest.setSplitMessages(splitMessages);
<ide> reqMap.put(capability, remoteRequest);
<ide> }
<ide> remoteRequest.setNumContainers(remoteRequest.getNumContainers() + 1); |
|
JavaScript | mit | d70553841b6e7c832babf560dc42c07044f2fd25 | 0 | AyoyAB/node-jwt | /**
* JSON Web Signature signing/validation module.
*
* @module jws
*/
var hmac = require('./hmac');
var base64url = require('./base64url');
/**
* Signing algorithms.
*
* @enum algorithm
*/
exports.algorithm = {
/** HMAC with SHA-256 */
HmacWithSha256: 'HS256',
/** RSA with PKCS#1 v 1.5 padding and SHA-256 */
RsaPkcs115WithSha256: 'RS256',
/** ECDSA with Suite B elliptic curve P-256 and SHA-256 */
EcdsaP256WithSha256: 'ES256'
};
/**
* Returns the corresponding HMAC algorithm for a given JWA algorithm.
*
* @function getMacAlgorithm
*
* @param {algorithm} algorithm A JWA algorithm
*
* @returns {String} The corresponding HMAC algorithm
*/
var getMacAlgorithm = function(algorithm) {
switch (algorithm) {
case exports.algorithm.HmacWithSha256:
return hmac.algorithm['HMAC-SHA256'];
default:
throw new Error('Unsupported algorithm: ' + algorithm);
}
};
/**
* Creates a JWS HMAC.
*
* @function createHmac
*
* @param {algorithm} algorithm The JWA algorithm
* @param {String} key The HMAC key
* @param {String} protectedHeader The JWS protected header
* @param {String} payload The JWS payload
*
* @returns {String} The JWS HMAC
*/
exports.createHmac = function(algorithm, key, protectedHeader, payload) {
var macAlgorithm = getMacAlgorithm(algorithm);
var keyBuffer = new Buffer(base64url.toBase64String(key), 'base64');
var payloadBuffer = new Buffer(protectedHeader + '.' + payload);
return base64url.fromBase64String(hmac.doHmac(macAlgorithm, keyBuffer, payloadBuffer).toString('base64'));
};
/**
* Validates a JWS HMAC.
*
* @function validateHmac
*
* @param {algorithm} algorithm The JWA algorithm
* @param {String} key The HMAC key
* @param {String} protectedHeader The JWS protected header
* @param {String} payload The JWS payload
* @param {String} expectedHmac The expected HMAC
*
* @returns {Boolean} True if the JWS HMAC is valid
*/
exports.validateHmac = function(algorithm, key, protectedHeader, payload, expectedHmac) {
var actualHmac = exports.createHmac(algorithm, key, protectedHeader, payload);
return actualHmac === expectedHmac;
};
| lib/jws.js | /**
* JSON Web Signature signing/validation module.
*
* @module jws
*/
var hmac = require('./hmac');
var base64url = require('./base64url');
/**
* Signing algorithms.
*
* @enum algorithm
*/
exports.algorithm = {
/** HMAC with SHA-256 */
HmacWithSha256: 'HS256',
/** RSA with PKCS#1 v 1.5 padding and SHA-256 */
RsaSsaWithSha256: 'RS256',
/** ECDSA with Suite B elliptic curve P-256 and SHA-256 */
EcdsaP256WithSha256: 'ES256'
};
/**
* Returns the corresponding HMAC algorithm for a given JWA algorithm.
*
* @function getMacAlgorithm
*
* @param {algorithm} algorithm A JWA algorithm
*
* @returns {String} The corresponding HMAC algorithm
*/
var getMacAlgorithm = function(algorithm) {
switch (algorithm) {
case exports.algorithm.HmacWithSha256:
return hmac.algorithm['HMAC-SHA256'];
default:
throw new Error('Unsupported algorithm: ' + algorithm);
}
};
/**
* Creates a JWS HMAC.
*
* @function createHmac
*
* @param {algorithm} algorithm The JWA algorithm
* @param {String} key The HMAC key
* @param {String} protectedHeader The JWS protected header
* @param {String} payload The JWS payload
*
* @returns {String} The JWS HMAC
*/
exports.createHmac = function(algorithm, key, protectedHeader, payload) {
var macAlgorithm = getMacAlgorithm(algorithm);
var keyBuffer = new Buffer(base64url.toBase64String(key), 'base64');
var payloadBuffer = new Buffer(protectedHeader + '.' + payload, 'binary');
return base64url.fromBase64String(hmac.doHmac(macAlgorithm, keyBuffer, payloadBuffer).toString('base64'));
};
/**
* Validates a JWS HMAC.
*
* @function validateHmac
*
* @param {algorithm} algorithm The JWA algorithm
* @param {String} key The HMAC key
* @param {String} protectedHeader The JWS protected header
* @param {String} payload The JWS payload
* @param {String} expectedHmac The expected HMAC
*
* @returns {Boolean} True if the JWS HMAC is valid
*/
exports.validateHmac = function(algorithm, key, protectedHeader, payload, expectedHmac) {
var actualHmac = exports.createHmac(algorithm, key, protectedHeader, payload);
return actualHmac === expectedHmac;
};
| More test code cleanup
| lib/jws.js | More test code cleanup | <ide><path>ib/jws.js
<ide> /** HMAC with SHA-256 */
<ide> HmacWithSha256: 'HS256',
<ide> /** RSA with PKCS#1 v 1.5 padding and SHA-256 */
<del> RsaSsaWithSha256: 'RS256',
<add> RsaPkcs115WithSha256: 'RS256',
<ide> /** ECDSA with Suite B elliptic curve P-256 and SHA-256 */
<ide> EcdsaP256WithSha256: 'ES256'
<ide> };
<ide> exports.createHmac = function(algorithm, key, protectedHeader, payload) {
<ide> var macAlgorithm = getMacAlgorithm(algorithm);
<ide> var keyBuffer = new Buffer(base64url.toBase64String(key), 'base64');
<del> var payloadBuffer = new Buffer(protectedHeader + '.' + payload, 'binary');
<add> var payloadBuffer = new Buffer(protectedHeader + '.' + payload);
<ide> return base64url.fromBase64String(hmac.doHmac(macAlgorithm, keyBuffer, payloadBuffer).toString('base64'));
<ide> };
<ide> |
|
Java | mit | 01ae1807fd98b136405afda37038f5d47e2c8df2 | 0 | lightblueseas/swing-components,lightblueseas/swing-components | /**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* 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 de.alpharogroup.swing.panels.lottery;
import java.util.LinkedHashSet;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
/**
* The class {@link LotteryBox} represents exactly one lottery box in a lottery ticket
*/
@Getter
@Setter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class LotteryBox
{
/** The index of this box in the lottery ticket */
@Builder.Default
int index = 0;
/** The maximum value of selected numbers. */
@Builder.Default
int maxNumbers = 6;
/** The max volume. */
@Builder.Default
int maxVolume = 49;
/** The min volume. */
@Builder.Default
int minVolume = 1;
/** The step count for the iteration */
@Builder.Default
int step = 1;
/** The selected numbers. */
LinkedHashSet<Integer> selectedNumbers;
/** The rows for the layout. */
@Builder.Default
int rows = 7;
/** The columns for the layout. */
@Builder.Default
int columns = 7;
}
| src/main/java/de/alpharogroup/swing/panels/lottery/LotteryBox.java | /**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* 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 de.alpharogroup.swing.panels.lottery;
import java.util.LinkedHashSet;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
/**
* The class {@link LotteryBox} represents exactly one lottery box in a lottery ticket
*/
@Getter
@Setter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class LotteryBox
{
/** The index of this box in the lottery ticket */
@Builder.Default
int index = 0;
/** The maximum value of selected numbers. */
@Builder.Default
int maxNumbers = 6;
/** The max volume. */
@Builder.Default
int maxVolume = 49;
/** The min volume. */
@Builder.Default
int minVolume = 1;
/** The selected numbers. */
LinkedHashSet<Integer> selectedNumbers;
/** The rows for the layout. */
@Builder.Default
int rows = 7;
/** The columns for the layout. */
@Builder.Default
int columns = 7;
} | Update LotteryBox.java | src/main/java/de/alpharogroup/swing/panels/lottery/LotteryBox.java | Update LotteryBox.java | <ide><path>rc/main/java/de/alpharogroup/swing/panels/lottery/LotteryBox.java
<ide> @Builder.Default
<ide> int minVolume = 1;
<ide>
<add> /** The step count for the iteration */
<add> @Builder.Default
<add> int step = 1;
<add>
<ide> /** The selected numbers. */
<ide> LinkedHashSet<Integer> selectedNumbers;
<ide> |
|
JavaScript | agpl-3.0 | 602d3e94b9b2d07ca7fc5522f3180eef33a67593 | 0 | schuel/hmmm,Openki/Openki,Openki/Openki,Openki/Openki,schuel/hmmm,schuel/hmmm | Template.region_sel_outer.created = function(){
this.subscribe("Regions");
var instance = this;
instance.searchingRegions = new ReactiveVar(false);
};
Template.region_sel_outer.helpers({
searchingRegions: function() {
return Template.instance().searchingRegions.get();
}
});
Template.regionsDisplay.helpers({
region: function(){
var region = Regions.findOne(Session.get('region'));
return region;
}
});
Template.regionsDisplay.events({
'click .-regionsDisplay': function(event, instance) {
instance.parentInstance().searchingRegions.set(true);
}
});
Template.region_sel.onCreated(function() {
this.regionSearch = new ReactiveVar('');
});
Template.region_sel.rendered = function(){
Template.instance().$('.-searchRegions').select();
};
var updateRegionSearch = function(event, instance) {
var search = instance.$('.-searchRegions').val();
search = String(search).trim();
instance.regionSearch.set(search);
};
Template.region_sel.helpers({
regions: function() {
var search = Template.instance().regionSearch.get();
var query = {};
if (search !== '') query = { name: new RegExp(search, 'i') };
return Regions.find(query);
},
regionNameMarked: function() {
var search = Template.instance().regionSearch.get();
var name = this.name;
if (search === '') return name;
var match = name.match(new RegExp(search, 'i'));
// To add markup we have to escape all the parts separately
var marked;
if (match) {
var term = match[0];
var parts = name.split(term);
marked = _.map(parts, Blaze._escape).join('<strong>'+Blaze._escape(term)+'</strong>');
} else {
marked = Blaze._escape(name);
}
return Spacebars.SafeString(marked);
},
region: function(){
var region = Regions.findOne(Session.get('region'));
return region;
},
allCourses: function() {
return _.reduce(Regions.find().fetch(), function(acc, region) {
return acc + region.courseCount;
}, 0);
},
allUpcomingEvents: function() {
return _.reduce(Regions.find().fetch(), function(acc, region) {
return acc + region.futureEventCount;
}, 0);
},
courses: function() {
return coursesFind({ region: this._id }).count();
},
currentRegion: function() {
var region = this._id || "all";
return region == Session.get('region');
}
});
Template.region_sel.events({
'click a.regionselect': function(event, instance){
event.preventDefault();
var region_id = this._id ? this._id : 'all';
var changed = Session.get('region') !== region_id;
localStorage.setItem("region", region_id); // to survive page reload
Session.set('region', region_id);
// When the region changes, we want the content of the page to update
// Many pages do not change when the region changed, so we go to
// the homepage for those
if (changed) {
var routeName = Router.current().route.getName();
var routesToKeep = ['home', 'find', 'locations', 'calendar'];
if (routesToKeep.indexOf(routeName) < 0) Router.go('/');
}
instance.parentInstance().searchingRegions.set(false);
},
'mouseover li.region a.regionselect': function() {
if (Session.get('region') == "all")
$('.courselist_course').not('.'+this._id).stop().fadeTo('slow', 0.33);
},
'mouseout li.region a.regionselect': function() {
if (Session.get('region') == "all")
$('.courselist_course').not('.'+this._id).stop().fadeTo('slow', 1);
},
'keyup .-searchRegions': _.debounce(updateRegionSearch, 100),
'focus .-searchRegions': function(event, instance) {
instance.$('.dropdown-toggle').dropdown('toggle');
}
});
| client/views/regions/regions.js | Template.region_sel_outer.created = function(){
this.subscribe("Regions");
var instance = this;
instance.searchingRegions = new ReactiveVar(false);
};
Template.region_sel_outer.helpers({
searchingRegions: function() {
return Template.instance().searchingRegions.get();
}
});
Template.regionsDisplay.helpers({
region: function(){
var region = Regions.findOne(Session.get('region'));
return region;
}
});
Template.regionsDisplay.events({
'click .-regionsDisplay': function(event, instance) {
instance.parentInstance().searchingRegions.set(true);
}
});
Template.region_sel.onCreated(function() {
this.regionSearch = new ReactiveVar('');
});
Template.region_sel.rendered = function(){
Template.instance().$('.-searchRegions').select();
};
var updateRegionSearch = function(event, instance) {
var search = instance.$('.-searchRegions').val();
search = String(search).trim();
instance.regionSearch.set(search);
};
Template.region_sel.helpers({
regions: function() {
var search = Template.instance().regionSearch.get();
var query = {};
if (search !== '') query = { name: new RegExp(search, 'i') };
return Regions.find(query);
},
regionNameMarked: function() {
var search = Template.instance().regionSearch.get();
var name = this.name;
if (search === '') return name;
var match = name.match(new RegExp(search, 'i'));
// To add markup we have to escape all the parts separately
var marked;
if (match) {
var term = match[0];
var parts = name.split(term);
marked = _.map(parts, Blaze._escape).join('<strong>'+Blaze._escape(term)+'</strong>');
} else {
marked = Blaze._escape(name);
}
return Spacebars.SafeString(marked);
},
region: function(){
var region = Regions.findOne(Session.get('region'));
return region;
},
allCourses: function() {
return _.reduce(Regions.find().fetch(), function(acc, region) {
return acc + region.courseCount;
}, 0);
},
allUpcomingEvents: function() {
return _.reduce(Regions.find().fetch(), function(acc, region) {
return acc + region.futureEventCount;
}, 0);
},
courses: function() {
return coursesFind({ region: this._id }).count();
},
currentRegion: function() {
var region = this._id || "all";
return region == Session.get('region');
}
});
Template.region_sel.events({
'click a.regionselect': function(event, instance){
event.preventDefault();
var region_id = this._id ? this._id : 'all';
var changed = Session.get('region') !== region_id;
localStorage.setItem("region", region_id); // to survive page reload
Session.set('region', region_id);
// When the region changes, we want the content of the page to update
// Many pages do not change when the region changed, so we go to
// the homepage for those
if (changed) {
var routeName = Router.current().route.getName();
var routesToKeep = ['home', 'find', 'locations', 'calendar'];
if (routesToKeep.indexOf(routeName) < 0) Router.go('/');
}
instance.parentInstance().searchingRegions.set(false);
},
'mouseover li.region a.regionselect': function() {
if (Session.get('region') == "all")
$('.courselist_course').not('.'+this._id).stop().fadeTo('slow', 0.33);
},
'mouseout li.region a.regionselect': function() {
if (Session.get('region') == "all")
$('.courselist_course').not('.'+this._id).stop().fadeTo('slow', 1);
},
'keyup .-searchRegions': _.debounce(updateRegionSearch, 100),
'focus .-searchRegions': function(event, instance) {
instance.$('.dropdown-toggle').dropdown('toggle');
updateRegionSearch(event, instance);
}
});
| avoit premature region search
| client/views/regions/regions.js | avoit premature region search | <ide><path>lient/views/regions/regions.js
<ide>
<ide> 'focus .-searchRegions': function(event, instance) {
<ide> instance.$('.dropdown-toggle').dropdown('toggle');
<del> updateRegionSearch(event, instance);
<ide> }
<ide> }); |
|
JavaScript | mit | 71c467635f70a097e669e4f21691293c4c73da94 | 0 | alphagov/govuk_elements,gavboulton/govuk_elements,alphagov/govuk_elements,gavboulton/govuk_elements,joelanman/govuk_elements,gavboulton/govuk_elements,gavboulton/govuk_elements,TFOH/govuk_elements,TFOH/govuk_elements,alphagov/govuk_elements,joelanman/govuk_elements,alphagov/govuk_elements | // <details> polyfill
// http://caniuse.com/#feat=details
// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737
// http://www.sitepoint.com/fixing-the-details-element/
(function () {
'use strict';
// Add event construct for modern browsers or IE
// which fires the callback with a pre-converted target reference
function addEvent(node, type, callback) {
if (node.addEventListener) {
node.addEventListener(type, function (e) {
callback(e, e.target);
}, false);
} else if (node.attachEvent) {
node.attachEvent('on' + type, function (e) {
callback(e, e.srcElement);
});
}
}
// Handle cross-modal click events
function addClickEvent(node, callback) {
// Prevent space(32) from scrolling the page
addEvent(node, 'keypress', function (e, target) {
if (target.nodeName === "SUMMARY") {
if (e.keyCode === 32) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
});
// When the key comes up - check if it is enter(13) or space(32)
addEvent(node, 'keyup', function (e, target) {
if (e.keyCode === 13 || e.keyCode === 32) { callback(e, target); }
});
addEvent(node, 'mouseup', function (e, target) {
callback(e, target);
});
}
// Get the nearest ancestor element of a node that matches a given tag name
function getAncestor(node, match) {
do {
if (!node || node.nodeName.toLowerCase() === match) {
break;
}
} while (node = node.parentNode);
return node;
}
// Create a started flag so we can prevent the initialisation
// function firing from both DOMContentLoaded and window.onload
var started = false;
// Initialisation function
function addDetailsPolyfill(list) {
// If this has already happened, just return
// else set the flag so it doesn't happen again
if (started) {
return;
}
started = true;
// Get the collection of details elements, but if that's empty
// then we don't need to bother with the rest of the scripting
if ((list = document.getElementsByTagName('details')).length === 0) {
return;
}
// else iterate through them to apply their initial state
var n = list.length, i = 0;
for (n; i < n; i++) {
var details = list[i];
// Detect native implementations
details.__native = typeof(details.open) == 'boolean';
// Save shortcuts to the inner summary and content elements
details.__summary = details.getElementsByTagName('summary').item(0);
details.__content = details.getElementsByTagName('div').item(0);
// If the content doesn't have an ID, assign it one now
// which we'll need for the summary's aria-controls assignment
if (!details.__content.id) {
details.__content.id = 'details-content-' + i;
}
// Add ARIA role="group" to details
details.setAttribute('role', 'group');
// Add role=button to summary
details.__summary.setAttribute('role', 'button');
// Add aria-controls
details.__summary.setAttribute('aria-controls', details.__content.id);
// Set tabindex so the summary is keyboard accessible
// details.__summary.setAttribute('tabindex', 0);
// http://www.saliences.com/browserBugs/tabIndex.html
details.__summary.tabIndex = 0;
// Detect initial open/closed state
// Native support - has 'open' attribute
if (details.open === true) {
details.__summary.setAttribute('aria-expanded', 'true');
details.__content.setAttribute('aria-hidden', 'false');
details.__content.style.display = 'block';
}
// Native support - doesn't have 'open' attribute
if (details.open === false) {
details.__summary.setAttribute('aria-expanded', 'false');
details.__content.setAttribute('aria-hidden', 'true');
details.__content.style.display = 'none';
}
// If this is not a native implementation
if (!details.__native) {
// Add an arrow
var twisty = document.createElement('i');
// Check for the 'open' attribute
// If open exists, but isn't supported it won't have a value
if (details.getAttribute('open') === "") {
details.__summary.setAttribute('aria-expanded', 'true');
details.__content.setAttribute('aria-hidden', 'false');
}
// If open doesn't exist - it will be null or undefined
if (details.getAttribute('open') == null || details.getAttribute('open') == "undefined" ) {
details.__summary.setAttribute('aria-expanded', 'false');
details.__content.setAttribute('aria-hidden', 'true');
details.__content.style.display = 'none';
}
}
// Create a circular reference from the summary back to its
// parent details element, for convenience in the click handler
details.__summary.__details = details;
// If this is not a native implementation, create an arrow
// inside the summary
if (!details.__native) {
var twisty = document.createElement('i');
if (details.getAttribute('open') === "") {
twisty.className = 'arrow arrow-open';
twisty.appendChild(document.createTextNode('\u25bc'));
} else {
twisty.className = 'arrow arrow-closed';
twisty.appendChild(document.createTextNode('\u25ba'));
}
details.__summary.__twisty = details.__summary.insertBefore(twisty, details.__summary.firstChild);
details.__summary.__twisty.setAttribute('aria-hidden', 'true');
}
}
// Define a statechange function that updates aria-expanded and style.display
// Also update the arrow position
function statechange(summary) {
var expanded = summary.__details.__summary.getAttribute('aria-expanded') == 'true';
var hidden = summary.__details.__content.getAttribute('aria-hidden') == 'true';
summary.__details.__summary.setAttribute('aria-expanded', (expanded ? 'false' : 'true'));
summary.__details.__content.setAttribute('aria-hidden', (hidden ? 'false' : 'true'));
summary.__details.__content.style.display = (expanded ? 'none' : 'block');
if (summary.__twisty) {
summary.__twisty.firstChild.nodeValue = (expanded ? '\u25ba' : '\u25bc');
summary.__twisty.setAttribute('class', (expanded ? 'arrow arrow-closed' : 'arrow arrow-open'));
}
return true;
}
// Bind a click event to handle summary elements
addClickEvent(document, function(e, summary) {
if (!(summary = getAncestor(summary, 'summary'))) {
return true;
}
return statechange(summary);
});
}
// Bind two load events for modern and older browsers
// If the first one fires it will set a flag to block the second one
// but if it's not supported then the second one will fire
addEvent(document, 'DOMContentLoaded', addDetailsPolyfill);
addEvent(window, 'load', addDetailsPolyfill);
})();
| public/javascripts/vendor/details.polyfill.js | // <details> polyfill
// http://caniuse.com/#feat=details
// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737
// http://www.sitepoint.com/fixing-the-details-element/
(function () {
// Add event construct for modern browsers or IE
// which fires the callback with a pre-converted target reference
function addEvent(node, type, callback) {
if (node.addEventListener) {
node.addEventListener(type, function (e) {
callback(e, e.target);
}, false);
} else if (node.attachEvent) {
node.attachEvent('on' + type, function (e) {
callback(e, e.srcElement);
});
}
}
// Handle cross-modal click events
function addClickEvent(node, callback) {
// Prevent space(32) from scrolling the page
addEvent(node, 'keypress', function (e, target) {
if (target.nodeName === "SUMMARY") {
if (e.keyCode === 32) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
});
// When the key comes up - check if it is enter(13) or space(32)
addEvent(node, 'keyup', function (e, target) {
if (e.keyCode === 13 || e.keyCode === 32) { callback(e, target); }
});
addEvent(node, 'mouseup', function (e, target) {
callback(e, target);
});
}
// Get the nearest ancestor element of a node that matches a given tag name
function getAncestor(node, match) {
do {
if (!node || node.nodeName.toLowerCase() === match) {
break;
}
} while (node = node.parentNode);
return node;
}
// Create a started flag so we can prevent the initialisation
// function firing from both DOMContentLoaded and window.onload
var started = false;
// Initialisation function
function addDetailsPolyfill(list) {
// If this has already happened, just return
// else set the flag so it doesn't happen again
if (started) {
return;
}
started = true;
// Get the collection of details elements, but if that's empty
// then we don't need to bother with the rest of the scripting
if ((list = document.getElementsByTagName('details')).length === 0) {
return;
}
// else iterate through them to apply their initial state
var n = list.length, i = 0;
for (n; i < n; i++) {
var details = list[i];
// Detect native implementations
details.__native = typeof(details.open) == 'boolean';
// Save shortcuts to the inner summary and content elements
details.__summary = details.getElementsByTagName('summary').item(0);
details.__content = details.getElementsByTagName('div').item(0);
// If the content doesn't have an ID, assign it one now
// which we'll need for the summary's aria-controls assignment
if (!details.__content.id) {
details.__content.id = 'details-content-' + i;
}
// Add ARIA role="group" to details
details.setAttribute('role', 'group');
// Add role=button to summary
details.__summary.setAttribute('role', 'button');
// Add aria-controls
details.__summary.setAttribute('aria-controls', details.__content.id);
// Set tabindex so the summary is keyboard accessible
// details.__summary.setAttribute('tabindex', 0);
// http://www.saliences.com/browserBugs/tabIndex.html
details.__summary.tabIndex = 0;
// Detect initial open/closed state
// Native support - has 'open' attribute
if (details.open === true) {
details.__summary.setAttribute('aria-expanded', 'true');
details.__content.setAttribute('aria-hidden', 'false');
details.__content.style.display = 'block';
}
// Native support - doesn't have 'open' attribute
if (details.open === false) {
details.__summary.setAttribute('aria-expanded', 'false');
details.__content.setAttribute('aria-hidden', 'true');
details.__content.style.display = 'none';
}
// If this is not a native implementation
if (!details.__native) {
// Add an arrow
var twisty = document.createElement('i');
// Check for the 'open' attribute
// If open exists, but isn't supported it won't have a value
if (details.getAttribute('open') === "") {
details.__summary.setAttribute('aria-expanded', 'true');
details.__content.setAttribute('aria-hidden', 'false');
}
// If open doesn't exist - it will be null or undefined
if (details.getAttribute('open') == null || details.getAttribute('open') == "undefined" ) {
details.__summary.setAttribute('aria-expanded', 'false');
details.__content.setAttribute('aria-hidden', 'true');
details.__content.style.display = 'none';
}
}
// Create a circular reference from the summary back to its
// parent details element, for convenience in the click handler
details.__summary.__details = details;
// If this is not a native implementation, create an arrow
// inside the summary
if (!details.__native) {
var twisty = document.createElement('i');
if (details.getAttribute('open') === "") {
twisty.className = 'arrow arrow-open';
twisty.appendChild(document.createTextNode('\u25bc'));
} else {
twisty.className = 'arrow arrow-closed';
twisty.appendChild(document.createTextNode('\u25ba'));
}
details.__summary.__twisty = details.__summary.insertBefore(twisty, details.__summary.firstChild);
details.__summary.__twisty.setAttribute('aria-hidden', 'true');
}
}
// Define a statechange function that updates aria-expanded and style.display
// Also update the arrow position
function statechange(summary) {
var expanded = summary.__details.__summary.getAttribute('aria-expanded') == 'true';
var hidden = summary.__details.__content.getAttribute('aria-hidden') == 'true';
summary.__details.__summary.setAttribute('aria-expanded', (expanded ? 'false' : 'true'));
summary.__details.__content.setAttribute('aria-hidden', (hidden ? 'false' : 'true'));
summary.__details.__content.style.display = (expanded ? 'none' : 'block');
if (summary.__twisty) {
summary.__twisty.firstChild.nodeValue = (expanded ? '\u25ba' : '\u25bc');
summary.__twisty.setAttribute('class', (expanded ? 'arrow arrow-closed' : 'arrow arrow-open'));
}
return true;
}
// Bind a click event to handle summary elements
addClickEvent(document, function(e, summary) {
if (!(summary = getAncestor(summary, 'summary'))) {
return true;
}
return statechange(summary);
});
}
// Bind two load events for modern and older browsers
// If the first one fires it will set a flag to block the second one
// but if it's not supported then the second one will fire
addEvent(document, 'DOMContentLoaded', addDetailsPolyfill);
addEvent(window, 'load', addDetailsPolyfill);
})();
| Add `use strict` for details polyfill.
| public/javascripts/vendor/details.polyfill.js | Add `use strict` for details polyfill. | <ide><path>ublic/javascripts/vendor/details.polyfill.js
<ide> // http://www.sitepoint.com/fixing-the-details-element/
<ide>
<ide> (function () {
<add> 'use strict';
<ide>
<ide> // Add event construct for modern browsers or IE
<ide> // which fires the callback with a pre-converted target reference |
|
Java | apache-2.0 | 7116f8bc507f1513ea158e82a21e374169e2c16d | 0 | kryptnostic/kodex | package com.kryptnostic.v2.storage.api;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.kryptnostic.kodex.v1.crypto.ciphers.BlockCiphertext;
import com.kryptnostic.v2.constants.Names;
import com.kryptnostic.v2.storage.models.CreateMetadataObjectRequest;
import com.kryptnostic.v2.storage.models.CreateObjectRequest;
import com.kryptnostic.v2.storage.models.ObjectMetadata;
import com.kryptnostic.v2.storage.models.ObjectMetadataEncryptedNode;
import com.kryptnostic.v2.storage.models.ObjectTreeLoadRequest;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.DELETE;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
/**
* @author Matthew Tamayo-Rios <[email protected]>
*
*/
public interface ObjectStorageApi {
String CONTROLLER = "/object";
// Parameter names
String ID = Names.ID_FIELD;
String VERSION = "version";
String BLOCK = "block";
// Paths
String OBJECT_ID_PATH = "/id/{" + ID + "}";
String VERSION_PATH = "/{" + VERSION + "}";
String CONTENTS_PATH = "/" + Names.CONTENTS;
String IV_PATH = "/iv";
String SALT_PATH = "/salt";
String TAG_PATH = "/tag";
String LEVELS_PATH = "/levels";
String METADATA_PATH = "/metadata";
String BULK_PATH = "/bulk";
String LATEST = "/latest";
String OBJECTMETADATA_PATH = "/objectmetadata";
String OBJECT_METADATA_PATH = OBJECTMETADATA_PATH + OBJECT_ID_PATH;
String VERSIONED_OBJECT_ID_PATH = OBJECT_ID_PATH + VERSION_PATH;
String LATEST_OBJECT_ID_PATH = LATEST + OBJECT_ID_PATH;
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER )
VersionedObjectKey createObject( @Body CreateObjectRequest request );
@GET( CONTROLLER + LATEST_OBJECT_ID_PATH )
VersionedObjectKey getLatestVersionedObjectKey( @Path( ID ) UUID id );
/**
* Lazy Person API for bulk reading base64 encoded block ciphertexts in bulk.
*
* @param objectIds
* @return
*/
@POST( CONTROLLER + BULK_PATH )
Map<UUID, BlockCiphertext> getObjects( @Body Set<UUID> objectIds );
//TODO: Consider adding an API the returns the version as part of the value.
/**
* Lazy Person API for writing base64 encoded block ciphertexts. Objects written via this API will be available
* through the more efficient byte level APIs.
*
* @param objectId
* @param ciphertext
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response setObjectFromBlockCiphertext(
@Path( ID ) UUID objectId,
@Path( VERSION ) long version,
@Body BlockCiphertext ciphertext );
/**
* Cached Lazy Person API for reading base64 encoded block ciphertexts. Objects readable by this API will be
* available through the more efficient byte level APIs.
*
* @param objectId
* @param version
* @return
*/
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH )
BlockCiphertext getObjectAsBlockCiphertext( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
/**
* Sets the IV for an object block
*
* @param objectId
* @param version
* @param iv
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + IV_PATH )
Response setObjectIv( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] iv );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + CONTENTS_PATH )
Response setObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] content );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + SALT_PATH )
Response setObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] salt );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + TAG_PATH )
Response setObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] tag );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + CONTENTS_PATH )
byte[] getObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + IV_PATH )
byte[] getObjectIV( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + SALT_PATH )
byte[] getObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + TAG_PATH )
byte[] getObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_METADATA_PATH )
ObjectMetadata getObjectMetadata( @Path( ID ) UUID id );
@DELETE( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response delete( @Path( ID ) UUID id, @Path( VERSION ) long version );
@DELETE( CONTROLLER + OBJECT_ID_PATH )
Response delete( @Path( ID ) UUID id );
@DELETE( CONTROLLER )
Set<UUID> deleteObjectTrees( @Body Set<UUID> objectTrees );
@POST( CONTROLLER + LEVELS_PATH )
Map<UUID, ObjectMetadataEncryptedNode> getObjectsByTypeAndLoadLevel( @Body ObjectTreeLoadRequest request );
// METADATA APIs
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER + METADATA_PATH )
VersionedObjectKey createMetadataObject( @Body CreateMetadataObjectRequest request );
}
| src/main/java/com/kryptnostic/v2/storage/api/ObjectStorageApi.java | package com.kryptnostic.v2.storage.api;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.kryptnostic.kodex.v1.crypto.ciphers.BlockCiphertext;
import com.kryptnostic.v2.constants.Names;
import com.kryptnostic.v2.storage.models.CreateMetadataObjectRequest;
import com.kryptnostic.v2.storage.models.CreateObjectRequest;
import com.kryptnostic.v2.storage.models.ObjectMetadata;
import com.kryptnostic.v2.storage.models.ObjectMetadataEncryptedNode;
import com.kryptnostic.v2.storage.models.ObjectTreeLoadRequest;
import com.kryptnostic.v2.storage.models.PaddedMetadataObjectIds;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.DELETE;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
/**
* @author Matthew Tamayo-Rios <[email protected]>
*
*/
public interface ObjectStorageApi {
String CONTROLLER = "/object";
// Parameter names
String ID = Names.ID_FIELD;
String VERSION = "version";
String BLOCK = "block";
// Paths
String OBJECT_ID_PATH = "/id/{" + ID + "}";
String VERSION_PATH = "/{" + VERSION + "}";
String CONTENTS_PATH = "/" + Names.CONTENTS;
String IV_PATH = "/iv";
String SALT_PATH = "/salt";
String TAG_PATH = "/tag";
String LEVELS_PATH = "/levels";
String METADATA_PATH = "/metadata";
String BULK_PATH = "/bulk";
String LATEST = "/latest";
String OBJECTMETADATA_PATH = "/objectmetadata";
String OBJECT_METADATA_PATH = OBJECTMETADATA_PATH + OBJECT_ID_PATH;
String VERSIONED_OBJECT_ID_PATH = OBJECT_ID_PATH + VERSION_PATH;
String LATEST_OBJECT_ID_PATH = LATEST + OBJECT_ID_PATH;
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER )
VersionedObjectKey createObject( @Body CreateObjectRequest request );
@GET( CONTROLLER + LATEST_OBJECT_ID_PATH )
VersionedObjectKey getLatestVersionedObjectKey( @Path( ID ) UUID id );
/**
* Lazy Person API for bulk reading base64 encoded block ciphertexts in bulk.
*
* @param objectIds
* @return
*/
@POST( CONTROLLER + BULK_PATH )
Map<UUID, BlockCiphertext> getObjects( @Body Set<UUID> objectIds );
//TODO: Consider adding an API the returns the version as part of the value.
/**
* Lazy Person API for writing base64 encoded block ciphertexts. Objects written via this API will be available
* through the more efficient byte level APIs.
*
* @param objectId
* @param ciphertext
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response setObjectFromBlockCiphertext(
@Path( ID ) UUID objectId,
@Path( VERSION ) long version,
@Body BlockCiphertext ciphertext );
/**
* Cached Lazy Person API for reading base64 encoded block ciphertexts. Objects readable by this API will be
* available through the more efficient byte level APIs.
*
* @param objectId
* @param version
* @return
*/
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH )
BlockCiphertext getObjectAsBlockCiphertext( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
/**
* Sets the IV for an object block
*
* @param objectId
* @param version
* @param iv
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + IV_PATH )
Response setObjectIv( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] iv );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + CONTENTS_PATH )
Response setObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] content );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + SALT_PATH )
Response setObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] salt );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + TAG_PATH )
Response setObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] tag );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + CONTENTS_PATH )
byte[] getObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + IV_PATH )
byte[] getObjectIV( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + SALT_PATH )
byte[] getObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + VERSIONED_OBJECT_ID_PATH + TAG_PATH )
byte[] getObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_METADATA_PATH )
ObjectMetadata getObjectMetadata( @Path( ID ) UUID id );
@DELETE( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response delete( @Path( ID ) UUID id, @Path( VERSION ) long version );
@DELETE( CONTROLLER + OBJECT_ID_PATH )
Response delete( @Path( ID ) UUID id );
@DELETE( CONTROLLER )
Set<UUID> deleteObjectTrees( @Body Set<UUID> objectTrees );
@POST( CONTROLLER + LEVELS_PATH )
Map<UUID, ObjectMetadataEncryptedNode> getObjectsByTypeAndLoadLevel( @Body ObjectTreeLoadRequest request );
// METADATA APIs
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER + METADATA_PATH )
VersionedObjectKey createMetadataObject( @Body CreateMetadataObjectRequest request );
@POST( CONTROLLER + METADATA_PATH + OBJECT_ID_PATH )
Response createMetadataEntry(
@Path( ID ) UUID objectId,
@Body Set<PaddedMetadataObjectIds> paddedMetadataObjectIds );
@DELETE( CONTROLLER + METADATA_PATH + OBJECT_ID_PATH )
Response createMetadataEntry( @Path( ID ) UUID objectId );
}
| remove unused calls
| src/main/java/com/kryptnostic/v2/storage/api/ObjectStorageApi.java | remove unused calls | <ide><path>rc/main/java/com/kryptnostic/v2/storage/api/ObjectStorageApi.java
<ide> import com.kryptnostic.v2.storage.models.ObjectMetadata;
<ide> import com.kryptnostic.v2.storage.models.ObjectMetadataEncryptedNode;
<ide> import com.kryptnostic.v2.storage.models.ObjectTreeLoadRequest;
<del>import com.kryptnostic.v2.storage.models.PaddedMetadataObjectIds;
<ide> import com.kryptnostic.v2.storage.models.VersionedObjectKey;
<ide>
<ide> import retrofit.client.Response;
<ide> @POST( CONTROLLER + METADATA_PATH )
<ide> VersionedObjectKey createMetadataObject( @Body CreateMetadataObjectRequest request );
<ide>
<del> @POST( CONTROLLER + METADATA_PATH + OBJECT_ID_PATH )
<del> Response createMetadataEntry(
<del> @Path( ID ) UUID objectId,
<del> @Body Set<PaddedMetadataObjectIds> paddedMetadataObjectIds );
<del>
<del> @DELETE( CONTROLLER + METADATA_PATH + OBJECT_ID_PATH )
<del> Response createMetadataEntry( @Path( ID ) UUID objectId );
<ide> } |
|
JavaScript | mit | 1758b64191b43d8254437f2145bdfd0a873d2ab7 | 0 | nicolasmccurdy/procrastinate,nicolasmccurdy/procrastinate | var assert = require('assert');
var fs = require('fs');
var path = require('path');
var procrastinate = require('..');
describe('procrastinate()', function () {
context('with an empty input', function () {
it('returns an empty string', function () {
assert.equal(procrastinate('mocha', ''), '');
});
});
var fileOptions = { encoding: 'utf-8' };
function getData(filename) {
return fs.readFileSync(path.join('test/data', filename), fileOptions);
}
var input = getData('input.txt');
context('with an input representing pending Mocha specs', function () {
var output = getData('mocha_output.js');
it('returns pending Mocha specs', function () {
assert.equal(procrastinate('mocha', input), output);
});
});
context('with an input representing pending RSpec specs', function () {
var output = getData('rspec_output.rb');
it('returns pending RSpec specs', function () {
assert.equal(procrastinate('rspec', input), output);
});
});
context('with an invalid formatter', function () {
it('throws an Error', function () {
assert.throws(function () {
procrastinate('notathinglol', '');
}, Error);
});
});
});
describe('procrastinate.formatters', function () {
it('is a list of Strings representing supported formatters', function () {
assert(Array.isArray(procrastinate.formatters));
procrastinate.formatters.forEach(function (formatter) {
assert.equal(typeof formatter, 'string');
assert(/^\w+$/.test(formatter));
});
});
});
describe('procrastinate.validateFormatter()', function () {
context('with a valid formatter', function () {
it('does nothing', function () {
procrastinate.validateFormatter('mocha');
});
});
context('with an invalid formatter', function () {
it('throws an Error', function () {
assert.throws(function () {
procrastinate.validateFormatter('notathinglol');
}, Error);
});
});
});
| test/index.js | var assert = require('assert');
var fs = require('fs');
var procrastinate = require('..');
describe('procrastinate()', function () {
context('with an empty input', function () {
it('returns an empty string', function () {
assert.equal(procrastinate('mocha', ''), '');
});
});
var fileOptions = { encoding: 'utf-8' };
var input = fs.readFileSync('test/data/input.txt', fileOptions);
context('with an input representing pending Mocha specs', function () {
var output = fs.readFileSync('test/data/mocha_output.js', fileOptions);
it('returns pending Mocha specs', function () {
assert.equal(procrastinate('mocha', input), output);
});
});
context('with an input representing pending RSpec specs', function () {
var output = fs.readFileSync('test/data/rspec_output.rb', fileOptions);
it('returns pending RSpec specs', function () {
assert.equal(procrastinate('rspec', input), output);
});
});
context('with an invalid formatter', function () {
it('throws an Error', function () {
assert.throws(function () {
procrastinate('notathinglol', '');
}, Error);
});
});
});
describe('procrastinate.formatters', function () {
it('is a list of Strings representing supported formatters', function () {
assert(Array.isArray(procrastinate.formatters));
procrastinate.formatters.forEach(function (formatter) {
assert.equal(typeof formatter, 'string');
assert(/^\w+$/.test(formatter));
});
});
});
describe('procrastinate.validateFormatter()', function () {
context('with a valid formatter', function () {
it('does nothing', function () {
procrastinate.validateFormatter('mocha');
});
});
context('with an invalid formatter', function () {
it('throws an Error', function () {
assert.throws(function () {
procrastinate.validateFormatter('notathinglol');
}, Error);
});
});
});
| Add a test helper function for reading data files
| test/index.js | Add a test helper function for reading data files | <ide><path>est/index.js
<ide> var assert = require('assert');
<ide> var fs = require('fs');
<add>var path = require('path');
<ide> var procrastinate = require('..');
<ide>
<ide> describe('procrastinate()', function () {
<ide> });
<ide>
<ide> var fileOptions = { encoding: 'utf-8' };
<del> var input = fs.readFileSync('test/data/input.txt', fileOptions);
<add>
<add> function getData(filename) {
<add> return fs.readFileSync(path.join('test/data', filename), fileOptions);
<add> }
<add>
<add> var input = getData('input.txt');
<ide>
<ide> context('with an input representing pending Mocha specs', function () {
<del> var output = fs.readFileSync('test/data/mocha_output.js', fileOptions);
<add> var output = getData('mocha_output.js');
<ide>
<ide> it('returns pending Mocha specs', function () {
<ide> assert.equal(procrastinate('mocha', input), output);
<ide> });
<ide>
<ide> context('with an input representing pending RSpec specs', function () {
<del> var output = fs.readFileSync('test/data/rspec_output.rb', fileOptions);
<add> var output = getData('rspec_output.rb');
<ide>
<ide> it('returns pending RSpec specs', function () {
<ide> assert.equal(procrastinate('rspec', input), output); |
|
JavaScript | isc | 4e654120122c1f36a0ebd1ced7a5db56a460db56 | 0 | bladerunner2020/node-red-contrib-mikrotik,bladerunner2020/node-red-contrib-mikrotik | /**
* Created by Bladerunner on 11/03/16.
*/
var mikrotik = require('mikronode-ng');
module.exports = function(RED) {
function NodeMikrotik(config) {
RED.nodes.createNode(this,config);
this.action = config.action;
this.ip = config.ip;
this.action = config.action;
var node = this;
var ip = node.ip;
var login = node.credentials.login;
var pass = node.credentials.pass;
var action;
switch (parseInt(node.action)) {
case 0:
action = '/log/print';
break;
case 1:
action = '/system/resource/print';
break;
case 2:
action = '/interface/wireless/registration-table/print';
break;
case 3:
action = '/system/reboot';
break;
case 9:
action = '';
break;
}
var connection = null;
this.on('input', function(msg) {
var cmd = action;
if (cmd == '') cmd = msg.payload;
if (cmd == '') return false;
connection = mikrotik.getConnection(ip, login, pass, {closeOnDone : true});
connection.getConnectPromise().then(function(conn) {
conn.getCommandPromise(cmd).then(function resolved(values) {
var parsed = mikrotik.parseItems(values);
var pl = [];
parsed.forEach(function(item) {
pl.push(item);
});
msg.payload = values;
node.send(msg);
}, function rejected(reason) {
node.error('Error executing cmd['+action+']: ' + JSON.stringify(reason));
});
},
function(err) {
node.error("Connection error: " + err);
}
);
});
this.on('close', function() {
connection && connection.connected && connection.close(true);
});
}
RED.nodes.registerType("mikrotik", NodeMikrotik, {
credentials: {
login: {type:"text"},
pass: {type:"password"}
}
});
};
| mikrotik.js | /**
* Created by Bladerunner on 11/03/16.
*/
var mikrotik = require('mikronode-ng');
module.exports = function(RED) {
function NodeMikrotik(config) {
RED.nodes.createNode(this,config);
this.action = config.action;
this.ip = config.ip;
this.action = config.action;
var node = this;
var ip = node.ip;
var login = node.credentials.login;
var pass = node.credentials.pass;
var action;
switch (parseInt(node.action)) {
case 0:
action = '/log/print';
break;
case 1:
action = '/system/resource/print';
break;
case 2:
action = '/interface/wireless/registration-table/print';
break;
case 3:
action = '/system/reboot';
break;
case 9:
action = '';
break;
}
var connection = null;
this.on('input', function(msg) {
if (action == '') action = msg.payload;
if(action == '') return false;
connection = mikrotik.getConnection(ip, login, pass, {closeOnDone : true});
connection.getConnectPromise().then(function(conn) {
conn.getCommandPromise(action).then(function resolved(values) {
var parsed = mikrotik.parseItems(values);
var pl = [];
parsed.forEach(function(item) {
pl.push(item);
});
msg.payload = values;
node.send(msg);
}, function rejected(reason) {
node.error('Error executing cmd['+action+']: ' + JSON.stringify(reason));
});
},
function(err) {
node.error("Connection error: " + err);
}
);
});
this.on('close', function() {
connection && connection.connected && connection.close(true);
});
}
RED.nodes.registerType("mikrotik", NodeMikrotik, {
credentials: {
login: {type:"text"},
pass: {type:"password"}
}
});
};
| fix once "action" bug (#2)
Bug: If used msg.payload, "action" variable not cleared in (assigned once). | mikrotik.js | fix once "action" bug (#2) | <ide><path>ikrotik.js
<ide> var connection = null;
<ide>
<ide> this.on('input', function(msg) {
<del> if (action == '') action = msg.payload;
<del> if(action == '') return false;
<add> var cmd = action;
<add> if (cmd == '') cmd = msg.payload;
<add> if (cmd == '') return false;
<ide> connection = mikrotik.getConnection(ip, login, pass, {closeOnDone : true});
<ide> connection.getConnectPromise().then(function(conn) {
<del> conn.getCommandPromise(action).then(function resolved(values) {
<add> conn.getCommandPromise(cmd).then(function resolved(values) {
<ide> var parsed = mikrotik.parseItems(values);
<ide> var pl = [];
<ide> parsed.forEach(function(item) { |
|
Java | mit | bb9252743b1d53a93e483d53095b0f239919a17b | 0 | hhu-stups/bmoth | package de.bmoth.ltl;
import de.bmoth.backend.ltl.LTLTransformations;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ParserException;
import de.bmoth.parser.ast.nodes.ltl.LTLBPredicateNode;
import de.bmoth.parser.ast.nodes.ltl.LTLFormula;
import de.bmoth.parser.ast.nodes.ltl.LTLNode;
import de.bmoth.parser.ast.nodes.ltl.LTLPrefixOperatorNode;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LTLTransformationTest {
@Test
public void testTransformation1() throws ParserException {
String formula = "not(G { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("FINALLY(NOT(EQUAL(1,1)))", node1.toString());
}
@Test
public void testTransformation2() throws ParserException {
String formula = "not(GG { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("FINALLY(NOT(EQUAL(1,1)))", node1.toString());
}
@Test
public void testTransformation3() throws ParserException {
String formula = "G not(E { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("GLOBALLY(NOT(EQUAL(1,1)))", node1.toString());
}
@Test
public void testTransformation4() throws ParserException {
String formula = "{1=1} U ({1=1} U {2=2})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("UNTIL(EQUAL(1,1),EQUAL(2,2))", node1.toString());
}
@Test
public void testTransformation5() throws ParserException {
String formula = "({1=1} U {2=2}) U {2=2}";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("UNTIL(EQUAL(1,1),EQUAL(2,2))", node1.toString());
}
@Test
@Ignore
public void testTransformation6() throws ParserException {
String formula = "not(G { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("FINALLY(NOT(EQUAL(1,1)))", node1.toString());
// check if we have the B not, not the LTL not
assertTrue(node1 instanceof LTLPrefixOperatorNode);
LTLPrefixOperatorNode node1PO = (LTLPrefixOperatorNode) node1;
assertEquals(LTLPrefixOperatorNode.Kind.FINALLY, node1PO.getKind());
assertTrue(node1PO.getArgument() instanceof LTLBPredicateNode);
}
}
| src/test/java/de/bmoth/ltl/LTLTransformationTest.java | package de.bmoth.ltl;
import de.bmoth.backend.ltl.LTLTransformations;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ParserException;
import de.bmoth.parser.ast.nodes.ltl.LTLFormula;
import de.bmoth.parser.ast.nodes.ltl.LTLNode;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LTLTransformationTest {
@Test
public void testTransformation1() throws ParserException {
String formula = "not(G { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("FINALLY(NOT(EQUAL(1,1)))", node1.toString());
}
@Test
public void testTransformation2() throws ParserException {
String formula = "not(GG { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("FINALLY(NOT(EQUAL(1,1)))", node1.toString());
}
@Test
public void testTransformation3() throws ParserException {
String formula = "G not(E { 1=1 })";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("GLOBALLY(NOT(EQUAL(1,1)))", node1.toString());
}
@Test
public void testTransformation4() throws ParserException {
String formula = "{1=1} U ({1=1} U {2=2})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("UNTIL(EQUAL(1,1),EQUAL(2,2))", node1.toString());
}
@Test
public void testTransformation5() throws ParserException {
String formula = "({1=1} U {2=2}) U {2=2}";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
assertEquals("UNTIL(EQUAL(1,1),EQUAL(2,2))", node1.toString());
}
}
| add test verifying if LTL not is pushed into the B predicate | src/test/java/de/bmoth/ltl/LTLTransformationTest.java | add test verifying if LTL not is pushed into the B predicate | <ide><path>rc/test/java/de/bmoth/ltl/LTLTransformationTest.java
<ide> import de.bmoth.backend.ltl.LTLTransformations;
<ide> import de.bmoth.parser.Parser;
<ide> import de.bmoth.parser.ParserException;
<add>import de.bmoth.parser.ast.nodes.ltl.LTLBPredicateNode;
<ide> import de.bmoth.parser.ast.nodes.ltl.LTLFormula;
<ide> import de.bmoth.parser.ast.nodes.ltl.LTLNode;
<add>import de.bmoth.parser.ast.nodes.ltl.LTLPrefixOperatorNode;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<ide>
<ide> public class LTLTransformationTest {
<ide>
<ide> LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
<ide> assertEquals("UNTIL(EQUAL(1,1),EQUAL(2,2))", node1.toString());
<ide> }
<add>
<add> @Test
<add> @Ignore
<add> public void testTransformation6() throws ParserException {
<add> String formula = "not(G { 1=1 })";
<add> LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
<add> LTLNode node1 = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
<add>
<add> assertEquals("FINALLY(NOT(EQUAL(1,1)))", node1.toString());
<add>
<add> // check if we have the B not, not the LTL not
<add> assertTrue(node1 instanceof LTLPrefixOperatorNode);
<add> LTLPrefixOperatorNode node1PO = (LTLPrefixOperatorNode) node1;
<add> assertEquals(LTLPrefixOperatorNode.Kind.FINALLY, node1PO.getKind());
<add>
<add> assertTrue(node1PO.getArgument() instanceof LTLBPredicateNode);
<add> }
<ide> } |
|
Java | apache-2.0 | d36549e64ba11c090073a645b18ecfd4f39c5e1d | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.database;
import android.content.Context;
import android.util.SparseIntArray;
import androidx.annotation.NonNull;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import org.apache.commons.lang3.tuple.ImmutablePair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Nullable;
import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.Property;
import io.objectbox.android.AndroidObjectBrowser;
import io.objectbox.query.LazyList;
import io.objectbox.query.Query;
import io.objectbox.query.QueryBuilder;
import me.devsaki.hentoid.BuildConfig;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.AttributeLocation;
import me.devsaki.hentoid.database.domains.Attribute_;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Content_;
import me.devsaki.hentoid.database.domains.ErrorRecord;
import me.devsaki.hentoid.database.domains.ErrorRecord_;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.GroupItem;
import me.devsaki.hentoid.database.domains.GroupItem_;
import me.devsaki.hentoid.database.domains.Group_;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.database.domains.ImageFile_;
import me.devsaki.hentoid.database.domains.MyObjectBox;
import me.devsaki.hentoid.database.domains.QueueRecord;
import me.devsaki.hentoid.database.domains.QueueRecord_;
import me.devsaki.hentoid.database.domains.SiteHistory;
import me.devsaki.hentoid.database.domains.SiteHistory_;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.util.AttributeMap;
import me.devsaki.hentoid.util.ContentHelper;
import me.devsaki.hentoid.util.Helper;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.RandomSeedSingleton;
import timber.log.Timber;
import static com.annimon.stream.Collectors.toList;
public class ObjectBoxDB {
// TODO - put indexes
// Status displayed in the library view (all books of the library; both internal and external)
private static final int[] libraryStatus = ContentHelper.getLibraryStatuses();
private static ObjectBoxDB instance;
private final BoxStore store;
private ObjectBoxDB(Context context) {
store = MyObjectBox.builder().androidContext(context.getApplicationContext()).maxSizeInKByte(Preferences.getMaxDbSizeKb()).build();
if (BuildConfig.DEBUG && BuildConfig.INCLUDE_OBJECTBOX_BROWSER) {
boolean started = new AndroidObjectBrowser(store).start(context.getApplicationContext());
Timber.i("ObjectBrowser started: %s", started);
}
}
// For testing (store generated by the test framework)
private ObjectBoxDB(BoxStore store) {
this.store = store;
}
// Use this to get db instance
public static synchronized ObjectBoxDB getInstance(Context context) {
// Use application context only
if (instance == null) {
instance = new ObjectBoxDB(context);
}
return instance;
}
// Use this to get db instance for testing (store generated by the test framework)
public static synchronized ObjectBoxDB getInstance(BoxStore store) {
// Use application context only
if (instance == null) {
instance = new ObjectBoxDB(store);
}
return instance;
}
void closeThreadResources() {
store.closeThreadResources();
}
long getDbSizeBytes() {
return store.sizeOnDisk();
}
long insertContent(Content content) {
List<Attribute> attributes = content.getAttributes();
Box<Attribute> attrBox = store.boxFor(Attribute.class);
Query<Attribute> attrByUniqueKey = attrBox.query().equal(Attribute_.type, 0).equal(Attribute_.name, "").build();
return store.callInTxNoException(() -> {
// Master data management managed manually
// Ensure all known attributes are replaced by their ID before being inserted
// Watch https://github.com/objectbox/objectbox-java/issues/509 for a lighter solution based on @Unique annotation
Attribute dbAttr;
Attribute inputAttr;
if (attributes != null)
// This transaction may consume a lot of DB readers depending on the number of attributes involved
for (int i = 0; i < attributes.size(); i++) {
inputAttr = attributes.get(i);
dbAttr = (Attribute) attrByUniqueKey.setParameter(Attribute_.name, inputAttr.getName())
.setParameter(Attribute_.type, inputAttr.getType().getCode())
.findFirst();
if (dbAttr != null) {
attributes.set(i, dbAttr); // If existing -> set the existing attribute
dbAttr.addLocationsFrom(inputAttr);
attrBox.put(dbAttr);
} else {
inputAttr.setName(inputAttr.getName().toLowerCase().trim()); // If new -> normalize the attribute
}
}
return store.boxFor(Content.class).put(content);
});
}
public void updateContentStatus(@NonNull final StatusContent updateFrom, @NonNull final StatusContent updateTo) {
List<Content> content = selectContentByStatus(updateFrom);
for (int i = 0; i < content.size(); i++) content.get(i).setStatus(updateTo);
store.boxFor(Content.class).put(content);
}
List<Content> selectContentByStatus(StatusContent status) {
return selectContentByStatusCodes(new int[]{status.getCode()});
}
private List<Content> selectContentByStatusCodes(int[] statusCodes) {
return store.boxFor(Content.class).query().in(Content_.status, statusCodes).build().find();
}
Query<Content> selectAllInternalBooksQ(boolean favsOnly) {
// All statuses except SAVED, DOWNLOADING, PAUSED and ERROR that imply the book is in the download queue
// and EXTERNAL because we only want to manage internal books here
int[] storedContentStatus = new int[]{
StatusContent.DOWNLOADED.getCode(),
StatusContent.MIGRATED.getCode(),
StatusContent.IGNORED.getCode(),
StatusContent.UNHANDLED_ERROR.getCode(),
StatusContent.CANCELED.getCode(),
StatusContent.ONLINE.getCode()
};
QueryBuilder<Content> query = store.boxFor(Content.class).query().in(Content_.status, storedContentStatus);
if (favsOnly) query.equal(Content_.favourite, true);
return query.build();
}
Query<Content> selectAllExternalBooksQ() {
return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.EXTERNAL.getCode()).build();
}
Query<Content> selectAllErrorJsonBooksQ() {
return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.ERROR.getCode()).notNull(Content_.jsonUri).notEqual(Content_.jsonUri, "").build();
}
Query<Content> selectAllQueueBooksQ() {
int[] storedContentStatus = new int[]{
StatusContent.SAVED.getCode(),
StatusContent.DOWNLOADING.getCode(),
StatusContent.PAUSED.getCode(),
StatusContent.ERROR.getCode()
};
return store.boxFor(Content.class).query().in(Content_.status, storedContentStatus).build();
}
Query<Content> selectAllFlaggedBooksQ() {
return store.boxFor(Content.class).query().equal(Content_.isFlaggedForDeletion, true).build();
}
void flagContentById(long[] contentId, boolean flag) {
Box<Content> contentBox = store.boxFor(Content.class);
for (long id : contentId) {
Content c = contentBox.get(id);
if (c != null) {
c.setFlaggedForDeletion(flag);
contentBox.put(c);
}
}
}
void deleteContent(Content content) {
deleteContentById(content.getId());
}
private void deleteContentById(long contentId) {
deleteContentById(new long[]{contentId});
}
/**
* Remove the given content and all related objects from the DB
* NB : ObjectBox v2.3.1 does not support cascade delete, so everything has to be done manually
*
* @param contentId IDs of the contents to be removed from the DB
*/
void deleteContentById(long[] contentId) {
Box<ErrorRecord> errorBox = store.boxFor(ErrorRecord.class);
Box<ImageFile> imageFileBox = store.boxFor(ImageFile.class);
Box<Attribute> attributeBox = store.boxFor(Attribute.class);
Box<AttributeLocation> locationBox = store.boxFor(AttributeLocation.class);
Box<Content> contentBox = store.boxFor(Content.class);
Box<GroupItem> groupItemBox = store.boxFor(GroupItem.class);
Box<Group> groupBox = store.boxFor(Group.class);
for (long id : contentId) {
Content c = contentBox.get(id);
if (c != null) {
store.runInTx(() -> {
if (c.getImageFiles() != null) {
for (ImageFile i : c.getImageFiles())
imageFileBox.remove(i); // Delete imageFiles
c.getImageFiles().clear(); // Clear links to all imageFiles
}
if (c.getErrorLog() != null) {
for (ErrorRecord e : c.getErrorLog())
errorBox.remove(e); // Delete error records
c.getErrorLog().clear(); // Clear links to all errorRecords
}
// Delete attribute when current content is the only content left on the attribute
for (Attribute a : c.getAttributes())
if (1 == a.contents.size()) {
for (AttributeLocation l : a.getLocations())
locationBox.remove(l); // Delete all locations
a.getLocations().clear(); // Clear location links
attributeBox.remove(a); // Delete the attribute itself
}
c.getAttributes().clear(); // Clear links to all attributes
// Delete corresponding groupItem
List<GroupItem> groupItems = groupItemBox.query().equal(GroupItem_.contentId, id).build().find();
for (GroupItem groupItem : groupItems) {
// If we're not in the Custom grouping and it's the only item of its group, delete the group
Group g = groupItem.group.getTarget();
if (g != null && !g.grouping.equals(Grouping.CUSTOM) && g.items.size() < 2)
groupBox.remove(g);
// Delete the item
groupItemBox.remove(groupItem);
}
contentBox.remove(c); // Remove the content itself
});
}
}
}
List<QueueRecord> selectQueue() {
return store.boxFor(QueueRecord.class).query().order(QueueRecord_.rank).build().find();
}
List<Content> selectQueueContents() {
List<Content> result = new ArrayList<>();
List<QueueRecord> queueRecords = selectQueue();
for (QueueRecord q : queueRecords) result.add(q.content.getTarget());
return result;
}
Query<QueueRecord> selectQueueContentsQ() {
return store.boxFor(QueueRecord.class).query().order(QueueRecord_.rank).build();
}
long selectMaxQueueOrder() {
return store.boxFor(QueueRecord.class).query().build().property(QueueRecord_.rank).max();
}
void insertQueue(long id, int order) {
store.boxFor(QueueRecord.class).put(new QueueRecord(id, order));
}
void updateQueue(@NonNull final List<QueueRecord> queue) {
Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class);
queueRecordBox.put(queue);
}
void deleteQueue(@NonNull Content content) {
deleteQueue(content.getId());
}
void deleteQueue(int queueIndex) {
store.boxFor(QueueRecord.class).remove(selectQueue().get(queueIndex).id);
}
void deleteQueue() {
store.boxFor(QueueRecord.class).removeAll();
}
private void deleteQueue(long contentId) {
Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class);
QueueRecord record = queueRecordBox.query().equal(QueueRecord_.contentId, contentId).build().findFirst();
if (record != null) queueRecordBox.remove(record);
}
Query<Content> selectVisibleContentQ() {
return selectContentSearchContentQ("", -1, Collections.emptyList(), false, Preferences.Constant.ORDER_FIELD_NONE, false);
}
@Nullable
Content selectContentById(long id) {
return store.boxFor(Content.class).get(id);
}
@Nullable
List<Content> selectContentById(List<Long> id) {
return store.boxFor(Content.class).get(id);
}
@Nullable
Content selectContentBySourceAndUrl(@NonNull Site site, @NonNull String url) {
return store.boxFor(Content.class).query().notEqual(Content_.url, "").equal(Content_.url, url).equal(Content_.site, site.getCode()).build().findFirst();
}
@Nullable
Content selectContentByFolderUri(@NonNull final String folderUri, boolean onlyFlagged) {
QueryBuilder<Content> queryBuilder = store.boxFor(Content.class).query().equal(Content_.storageUri, folderUri);
if (onlyFlagged) queryBuilder.equal(Content_.isFlaggedForDeletion, true);
return queryBuilder.build().findFirst();
}
private static long[] getIdsFromAttributes(@NonNull List<Attribute> attrs) {
long[] result = new long[attrs.size()];
if (!attrs.isEmpty()) {
int index = 0;
for (Attribute a : attrs) result[index++] = a.getId();
}
return result;
}
private void applySortOrder(
QueryBuilder<Content> query,
long groupId,
int orderField,
boolean orderDesc) {
// Random ordering is tricky (see https://github.com/objectbox/objectbox-java/issues/17)
// => Implemented post-query build
if (orderField == Preferences.Constant.ORDER_FIELD_RANDOM) return;
// Custom ordering depends on another "table"
// => Implemented post-query build
if (orderField == Preferences.Constant.ORDER_FIELD_CUSTOM) {
//query.sort(new Content.GroupItemOrderComparator(groupId)); // doesn't work with PagedList because it uses Query.find(final long offset, final long limit)
//query.backlink(GroupItem_.content).order(GroupItem_.order); // doesn't work yet (see https://github.com/objectbox/objectbox-java/issues/141)
return;
}
Property<Content> field = getPropertyFromField(orderField);
if (null == field) return;
if (orderDesc) query.orderDesc(field);
else query.order(field);
// Specifics sub-sorting fields when ordering by reads
if (orderField == Preferences.Constant.ORDER_FIELD_READS) {
if (orderDesc) query.orderDesc(Content_.lastReadDate);
else query.order(Content_.lastReadDate).orderDesc(Content_.downloadDate);
}
}
@Nullable
private Property<Content> getPropertyFromField(int prefsFieldCode) {
switch (prefsFieldCode) {
case Preferences.Constant.ORDER_FIELD_TITLE:
return Content_.title;
case Preferences.Constant.ORDER_FIELD_ARTIST:
return Content_.author; // Might not be what users want when there are multiple authors
case Preferences.Constant.ORDER_FIELD_NB_PAGES:
return Content_.qtyPages;
case Preferences.Constant.ORDER_FIELD_DOWNLOAD_DATE:
return Content_.downloadDate;
case Preferences.Constant.ORDER_FIELD_UPLOAD_DATE:
return Content_.uploadDate;
case Preferences.Constant.ORDER_FIELD_READ_DATE:
return Content_.lastReadDate;
case Preferences.Constant.ORDER_FIELD_READS:
return Content_.reads;
case Preferences.Constant.ORDER_FIELD_SIZE:
return Content_.size;
default:
return null;
}
}
Query<Content> selectContentSearchContentQ(
String title,
long groupId,
List<Attribute> metadata,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField)
return store.boxFor(Content.class).query().build();
AttributeMap metadataMap = new AttributeMap();
metadataMap.addAll(metadata);
boolean hasTitleFilter = (title != null && title.length() > 0);
boolean hasGroupFilter = (groupId > 0);
List<Attribute> sources = metadataMap.get(AttributeType.SOURCE);
boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE)
&& (sources != null)
&& !(sources.isEmpty());
boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0);
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (hasSiteFilter)
query.in(Content_.site, getIdsFromAttributes(sources));
if (filterFavourites) query.equal(Content_.favourite, true);
if (hasTitleFilter) query.contains(Content_.title, title);
if (hasTagFilter) {
for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) {
AttributeType attrType = entry.getKey();
if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database
List<Attribute> attrs = entry.getValue();
if (attrs != null && !attrs.isEmpty()) {
query.in(Content_.id, selectFilteredContent(attrs, false));
}
}
}
}
if (hasGroupFilter) {
query.in(Content_.id, selectFilteredContent(groupId));
}
applySortOrder(query, groupId, orderField, orderDesc);
return query.build();
}
long[] selectContentSearchContentByGroupItem(
String title,
long groupId,
List<Attribute> metadata,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
if (orderField != Preferences.Constant.ORDER_FIELD_CUSTOM) return new long[]{};
AttributeMap metadataMap = new AttributeMap();
metadataMap.addAll(metadata);
boolean hasTitleFilter = (title != null && title.length() > 0);
boolean hasGroupFilter = (groupId > 0);
List<Attribute> sources = metadataMap.get(AttributeType.SOURCE);
boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE)
&& (sources != null)
&& !(sources.isEmpty());
boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0);
// Pre-filter and order on GroupItem
QueryBuilder<GroupItem> query = store.boxFor(GroupItem.class).query();
if (hasGroupFilter) query.equal(GroupItem_.groupId, groupId);
if (orderDesc) query.orderDesc(GroupItem_.order);
else query.order(GroupItem_.order);
// Get linked Content
QueryBuilder<Content> contentQuery = query.link(GroupItem_.content);
if (hasSiteFilter)
contentQuery.in(Content_.site, getIdsFromAttributes(sources));
if (filterFavourites) contentQuery.equal(Content_.favourite, true);
if (hasTitleFilter) contentQuery.contains(Content_.title, title);
if (hasTagFilter) {
for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) {
AttributeType attrType = entry.getKey();
if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database
List<Attribute> attrs = entry.getValue();
if (attrs != null && !attrs.isEmpty()) {
contentQuery.in(Content_.id, selectFilteredContent(attrs, false));
}
}
}
}
return Helper.getPrimitiveLongArrayFromList(Stream.of(query.build().find()).map(gi -> gi.content.getTargetId()).toList());
}
private Query<Content> selectContentUniversalAttributesQ(String queryStr, long groupId, boolean filterFavourites) {
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (filterFavourites) query.equal(Content_.favourite, true);
query.link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE);
if (groupId > 0) query.in(Content_.id, selectFilteredContent(groupId));
return query.build();
}
private Query<Content> selectContentUniversalContentQ(
String queryStr,
long groupId,
boolean filterFavourites,
long[] additionalIds,
int orderField,
boolean orderDesc) {
if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField)
return store.boxFor(Content.class).query().build();
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (filterFavourites) query.equal(Content_.favourite, true);
query.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE);
query.or().equal(Content_.uniqueSiteId, queryStr);
// query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1
query.or().in(Content_.id, additionalIds);
if (groupId > 0) query.in(Content_.id, selectFilteredContent(groupId));
applySortOrder(query, groupId, orderField, orderDesc);
return query.build();
}
private long[] selectContentUniversalContentByGroupItem(
String queryStr,
long groupId,
boolean filterFavourites,
long[] additionalIds,
int orderField,
boolean orderDesc) {
if (orderField != Preferences.Constant.ORDER_FIELD_CUSTOM) return new long[]{};
// Pre-filter and order on GroupItem
QueryBuilder<GroupItem> query = store.boxFor(GroupItem.class).query();
if (groupId > 0) query.equal(GroupItem_.groupId, groupId);
if (orderDesc) query.orderDesc(GroupItem_.order);
else query.order(GroupItem_.order);
// Get linked content
QueryBuilder<Content> contentQuery = query.link(GroupItem_.content);
contentQuery.in(Content_.status, libraryStatus);
if (filterFavourites) contentQuery.equal(Content_.favourite, true);
contentQuery.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE);
contentQuery.or().equal(Content_.uniqueSiteId, queryStr);
// query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1
contentQuery.or().in(Content_.id, additionalIds);
if (groupId > 0) contentQuery.in(Content_.id, selectFilteredContent(groupId));
return Helper.getPrimitiveLongArrayFromList(Stream.of(query.build().find()).map(gi -> gi.content.getTargetId()).toList());
}
Query<Content> selectContentUniversalQ(
String queryStr,
long groupId,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
// Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201)
// querying Content and attributes have to be done separately
Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites);
return selectContentUniversalContentQ(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc);
}
long[] selectContentUniversalByGroupItem(
String queryStr,
long groupId,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
// Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201)
// querying Content and attributes have to be done separately
Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites);
return selectContentUniversalContentByGroupItem(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc);
}
private static long[] shuffleRandomSortId(Query<Content> query) {
LazyList<Content> lazyList = query.findLazy();
List<Integer> order = new ArrayList<>();
for (int i = 0; i < lazyList.size(); i++) order.add(i);
Collections.shuffle(order, new Random(RandomSeedSingleton.getInstance().getSeed()));
List<Long> result = new ArrayList<>();
for (int i = 0; i < order.size(); i++) {
result.add(lazyList.get(order.get(i)).getId());
}
return Helper.getPrimitiveLongArrayFromList(result);
}
// TODO adapt
long[] selectContentSearchId(String title, long groupId, List<Attribute> tags, boolean filterFavourites, int orderField, boolean orderDesc) {
long[] result;
Query<Content> query = selectContentSearchContentQ(title, groupId, tags, filterFavourites, orderField, orderDesc);
if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) {
result = query.findIds();
} else {
result = shuffleRandomSortId(query);
}
return result;
}
// TODO adapt
long[] selectContentUniversalId(String queryStr, long groupId, boolean filterFavourites, int orderField, boolean orderDesc) {
long[] result;
// Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201)
// querying Content and attributes have to be done separately
Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites);
Query<Content> query = selectContentUniversalContentQ(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc);
if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) {
result = query.findIds();
} else {
result = shuffleRandomSortId(query);
}
return result;
}
private long[] selectFilteredContent(long groupId) {
if (groupId < 1) return new long[0];
return Helper.getPrimitiveLongArrayFromList(store.boxFor(Group.class).get(groupId).getContentIds());
}
private long[] selectFilteredContent(List<Attribute> attrs, boolean filterFavourites) {
if (null == attrs || attrs.isEmpty()) return new long[0];
// Pre-build queries to reuse them efficiently within the loops
QueryBuilder<Content> contentFromSourceQueryBuilder = store.boxFor(Content.class).query();
contentFromSourceQueryBuilder.in(Content_.status, libraryStatus);
contentFromSourceQueryBuilder.equal(Content_.site, 1);
if (filterFavourites) contentFromSourceQueryBuilder.equal(Content_.favourite, true);
Query<Content> contentFromSourceQuery = contentFromSourceQueryBuilder.build();
QueryBuilder<Content> contentFromAttributesQueryBuilder = store.boxFor(Content.class).query();
contentFromAttributesQueryBuilder.in(Content_.status, libraryStatus);
if (filterFavourites) contentFromAttributesQueryBuilder.equal(Content_.favourite, true);
contentFromAttributesQueryBuilder.link(Content_.attributes)
.equal(Attribute_.type, 0)
.equal(Attribute_.name, "");
Query<Content> contentFromAttributesQuery = contentFromAttributesQueryBuilder.build();
// Cumulative query loop
// Each iteration restricts the results of the next because advanced search uses an AND logic
List<Long> results = Collections.emptyList();
long[] ids;
for (Attribute attr : attrs) {
if (attr.getType().equals(AttributeType.SOURCE)) {
ids = contentFromSourceQuery.setParameter(Content_.site, attr.getId()).findIds();
} else {
ids = contentFromAttributesQuery.setParameter(Attribute_.type, attr.getType().getCode())
.setParameter(Attribute_.name, attr.getName()).findIds();
}
if (results.isEmpty()) results = Helper.getListFromPrimitiveArray(ids);
else {
// Filter results with newly found IDs (only common IDs should stay)
List<Long> idsAsList = Helper.getListFromPrimitiveArray(ids);
results.retainAll(idsAsList);
}
}
return Helper.getPrimitiveLongArrayFromList(results);
}
List<Attribute> selectAvailableSources() {
return selectAvailableSources(null);
}
List<Attribute> selectAvailableSources(List<Attribute> filter) {
List<Attribute> result = new ArrayList<>();
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (filter != null && !filter.isEmpty()) {
AttributeMap metadataMap = new AttributeMap();
metadataMap.addAll(filter);
List<Attribute> params = metadataMap.get(AttributeType.SOURCE);
if (params != null && !params.isEmpty())
query.in(Content_.site, getIdsFromAttributes(params));
for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) {
AttributeType attrType = entry.getKey();
if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database
List<Attribute> attrs = entry.getValue();
if (attrs != null && !attrs.isEmpty())
query.in(Content_.id, selectFilteredContent(attrs, false));
}
}
}
List<Content> content = query.build().find();
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by source
Map<Site, List<Content>> map = Stream.of(content).collect(Collectors.groupingBy(Content::getSite));
for (Map.Entry<Site, List<Content>> entry : map.entrySet()) {
Site site = entry.getKey();
int size = (null == entry.getValue()) ? 0 : entry.getValue().size();
result.add(new Attribute(AttributeType.SOURCE, site.getDescription()).setExternalId(site.getCode()).setCount(size));
}
// Order by count desc
result = Stream.of(result).sortBy(a -> -a.getCount()).collect(toList());
return result;
}
Query<Content> selectErrorContentQ() {
return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.ERROR.getCode()).orderDesc(Content_.downloadDate).build();
}
private Query<Attribute> queryAvailableAttributes(
@NonNull final AttributeType type,
String filter,
long[] filteredContent) {
QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query();
query.equal(Attribute_.type, type.getCode());
if (filter != null && !filter.trim().isEmpty())
query.contains(Attribute_.name, filter.trim(), QueryBuilder.StringOrder.CASE_INSENSITIVE);
if (filteredContent.length > 0)
query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus);
else
query.link(Attribute_.contents).in(Content_.status, libraryStatus);
return query.build();
}
long countAvailableAttributes(AttributeType
type, List<Attribute> attributeFilter, String filter, boolean filterFavourites) {
return queryAvailableAttributes(type, filter, selectFilteredContent(attributeFilter, filterFavourites)).count();
}
@SuppressWarnings("squid:S2184")
// In our case, limit() argument has to be human-readable -> no issue concerning its type staying in the int range
List<Attribute> selectAvailableAttributes(
@NonNull AttributeType type,
List<Attribute> attributeFilter,
String filter,
boolean filterFavourites,
int sortOrder,
int page,
int itemsPerPage) {
long[] filteredContent = selectFilteredContent(attributeFilter, filterFavourites);
List<Long> filteredContentAsList = Helper.getListFromPrimitiveArray(filteredContent);
List<Integer> libraryStatusAsList = Helper.getListFromPrimitiveArray(libraryStatus);
List<Attribute> result = queryAvailableAttributes(type, filter, filteredContent).find();
// Compute attribute count for sorting
long count;
for (Attribute a : result) {
count = Stream.of(a.contents)
.filter(c -> libraryStatusAsList.contains(c.getStatus().getCode()))
.filter(c -> filteredContentAsList.isEmpty() || filteredContentAsList.contains(c.getId()))
.count();
a.setCount((int) count);
}
// Apply sort order
Stream<Attribute> s = Stream.of(result);
if (Preferences.Constant.ORDER_ATTRIBUTES_ALPHABETIC == sortOrder) {
s = s.sortBy(a -> -a.getCount()).sortBy(Attribute::getName);
} else {
s = s.sortBy(Attribute::getName).sortBy(a -> -a.getCount());
}
// Apply paging
if (itemsPerPage > 0) {
int start = (page - 1) * itemsPerPage;
s = s.limit(page * itemsPerPage).skip(start); // squid:S2184 here because int * int -> int (not long)
}
return s.collect(toList());
}
SparseIntArray countAvailableAttributesPerType() {
return countAvailableAttributesPerType(null);
}
SparseIntArray countAvailableAttributesPerType(List<Attribute> attributeFilter) {
// Get Content filtered by current selection
long[] filteredContent = selectFilteredContent(attributeFilter, false);
// Get available attributes of the resulting content list
QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query();
if (filteredContent.length > 0)
query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus);
else
query.link(Attribute_.contents).in(Content_.status, libraryStatus);
List<Attribute> attributes = query.build().find();
SparseIntArray result = new SparseIntArray();
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by type
Map<AttributeType, List<Attribute>> map = Stream.of(attributes).collect(Collectors.groupingBy(Attribute::getType));
for (Map.Entry<AttributeType, List<Attribute>> entry : map.entrySet()) {
AttributeType t = entry.getKey();
int size = (null == entry.getValue()) ? 0 : entry.getValue().size();
result.append(t.getCode(), size);
}
return result;
}
void updateImageFileStatusParamsMimeTypeUriSize(@NonNull ImageFile image) {
Box<ImageFile> imgBox = store.boxFor(ImageFile.class);
ImageFile img = imgBox.get(image.getId());
if (img != null) {
img.setStatus(image.getStatus());
img.setDownloadParams(image.getDownloadParams());
img.setMimeType(image.getMimeType());
img.setFileUri(image.getFileUri());
img.setSize(image.getSize());
imgBox.put(img);
}
}
void updateImageContentStatus(
long contentId,
@Nullable StatusContent updateFrom,
@NonNull StatusContent updateTo) {
QueryBuilder<ImageFile> query = store.boxFor(ImageFile.class).query();
if (updateFrom != null) query.equal(ImageFile_.status, updateFrom.getCode());
List<ImageFile> imgs = query.equal(ImageFile_.contentId, contentId).build().find();
if (imgs.isEmpty()) return;
for (int i = 0; i < imgs.size(); i++) imgs.get(i).setStatus(updateTo);
store.boxFor(ImageFile.class).put(imgs);
}
void updateImageFileUrl(@NonNull final ImageFile image) {
Box<ImageFile> imgBox = store.boxFor(ImageFile.class);
ImageFile img = imgBox.get(image.getId());
if (img != null) {
img.setUrl(image.getUrl());
imgBox.put(img);
}
}
// Returns a list of processed images grouped by status, with count and filesize
Map<StatusContent, ImmutablePair<Integer, Long>> countProcessedImagesById(long contentId) {
QueryBuilder<ImageFile> imgQuery = store.boxFor(ImageFile.class).query();
imgQuery.equal(ImageFile_.contentId, contentId);
List<ImageFile> images = imgQuery.build().find();
Map<StatusContent, ImmutablePair<Integer, Long>> result = new EnumMap<>(StatusContent.class);
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by type
Map<StatusContent, List<ImageFile>> map = Stream.of(images).collect(Collectors.groupingBy(ImageFile::getStatus));
for (Map.Entry<StatusContent, List<ImageFile>> entry : map.entrySet()) {
StatusContent t = entry.getKey();
int count = 0;
long size = 0;
if (entry.getValue() != null) {
count = entry.getValue().size();
for (ImageFile img : entry.getValue()) size += img.getSize();
}
result.put(t, new ImmutablePair<>(count, size));
}
return result;
}
Map<Site, ImmutablePair<Integer, Long>> selectMemoryUsagePerSource() {
// Get all downloaded images regardless of the book's status
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode()});
List<Content> books = query.build().find();
Map<Site, ImmutablePair<Integer, Long>> result = new EnumMap<>(Site.class);
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by type
Map<Site, List<Content>> map = Stream.of(books).collect(Collectors.groupingBy(Content::getSite));
for (Map.Entry<Site, List<Content>> entry : map.entrySet()) {
Site s = entry.getKey();
int count = 0;
long size = 0;
if (entry.getValue() != null) {
count = entry.getValue().size();
for (Content c : entry.getValue()) size += c.getSize();
}
result.put(s, new ImmutablePair<>(count, size));
}
return result;
}
void insertErrorRecord(@NonNull final ErrorRecord record) {
store.boxFor(ErrorRecord.class).put(record);
}
List<ErrorRecord> selectErrorRecordByContentId(long contentId) {
return store.boxFor(ErrorRecord.class).query().equal(ErrorRecord_.contentId, contentId).build().find();
}
void deleteErrorRecords(long contentId) {
List<ErrorRecord> records = selectErrorRecordByContentId(contentId);
store.boxFor(ErrorRecord.class).remove(records);
}
void insertImageFile(@NonNull ImageFile img) {
if (img.getId() > 0) store.boxFor(ImageFile.class).put(img);
}
void deleteImageFiles(long contentId) {
store.boxFor(ImageFile.class).query().equal(ImageFile_.contentId, contentId).build().remove();
}
void deleteImageFiles(List<ImageFile> images) {
store.boxFor(ImageFile.class).remove(images);
}
void insertImageFiles(@NonNull List<ImageFile> imgs) {
store.boxFor(ImageFile.class).put(imgs);
}
@Nullable
ImageFile selectImageFile(long id) {
if (id > 0) return store.boxFor(ImageFile.class).get(id);
else return null;
}
Query<ImageFile> selectDownloadedImagesFromContent(long id) {
QueryBuilder<ImageFile> builder = store.boxFor(ImageFile.class).query();
builder.equal(ImageFile_.contentId, id);
builder.in(ImageFile_.status, new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.EXTERNAL.getCode()});
builder.order(ImageFile_.order);
return builder.build();
}
void insertSiteHistory(@NonNull Site site, @NonNull String url) {
SiteHistory siteHistory = selectHistory(site);
if (siteHistory != null) {
siteHistory.setUrl(url);
store.boxFor(SiteHistory.class).put(siteHistory);
} else {
store.boxFor(SiteHistory.class).put(new SiteHistory(site, url));
}
}
@Nullable
SiteHistory selectHistory(@NonNull Site s) {
return store.boxFor(SiteHistory.class).query().equal(SiteHistory_.site, s.getCode()).build().findFirst();
}
long insertGroup(Group group) {
return store.boxFor(Group.class).put(group);
}
long insertGroupItem(GroupItem item) {
return store.boxFor(GroupItem.class).put(item);
}
long countGroupsFor(Grouping grouping) {
return store.boxFor(Group.class).query().equal(Group_.grouping, grouping.getId()).build().count();
}
Query<Group> selectGroupsQ(int grouping, int orderStyle) {
QueryBuilder<Group> qb = store.boxFor(Group.class).query().equal(Group_.grouping, grouping);
if (0 == orderStyle) qb.order(Group_.name);
// Order by number of children is done by the DAO
else if (2 == orderStyle) qb.order(Group_.order);
return qb.build();
}
@Nullable
Group selectGroup(long groupId) {
return store.boxFor(Group.class).get(groupId);
}
Query<Group> selectGroupsByFlagQ(int grouping, int flag) {
return store.boxFor(Group.class).query().equal(Group_.grouping, grouping).equal(Group_.flag, flag).build();
}
/**
* ONE-SHOT USE QUERIES (MIGRATION & MAINTENANCE)
*/
List<Content> selectContentWithOldPururinHost() {
return store.boxFor(Content.class).query().contains(Content_.coverImageUrl, "://api.pururin.io/images/").build().find();
}
List<Content> selectContentWithOldTsuminoCovers() {
return store.boxFor(Content.class).query().contains(Content_.coverImageUrl, "://www.tsumino.com/Image/Thumb/").build().find();
}
List<Content> selectDownloadedContentWithNoSize() {
return store.boxFor(Content.class).query().in(Content_.status, libraryStatus).isNull(Content_.size).build().find();
}
public Query<Content> selectOldStoredContentQ() {
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, new int[]{
StatusContent.DOWNLOADING.getCode(),
StatusContent.PAUSED.getCode(),
StatusContent.DOWNLOADED.getCode(),
StatusContent.ERROR.getCode(),
StatusContent.MIGRATED.getCode()});
query.notNull(Content_.storageFolder);
query.notEqual(Content_.storageFolder, "");
return query.build();
}
long[] selectStoredContentIds(boolean nonFavouritesOnly, boolean includeQueued) {
QueryBuilder<Content> query = store.boxFor(Content.class).query();
if (includeQueued)
query.in(Content_.status, new int[]{
StatusContent.DOWNLOADING.getCode(),
StatusContent.PAUSED.getCode(),
StatusContent.DOWNLOADED.getCode(),
StatusContent.ERROR.getCode(),
StatusContent.MIGRATED.getCode()});
else
query.in(Content_.status, new int[]{
StatusContent.DOWNLOADED.getCode(),
StatusContent.MIGRATED.getCode()});
query.notNull(Content_.storageUri);
query.notEqual(Content_.storageUri, "");
if (nonFavouritesOnly) query.equal(Content_.favourite, false);
return query.build().findIds();
}
}
| app/src/main/java/me/devsaki/hentoid/database/ObjectBoxDB.java | package me.devsaki.hentoid.database;
import android.content.Context;
import android.util.SparseIntArray;
import androidx.annotation.NonNull;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import org.apache.commons.lang3.tuple.ImmutablePair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Nullable;
import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.Property;
import io.objectbox.android.AndroidObjectBrowser;
import io.objectbox.query.LazyList;
import io.objectbox.query.Query;
import io.objectbox.query.QueryBuilder;
import me.devsaki.hentoid.BuildConfig;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.AttributeLocation;
import me.devsaki.hentoid.database.domains.Attribute_;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Content_;
import me.devsaki.hentoid.database.domains.ErrorRecord;
import me.devsaki.hentoid.database.domains.ErrorRecord_;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.GroupItem;
import me.devsaki.hentoid.database.domains.GroupItem_;
import me.devsaki.hentoid.database.domains.Group_;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.database.domains.ImageFile_;
import me.devsaki.hentoid.database.domains.MyObjectBox;
import me.devsaki.hentoid.database.domains.QueueRecord;
import me.devsaki.hentoid.database.domains.QueueRecord_;
import me.devsaki.hentoid.database.domains.SiteHistory;
import me.devsaki.hentoid.database.domains.SiteHistory_;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.util.AttributeMap;
import me.devsaki.hentoid.util.ContentHelper;
import me.devsaki.hentoid.util.Helper;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.RandomSeedSingleton;
import timber.log.Timber;
import static com.annimon.stream.Collectors.toList;
public class ObjectBoxDB {
// TODO - put indexes
// Status displayed in the library view (all books of the library; both internal and external)
private static final int[] libraryStatus = ContentHelper.getLibraryStatuses();
private static ObjectBoxDB instance;
private final BoxStore store;
private ObjectBoxDB(Context context) {
store = MyObjectBox.builder().androidContext(context.getApplicationContext()).maxSizeInKByte(Preferences.getMaxDbSizeKb()).build();
if (BuildConfig.DEBUG && BuildConfig.INCLUDE_OBJECTBOX_BROWSER) {
boolean started = new AndroidObjectBrowser(store).start(context.getApplicationContext());
Timber.i("ObjectBrowser started: %s", started);
}
}
// For testing (store generated by the test framework)
private ObjectBoxDB(BoxStore store) {
this.store = store;
}
// Use this to get db instance
public static synchronized ObjectBoxDB getInstance(Context context) {
// Use application context only
if (instance == null) {
instance = new ObjectBoxDB(context);
}
return instance;
}
// Use this to get db instance for testing (store generated by the test framework)
public static synchronized ObjectBoxDB getInstance(BoxStore store) {
// Use application context only
if (instance == null) {
instance = new ObjectBoxDB(store);
}
return instance;
}
void closeThreadResources() {
store.closeThreadResources();
}
long getDbSizeBytes() {
return store.sizeOnDisk();
}
long insertContent(Content content) {
List<Attribute> attributes = content.getAttributes();
Box<Attribute> attrBox = store.boxFor(Attribute.class);
Query<Attribute> attrByUniqueKey = attrBox.query().equal(Attribute_.type, 0).equal(Attribute_.name, "").build();
return store.callInTxNoException(() -> {
// Master data management managed manually
// Ensure all known attributes are replaced by their ID before being inserted
// Watch https://github.com/objectbox/objectbox-java/issues/509 for a lighter solution based on @Unique annotation
Attribute dbAttr;
Attribute inputAttr;
if (attributes != null)
// This transaction may consume a lot of DB readers depending on the number of attributes involved
for (int i = 0; i < attributes.size(); i++) {
inputAttr = attributes.get(i);
dbAttr = (Attribute) attrByUniqueKey.setParameter(Attribute_.name, inputAttr.getName())
.setParameter(Attribute_.type, inputAttr.getType().getCode())
.findFirst();
if (dbAttr != null) {
attributes.set(i, dbAttr); // If existing -> set the existing attribute
dbAttr.addLocationsFrom(inputAttr);
attrBox.put(dbAttr);
} else {
inputAttr.setName(inputAttr.getName().toLowerCase().trim()); // If new -> normalize the attribute
}
}
return store.boxFor(Content.class).put(content);
});
}
public void updateContentStatus(@NonNull final StatusContent updateFrom, @NonNull final StatusContent updateTo) {
List<Content> content = selectContentByStatus(updateFrom);
for (int i = 0; i < content.size(); i++) content.get(i).setStatus(updateTo);
store.boxFor(Content.class).put(content);
}
List<Content> selectContentByStatus(StatusContent status) {
return selectContentByStatusCodes(new int[]{status.getCode()});
}
private List<Content> selectContentByStatusCodes(int[] statusCodes) {
return store.boxFor(Content.class).query().in(Content_.status, statusCodes).build().find();
}
Query<Content> selectAllInternalBooksQ(boolean favsOnly) {
// All statuses except SAVED, DOWNLOADING, PAUSED and ERROR that imply the book is in the download queue
// and EXTERNAL because we only want to manage internal books here
int[] storedContentStatus = new int[]{
StatusContent.DOWNLOADED.getCode(),
StatusContent.MIGRATED.getCode(),
StatusContent.IGNORED.getCode(),
StatusContent.UNHANDLED_ERROR.getCode(),
StatusContent.CANCELED.getCode(),
StatusContent.ONLINE.getCode()
};
QueryBuilder<Content> query = store.boxFor(Content.class).query().in(Content_.status, storedContentStatus);
if (favsOnly) query.equal(Content_.favourite, true);
return query.build();
}
Query<Content> selectAllExternalBooksQ() {
return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.EXTERNAL.getCode()).build();
}
Query<Content> selectAllErrorJsonBooksQ() {
return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.ERROR.getCode()).notNull(Content_.jsonUri).notEqual(Content_.jsonUri, "").build();
}
Query<Content> selectAllQueueBooksQ() {
int[] storedContentStatus = new int[]{
StatusContent.SAVED.getCode(),
StatusContent.DOWNLOADING.getCode(),
StatusContent.PAUSED.getCode(),
StatusContent.ERROR.getCode()
};
return store.boxFor(Content.class).query().in(Content_.status, storedContentStatus).build();
}
Query<Content> selectAllFlaggedBooksQ() {
return store.boxFor(Content.class).query().equal(Content_.isFlaggedForDeletion, true).build();
}
void flagContentById(long[] contentId, boolean flag) {
Box<Content> contentBox = store.boxFor(Content.class);
for (long id : contentId) {
Content c = contentBox.get(id);
if (c != null) {
c.setFlaggedForDeletion(flag);
contentBox.put(c);
}
}
}
void deleteContent(Content content) {
deleteContentById(content.getId());
}
private void deleteContentById(long contentId) {
deleteContentById(new long[]{contentId});
}
/**
* Remove the given content and all related objects from the DB
* NB : ObjectBox v2.3.1 does not support cascade delete, so everything has to be done manually
*
* @param contentId IDs of the contents to be removed from the DB
*/
void deleteContentById(long[] contentId) {
Box<ErrorRecord> errorBox = store.boxFor(ErrorRecord.class);
Box<ImageFile> imageFileBox = store.boxFor(ImageFile.class);
Box<Attribute> attributeBox = store.boxFor(Attribute.class);
Box<AttributeLocation> locationBox = store.boxFor(AttributeLocation.class);
Box<Content> contentBox = store.boxFor(Content.class);
Box<GroupItem> groupItemBox = store.boxFor(GroupItem.class);
Box<Group> groupBox = store.boxFor(Group.class);
for (long id : contentId) {
Content c = contentBox.get(id);
if (c != null) {
store.runInTx(() -> {
if (c.getImageFiles() != null) {
for (ImageFile i : c.getImageFiles())
imageFileBox.remove(i); // Delete imageFiles
c.getImageFiles().clear(); // Clear links to all imageFiles
}
if (c.getErrorLog() != null) {
for (ErrorRecord e : c.getErrorLog())
errorBox.remove(e); // Delete error records
c.getErrorLog().clear(); // Clear links to all errorRecords
}
// Delete attribute when current content is the only content left on the attribute
for (Attribute a : c.getAttributes())
if (1 == a.contents.size()) {
for (AttributeLocation l : a.getLocations())
locationBox.remove(l); // Delete all locations
a.getLocations().clear(); // Clear location links
attributeBox.remove(a); // Delete the attribute itself
}
c.getAttributes().clear(); // Clear links to all attributes
// Delete corresponding groupItem
List<GroupItem> groupItems = groupItemBox.query().equal(GroupItem_.contentId, id).build().find();
for (GroupItem groupItem : groupItems) {
// If we're not in the Custom grouping and it's the only item of its group, delete the group
Group g = groupItem.group.getTarget();
if (g != null && !g.grouping.equals(Grouping.CUSTOM) && g.items.size() < 2)
groupBox.remove(g);
// Delete the item
groupItemBox.remove(groupItem);
}
contentBox.remove(c); // Remove the content itself
});
}
}
}
List<QueueRecord> selectQueue() {
return store.boxFor(QueueRecord.class).query().order(QueueRecord_.rank).build().find();
}
List<Content> selectQueueContents() {
List<Content> result = new ArrayList<>();
List<QueueRecord> queueRecords = selectQueue();
for (QueueRecord q : queueRecords) result.add(q.content.getTarget());
return result;
}
Query<QueueRecord> selectQueueContentsQ() {
return store.boxFor(QueueRecord.class).query().order(QueueRecord_.rank).build();
}
long selectMaxQueueOrder() {
return store.boxFor(QueueRecord.class).query().build().property(QueueRecord_.rank).max();
}
void insertQueue(long id, int order) {
store.boxFor(QueueRecord.class).put(new QueueRecord(id, order));
}
void updateQueue(@NonNull final List<QueueRecord> queue) {
Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class);
queueRecordBox.put(queue);
}
void deleteQueue(@NonNull Content content) {
deleteQueue(content.getId());
}
void deleteQueue(int queueIndex) {
store.boxFor(QueueRecord.class).remove(selectQueue().get(queueIndex).id);
}
void deleteQueue() {
store.boxFor(QueueRecord.class).removeAll();
}
private void deleteQueue(long contentId) {
Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class);
QueueRecord record = queueRecordBox.query().equal(QueueRecord_.contentId, contentId).build().findFirst();
if (record != null) queueRecordBox.remove(record);
}
Query<Content> selectVisibleContentQ() {
return selectContentSearchContentQ("", -1, Collections.emptyList(), false, Preferences.Constant.ORDER_FIELD_NONE, false);
}
@Nullable
Content selectContentById(long id) {
return store.boxFor(Content.class).get(id);
}
@Nullable
List<Content> selectContentById(List<Long> id) {
return store.boxFor(Content.class).get(id);
}
@Nullable
Content selectContentBySourceAndUrl(@NonNull Site site, @NonNull String url) {
return store.boxFor(Content.class).query().notEqual(Content_.url, "").equal(Content_.url, url).equal(Content_.site, site.getCode()).build().findFirst();
}
@Nullable
Content selectContentByFolderUri(@NonNull final String folderUri, boolean onlyFlagged) {
QueryBuilder<Content> queryBuilder = store.boxFor(Content.class).query().equal(Content_.storageUri, folderUri);
if (onlyFlagged) queryBuilder.equal(Content_.isFlaggedForDeletion, true);
return queryBuilder.build().findFirst();
}
private static long[] getIdsFromAttributes(@NonNull List<Attribute> attrs) {
long[] result = new long[attrs.size()];
if (!attrs.isEmpty()) {
int index = 0;
for (Attribute a : attrs) result[index++] = a.getId();
}
return result;
}
private void applySortOrder(
QueryBuilder<Content> query,
long groupId,
int orderField,
boolean orderDesc) {
// Random ordering is tricky (see https://github.com/objectbox/objectbox-java/issues/17)
// => Implemented post-query build
if (orderField == Preferences.Constant.ORDER_FIELD_RANDOM) return;
// Custom ordering depends on another "table"
// => Implemented post-query build
if (orderField == Preferences.Constant.ORDER_FIELD_CUSTOM) {
//query.sort(new Content.GroupItemOrderComparator(groupId)); // doesn't work with PagedList because it uses Query.find(final long offset, final long limit)
//query.backlink(GroupItem_.content).order(GroupItem_.order); // doesn't work yet (see https://github.com/objectbox/objectbox-java/issues/141)
return;
}
Property<Content> field = getPropertyFromField(orderField);
if (null == field) return;
if (orderDesc) query.orderDesc(field);
else query.order(field);
// Specifics sub-sorting fields when ordering by reads
if (orderField == Preferences.Constant.ORDER_FIELD_READS) {
if (orderDesc) query.orderDesc(Content_.lastReadDate);
else query.order(Content_.lastReadDate).orderDesc(Content_.downloadDate);
}
}
@Nullable
private Property<Content> getPropertyFromField(int prefsFieldCode) {
switch (prefsFieldCode) {
case Preferences.Constant.ORDER_FIELD_TITLE:
return Content_.title;
case Preferences.Constant.ORDER_FIELD_ARTIST:
return Content_.author; // Might not be what users want when there are multiple authors
case Preferences.Constant.ORDER_FIELD_NB_PAGES:
return Content_.qtyPages;
case Preferences.Constant.ORDER_FIELD_DOWNLOAD_DATE:
return Content_.downloadDate;
case Preferences.Constant.ORDER_FIELD_UPLOAD_DATE:
return Content_.uploadDate;
case Preferences.Constant.ORDER_FIELD_READ_DATE:
return Content_.lastReadDate;
case Preferences.Constant.ORDER_FIELD_READS:
return Content_.reads;
case Preferences.Constant.ORDER_FIELD_SIZE:
return Content_.size;
default:
return null;
}
}
Query<Content> selectContentSearchContentQ(
String title,
long groupId,
List<Attribute> metadata,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField)
return store.boxFor(Content.class).query().build();
AttributeMap metadataMap = new AttributeMap();
metadataMap.addAll(metadata);
boolean hasTitleFilter = (title != null && title.length() > 0);
boolean hasGroupFilter = (groupId > 0);
List<Attribute> sources = metadataMap.get(AttributeType.SOURCE);
boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE)
&& (sources != null)
&& !(sources.isEmpty());
boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0);
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (hasSiteFilter)
query.in(Content_.site, getIdsFromAttributes(sources));
if (filterFavourites) query.equal(Content_.favourite, true);
if (hasTitleFilter) query.contains(Content_.title, title);
if (hasTagFilter) {
for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) {
AttributeType attrType = entry.getKey();
if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database
List<Attribute> attrs = entry.getValue();
if (attrs != null && !attrs.isEmpty()) {
query.in(Content_.id, selectFilteredContent(attrs, false));
}
}
}
}
if (hasGroupFilter) {
query.in(Content_.id, selectFilteredContent(groupId));
}
applySortOrder(query, groupId, orderField, orderDesc);
return query.build();
}
long[] selectContentSearchContentByGroupItem(
String title,
long groupId,
List<Attribute> metadata,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
if (orderField != Preferences.Constant.ORDER_FIELD_CUSTOM) return new long[]{};
AttributeMap metadataMap = new AttributeMap();
metadataMap.addAll(metadata);
boolean hasTitleFilter = (title != null && title.length() > 0);
boolean hasGroupFilter = (groupId > 0);
List<Attribute> sources = metadataMap.get(AttributeType.SOURCE);
boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE)
&& (sources != null)
&& !(sources.isEmpty());
boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0);
// Pre-filter and order on GroupItem
QueryBuilder<GroupItem> query = store.boxFor(GroupItem.class).query();
if (hasGroupFilter) query.equal(GroupItem_.groupId, groupId);
if (orderDesc) query.orderDesc(GroupItem_.order);
else query.order(GroupItem_.order);
// Get linked Content
QueryBuilder<Content> contentQuery = query.link(GroupItem_.content);
if (hasSiteFilter)
contentQuery.in(Content_.site, getIdsFromAttributes(sources));
if (filterFavourites) contentQuery.equal(Content_.favourite, true);
if (hasTitleFilter) contentQuery.contains(Content_.title, title);
if (hasTagFilter) {
for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) {
AttributeType attrType = entry.getKey();
if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database
List<Attribute> attrs = entry.getValue();
if (attrs != null && !attrs.isEmpty()) {
contentQuery.in(Content_.id, selectFilteredContent(attrs, false));
}
}
}
}
return Helper.getPrimitiveLongArrayFromList(Stream.of(query.build().find()).map(gi -> gi.content.getTargetId()).toList());
}
private Query<Content> selectContentUniversalAttributesQ(String queryStr, long groupId, boolean filterFavourites) {
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (filterFavourites) query.equal(Content_.favourite, true);
query.link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE);
if (groupId > 0) query.in(Content_.id, selectFilteredContent(groupId));
return query.build();
}
private Query<Content> selectContentUniversalContentQ(
String queryStr,
long groupId,
boolean filterFavourites,
long[] additionalIds,
int orderField,
boolean orderDesc) {
if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField)
return store.boxFor(Content.class).query().build();
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (filterFavourites) query.equal(Content_.favourite, true);
query.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE);
query.or().equal(Content_.uniqueSiteId, queryStr);
// query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1
query.or().in(Content_.id, additionalIds);
if (groupId > 0) query.in(Content_.id, selectFilteredContent(groupId));
applySortOrder(query, groupId, orderField, orderDesc);
return query.build();
}
private long[] selectContentUniversalContentByGroupItem(
String queryStr,
long groupId,
boolean filterFavourites,
long[] additionalIds,
int orderField,
boolean orderDesc) {
if (orderField != Preferences.Constant.ORDER_FIELD_CUSTOM) return new long[]{};
// Pre-filter and order on GroupItem
QueryBuilder<GroupItem> query = store.boxFor(GroupItem.class).query();
if (groupId > 0) query.equal(GroupItem_.groupId, groupId);
if (orderDesc) query.orderDesc(GroupItem_.order);
else query.order(GroupItem_.order);
// Get linked content
QueryBuilder<Content> contentQuery = query.link(GroupItem_.content);
contentQuery.in(Content_.status, libraryStatus);
if (filterFavourites) contentQuery.equal(Content_.favourite, true);
contentQuery.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE);
contentQuery.or().equal(Content_.uniqueSiteId, queryStr);
// query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1
contentQuery.or().in(Content_.id, additionalIds);
if (groupId > 0) contentQuery.in(Content_.id, selectFilteredContent(groupId));
return Helper.getPrimitiveLongArrayFromList(Stream.of(query.build().find()).map(gi -> gi.content.getTargetId()).toList());
}
Query<Content> selectContentUniversalQ(
String queryStr,
long groupId,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
// Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201)
// querying Content and attributes have to be done separately
Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites);
return selectContentUniversalContentQ(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc);
}
long[] selectContentUniversalByGroupItem(
String queryStr,
long groupId,
boolean filterFavourites,
int orderField,
boolean orderDesc) {
// Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201)
// querying Content and attributes have to be done separately
Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites);
return selectContentUniversalContentByGroupItem(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc);
}
private static long[] shuffleRandomSortId(Query<Content> query) {
LazyList<Content> lazyList = query.findLazy();
List<Integer> order = new ArrayList<>();
for (int i = 0; i < lazyList.size(); i++) order.add(i);
Collections.shuffle(order, new Random(RandomSeedSingleton.getInstance().getSeed()));
List<Long> result = new ArrayList<>();
for (int i = 0; i < order.size(); i++) {
result.add(lazyList.get(order.get(i)).getId());
}
return Helper.getPrimitiveLongArrayFromList(result);
}
// TODO adapt
long[] selectContentSearchId(String title, long groupId, List<Attribute> tags, boolean filterFavourites, int orderField, boolean orderDesc) {
long[] result;
Query<Content> query = selectContentSearchContentQ(title, groupId, tags, filterFavourites, orderField, orderDesc);
if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) {
result = query.findIds();
} else {
result = shuffleRandomSortId(query);
}
return result;
}
// TODO adapt
long[] selectContentUniversalId(String queryStr, long groupId, boolean filterFavourites, int orderField, boolean orderDesc) {
long[] result;
// Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201)
// querying Content and attributes have to be done separately
Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites);
Query<Content> query = selectContentUniversalContentQ(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc);
if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) {
result = query.findIds();
} else {
result = shuffleRandomSortId(query);
}
return result;
}
private long[] selectFilteredContent(long groupId) {
if (groupId < 1) return new long[0];
return Helper.getPrimitiveLongArrayFromList(store.boxFor(Group.class).get(groupId).getContentIds());
}
private long[] selectFilteredContent(List<Attribute> attrs, boolean filterFavourites) {
if (null == attrs || attrs.isEmpty()) return new long[0];
// Pre-build queries to reuse them efficiently within the loops
QueryBuilder<Content> contentFromSourceQueryBuilder = store.boxFor(Content.class).query();
contentFromSourceQueryBuilder.in(Content_.status, libraryStatus);
contentFromSourceQueryBuilder.equal(Content_.site, 1);
if (filterFavourites) contentFromSourceQueryBuilder.equal(Content_.favourite, true);
Query<Content> contentFromSourceQuery = contentFromSourceQueryBuilder.build();
QueryBuilder<Content> contentFromAttributesQueryBuilder = store.boxFor(Content.class).query();
contentFromAttributesQueryBuilder.in(Content_.status, libraryStatus);
if (filterFavourites) contentFromAttributesQueryBuilder.equal(Content_.favourite, true);
contentFromAttributesQueryBuilder.link(Content_.attributes)
.equal(Attribute_.type, 0)
.equal(Attribute_.name, "");
Query<Content> contentFromAttributesQuery = contentFromAttributesQueryBuilder.build();
// Cumulative query loop
// Each iteration restricts the results of the next because advanced search uses an AND logic
List<Long> results = Collections.emptyList();
long[] ids;
for (Attribute attr : attrs) {
if (attr.getType().equals(AttributeType.SOURCE)) {
ids = contentFromSourceQuery.setParameter(Content_.site, attr.getId()).findIds();
} else {
ids = contentFromAttributesQuery.setParameter(Attribute_.type, attr.getType().getCode())
.setParameter(Attribute_.name, attr.getName()).findIds();
}
if (results.isEmpty()) results = Helper.getListFromPrimitiveArray(ids);
else {
// Filter results with newly found IDs (only common IDs should stay)
List<Long> idsAsList = Helper.getListFromPrimitiveArray(ids);
results.retainAll(idsAsList);
}
}
return Helper.getPrimitiveLongArrayFromList(results);
}
List<Attribute> selectAvailableSources() {
return selectAvailableSources(null);
}
List<Attribute> selectAvailableSources(List<Attribute> filter) {
List<Attribute> result = new ArrayList<>();
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, libraryStatus);
if (filter != null && !filter.isEmpty()) {
AttributeMap metadataMap = new AttributeMap();
metadataMap.addAll(filter);
List<Attribute> params = metadataMap.get(AttributeType.SOURCE);
if (params != null && !params.isEmpty())
query.in(Content_.site, getIdsFromAttributes(params));
for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) {
AttributeType attrType = entry.getKey();
if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database
List<Attribute> attrs = entry.getValue();
if (attrs != null && !attrs.isEmpty())
query.in(Content_.id, selectFilteredContent(attrs, false));
}
}
}
List<Content> content = query.build().find();
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by source
Map<Site, List<Content>> map = Stream.of(content).collect(Collectors.groupingBy(Content::getSite));
for (Map.Entry<Site, List<Content>> entry : map.entrySet()) {
Site site = entry.getKey();
int size = (null == entry.getValue()) ? 0 : entry.getValue().size();
result.add(new Attribute(AttributeType.SOURCE, site.getDescription()).setExternalId(site.getCode()).setCount(size));
}
// Order by count desc
result = Stream.of(result).sortBy(a -> -a.getCount()).collect(toList());
return result;
}
Query<Content> selectErrorContentQ() {
return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.ERROR.getCode()).orderDesc(Content_.downloadDate).build();
}
private Query<Attribute> queryAvailableAttributes(
@NonNull final AttributeType type,
String filter,
long[] filteredContent) {
QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query();
query.equal(Attribute_.type, type.getCode());
if (filter != null && !filter.trim().isEmpty())
query.contains(Attribute_.name, filter.trim(), QueryBuilder.StringOrder.CASE_INSENSITIVE);
if (filteredContent.length > 0)
query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus);
else
query.link(Attribute_.contents).in(Content_.status, libraryStatus);
return query.build();
}
long countAvailableAttributes(AttributeType
type, List<Attribute> attributeFilter, String filter, boolean filterFavourites) {
return queryAvailableAttributes(type, filter, selectFilteredContent(attributeFilter, filterFavourites)).count();
}
@SuppressWarnings("squid:S2184")
// In our case, limit() argument has to be human-readable -> no issue concerning its type staying in the int range
List<Attribute> selectAvailableAttributes(
@NonNull AttributeType type,
List<Attribute> attributeFilter,
String filter,
boolean filterFavourites,
int sortOrder,
int page,
int itemsPerPage) {
long[] filteredContent = selectFilteredContent(attributeFilter, filterFavourites);
List<Long> filteredContentAsList = Helper.getListFromPrimitiveArray(filteredContent);
List<Integer> libraryStatusAsList = Helper.getListFromPrimitiveArray(libraryStatus);
List<Attribute> result = queryAvailableAttributes(type, filter, filteredContent).find();
// Compute attribute count for sorting
long count;
for (Attribute a : result) {
count = Stream.of(a.contents)
.filter(c -> libraryStatusAsList.contains(c.getStatus().getCode()))
.filter(c -> filteredContentAsList.isEmpty() || filteredContentAsList.contains(c.getId()))
.count();
a.setCount((int) count);
}
// Apply sort order
Stream<Attribute> s = Stream.of(result);
if (Preferences.Constant.ORDER_ATTRIBUTES_ALPHABETIC == sortOrder) {
s = s.sortBy(a -> -a.getCount()).sortBy(Attribute::getName);
} else {
s = s.sortBy(Attribute::getName).sortBy(a -> -a.getCount());
}
// Apply paging
if (itemsPerPage > 0) {
int start = (page - 1) * itemsPerPage;
s = s.limit(page * itemsPerPage).skip(start); // squid:S2184 here because int * int -> int (not long)
}
return s.collect(toList());
}
SparseIntArray countAvailableAttributesPerType() {
return countAvailableAttributesPerType(null);
}
SparseIntArray countAvailableAttributesPerType(List<Attribute> attributeFilter) {
// Get Content filtered by current selection
long[] filteredContent = selectFilteredContent(attributeFilter, false);
// Get available attributes of the resulting content list
QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query();
if (filteredContent.length > 0)
query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus);
else
query.link(Attribute_.contents).in(Content_.status, libraryStatus);
List<Attribute> attributes = query.build().find();
SparseIntArray result = new SparseIntArray();
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by type
Map<AttributeType, List<Attribute>> map = Stream.of(attributes).collect(Collectors.groupingBy(Attribute::getType));
for (Map.Entry<AttributeType, List<Attribute>> entry : map.entrySet()) {
AttributeType t = entry.getKey();
int size = (null == entry.getValue()) ? 0 : entry.getValue().size();
result.append(t.getCode(), size);
}
return result;
}
void updateImageFileStatusParamsMimeTypeUriSize(@NonNull ImageFile image) {
Box<ImageFile> imgBox = store.boxFor(ImageFile.class);
ImageFile img = imgBox.get(image.getId());
if (img != null) {
img.setStatus(image.getStatus());
img.setDownloadParams(image.getDownloadParams());
img.setMimeType(image.getMimeType());
img.setFileUri(image.getFileUri());
img.setSize(image.getSize());
imgBox.put(img);
}
}
void updateImageContentStatus(
long contentId,
@Nullable StatusContent updateFrom,
@NonNull StatusContent updateTo) {
QueryBuilder<ImageFile> query = store.boxFor(ImageFile.class).query();
if (updateFrom != null) query.equal(ImageFile_.status, updateFrom.getCode());
List<ImageFile> imgs = query.equal(ImageFile_.contentId, contentId).build().find();
if (imgs.isEmpty()) return;
for (int i = 0; i < imgs.size(); i++) imgs.get(i).setStatus(updateTo);
store.boxFor(ImageFile.class).put(imgs);
}
void updateImageFileUrl(@NonNull final ImageFile image) {
Box<ImageFile> imgBox = store.boxFor(ImageFile.class);
ImageFile img = imgBox.get(image.getId());
if (img != null) {
img.setUrl(image.getUrl());
imgBox.put(img);
}
}
// Returns a list of processed images grouped by status, with count and filesize
Map<StatusContent, ImmutablePair<Integer, Long>> countProcessedImagesById(long contentId) {
QueryBuilder<ImageFile> imgQuery = store.boxFor(ImageFile.class).query();
imgQuery.equal(ImageFile_.contentId, contentId);
List<ImageFile> images = imgQuery.build().find();
Map<StatusContent, ImmutablePair<Integer, Long>> result = new EnumMap<>(StatusContent.class);
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by type
Map<StatusContent, List<ImageFile>> map = Stream.of(images).collect(Collectors.groupingBy(ImageFile::getStatus));
for (Map.Entry<StatusContent, List<ImageFile>> entry : map.entrySet()) {
StatusContent t = entry.getKey();
int count = 0;
long size = 0;
if (entry.getValue() != null) {
count = entry.getValue().size();
for (ImageFile img : entry.getValue()) size += img.getSize();
}
result.put(t, new ImmutablePair<>(count, size));
}
return result;
}
Map<Site, ImmutablePair<Integer, Long>> selectMemoryUsagePerSource() {
// Get all downloaded images regardless of the book's status
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode()});
List<Content> books = query.build().find();
Map<Site, ImmutablePair<Integer, Long>> result = new EnumMap<>(Site.class);
// SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
// (see https://github.com/objectbox/objectbox-java/issues/422)
// => Group by and count have to be done manually (thanks God Stream exists !)
// Group and count by type
Map<Site, List<Content>> map = Stream.of(books).collect(Collectors.groupingBy(Content::getSite));
for (Map.Entry<Site, List<Content>> entry : map.entrySet()) {
Site s = entry.getKey();
int count = 0;
long size = 0;
if (entry.getValue() != null) {
count = entry.getValue().size();
for (Content c : entry.getValue()) size += c.getSize();
}
result.put(s, new ImmutablePair<>(count, size));
}
return result;
}
void insertErrorRecord(@NonNull final ErrorRecord record) {
store.boxFor(ErrorRecord.class).put(record);
}
List<ErrorRecord> selectErrorRecordByContentId(long contentId) {
return store.boxFor(ErrorRecord.class).query().equal(ErrorRecord_.contentId, contentId).build().find();
}
void deleteErrorRecords(long contentId) {
List<ErrorRecord> records = selectErrorRecordByContentId(contentId);
store.boxFor(ErrorRecord.class).remove(records);
}
void insertImageFile(@NonNull ImageFile img) {
if (img.getId() > 0) store.boxFor(ImageFile.class).put(img);
}
void deleteImageFiles(long contentId) {
store.boxFor(ImageFile.class).query().equal(ImageFile_.contentId, contentId).build().remove();
}
void deleteImageFiles(List<ImageFile> images) {
store.boxFor(ImageFile.class).remove(images);
}
void insertImageFiles(@NonNull List<ImageFile> imgs) {
store.boxFor(ImageFile.class).put(imgs);
}
@Nullable
ImageFile selectImageFile(long id) {
if (id > 0) return store.boxFor(ImageFile.class).get(id);
else return null;
}
Query<ImageFile> selectDownloadedImagesFromContent(long id) {
QueryBuilder<ImageFile> builder = store.boxFor(ImageFile.class).query();
builder.equal(ImageFile_.contentId, id);
builder.in(ImageFile_.status, new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.EXTERNAL.getCode()});
builder.order(ImageFile_.order);
return builder.build();
}
void insertSiteHistory(@NonNull Site site, @NonNull String url) {
SiteHistory siteHistory = selectHistory(site);
if (siteHistory != null) {
siteHistory.setUrl(url);
store.boxFor(SiteHistory.class).put(siteHistory);
} else {
store.boxFor(SiteHistory.class).put(new SiteHistory(site, url));
}
}
@Nullable
SiteHistory selectHistory(@NonNull Site s) {
return store.boxFor(SiteHistory.class).query().equal(SiteHistory_.site, s.getCode()).build().findFirst();
}
long insertGroup(Group group) {
return store.boxFor(Group.class).put(group);
}
long insertGroupItem(GroupItem item) {
return store.boxFor(GroupItem.class).put(item);
}
long countGroupsFor(Grouping grouping) {
return store.boxFor(Group.class).query().equal(Group_.grouping, grouping.getId()).build().count();
}
Query<Group> selectGroupsQ(int grouping, int orderStyle) {
QueryBuilder<Group> qb = store.boxFor(Group.class).query().equal(Group_.grouping, grouping);
if (0 == orderStyle) qb.order(Group_.name);
// TODO implement order by number of children
// Option 1 : Post-query sorting (in ViewModel ?)
// Option 2 : Don't use LiveData
//else if (1 == orderStyle) qb.order(Group_.items);
else if (2 == orderStyle) qb.order(Group_.order);
return qb.build();
}
@Nullable
Group selectGroup(long groupId) {
return store.boxFor(Group.class).get(groupId);
}
Query<Group> selectGroupsByFlagQ(int grouping, int flag) {
return store.boxFor(Group.class).query().equal(Group_.grouping, grouping).equal(Group_.flag, flag).build();
}
/**
* ONE-SHOT USE QUERIES (MIGRATION & MAINTENANCE)
*/
List<Content> selectContentWithOldPururinHost() {
return store.boxFor(Content.class).query().contains(Content_.coverImageUrl, "://api.pururin.io/images/").build().find();
}
List<Content> selectContentWithOldTsuminoCovers() {
return store.boxFor(Content.class).query().contains(Content_.coverImageUrl, "://www.tsumino.com/Image/Thumb/").build().find();
}
List<Content> selectDownloadedContentWithNoSize() {
return store.boxFor(Content.class).query().in(Content_.status, libraryStatus).isNull(Content_.size).build().find();
}
public Query<Content> selectOldStoredContentQ() {
QueryBuilder<Content> query = store.boxFor(Content.class).query();
query.in(Content_.status, new int[]{
StatusContent.DOWNLOADING.getCode(),
StatusContent.PAUSED.getCode(),
StatusContent.DOWNLOADED.getCode(),
StatusContent.ERROR.getCode(),
StatusContent.MIGRATED.getCode()});
query.notNull(Content_.storageFolder);
query.notEqual(Content_.storageFolder, "");
return query.build();
}
long[] selectStoredContentIds(boolean nonFavouritesOnly, boolean includeQueued) {
QueryBuilder<Content> query = store.boxFor(Content.class).query();
if (includeQueued)
query.in(Content_.status, new int[]{
StatusContent.DOWNLOADING.getCode(),
StatusContent.PAUSED.getCode(),
StatusContent.DOWNLOADED.getCode(),
StatusContent.ERROR.getCode(),
StatusContent.MIGRATED.getCode()});
else
query.in(Content_.status, new int[]{
StatusContent.DOWNLOADED.getCode(),
StatusContent.MIGRATED.getCode()});
query.notNull(Content_.storageUri);
query.notEqual(Content_.storageUri, "");
if (nonFavouritesOnly) query.equal(Content_.favourite, false);
return query.build().findIds();
}
}
| Cleanup
| app/src/main/java/me/devsaki/hentoid/database/ObjectBoxDB.java | Cleanup | <ide><path>pp/src/main/java/me/devsaki/hentoid/database/ObjectBoxDB.java
<ide> QueryBuilder<Group> qb = store.boxFor(Group.class).query().equal(Group_.grouping, grouping);
<ide>
<ide> if (0 == orderStyle) qb.order(Group_.name);
<del> // TODO implement order by number of children
<del> // Option 1 : Post-query sorting (in ViewModel ?)
<del> // Option 2 : Don't use LiveData
<del> //else if (1 == orderStyle) qb.order(Group_.items);
<add> // Order by number of children is done by the DAO
<ide> else if (2 == orderStyle) qb.order(Group_.order);
<ide>
<ide> return qb.build(); |
|
Java | apache-2.0 | 5d47e3871fd1464f0ed97ace9b9ab187a362dad5 | 0 | michal-lipski/java8-workshop,nurkiewicz/java8-workshop,michal-lipski/java8-workshop | package com.nurkiewicz.java8;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
/**
* Hint: String.chars()
*/
public class J05b_StringsTest {
@Test
public void arrAllCharactersDigits() throws Exception {
assertThat(onlyDigits("+12 345-678 (90)")).isFalse();
assertThat(onlyDigits("100 200 300")).isFalse();
assertThat(onlyDigits("1234567890")).isTrue();
}
private boolean onlyDigits(String phone) {
return true;
}
@Test
public void hasAnyNonAlphabeticCharacters() throws Exception {
assertThat(anyNonAlphabetic("abc")).isFalse();
assertThat(anyNonAlphabetic("CamelCase")).isFalse();
assertThat(anyNonAlphabetic("_underscore")).isTrue();
assertThat(anyNonAlphabetic("Big bang!")).isTrue();
assertThat(anyNonAlphabetic("#%@")).isTrue();
}
private boolean anyNonAlphabetic(String s) {
return true;
}
/**
* Hint: String.join()
*/
@Test
public void shouldJoinMultipleStringsIntoString() throws Exception {
//given
final List<String> ids = Arrays.asList("1", "2", "3", "4");
//when
final String joined = "";
//then
assertThat(joined).isEqualTo("1, 2, 3, 4");
}
@Test
public void shouldJoinMultipleIntsIntoString() throws Exception {
//given
final List<Integer> ids = Arrays.asList(1, 2, 3, 4);
//when
final String joined = "";
//then
assertThat(joined).isEqualTo("1, 2, 3, 4");
}
/**
* Hint: StringJoiner
*/
@Test
public void shouldJoinSeparateInts() throws Exception {
//given
String x = "X";
String y = "Y";
String z = "Z";
//when
String joined = "";
//then
assertThat(joined).isEqualTo("<X-Y-Z>");
}
}
| src/test/java/com/nurkiewicz/java8/J05b_StringsTest.java | package com.nurkiewicz.java8;
import org.junit.Ignore;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
/**
* Hint: String.chars()
*/
@Ignore
public class J05b_StringsTest {
@Test
public void arrAllCharactersDigits() throws Exception {
assertThat(onlyDigits("+12 345-678 (90)")).isFalse();
assertThat(onlyDigits("100 200 300")).isFalse();
assertThat(onlyDigits("1234567890")).isTrue();
}
private boolean onlyDigits(String phone) {
return true;
}
@Test
public void hasAnyNonAlphabeticCharacters() throws Exception {
assertThat(anyNonAlphabetic("abc")).isFalse();
assertThat(anyNonAlphabetic("CamelCase")).isFalse();
assertThat(anyNonAlphabetic("_underscore")).isTrue();
assertThat(anyNonAlphabetic("Big bang!")).isTrue();
assertThat(anyNonAlphabetic("#%@")).isTrue();
}
private boolean anyNonAlphabetic(String s) {
return true;
}
}
| String tests
| src/test/java/com/nurkiewicz/java8/J05b_StringsTest.java | String tests | <ide><path>rc/test/java/com/nurkiewicz/java8/J05b_StringsTest.java
<ide> package com.nurkiewicz.java8;
<ide>
<del>import org.junit.Ignore;
<ide> import org.junit.Test;
<add>
<add>import java.util.Arrays;
<add>import java.util.List;
<ide>
<ide> import static org.fest.assertions.api.Assertions.assertThat;
<ide>
<ide> /**
<ide> * Hint: String.chars()
<ide> */
<del>@Ignore
<ide> public class J05b_StringsTest {
<ide>
<ide> @Test
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * Hint: String.join()
<add> */
<add> @Test
<add> public void shouldJoinMultipleStringsIntoString() throws Exception {
<add> //given
<add> final List<String> ids = Arrays.asList("1", "2", "3", "4");
<add>
<add> //when
<add> final String joined = "";
<add>
<add> //then
<add> assertThat(joined).isEqualTo("1, 2, 3, 4");
<add> }
<add>
<add> @Test
<add> public void shouldJoinMultipleIntsIntoString() throws Exception {
<add> //given
<add> final List<Integer> ids = Arrays.asList(1, 2, 3, 4);
<add>
<add> //when
<add> final String joined = "";
<add>
<add> //then
<add> assertThat(joined).isEqualTo("1, 2, 3, 4");
<add> }
<add>
<add> /**
<add> * Hint: StringJoiner
<add> */
<add> @Test
<add> public void shouldJoinSeparateInts() throws Exception {
<add> //given
<add> String x = "X";
<add> String y = "Y";
<add> String z = "Z";
<add>
<add> //when
<add> String joined = "";
<add>
<add> //then
<add> assertThat(joined).isEqualTo("<X-Y-Z>");
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | b98d315050d82843a31158dfe18ab9e79c70d8b3 | 0 | shinymayhem/radio-presets-widget | /*
* Copyright (C) 2013 Reese Wilson | Shiny Mayhem
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.shinymayhem.radiopresets;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.webkit.URLUtil;
import android.widget.Toast;
public class RadioPlayer extends Service implements OnPreparedListener, OnBufferingUpdateListener, OnInfoListener, OnCompletionListener, OnErrorListener, OnAudioFocusChangeListener {
public final static int ONGOING_NOTIFICATION = 1;
//public final static String ACTION = "com.shinymayhem.radiopresets.ACTION";
public final static String ACTION_STOP = "com.shinymayhem.radiopresets.ACTION_STOP";
public final static String ACTION_PLAY = "com.shinymayhem.radiopresets.ACTION_PLAY";
public final static String ACTION_NEXT = "com.shinymayhem.radiopresets.ACTION_NEXT";
public final static String ACTION_PREVIOUS = "com.shinymayhem.radiopresets.ACTION_PREVIOUS";
public final static String ACTION_MEDIA_BUTTON = "com.shinymayhem.radiopresets.MEDIA_BUTTON";
public String state = STATE_UNINITIALIZED;
public final static String STATE_UNINITIALIZED = "Uninitialized";
public final static String STATE_INITIALIZING = "Initializing";
public final static String STATE_PREPARING = "Preparing";
public final static String STATE_PLAYING = "Playing";
public final static String STATE_BUFFERING = "Buffering";
public final static String STATE_PAUSED = "Paused";
public final static String STATE_PHONE = "Phone";
public final static String STATE_ERROR = "Error";
public final static String STATE_RESTARTING = "Restarting";
public final static String STATE_STOPPING = "Stopping";
public final static String STATE_STOPPED = "Stopped";
public final static String STATE_COMPLETE = "Complete";
public final static String STATE_END = "Ended";
public final static int NETWORK_STATE_DISCONNECTED = -1;
protected NetworkInfo mNetworkInfo;
protected int mNetworkState;
protected MediaPlayer mMediaPlayer;
protected MediaPlayer mNextPlayer;
private NetworkReceiver mReceiver;
private NoisyAudioStreamReceiver mNoisyReceiver;
private PhoneCallReceiver mPhoneReceiver;
private AudioManager mAudioManager;
private boolean mMediaButtonEventReceiverRegistered = false;
private MediaButtonReceiver mButtonReceiver;// = new MediaButtonReceiver();
//private OnAudioFocusChangeListener mFocusListener;
private boolean mAudioFocused = false;
protected String mUrl;
protected String mTitle;
protected int mPreset;
protected boolean mInterrupted = false;
private final IBinder mBinder = new LocalBinder();
protected boolean mBound = false;
protected Logger mLogger = new Logger();
protected Intent mIntent;
protected NotificationManager mNotificationManager;
public class LocalBinder extends Binder
{
RadioPlayer getService()
{
return RadioPlayer.this;
}
}
@Override
public void onCreate()
{
log("onCreate()", "d");
//initialize managers
if (mNotificationManager == null)
{
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
if (mAudioManager == null)
{
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
//remove pending intents if they exist
stopInfo();
registerNetworkReceiver();
registerButtonReceiver();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
log("onStartCommand()", "d");
//check if resuming after close for memory, or other crash
if ((flags & Service.START_FLAG_REDELIVERY) != 0)
{
log("------------------------------------------", "v");
log("intent redelivery, restarting. maybe handle this with dialog? notification with resume action?", "v");
log("------------------------------------------", "v");
}
mIntent = intent;
if (intent == null)
{
log("no intent", "w");
}
else
{
//TODO find out why service starts again after STOP action in intent (does it still?)
String action = intent.getAction();
if (action == null)
{
log("no action specified, not sure why", "w");
//return flag indicating no further action needed if service is stopped by system and later resumes
return START_NOT_STICKY;
}
else if (action.equals(Intent.ACTION_RUN)) //called when service is being bound
{
log("service being started before bound", "v");
return START_NOT_STICKY;
}
else if (action.equals(ACTION_PLAY.toString())) //Play intent
{
log("PLAY action in intent", "v");
int preset = Integer.valueOf(intent.getIntExtra(MainActivity.EXTRA_STATION_PRESET, 0));
log("preset in action:" + String.valueOf(preset), "v");
play(preset);
//return START_REDELIVER_INTENT;
return START_NOT_STICKY;
}
else if (action.equals(ACTION_NEXT.toString())) //Next preset intent
{
log("NEXT action in intent", "v");
nextPreset();
return START_NOT_STICKY;
}
else if (action.equals(ACTION_PREVIOUS.toString())) //Previous preset intent
{
log("PREVIOUS action in intent", "v");
previousPreset();
return START_NOT_STICKY;
}
else if (action.equals(ACTION_STOP.toString())) //Stop intent
{
log("STOP action in intent", "v");
end();
return START_NOT_STICKY;
}
else
{
String str = "Unknown Action:";
str += action;
log(str, "w");
//Log.i(getPackageName(), str);
}
}
//return START_STICKY;
return START_NOT_STICKY;
//return START_REDELIVER_INTENT;
}
@SuppressLint("NewApi")
public void onPrepared(MediaPlayer mediaPlayer)
{
log("onPrepared()", "d");
if (state.equals(RadioPlayer.STATE_RESTARTING) || state.equals(RadioPlayer.STATE_COMPLETE))
{
log("newPlayer ready", "i");
}
else
{
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
mAudioFocused = true;
log("mediaPlayer.start()", "v");
mediaPlayer.start();
state = RadioPlayer.STATE_PLAYING;
if (mInterrupted)
{
log("set interrupted = false", "v");
}
mInterrupted = false;
Notification notification = updateNotification("Playing", "Stop", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
startForeground(ONGOING_NOTIFICATION, notification);
log("start foreground notification: playing", "v");
Toast.makeText(this, "Playing", Toast.LENGTH_SHORT).show();
}
else if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED)
{
mAudioFocused = false;
log("audio focus failed", "w");
//TODO find a better way to deal with this
Toast.makeText(this, "Could not gain audio focus", Toast.LENGTH_SHORT).show();
}
}
}
public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra)
{
log("onInfo()", "d");
//TextView status = (TextView) findViewById(R.id.status);
if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END)
{
//Log.i(getPackageName(), "done buffering");
log("done buffering", "v");
if (mediaPlayer.isPlaying())
{
// status.setText("Playing");
}
else
{
// status.setText("Stopped");
}
Notification notification = updateNotification("Playing", "Stop", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
state = RadioPlayer.STATE_PLAYING;
return true;
}
else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START)
{
log("start buffering", "v");
//Log.i(getPackageName(), "start buffering");
//status.setText("Buffering...");
Notification notification = updateNotification("Buffering", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
state = RadioPlayer.STATE_BUFFERING;
return true;
}
else if (what == 703)
{
String str = "bandwidth:";
str += extra;
log(str, "v");
//Log.i(getPackageName(), str);
}
else
{
log("media player info", "v");
//Log.i(getPackageName(), "media player info");
}
/*String statusString = "\nInfo: ";
statusString += what;
statusString += ":";
statusString += extra;
status.append(statusString);*/
return false;
}
@Override
public void onBufferingUpdate(MediaPlayer player, int percent) {
log("buffering percent:" + String.valueOf(percent), "v");
}
public void onCompletion(MediaPlayer mediaPlayer)
{
//mediaPlayer.reset();
//mediaPlayer.release();
log("onCompletion()", "d");
state = RadioPlayer.STATE_COMPLETE;
//TODO update notification?
if (mInterrupted)
{
Toast.makeText(this, "Playback completed after interruption", Toast.LENGTH_SHORT).show();
log("Playback completed after interruption, should restart when network connects again", "v");
}
else
{
//still an interruption, streaming shouldn't complete
Toast.makeText(this, "Playback completed, no interruption reported", Toast.LENGTH_SHORT).show();
log("Playback completed, no network interruption reported, restart", "v");
//restart();
play();
}
if (mNextPlayer != null)
{
log("swapping players", "v");
mediaPlayer.release();
mediaPlayer = mNextPlayer;
mNextPlayer = null;
if (mediaPlayer.isPlaying())
{
state = RadioPlayer.STATE_PLAYING;
if (mInterrupted)
{
log("set interrupted = false", "v");
}
mInterrupted = false;
log("new player playing", "i");
//TODO update notification to indicate resumed playback
}
else
{
log("new player not playing", "w");
}
}
else
{
log("no next player specified", "w");
}
//stopForeground(true);
//playing = false;
//TextView status = (TextView) findViewById(R.id.status);
//status.append("\nComplete");
}
public boolean onError(MediaPlayer mediaPlayer, int what, int extra)
{
log("onError()", "e");
//check if mediaPlayer is or needs to be released
stopInfo(getResources().getString(R.string.widget_error_status)); //stopForeground(true);
if (mediaPlayer != null)
{
try
{
if (state != RadioPlayer.STATE_PREPARING)
{
mediaPlayer.stop();
}
log("media player stopped", "v");
}
catch (IllegalStateException e)
{
log("Illegal state to stop. uninitialized? not yet prepared?", "e");
}
mediaPlayer.release();
mediaPlayer = null;
mMediaPlayer = null;
}
String oldState = state;
state = RadioPlayer.STATE_ERROR;
//TextView status = (TextView) findViewById(R.id.status);
String statusString = "";
if (oldState.equals("Preparing"))
{
//TODO notify user somehow
statusString = "An error occurred while trying to connect to the server. ";
if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == -2147483648)
{
statusString += "Bad URL or file format?";
}
}
else
{
statusString = "Not error while preparing:";
}
if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == MediaPlayer.MEDIA_ERROR_IO)
{
statusString += "Media IO Error";
}
else if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT)
{
statusString += "Timed out";
}
else
{
statusString += what;
statusString += ":";
statusString += extra;
}
log(statusString, "e");
//status.append(statusString);
Toast.makeText(this, statusString, Toast.LENGTH_LONG).show();
if (oldState.equals("Preparing"))
{
stop();
}
return false;
}
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
{
mAudioFocused = false;
log("AUDIOFOCUS_LOSS_TRANSIENT", "v");
// Pause playback
pause();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mAudioFocused = true;
log("AUDIOFOCUS_GAIN", "v");
// Resume playback or unduck
if (!isPlaying())
{
if (mPreset == 0)
{
//should this really start playing?
play(1); //TODO get from storage
}
}
else
{
if (state.equals(STATE_PAUSED))
{
resume();
}
else
{
log("focus gained, but not resumed?", "w");
//play();
}
}
unduck();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
log("AUDIOFOCUS_LOSS", "v");
if (mMediaButtonEventReceiverRegistered)
{
log("unregister button receiver", "v");
mAudioManager.unregisterMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
mMediaButtonEventReceiverRegistered = false;
}
else
{
log("button receiver already unregistered", "v");
}
if (mAudioFocused)
{
log("abandon focus", "v");
mAudioManager.abandonAudioFocus(this);
mAudioFocused = false;
}
else
{
log("focus already abandoned", "v");
}
// Stop playback
stop();
}
else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// Lower the volume
log("AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK", "v");
duck();
}
}
private void duck()
{
log("duck()", "v");
//mDucked = true;
if (mMediaPlayer != null)
{
int volume = 20;
float log1=(float)(Math.log(100-volume)/Math.log(100));
log("lowering volume to " + String.valueOf(log1), "v");
mMediaPlayer.setVolume(1-log1, 1-log1);
//mMediaPlayer.setVolume(leftVolume, rightVolume)
}
}
private void unduck()
{
log("unduck()", "v");
//mDucked = false;
if (mMediaPlayer != null)
{
mMediaPlayer.setVolume(1, 1);
//mMediaPlayer.setVolume(leftVolume, rightVolume)
}
}
private void stopInfo(String status)
{
stopForeground(true);
this.updateWidget(getResources().getString(R.string.widget_initial_title), status);
}
private void stopInfo()
{
this.stopInfo(getResources().getString(R.string.widget_stopped_status));
}
private void registerNetworkReceiver()
{
//register network receiver
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
if (mReceiver != null)
{
log("------------------------------------------", "v");
log("network receiver already registered, find out why", "w");
log("------------------------------------------", "v");
this.unregisterReceiver(mReceiver);
mReceiver = null;
}
mReceiver = new NetworkReceiver();
log("registering network change broadcast receiver", "v");
this.registerReceiver(mReceiver, filter);
}
private void registerButtonReceiver()
{
//register media button receiver
if (mButtonReceiver != null)
{
log("media button listener already registered", "v");
this.unregisterReceiver(mButtonReceiver);
mButtonReceiver = null;
}
log("register media button listener", "v");
mButtonReceiver = new MediaButtonReceiver();
registerReceiver(mButtonReceiver, new IntentFilter(ACTION_MEDIA_BUTTON));
//set RemoteControlReceiver to be the sole receiver of media button actions
if (mMediaButtonEventReceiverRegistered == false)
{
log("registering media button listener", "v");
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
mMediaButtonEventReceiverRegistered = true;
}
}
protected PendingIntent getPreviousIntent()
{
Intent intent = new Intent(this, RadioPlayer.class).setAction(ACTION_PREVIOUS);
return PendingIntent.getService(this, 0, intent, 0);
}
protected PendingIntent getStopIntent()
{
Intent intent = new Intent(this, RadioPlayer.class).setAction(ACTION_STOP);
return PendingIntent.getService(this, 0, intent, 0);
}
protected PendingIntent getNextIntent()
{
Intent intent = new Intent(this, RadioPlayer.class).setAction(ACTION_NEXT);
return PendingIntent.getService(this, 0, intent, 0);
}
protected void play()
{
log("play()", "d");
/*if (this.mUrl == null)
{
log("url not set", "e");
}
else
{
String str = "url:";
str += this.mUrl;
log(str, "v");
}
this.play(this.mUrl);*/
if (mPreset == 0)
{
log("preset = 0", "e");
}
play(mPreset);
}
//called from bound ui, possibly notification action, if implemented
//possible start states: any
protected void play(int preset)
{
log("play(preset)", "d");
if (preset == 0)
{
log("preset = 0", "e");
throw new IllegalArgumentException("Preset = 0");
}
this.mPreset = preset;
state = RadioPlayer.STATE_INITIALIZING;
if (isConnected())
{
log("setting network type", "v");
mNetworkState = this.getConnectionType();
}
else
{
//TODO handle this, let user know
log("setting network state to disconnected", "v");
mNetworkState = RadioPlayer.NETWORK_STATE_DISCONNECTED;
//TODO ask user if it should play on network resume
Toast.makeText(this, "tried to play with no network", Toast.LENGTH_LONG).show();
log("no network, should be handled by ui? returning", "e");
//if disconnected while preparing, mediaplayer is null, then getting here will stop playback attempts
if (mInterrupted)
{
log("interrupted, so set state to playing so it will wait for network to resume", "v");
state = RadioPlayer.STATE_PLAYING;
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
}
else
{
log("wasn't interrupted, so remove any notifications and reset to uninitialized", "v");
state = RadioPlayer.STATE_UNINITIALIZED;
if (mMediaPlayer != null)
{
log("media player not null, releasing", "v");
mMediaPlayer.release();
mMediaPlayer = null;
}
stopInfo(); //stopForeground(true);
}
return;
}
this.mPreset = preset;
Uri uri = Uri.parse(RadioContentProvider.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(preset));
String[] projection = {RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER, RadioDbContract.StationEntry.COLUMN_NAME_TITLE, RadioDbContract.StationEntry.COLUMN_NAME_URL};
String selection = null;
String[] selectionArgs = null;
String sortOrder = RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int count = cursor.getCount();
if (count < 1)
{
log("no results found", "e");
throw new SQLiteException("Selected preset not found"); //TODO find correct exception to throw, or handle this some other way
}
else
{
cursor.moveToFirst();
mPreset = (int)cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
mTitle = cursor.getString(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_TITLE));
mUrl = cursor.getString(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_URL));
}
//begin listen for headphones unplugged
if (mNoisyReceiver == null)
{
mNoisyReceiver = new NoisyAudioStreamReceiver();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(mNoisyReceiver, intentFilter);
log("register noisy receiver", "v");
}
else
{
log("noisy receiver already registered", "v");
}
//begin listen for phone call
if (mPhoneReceiver == null)
{
mPhoneReceiver = new PhoneCallReceiver();
IntentFilter intentFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(mPhoneReceiver, intentFilter);
log("register phone receiver", "v");
}
else
{
log("phone receiver already registered", "v");
}
if (mMediaPlayer != null)
{
log("releasing old media player", "v");
mMediaPlayer.release();
mMediaPlayer = null;
}
log("creating new media player", "v");
this.mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//str += mUrl;
log("setting datasource for '" + mTitle + "' at '" + mUrl + "'", "v");
try
{
mMediaPlayer.setDataSource(mUrl);
}
catch (IOException e)
{
//TODO handle this somehow, let user know
log("setting data source failed", "e");
Toast.makeText(this, "Setting data source failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
initializePlayer(mMediaPlayer);
state = RadioPlayer.STATE_PREPARING;
Notification notification = updateNotification("Preparing", "Cancel", true);
//mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
startForeground(ONGOING_NOTIFICATION, notification);
updateWidget("Preparing");
mMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
log("preparing async", "d");
Toast.makeText(this, "Preparing", Toast.LENGTH_SHORT).show();
}
protected void nextPreset()
{
log("nextPreset()", "v");
mPreset++;
Uri uri = Uri.parse(RadioContentProvider.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(mPreset));
String[] projection = {RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER};
String selection = null;
String[] selectionArgs = null;
String sortOrder = RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int count = cursor.getCount();
if (count < 1 && mPreset == 1)
{
log("no stations, unless db integrity lost", "w");
return; //TODO notify user?
}
else if (count < 1)
{
mPreset = 0;
log("incremented preset but nothing found, must be at end, start at 1", "v");
this.nextPreset(); //try again, starting at 0
}
else
{
cursor.moveToFirst();
mPreset = (int)cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
log("incremented preset, playing " + String.valueOf(mPreset), "v");
play();
}
}
//FIXME duplicate code from radioContentProvider
protected int getMaxPresetNumber()
{
Uri uri = RadioContentProvider.CONTENT_URI_PRESETS_MAX;
String[] projection = null;
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
long preset = 0;
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
preset = cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
}
cursor.close();
return (int)preset;
}
protected void previousPreset()
{
log("previousPreset()", "v");
mPreset--;
if (mPreset <= 0)
{
////call() not supported until api 11
//Uri maxUri = RadioContentProvider.CONTENT_URI_PRESETS_MAX;
//Bundle values = getContentResolver().call(maxUri, "getMaxPresetNumber", null, null);
//mPreset = values.getInt(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER);
mPreset = getMaxPresetNumber();
if (mPreset == 0) //no stations?
{
log("no stations, unless getMaxPresetNumber doesn't work", "w");
return; //TODO notify user?
}
//play();
//return;
}
//find out if the desired station exists
Uri uri = Uri.parse(RadioContentProvider.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(mPreset));
String[] projection = {RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER};
String selection = null;
String[] selectionArgs = null;
String sortOrder = RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int count = cursor.getCount();
if (count < 1)
{
log("no station found below current, but not 0", "e");
throw new SQLiteException("No station found below current, but not 0"); //TODO find correct exception to throw, or handle this some other way
}
else
{
cursor.moveToFirst();
mPreset = (int)cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
log("decremented preset, playing " + String.valueOf(mPreset), "v");
play();
}
}
protected void setVolume(int percent)
{
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int newVolume = (int)((long)(percent/100)*maxVolume);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
/*log("setting volume to " + String.valueOf(percent), "v");
float log1=(float)(Math.log(100-percent)/Math.log(100));
log("lowering volume to " + String.valueOf(log1), "v");
mMediaPlayer.setVolume(1-log1, 1-log1);*/
}
protected Intent getWidgetUpdateIntent(String text1, String text2)
{
Intent intent = new Intent(this, com.shinymayhem.radiopresets.PresetButtonsWidgetProvider.class);
intent.setAction(PresetButtonsWidgetProvider.ACTION_UPDATE_TEXT);
intent.putExtra(com.shinymayhem.radiopresets.PresetButtonsWidgetProvider.EXTRA_TEXT1, text1);
intent.putExtra(com.shinymayhem.radiopresets.PresetButtonsWidgetProvider.EXTRA_TEXT2, text2);
//intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
protected void updateWidget(String text)
{
Intent intent = this.getWidgetUpdateIntent(String.valueOf(mPreset) + ". " + mTitle, text);
this.sendBroadcast(intent);
}
protected void updateWidget(String title, String status)
{
Intent intent = this.getWidgetUpdateIntent(title, status);
this.sendBroadcast(intent);
}
protected Notification updateNotification(String status, String stopText, boolean updateTicker)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(String.valueOf(mPreset) + ". " + mTitle)
.setContentText(status)
//.addAction(R.drawable.av_previous, getResources().getString(R.string.previous), getPreviousIntent())
//.addAction(R.drawable.av_stop, stopText, getStopIntent())
//.addAction(R.drawable.av_next, getResources().getString(R.string.next), getNextIntent())
.addAction(R.drawable.av_previous, null, getPreviousIntent())
.addAction(R.drawable.av_stop, null, getStopIntent())
.setUsesChronometer(true)
.addAction(R.drawable.av_next, null, getNextIntent())
.setLargeIcon(((BitmapDrawable)getResources().getDrawable(R.drawable.app_icon)).getBitmap())
.setSmallIcon(R.drawable.app_notification);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//TODO taskstack builder only available since 4.1
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
//stackBuilder.addNextIntent(nextIntent)
Intent resultIntent = new Intent(this, MainActivity.class);
//resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); //why is this not needed?
stackBuilder.addNextIntent(resultIntent);
PendingIntent intent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(intent);
if (updateTicker)
{
builder.setTicker(status);
//startForeground(ONGOING_NOTIFICATION, builder.build());
}
else
{
//mNotificationManager.notify(ONGOING_NOTIFICATION, builder.build());
}
this.updateWidget(status);
return builder.build();
}
protected void initializePlayer(MediaPlayer player)
{
log("initializePlayer()", "d");
player.setOnPreparedListener(this);
player.setOnInfoListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
player.setOnBufferingUpdateListener(this);
return;
}
protected void pause()
{
log("pause()", "v");
if (mMediaPlayer == null)
{
log("null media player", "w");
}
else if (state.equals(RadioPlayer.STATE_PREPARING))
{
log("pause called while preparing", "v");
mMediaPlayer.release();
mMediaPlayer = null;
}
else
{
log("pause playback", "v");
mMediaPlayer.stop();
if (mAudioFocused)
{
log("abandon audio focus", "v");
mAudioManager.abandonAudioFocus(this);
}
else
{
log("audio focus already abandoned", "w");
}
mMediaPlayer.release();
mMediaPlayer = null;
}
Notification notification = updateNotification("Paused", "Cancel", false);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
/*try
{
unregisterReceiver(mNoisyReceiver);
mNoisyReceiver = null;
log("unregistering noisyReceiver", "v");
}
catch (IllegalArgumentException e)
{
log("noisyReceiver already unregistered", "e");
}*/
state = STATE_PAUSED;
}
protected void resume()
{
log("resume()", "v");
/*mNoisyReceiver = new NoisyAudioStreamReceiver();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(mNoisyReceiver, intentFilter);
log("register noisy receiver", "v");*/
play();
}
//called from onDestroy, end
protected void stop()
{
log("stop()", "d");
/*
log("Stop button received, sending stop intent", "d");
Intent intent = new Intent(this, RadioPlayer.class);
intent.setAction(RadioPlayer.ACTION_STOP);
startService(intent);*/
//stop command called, reset interrupted flag
if (mInterrupted)
{
log("set interrupted = false", "v");
}
mInterrupted = false;
if (state.equals(RadioPlayer.STATE_STOPPED) || state.equals(RadioPlayer.STATE_END) || state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
log("already stopped", "v");
return;
}
if (mMediaPlayer == null)
{
state = RadioPlayer.STATE_STOPPING;
log("null media player", "w");
}
else if (state.equals(RadioPlayer.STATE_PREPARING))
{
state = RadioPlayer.STATE_STOPPING; //store oldstate to move state change outside of conditionals
log("stop called while preparing", "v");
stopInfo(); //stopForeground(true);
mMediaPlayer.release();
mMediaPlayer = null;
}
else
{
state = RadioPlayer.STATE_STOPPING;
log("stopping playback", "v");
Toast.makeText(this, "Stopping playback", Toast.LENGTH_SHORT).show();
stopInfo(); //stopForeground(true);
mMediaPlayer.stop();
if (mAudioFocused == true)
{
log("abandon audio focus", "v");
mAudioManager.abandonAudioFocus(this);
}
else
{
log("focus already abandoned", "w");
}
//mediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
try
{
unregisterReceiver(mNoisyReceiver);
mNoisyReceiver = null;
log("unregistering noisyReceiver", "v");
}
catch (IllegalArgumentException e)
{
log("noisyReceiver already unregistered", "e");
}
try
{
unregisterReceiver(mPhoneReceiver);
mPhoneReceiver = null;
log("unregistering phoneReceiver", "v");
}
catch (IllegalArgumentException e)
{
log("phoneReceiver already unregistered", "e");
}
//clear any intents so player isn't started accidentally
//log("experimental fix for service autostarting, redeliver-intent flag", "v");
//mIntent.setAction(null);
state = RadioPlayer.STATE_STOPPED;
}
//called from unbound, headphones unplugged, notification->stop
protected void end()
{
log("end()", "d");
stop();
if (!mBound)
{
log("not bound, stopping service with stopself", "d");
stopSelf();
//Intent intent = new Intent(this, RadioPlayer.class);
//stopSelf();
//only stops service intent started with play action? not sure. not even sure if that would work
//what should happen is
//intent.setAction(RadioPlayer.ACTION_PLAY);
//this.stopService(intent);
state = RadioPlayer.STATE_END;
}
else
{
String str = "still bound";
log(str, "v");
}
}
//called from onComplete or network change if no network and was playing
/*
protected void restart()
{
log("restart()", "d");
state = RadioPlayer.STATE_RESTARTING;
if (mNextPlayer != null)
{
log("nextPlayer not null","e");
mNextPlayer.release();
mNextPlayer = null;
}
this.mNextPlayer = new MediaPlayer();
mNextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
String str = "setting nextPlayer data source: ";
str += mUrl;
log(str, "v");
try
{
mNextPlayer.setDataSource(mUrl);
}
catch (IOException e)
{
//TODO handle this somehow
log("setting nextPlayer data source failed", "e");
Toast.makeText(this, "Setting data source failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
initializePlayer(mNextPlayer);
//TODO handle older versions
//check for errors or invalid states
try
{
mMediaPlayer.stop();
}
catch (IllegalStateException e)
{
log("old player in wrong state to stop", "e");
}
try
{
boolean playing = mMediaPlayer.isPlaying();
if (playing)
{
log("old player playing, new player ready to set", "v");
}
else
{
log("old player not playing, might not be safe to setnext", "w");
}
}
catch (IllegalStateException e)
{
log("old player in wrong state to check if playing", "e");
}
//check to see if playback completed
if (state == RadioPlayer.STATE_COMPLETE)
{
log("playback completed", "e");
return;
}
try
{
mMediaPlayer.setNextMediaPlayer(mNextPlayer);
log("nextplayer set", "v");
}
catch (IllegalStateException e)
{
log("old player in wrong state to setnext", "e");
}
//if (mediaPlayer.isPlaying())
//{
// log("was still playing, stopping", "v");
// mediaPlayer.stop();
//}
//log("restarting/preparing", "v");
//mediaPlayer.prepareAsync();
//Log.i(getPackageName(), "restarting playback");
//if (playing)
//{
// mediaPlayer.stop();
// mediaPlayer.release();
// playing = false;
//}
//play();
}
*/
public boolean isPlaying()
{
return (
state.equals(RadioPlayer.STATE_BUFFERING) ||
state.equals(RadioPlayer.STATE_PLAYING) ||
state.equals(RadioPlayer.STATE_PAUSED) ||
state.equals(RadioPlayer.STATE_PHONE) ||
state.equals(RadioPlayer.STATE_PREPARING) ||
state.equals(RadioPlayer.STATE_INITIALIZING) ||
state.equals(RadioPlayer.STATE_COMPLETE) || //service should still stay alive and listen for network changes to resume
state.equals(RadioPlayer.STATE_RESTARTING)
);
}
protected boolean isConnected()
{
ConnectivityManager network = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = network.getActiveNetworkInfo();
mNetworkInfo = info;
if (info == null)
{
return false;
}
return true;
}
protected int getConnectionType()
{
String str = "";
int newState = mNetworkInfo.getType();
switch (newState)
{
case ConnectivityManager.TYPE_WIFI:
str += "wifi";
break;
case ConnectivityManager.TYPE_MOBILE:
str += "mobile";
break;
case ConnectivityManager.TYPE_MOBILE_DUN:
str += "mobile-dun";
break;
case ConnectivityManager.TYPE_MOBILE_HIPRI:
str += "moblie-hipri";
break;
case ConnectivityManager.TYPE_MOBILE_MMS:
str += "mobile-mms";
break;
case ConnectivityManager.TYPE_MOBILE_SUPL:
str += "mobile-supl";
break;
case ConnectivityManager.TYPE_WIMAX:
str += "wimax";
break;
case ConnectivityManager.TYPE_ETHERNET:
str += "ethernet";
break;
case ConnectivityManager.TYPE_BLUETOOTH:
str += "bluetooth";
break;
case ConnectivityManager.TYPE_DUMMY:
str += "dummy";
break;
}
str += " detected";
log(str, "v");
return newState;
}
public static boolean validateUrl(String url)
{
if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url))
{
//log("not a valid http or https url", "v");
return false;
}
//check for empty after prefix
if (url == "http://" || url == "https://")
{
return false;
}
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try
{
mediaPlayer.setDataSource(url);
mediaPlayer.release();
}
catch (IOException e)
{
return false;
}
return true;
}
@Override
public IBinder onBind(Intent intent) {
log("onBind()", "d");
//Log.i(getPackageName(), "binding service");
mBound=true;
return mBinder;
}
@Override
public void onRebind(Intent intent)
{
log("onRebind()", "d");
//Log.i(getPackageName(), "rebinding service");
}
@Override
public boolean onUnbind(Intent intent)
{
log("onUnbind()", "d");
//Log.i(getPackageName(), "unbinding service");
mBound = false;
if (!isPlaying())
{
end();
}
return false;
}
@Override
public void onDestroy() {
log("onDestroy()", "d");
this.stop();
Toast.makeText(this, "Stopping service", Toast.LENGTH_SHORT).show();
//don't need to listen for network changes anymore
if (mReceiver != null) {
log("unregister network receiver", "v");
this.unregisterReceiver(mReceiver);
mReceiver = null;
}
else
{
log("unregistering network receiver failed, null", "e");
}
if (mButtonReceiver != null) {
log("unregister media button receiver", "v");
this.unregisterReceiver(mButtonReceiver);
mButtonReceiver = null;
}
else
{
log("unregistering network receiver failed, null", "e");
}
}
public class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("received remote control action", "v");
if (ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
switch (event.getKeyCode())
{
case KeyEvent.KEYCODE_MEDIA_PLAY:
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
nextPreset();
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
previousPreset();
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_STOP:
stop();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_HEADSETHOOK:
if (isPlaying() && state != STATE_PAUSED)
{
pause();
}
else
{
if (mPreset == 0) //TODO store last played preset somewhere
{
play(1);
}
else
{
resume();
}
}
default:
log("other button:" + String.valueOf(event.getKeyCode()), "v");
}
}
else
{
log("other remote action?", "v");
}
}
}
private class NoisyAudioStreamReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (state != STATE_PHONE && state != STATE_PAUSED && AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
log("headphones unplugged", "v");
end();
}
else
{
log("headphones unplugged, but it is paused", "v");
}
}
}
private class PhoneCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("phone call receiver onReceive()", "v");
String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
log("phone ringing", "v");
if (isPlaying())
{
pause();
state = STATE_PHONE;
}
}
else if (phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE) && state.equals(STATE_PHONE))
{
log("resuming after phone call", "v");
resume();
}
else
{
log("outgoing phone call?", "v");
if (isPlaying())
{
pause();
state = STATE_PHONE;
}
}
}
}
//handle network changes
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("received network change broadcast", "v");
//Log.i(getPackageName(), "received network change broadcast");
if (mMediaPlayer == null && state.equals(RadioPlayer.STATE_PREPARING))
{
log("recover from disconnect while preparing", "v");
//Log.i(getPackageName(), "no media player, don't care about connection updates");
play();
return;
}
else if (mMediaPlayer == null && state != RadioPlayer.STATE_UNINITIALIZED)
{
log("media player null, will cause problems if connected", "e");
}
else if (mMediaPlayer != null && state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
log("-------------------------------", "d");
log ("mediaPlayer not null, but uninitialized. how did this happen?", "w");
log("-------------------------------", "d");
}
String str = "";
if (isConnected())
{
int newState = getConnectionType();
if (mNetworkState != newState)
{
str = "network type changed";
if (state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
str += " but uninitialized so it doesn't matter. ";
}
else if (state.equals(RadioPlayer.STATE_STOPPED) || state.equals(RadioPlayer.STATE_STOPPING))
{
str += " but stopped so it doesn't matter. ";
}
else if (state.equals(RadioPlayer.STATE_END))
{
str += " but ended so it doesn't matter. ";
}
else if (state.equals(RadioPlayer.STATE_PAUSED) || state.equals(RadioPlayer.STATE_PHONE))
{
str += " but paused so it doesn't matter. ";
}
else if (mInterrupted == false)
{
Notification notification = updateNotification("Network updated, reconnecting", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
str += " and now interrupted";
mInterrupted = true;
}
else
{
str += " but previously interrupted";
}
str += "old:" + mNetworkState;
str += ", new:" + newState;
log(str, "v");
log("setting network state ivar", "v");
mNetworkState = newState;
//if uninitialized, no preset picked yet. if stopped or paused, don't restart
if (state.equals(RadioPlayer.STATE_UNINITIALIZED) ||
state.equals(RadioPlayer.STATE_STOPPED) ||
state.equals(RadioPlayer.STATE_STOPPING) ||
state.equals(RadioPlayer.STATE_PAUSED) ||
state.equals(RadioPlayer.STATE_PHONE) ||
state.equals(RadioPlayer.STATE_END)
)
{
log("unitialized or stopped/paused/ended, don't try to start or restart", "v");
return;
}
boolean start = false;
if (mMediaPlayer == null)
{
log("-------------------------------", "d");
log("find out how we got here", "e");
log("trying to play when not connected?", "v");
log("disconnected while initializing? ", "v");
log("-------------------------------", "d");
}
else
{
try
{
mMediaPlayer.isPlaying();
}
catch (IllegalStateException e)
{
log("illegal state detected, can't restart, start from scratch instead", "e");
start = true;
}
//can't set nextplayer after complete, so just start fresh
if (state.equals(RadioPlayer.STATE_COMPLETE) || start)
{
log("complete or start=true", "v");
}
//network interrupted playback but isn't done playing from buffer yet
//set nextplayer and wait for current player to complete
else
{
log("!complete && start!=true", "v");
//play();
//TODO figure out if restart is possible, or too buggy
//restart();
//return;
}
}
play();
}
else
{
str ="network type same";
log(str, "v");
}
}
else
{
str = "";
boolean alreadyDisconnected = (mNetworkState == RadioPlayer.NETWORK_STATE_DISCONNECTED);
if (alreadyDisconnected)
{
str = "still ";
}
else if (isPlaying())
{
mInterrupted = true;
log ("setting interrupted to true", "v");
}
str += "not connected. ";
str += "old:" + mNetworkState;
str += ", new:" + Integer.toString(RadioPlayer.NETWORK_STATE_DISCONNECTED);
log(str, "v");
log("setting network state ivar to disconnected", "v");
mNetworkState = RadioPlayer.NETWORK_STATE_DISCONNECTED;
//TODO figure out the best thing to do for each state
if (state.equals(RadioPlayer.STATE_PREPARING)) //this will lead to a mediaioerror when it reaches prepared
{
mMediaPlayer.release();
mMediaPlayer = null;
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
log("-------------------------------", "d");
log("network connection lost while preparing? set null mediaplayer", "d");
log("-------------------------------", "d");
}
else if (state.equals(RadioPlayer.STATE_INITIALIZING))
{
if (alreadyDisconnected)
{
log("looks like it was trying to play when not connected", "d");
}
else
{
log("disconnected while initializing? this could be bad", "e");
}
}
else if (state.equals(RadioPlayer.STATE_ERROR))
{
Notification notification = updateNotification("Error. Will resume?", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
mMediaPlayer.release();
mMediaPlayer = null;
log("-------------------------------", "d");
log("not sure what to do, how did we get here?", "d");
log("-------------------------------", "d");
}
else if (state.equals(RadioPlayer.STATE_STOPPED))
{
log("disconnected while stopped, don't care", "v");
}
else if (state.equals(RadioPlayer.STATE_PLAYING))
{
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
log("disconnected while playing. should resume when network does", "v");
}
else if (state.equals(RadioPlayer.STATE_BUFFERING))
{
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
log("disconnected while buffering. should resume when network does", "v");
}
else if (state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
if (mMediaPlayer == null)
{
log("disconnected while uninitialized", "v");
}
else
{
//TODO throw exception? handle silently?
//might not cause problems, but shouldn't happen
log("-------------------------------", "d");
log("media player is not null, how did we get here?", "i");
log("-------------------------------", "d");
}
}
else
{
if (mPreset == 0)
{
Notification notification = updateNotification("bad state detected", "stop?", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
}
else
{
Notification notification = updateNotification("Waiting for network?", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
}
log("-------------------------------", "d");
log("other state", "i");
log("-------------------------------", "d");
}
}
}
}
private void log(String text, String level)
{
mLogger.log(this, "State:" + state + ":\t\t\t\t" + text, level);
}
public void clearLog()
{
//File file = getFileStreamPath(LOG_FILENAME);
deleteFile(MainActivity.LOG_FILENAME);
//logging something should recreate the log file
log("log file deleted", "i");
}
public void copyLog()
{
//String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = getExternalFilesDir(null).getAbsolutePath();
File src = getFileStreamPath(MainActivity.LOG_FILENAME);
File dst = new File(path + File.separator + MainActivity.LOG_FILENAME);
try {
if (dst.createNewFile())
{
log("sd file created", "v");
//Log.i(getPackageName(), "sd file created");
}
else
{
log("sd file exists?", "v");
//Log.i(getPackageName(), "sd file exists?");
}
} catch (IOException e2) {
log("sd file error", "e");
Toast.makeText(this, "sd file error", Toast.LENGTH_SHORT).show();
e2.printStackTrace();
}
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream(src).getChannel();
} catch (FileNotFoundException e1) {
log("in file not found", "e");
Toast.makeText(this, "in file not found", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
try {
out = new FileOutputStream(dst).getChannel();
} catch (FileNotFoundException e1) {
log("out file not found", "e");
Toast.makeText(this, "out file not found", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
try
{
in.transferTo(0, in.size(), out);
String str = "log file copied to ";
str += path + File.separator + MainActivity.LOG_FILENAME;
log(str, "i");
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
clearLog();
} catch (IOException e) {
log("error copying log file", "e");
Toast.makeText(this, "error copying log file", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
finally
{
}
}
}
| src/com/shinymayhem/radiopresets/RadioPlayer.java | /*
* Copyright (C) 2013 Reese Wilson | Shiny Mayhem
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.shinymayhem.radiopresets;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.webkit.URLUtil;
import android.widget.Toast;
public class RadioPlayer extends Service implements OnPreparedListener, OnBufferingUpdateListener, OnInfoListener, OnCompletionListener, OnErrorListener, OnAudioFocusChangeListener {
public final static int ONGOING_NOTIFICATION = 1;
//public final static String ACTION = "com.shinymayhem.radiopresets.ACTION";
public final static String ACTION_STOP = "com.shinymayhem.radiopresets.ACTION_STOP";
public final static String ACTION_PLAY = "com.shinymayhem.radiopresets.ACTION_PLAY";
public final static String ACTION_NEXT = "com.shinymayhem.radiopresets.ACTION_NEXT";
public final static String ACTION_PREVIOUS = "com.shinymayhem.radiopresets.ACTION_PREVIOUS";
public final static String ACTION_MEDIA_BUTTON = "com.shinymayhem.radiopresets.MEDIA_BUTTON";
public String state = STATE_UNINITIALIZED;
public final static String STATE_UNINITIALIZED = "Uninitialized";
public final static String STATE_INITIALIZING = "Initializing";
public final static String STATE_PREPARING = "Preparing";
public final static String STATE_PLAYING = "Playing";
public final static String STATE_BUFFERING = "Buffering";
public final static String STATE_PAUSED = "Paused";
public final static String STATE_PHONE = "Phone";
public final static String STATE_ERROR = "Error";
public final static String STATE_RESTARTING = "Restarting";
public final static String STATE_STOPPING = "Stopping";
public final static String STATE_STOPPED = "Stopped";
public final static String STATE_COMPLETE = "Complete";
public final static String STATE_END = "Ended";
public final static int NETWORK_STATE_DISCONNECTED = -1;
protected NetworkInfo mNetworkInfo;
protected int mNetworkState;
protected MediaPlayer mMediaPlayer;
protected MediaPlayer mNextPlayer;
private NetworkReceiver mReceiver;
private NoisyAudioStreamReceiver mNoisyReceiver;
private PhoneCallReceiver mPhoneReceiver;
private AudioManager mAudioManager;
private boolean mMediaButtonEventReceiverRegistered = false;
private MediaButtonReceiver mButtonReceiver;// = new MediaButtonReceiver();
//private OnAudioFocusChangeListener mFocusListener;
private boolean mAudioFocused = false;
protected String mUrl;
protected String mTitle;
protected int mPreset;
protected boolean mInterrupted = false;
private final IBinder mBinder = new LocalBinder();
protected boolean mBound = false;
protected Logger mLogger = new Logger();
protected Intent mIntent;
protected NotificationManager mNotificationManager;
public class LocalBinder extends Binder
{
RadioPlayer getService()
{
return RadioPlayer.this;
}
}
@Override
public void onCreate()
{
log("onCreate()", "d");
//initialize managers
if (mNotificationManager == null)
{
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
if (mAudioManager == null)
{
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
//remove pending intents if they exist
stopInfo();
registerNetworkReceiver();
registerButtonReceiver();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
log("onStartCommand()", "d");
//check if resuming after close for memory, or other crash
if ((flags & Service.START_FLAG_REDELIVERY) != 0)
{
log("------------------------------------------", "v");
log("intent redelivery, restarting. maybe handle this with dialog? notification with resume action?", "v");
log("------------------------------------------", "v");
}
mIntent = intent;
if (intent == null)
{
log("no intent", "w");
}
else
{
//TODO find out why service starts again after STOP action in intent (does it still?)
String action = intent.getAction();
if (action == null)
{
log("no action specified, not sure why", "w");
//return flag indicating no further action needed if service is stopped by system and later resumes
return START_NOT_STICKY;
}
else if (action.equals(Intent.ACTION_RUN)) //called when service is being bound
{
log("service being started before bound", "v");
return START_NOT_STICKY;
}
else if (action.equals(ACTION_PLAY.toString())) //Play intent
{
log("PLAY action in intent", "v");
int preset = Integer.valueOf(intent.getIntExtra(MainActivity.EXTRA_STATION_PRESET, 0));
log("preset in action:" + String.valueOf(preset), "v");
play(preset);
return START_REDELIVER_INTENT;
}
else if (action.equals(ACTION_NEXT.toString())) //Next preset intent
{
log("NEXT action in intent", "v");
nextPreset();
return START_NOT_STICKY;
}
else if (action.equals(ACTION_PREVIOUS.toString())) //Previous preset intent
{
log("PREVIOUS action in intent", "v");
previousPreset();
return START_NOT_STICKY;
}
else if (action.equals(ACTION_STOP.toString())) //Stop intent
{
log("STOP action in intent", "v");
end();
return START_NOT_STICKY;
}
else
{
String str = "Unknown Action:";
str += action;
log(str, "w");
//Log.i(getPackageName(), str);
}
}
//return START_STICKY;
return START_NOT_STICKY;
//return START_REDELIVER_INTENT;
}
@SuppressLint("NewApi")
public void onPrepared(MediaPlayer mediaPlayer)
{
log("onPrepared()", "d");
if (state.equals(RadioPlayer.STATE_RESTARTING) || state.equals(RadioPlayer.STATE_COMPLETE))
{
log("newPlayer ready", "i");
}
else
{
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
mAudioFocused = true;
log("mediaPlayer.start()", "v");
mediaPlayer.start();
state = RadioPlayer.STATE_PLAYING;
if (mInterrupted)
{
log("set interrupted = false", "v");
}
mInterrupted = false;
Notification notification = updateNotification("Playing", "Stop", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
startForeground(ONGOING_NOTIFICATION, notification);
log("start foreground notification: playing", "v");
Toast.makeText(this, "Playing", Toast.LENGTH_SHORT).show();
}
else if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED)
{
mAudioFocused = false;
log("audio focus failed", "w");
//TODO find a better way to deal with this
Toast.makeText(this, "Could not gain audio focus", Toast.LENGTH_SHORT).show();
}
}
}
public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra)
{
log("onInfo()", "d");
//TextView status = (TextView) findViewById(R.id.status);
if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END)
{
//Log.i(getPackageName(), "done buffering");
log("done buffering", "v");
if (mediaPlayer.isPlaying())
{
// status.setText("Playing");
}
else
{
// status.setText("Stopped");
}
Notification notification = updateNotification("Playing", "Stop", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
state = RadioPlayer.STATE_PLAYING;
return true;
}
else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START)
{
log("start buffering", "v");
//Log.i(getPackageName(), "start buffering");
//status.setText("Buffering...");
Notification notification = updateNotification("Buffering", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
state = RadioPlayer.STATE_BUFFERING;
return true;
}
else if (what == 703)
{
String str = "bandwidth:";
str += extra;
log(str, "v");
//Log.i(getPackageName(), str);
}
else
{
log("media player info", "v");
//Log.i(getPackageName(), "media player info");
}
/*String statusString = "\nInfo: ";
statusString += what;
statusString += ":";
statusString += extra;
status.append(statusString);*/
return false;
}
@Override
public void onBufferingUpdate(MediaPlayer player, int percent) {
log("buffering percent:" + String.valueOf(percent), "v");
}
public void onCompletion(MediaPlayer mediaPlayer)
{
//mediaPlayer.reset();
//mediaPlayer.release();
log("onCompletion()", "d");
state = RadioPlayer.STATE_COMPLETE;
//TODO update notification?
if (mInterrupted)
{
Toast.makeText(this, "Playback completed after interruption", Toast.LENGTH_SHORT).show();
log("Playback completed after interruption, should restart when network connects again", "v");
}
else
{
//still an interruption, streaming shouldn't complete
Toast.makeText(this, "Playback completed, no interruption reported", Toast.LENGTH_SHORT).show();
log("Playback completed, no network interruption reported, restart", "v");
//restart();
play();
}
if (mNextPlayer != null)
{
log("swapping players", "v");
mediaPlayer.release();
mediaPlayer = mNextPlayer;
mNextPlayer = null;
if (mediaPlayer.isPlaying())
{
state = RadioPlayer.STATE_PLAYING;
if (mInterrupted)
{
log("set interrupted = false", "v");
}
mInterrupted = false;
log("new player playing", "i");
//TODO update notification to indicate resumed playback
}
else
{
log("new player not playing", "w");
}
}
else
{
log("no next player specified", "w");
}
//stopForeground(true);
//playing = false;
//TextView status = (TextView) findViewById(R.id.status);
//status.append("\nComplete");
}
public boolean onError(MediaPlayer mediaPlayer, int what, int extra)
{
log("onError()", "e");
//check if mediaPlayer is or needs to be released
stopInfo(getResources().getString(R.string.widget_error_status)); //stopForeground(true);
if (mediaPlayer != null)
{
try
{
if (state != RadioPlayer.STATE_PREPARING)
{
mediaPlayer.stop();
}
log("media player stopped", "v");
}
catch (IllegalStateException e)
{
log("Illegal state to stop. uninitialized? not yet prepared?", "e");
}
mediaPlayer.release();
mediaPlayer = null;
mMediaPlayer = null;
}
String oldState = state;
state = RadioPlayer.STATE_ERROR;
//TextView status = (TextView) findViewById(R.id.status);
String statusString = "";
if (oldState.equals("Preparing"))
{
//TODO notify user somehow
statusString = "An error occurred while trying to connect to the server. ";
if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == -2147483648)
{
statusString += "Bad URL or file format?";
}
}
else
{
statusString = "Not error while preparing:";
}
if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == MediaPlayer.MEDIA_ERROR_IO)
{
statusString += "Media IO Error";
}
else if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT)
{
statusString += "Timed out";
}
else
{
statusString += what;
statusString += ":";
statusString += extra;
}
log(statusString, "e");
//status.append(statusString);
Toast.makeText(this, statusString, Toast.LENGTH_LONG).show();
if (oldState.equals("Preparing"))
{
stop();
}
return false;
}
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
{
mAudioFocused = false;
log("AUDIOFOCUS_LOSS_TRANSIENT", "v");
// Pause playback
pause();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mAudioFocused = true;
log("AUDIOFOCUS_GAIN", "v");
// Resume playback or unduck
if (!isPlaying())
{
if (mPreset == 0)
{
//should this really start playing?
play(1); //TODO get from storage
}
}
else
{
if (state.equals(STATE_PAUSED))
{
resume();
}
else
{
log("focus gained, but not resumed?", "w");
//play();
}
}
unduck();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
log("AUDIOFOCUS_LOSS", "v");
if (mMediaButtonEventReceiverRegistered)
{
log("unregister button receiver", "v");
mAudioManager.unregisterMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
mMediaButtonEventReceiverRegistered = false;
}
else
{
log("button receiver already unregistered", "v");
}
if (mAudioFocused)
{
log("abandon focus", "v");
mAudioManager.abandonAudioFocus(this);
mAudioFocused = false;
}
else
{
log("focus already abandoned", "v");
}
// Stop playback
stop();
}
else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// Lower the volume
log("AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK", "v");
duck();
}
}
private void duck()
{
log("duck()", "v");
//mDucked = true;
if (mMediaPlayer != null)
{
int volume = 20;
float log1=(float)(Math.log(100-volume)/Math.log(100));
log("lowering volume to " + String.valueOf(log1), "v");
mMediaPlayer.setVolume(1-log1, 1-log1);
//mMediaPlayer.setVolume(leftVolume, rightVolume)
}
}
private void unduck()
{
log("unduck()", "v");
//mDucked = false;
if (mMediaPlayer != null)
{
mMediaPlayer.setVolume(1, 1);
//mMediaPlayer.setVolume(leftVolume, rightVolume)
}
}
private void stopInfo(String status)
{
stopForeground(true);
this.updateWidget(getResources().getString(R.string.widget_initial_title), status);
}
private void stopInfo()
{
this.stopInfo(getResources().getString(R.string.widget_stopped_status));
}
private void registerNetworkReceiver()
{
//register network receiver
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
if (mReceiver != null)
{
log("------------------------------------------", "v");
log("network receiver already registered, find out why", "w");
log("------------------------------------------", "v");
this.unregisterReceiver(mReceiver);
mReceiver = null;
}
mReceiver = new NetworkReceiver();
log("registering network change broadcast receiver", "v");
this.registerReceiver(mReceiver, filter);
}
private void registerButtonReceiver()
{
//register media button receiver
if (mButtonReceiver != null)
{
log("media button listener already registered", "v");
this.unregisterReceiver(mButtonReceiver);
mButtonReceiver = null;
}
log("register media button listener", "v");
mButtonReceiver = new MediaButtonReceiver();
registerReceiver(mButtonReceiver, new IntentFilter(ACTION_MEDIA_BUTTON));
//set RemoteControlReceiver to be the sole receiver of media button actions
if (mMediaButtonEventReceiverRegistered == false)
{
log("registering media button listener", "v");
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
mMediaButtonEventReceiverRegistered = true;
}
}
protected PendingIntent getPreviousIntent()
{
Intent intent = new Intent(this, RadioPlayer.class).setAction(ACTION_PREVIOUS);
return PendingIntent.getService(this, 0, intent, 0);
}
protected PendingIntent getStopIntent()
{
Intent intent = new Intent(this, RadioPlayer.class).setAction(ACTION_STOP);
return PendingIntent.getService(this, 0, intent, 0);
}
protected PendingIntent getNextIntent()
{
Intent intent = new Intent(this, RadioPlayer.class).setAction(ACTION_NEXT);
return PendingIntent.getService(this, 0, intent, 0);
}
protected void play()
{
log("play()", "d");
/*if (this.mUrl == null)
{
log("url not set", "e");
}
else
{
String str = "url:";
str += this.mUrl;
log(str, "v");
}
this.play(this.mUrl);*/
if (mPreset == 0)
{
log("preset = 0", "e");
}
play(mPreset);
}
//called from bound ui, possibly notification action, if implemented
//possible start states: any
protected void play(int preset)
{
log("play(preset)", "d");
if (preset == 0)
{
log("preset = 0", "e");
throw new IllegalArgumentException("Preset = 0");
}
this.mPreset = preset;
state = RadioPlayer.STATE_INITIALIZING;
if (isConnected())
{
log("setting network type", "v");
mNetworkState = this.getConnectionType();
}
else
{
//TODO handle this, let user know
log("setting network state to disconnected", "v");
mNetworkState = RadioPlayer.NETWORK_STATE_DISCONNECTED;
//TODO ask user if it should play on network resume
Toast.makeText(this, "tried to play with no network", Toast.LENGTH_LONG).show();
log("no network, should be handled by ui? returning", "e");
//if disconnected while preparing, mediaplayer is null, then getting here will stop playback attempts
if (mInterrupted)
{
log("interrupted, so set state to playing so it will wait for network to resume", "v");
state = RadioPlayer.STATE_PLAYING;
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
}
else
{
log("wasn't interrupted, so remove any notifications and reset to uninitialized", "v");
state = RadioPlayer.STATE_UNINITIALIZED;
if (mMediaPlayer != null)
{
log("media player not null, releasing", "v");
mMediaPlayer.release();
mMediaPlayer = null;
}
stopInfo(); //stopForeground(true);
}
return;
}
this.mPreset = preset;
Uri uri = Uri.parse(RadioContentProvider.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(preset));
String[] projection = {RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER, RadioDbContract.StationEntry.COLUMN_NAME_TITLE, RadioDbContract.StationEntry.COLUMN_NAME_URL};
String selection = null;
String[] selectionArgs = null;
String sortOrder = RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int count = cursor.getCount();
if (count < 1)
{
log("no results found", "e");
throw new SQLiteException("Selected preset not found"); //TODO find correct exception to throw, or handle this some other way
}
else
{
cursor.moveToFirst();
mPreset = (int)cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
mTitle = cursor.getString(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_TITLE));
mUrl = cursor.getString(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_URL));
}
//begin listen for headphones unplugged
if (mNoisyReceiver == null)
{
mNoisyReceiver = new NoisyAudioStreamReceiver();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(mNoisyReceiver, intentFilter);
log("register noisy receiver", "v");
}
else
{
log("noisy receiver already registered", "v");
}
//begin listen for phone call
if (mPhoneReceiver == null)
{
mPhoneReceiver = new PhoneCallReceiver();
IntentFilter intentFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(mPhoneReceiver, intentFilter);
log("register phone receiver", "v");
}
else
{
log("phone receiver already registered", "v");
}
if (mMediaPlayer != null)
{
log("releasing old media player", "v");
mMediaPlayer.release();
mMediaPlayer = null;
}
log("creating new media player", "v");
this.mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//str += mUrl;
log("setting datasource for '" + mTitle + "' at '" + mUrl + "'", "v");
try
{
mMediaPlayer.setDataSource(mUrl);
}
catch (IOException e)
{
//TODO handle this somehow, let user know
log("setting data source failed", "e");
Toast.makeText(this, "Setting data source failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
initializePlayer(mMediaPlayer);
state = RadioPlayer.STATE_PREPARING;
Notification notification = updateNotification("Preparing", "Cancel", true);
//mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
startForeground(ONGOING_NOTIFICATION, notification);
updateWidget("Preparing");
mMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
log("preparing async", "d");
Toast.makeText(this, "Preparing", Toast.LENGTH_SHORT).show();
}
protected void nextPreset()
{
log("nextPreset()", "v");
mPreset++;
Uri uri = Uri.parse(RadioContentProvider.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(mPreset));
String[] projection = {RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER};
String selection = null;
String[] selectionArgs = null;
String sortOrder = RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int count = cursor.getCount();
if (count < 1 && mPreset == 1)
{
log("no stations, unless db integrity lost", "w");
return; //TODO notify user?
}
else if (count < 1)
{
mPreset = 0;
log("incremented preset but nothing found, must be at end, start at 1", "v");
this.nextPreset(); //try again, starting at 0
}
else
{
cursor.moveToFirst();
mPreset = (int)cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
log("incremented preset, playing " + String.valueOf(mPreset), "v");
play();
}
}
//FIXME duplicate code from radioContentProvider
protected int getMaxPresetNumber()
{
Uri uri = RadioContentProvider.CONTENT_URI_PRESETS_MAX;
String[] projection = null;
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
long preset = 0;
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
preset = cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
}
cursor.close();
return (int)preset;
}
protected void previousPreset()
{
log("previousPreset()", "v");
mPreset--;
if (mPreset <= 0)
{
////call() not supported until api 11
//Uri maxUri = RadioContentProvider.CONTENT_URI_PRESETS_MAX;
//Bundle values = getContentResolver().call(maxUri, "getMaxPresetNumber", null, null);
//mPreset = values.getInt(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER);
mPreset = getMaxPresetNumber();
if (mPreset == 0) //no stations?
{
log("no stations, unless getMaxPresetNumber doesn't work", "w");
return; //TODO notify user?
}
//play();
//return;
}
//find out if the desired station exists
Uri uri = Uri.parse(RadioContentProvider.CONTENT_URI_PRESETS.toString() + "/" + String.valueOf(mPreset));
String[] projection = {RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER};
String selection = null;
String[] selectionArgs = null;
String sortOrder = RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER;
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int count = cursor.getCount();
if (count < 1)
{
log("no station found below current, but not 0", "e");
throw new SQLiteException("No station found below current, but not 0"); //TODO find correct exception to throw, or handle this some other way
}
else
{
cursor.moveToFirst();
mPreset = (int)cursor.getLong(cursor.getColumnIndexOrThrow(RadioDbContract.StationEntry.COLUMN_NAME_PRESET_NUMBER));
log("decremented preset, playing " + String.valueOf(mPreset), "v");
play();
}
}
protected void setVolume(int percent)
{
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int newVolume = (int)((long)(percent/100)*maxVolume);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
/*log("setting volume to " + String.valueOf(percent), "v");
float log1=(float)(Math.log(100-percent)/Math.log(100));
log("lowering volume to " + String.valueOf(log1), "v");
mMediaPlayer.setVolume(1-log1, 1-log1);*/
}
protected Intent getWidgetUpdateIntent(String text1, String text2)
{
Intent intent = new Intent(this, com.shinymayhem.radiopresets.PresetButtonsWidgetProvider.class);
intent.setAction(PresetButtonsWidgetProvider.ACTION_UPDATE_TEXT);
intent.putExtra(com.shinymayhem.radiopresets.PresetButtonsWidgetProvider.EXTRA_TEXT1, text1);
intent.putExtra(com.shinymayhem.radiopresets.PresetButtonsWidgetProvider.EXTRA_TEXT2, text2);
//intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
protected void updateWidget(String text)
{
Intent intent = this.getWidgetUpdateIntent(String.valueOf(mPreset) + ". " + mTitle, text);
this.sendBroadcast(intent);
}
protected void updateWidget(String title, String status)
{
Intent intent = this.getWidgetUpdateIntent(title, status);
this.sendBroadcast(intent);
}
protected Notification updateNotification(String status, String stopText, boolean updateTicker)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(String.valueOf(mPreset) + ". " + mTitle)
.setContentText(status)
//.addAction(R.drawable.av_previous, getResources().getString(R.string.previous), getPreviousIntent())
//.addAction(R.drawable.av_stop, stopText, getStopIntent())
//.addAction(R.drawable.av_next, getResources().getString(R.string.next), getNextIntent())
.addAction(R.drawable.av_previous, null, getPreviousIntent())
.addAction(R.drawable.av_stop, null, getStopIntent())
.setUsesChronometer(true)
.addAction(R.drawable.av_next, null, getNextIntent())
.setLargeIcon(((BitmapDrawable)getResources().getDrawable(R.drawable.app_icon)).getBitmap())
.setSmallIcon(R.drawable.app_notification);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//TODO taskstack builder only available since 4.1
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
//stackBuilder.addNextIntent(nextIntent)
Intent resultIntent = new Intent(this, MainActivity.class);
//resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); //why is this not needed?
stackBuilder.addNextIntent(resultIntent);
PendingIntent intent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(intent);
if (updateTicker)
{
builder.setTicker(status);
//startForeground(ONGOING_NOTIFICATION, builder.build());
}
else
{
//mNotificationManager.notify(ONGOING_NOTIFICATION, builder.build());
}
this.updateWidget(status);
return builder.build();
}
protected void initializePlayer(MediaPlayer player)
{
log("initializePlayer()", "d");
player.setOnPreparedListener(this);
player.setOnInfoListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
player.setOnBufferingUpdateListener(this);
return;
}
protected void pause()
{
log("pause()", "v");
if (mMediaPlayer == null)
{
log("null media player", "w");
}
else if (state.equals(RadioPlayer.STATE_PREPARING))
{
log("pause called while preparing", "v");
mMediaPlayer.release();
mMediaPlayer = null;
}
else
{
log("pause playback", "v");
mMediaPlayer.stop();
if (mAudioFocused)
{
log("abandon audio focus", "v");
mAudioManager.abandonAudioFocus(this);
}
else
{
log("audio focus already abandoned", "w");
}
mMediaPlayer.release();
mMediaPlayer = null;
}
Notification notification = updateNotification("Paused", "Cancel", false);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
/*try
{
unregisterReceiver(mNoisyReceiver);
mNoisyReceiver = null;
log("unregistering noisyReceiver", "v");
}
catch (IllegalArgumentException e)
{
log("noisyReceiver already unregistered", "e");
}*/
state = STATE_PAUSED;
}
protected void resume()
{
log("resume()", "v");
/*mNoisyReceiver = new NoisyAudioStreamReceiver();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(mNoisyReceiver, intentFilter);
log("register noisy receiver", "v");*/
play();
}
//called from onDestroy, end
protected void stop()
{
log("stop()", "d");
/*
log("Stop button received, sending stop intent", "d");
Intent intent = new Intent(this, RadioPlayer.class);
intent.setAction(RadioPlayer.ACTION_STOP);
startService(intent);*/
//stop command called, reset interrupted flag
if (mInterrupted)
{
log("set interrupted = false", "v");
}
mInterrupted = false;
if (state.equals(RadioPlayer.STATE_STOPPED) || state.equals(RadioPlayer.STATE_END) || state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
log("already stopped", "v");
return;
}
if (mMediaPlayer == null)
{
state = RadioPlayer.STATE_STOPPING;
log("null media player", "w");
}
else if (state.equals(RadioPlayer.STATE_PREPARING))
{
state = RadioPlayer.STATE_STOPPING; //store oldstate to move state change outside of conditionals
log("stop called while preparing", "v");
stopInfo(); //stopForeground(true);
mMediaPlayer.release();
mMediaPlayer = null;
}
else
{
state = RadioPlayer.STATE_STOPPING;
log("stopping playback", "v");
Toast.makeText(this, "Stopping playback", Toast.LENGTH_SHORT).show();
stopInfo(); //stopForeground(true);
mMediaPlayer.stop();
if (mAudioFocused == true)
{
log("abandon audio focus", "v");
mAudioManager.abandonAudioFocus(this);
}
else
{
log("focus already abandoned", "w");
}
//mediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
try
{
unregisterReceiver(mNoisyReceiver);
mNoisyReceiver = null;
log("unregistering noisyReceiver", "v");
}
catch (IllegalArgumentException e)
{
log("noisyReceiver already unregistered", "e");
}
try
{
unregisterReceiver(mPhoneReceiver);
mPhoneReceiver = null;
log("unregistering phoneReceiver", "v");
}
catch (IllegalArgumentException e)
{
log("phoneReceiver already unregistered", "e");
}
//clear any intents so player isn't started accidentally
//log("experimental fix for service autostarting, redeliver-intent flag", "v");
//mIntent.setAction(null);
state = RadioPlayer.STATE_STOPPED;
}
//called from unbound, headphones unplugged, notification->stop
protected void end()
{
log("end()", "d");
stop();
if (!mBound)
{
log("not bound, stopping service with stopself", "d");
stopSelf();
//Intent intent = new Intent(this, RadioPlayer.class);
//stopSelf();
//only stops service intent started with play action? not sure. not even sure if that would work
//what should happen is
//intent.setAction(RadioPlayer.ACTION_PLAY);
//this.stopService(intent);
state = RadioPlayer.STATE_END;
}
else
{
String str = "still bound";
log(str, "v");
}
}
//called from onComplete or network change if no network and was playing
/*
protected void restart()
{
log("restart()", "d");
state = RadioPlayer.STATE_RESTARTING;
if (mNextPlayer != null)
{
log("nextPlayer not null","e");
mNextPlayer.release();
mNextPlayer = null;
}
this.mNextPlayer = new MediaPlayer();
mNextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
String str = "setting nextPlayer data source: ";
str += mUrl;
log(str, "v");
try
{
mNextPlayer.setDataSource(mUrl);
}
catch (IOException e)
{
//TODO handle this somehow
log("setting nextPlayer data source failed", "e");
Toast.makeText(this, "Setting data source failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
initializePlayer(mNextPlayer);
//TODO handle older versions
//check for errors or invalid states
try
{
mMediaPlayer.stop();
}
catch (IllegalStateException e)
{
log("old player in wrong state to stop", "e");
}
try
{
boolean playing = mMediaPlayer.isPlaying();
if (playing)
{
log("old player playing, new player ready to set", "v");
}
else
{
log("old player not playing, might not be safe to setnext", "w");
}
}
catch (IllegalStateException e)
{
log("old player in wrong state to check if playing", "e");
}
//check to see if playback completed
if (state == RadioPlayer.STATE_COMPLETE)
{
log("playback completed", "e");
return;
}
try
{
mMediaPlayer.setNextMediaPlayer(mNextPlayer);
log("nextplayer set", "v");
}
catch (IllegalStateException e)
{
log("old player in wrong state to setnext", "e");
}
//if (mediaPlayer.isPlaying())
//{
// log("was still playing, stopping", "v");
// mediaPlayer.stop();
//}
//log("restarting/preparing", "v");
//mediaPlayer.prepareAsync();
//Log.i(getPackageName(), "restarting playback");
//if (playing)
//{
// mediaPlayer.stop();
// mediaPlayer.release();
// playing = false;
//}
//play();
}
*/
public boolean isPlaying()
{
return (
state.equals(RadioPlayer.STATE_BUFFERING) ||
state.equals(RadioPlayer.STATE_PLAYING) ||
state.equals(RadioPlayer.STATE_PAUSED) ||
state.equals(RadioPlayer.STATE_PHONE) ||
state.equals(RadioPlayer.STATE_PREPARING) ||
state.equals(RadioPlayer.STATE_INITIALIZING) ||
state.equals(RadioPlayer.STATE_COMPLETE) || //service should still stay alive and listen for network changes to resume
state.equals(RadioPlayer.STATE_RESTARTING)
);
}
protected boolean isConnected()
{
ConnectivityManager network = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = network.getActiveNetworkInfo();
mNetworkInfo = info;
if (info == null)
{
return false;
}
return true;
}
protected int getConnectionType()
{
String str = "";
int newState = mNetworkInfo.getType();
switch (newState)
{
case ConnectivityManager.TYPE_WIFI:
str += "wifi";
break;
case ConnectivityManager.TYPE_MOBILE:
str += "mobile";
break;
case ConnectivityManager.TYPE_MOBILE_DUN:
str += "mobile-dun";
break;
case ConnectivityManager.TYPE_MOBILE_HIPRI:
str += "moblie-hipri";
break;
case ConnectivityManager.TYPE_MOBILE_MMS:
str += "mobile-mms";
break;
case ConnectivityManager.TYPE_MOBILE_SUPL:
str += "mobile-supl";
break;
case ConnectivityManager.TYPE_WIMAX:
str += "wimax";
break;
case ConnectivityManager.TYPE_ETHERNET:
str += "ethernet";
break;
case ConnectivityManager.TYPE_BLUETOOTH:
str += "bluetooth";
break;
case ConnectivityManager.TYPE_DUMMY:
str += "dummy";
break;
}
str += " detected";
log(str, "v");
return newState;
}
public static boolean validateUrl(String url)
{
if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url))
{
//log("not a valid http or https url", "v");
return false;
}
//check for empty after prefix
if (url == "http://" || url == "https://")
{
return false;
}
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try
{
mediaPlayer.setDataSource(url);
mediaPlayer.release();
}
catch (IOException e)
{
return false;
}
return true;
}
@Override
public IBinder onBind(Intent intent) {
log("onBind()", "d");
//Log.i(getPackageName(), "binding service");
mBound=true;
return mBinder;
}
@Override
public void onRebind(Intent intent)
{
log("onRebind()", "d");
//Log.i(getPackageName(), "rebinding service");
}
@Override
public boolean onUnbind(Intent intent)
{
log("onUnbind()", "d");
//Log.i(getPackageName(), "unbinding service");
mBound = false;
if (!isPlaying())
{
end();
}
return false;
}
@Override
public void onDestroy() {
log("onDestroy()", "d");
this.stop();
Toast.makeText(this, "Stopping service", Toast.LENGTH_SHORT).show();
//don't need to listen for network changes anymore
if (mReceiver != null) {
log("unregister network receiver", "v");
this.unregisterReceiver(mReceiver);
mReceiver = null;
}
else
{
log("unregistering network receiver failed, null", "e");
}
if (mButtonReceiver != null) {
log("unregister media button receiver", "v");
this.unregisterReceiver(mButtonReceiver);
mButtonReceiver = null;
}
else
{
log("unregistering network receiver failed, null", "e");
}
}
public class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("received remote control action", "v");
if (ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
switch (event.getKeyCode())
{
case KeyEvent.KEYCODE_MEDIA_PLAY:
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
nextPreset();
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
previousPreset();
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_STOP:
stop();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_HEADSETHOOK:
if (isPlaying() && state != STATE_PAUSED)
{
pause();
}
else
{
if (mPreset == 0) //TODO store last played preset somewhere
{
play(1);
}
else
{
resume();
}
}
default:
log("other button:" + String.valueOf(event.getKeyCode()), "v");
}
}
else
{
log("other remote action?", "v");
}
}
}
private class NoisyAudioStreamReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (state != STATE_PHONE && state != STATE_PAUSED && AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
log("headphones unplugged", "v");
end();
}
else
{
log("headphones unplugged, but it is paused", "v");
}
}
}
private class PhoneCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("phone call receiver onReceive()", "v");
String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
log("phone ringing", "v");
if (isPlaying())
{
pause();
state = STATE_PHONE;
}
}
else if (phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE) && state.equals(STATE_PHONE))
{
log("resuming after phone call", "v");
resume();
}
else
{
log("outgoing phone call?", "v");
if (isPlaying())
{
pause();
state = STATE_PHONE;
}
}
}
}
//handle network changes
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("received network change broadcast", "v");
//Log.i(getPackageName(), "received network change broadcast");
if (mMediaPlayer == null && state.equals(RadioPlayer.STATE_PREPARING))
{
log("recover from disconnect while preparing", "v");
//Log.i(getPackageName(), "no media player, don't care about connection updates");
play();
return;
}
else if (mMediaPlayer == null && state != RadioPlayer.STATE_UNINITIALIZED)
{
log("media player null, will cause problems if connected", "e");
}
else if (mMediaPlayer != null && state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
log("-------------------------------", "d");
log ("mediaPlayer not null, but uninitialized. how did this happen?", "w");
log("-------------------------------", "d");
}
String str = "";
if (isConnected())
{
int newState = getConnectionType();
if (mNetworkState != newState)
{
str = "network type changed";
if (state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
str += " but uninitialized so it doesn't matter. ";
}
else if (state.equals(RadioPlayer.STATE_STOPPED) || state.equals(RadioPlayer.STATE_STOPPING))
{
str += " but stopped so it doesn't matter. ";
}
else if (state.equals(RadioPlayer.STATE_END))
{
str += " but ended so it doesn't matter. ";
}
else if (state.equals(RadioPlayer.STATE_PAUSED) || state.equals(RadioPlayer.STATE_PHONE))
{
str += " but paused so it doesn't matter. ";
}
else if (mInterrupted == false)
{
Notification notification = updateNotification("Network updated, reconnecting", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
str += " and now interrupted";
mInterrupted = true;
}
else
{
str += " but previously interrupted";
}
str += "old:" + mNetworkState;
str += ", new:" + newState;
log(str, "v");
log("setting network state ivar", "v");
mNetworkState = newState;
//if uninitialized, no preset picked yet. if stopped or paused, don't restart
if (state.equals(RadioPlayer.STATE_UNINITIALIZED) ||
state.equals(RadioPlayer.STATE_STOPPED) ||
state.equals(RadioPlayer.STATE_STOPPING) ||
state.equals(RadioPlayer.STATE_PAUSED) ||
state.equals(RadioPlayer.STATE_PHONE) ||
state.equals(RadioPlayer.STATE_END)
)
{
log("unitialized or stopped/paused/ended, don't try to start or restart", "v");
return;
}
boolean start = false;
if (mMediaPlayer == null)
{
log("-------------------------------", "d");
log("find out how we got here", "e");
log("trying to play when not connected?", "v");
log("disconnected while initializing? ", "v");
log("-------------------------------", "d");
}
else
{
try
{
mMediaPlayer.isPlaying();
}
catch (IllegalStateException e)
{
log("illegal state detected, can't restart, start from scratch instead", "e");
start = true;
}
//can't set nextplayer after complete, so just start fresh
if (state.equals(RadioPlayer.STATE_COMPLETE) || start)
{
log("complete or start=true", "v");
}
//network interrupted playback but isn't done playing from buffer yet
//set nextplayer and wait for current player to complete
else
{
log("!complete && start!=true", "v");
//play();
//TODO figure out if restart is possible, or too buggy
//restart();
//return;
}
}
play();
}
else
{
str ="network type same";
log(str, "v");
}
}
else
{
str = "";
boolean alreadyDisconnected = (mNetworkState == RadioPlayer.NETWORK_STATE_DISCONNECTED);
if (alreadyDisconnected)
{
str = "still ";
}
else if (isPlaying())
{
mInterrupted = true;
log ("setting interrupted to true", "v");
}
str += "not connected. ";
str += "old:" + mNetworkState;
str += ", new:" + Integer.toString(RadioPlayer.NETWORK_STATE_DISCONNECTED);
log(str, "v");
log("setting network state ivar to disconnected", "v");
mNetworkState = RadioPlayer.NETWORK_STATE_DISCONNECTED;
//TODO figure out the best thing to do for each state
if (state.equals(RadioPlayer.STATE_PREPARING)) //this will lead to a mediaioerror when it reaches prepared
{
mMediaPlayer.release();
mMediaPlayer = null;
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
log("-------------------------------", "d");
log("network connection lost while preparing? set null mediaplayer", "d");
log("-------------------------------", "d");
}
else if (state.equals(RadioPlayer.STATE_INITIALIZING))
{
if (alreadyDisconnected)
{
log("looks like it was trying to play when not connected", "d");
}
else
{
log("disconnected while initializing? this could be bad", "e");
}
}
else if (state.equals(RadioPlayer.STATE_ERROR))
{
Notification notification = updateNotification("Error. Will resume?", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
mMediaPlayer.release();
mMediaPlayer = null;
log("-------------------------------", "d");
log("not sure what to do, how did we get here?", "d");
log("-------------------------------", "d");
}
else if (state.equals(RadioPlayer.STATE_STOPPED))
{
log("disconnected while stopped, don't care", "v");
}
else if (state.equals(RadioPlayer.STATE_PLAYING))
{
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
log("disconnected while playing. should resume when network does", "v");
}
else if (state.equals(RadioPlayer.STATE_BUFFERING))
{
Notification notification = updateNotification("Waiting for network", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
log("disconnected while buffering. should resume when network does", "v");
}
else if (state.equals(RadioPlayer.STATE_UNINITIALIZED))
{
if (mMediaPlayer == null)
{
log("disconnected while uninitialized", "v");
}
else
{
//TODO throw exception? handle silently?
//might not cause problems, but shouldn't happen
log("-------------------------------", "d");
log("media player is not null, how did we get here?", "i");
log("-------------------------------", "d");
}
}
else
{
if (mPreset == 0)
{
Notification notification = updateNotification("bad state detected", "stop?", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
}
else
{
Notification notification = updateNotification("Waiting for network?", "Cancel", true);
mNotificationManager.notify(ONGOING_NOTIFICATION, notification);
}
log("-------------------------------", "d");
log("other state", "i");
log("-------------------------------", "d");
}
}
}
}
private void log(String text, String level)
{
mLogger.log(this, "State:" + state + ":\t\t\t\t" + text, level);
}
public void clearLog()
{
//File file = getFileStreamPath(LOG_FILENAME);
deleteFile(MainActivity.LOG_FILENAME);
//logging something should recreate the log file
log("log file deleted", "i");
}
public void copyLog()
{
//String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = getExternalFilesDir(null).getAbsolutePath();
File src = getFileStreamPath(MainActivity.LOG_FILENAME);
File dst = new File(path + File.separator + MainActivity.LOG_FILENAME);
try {
if (dst.createNewFile())
{
log("sd file created", "v");
//Log.i(getPackageName(), "sd file created");
}
else
{
log("sd file exists?", "v");
//Log.i(getPackageName(), "sd file exists?");
}
} catch (IOException e2) {
log("sd file error", "e");
Toast.makeText(this, "sd file error", Toast.LENGTH_SHORT).show();
e2.printStackTrace();
}
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream(src).getChannel();
} catch (FileNotFoundException e1) {
log("in file not found", "e");
Toast.makeText(this, "in file not found", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
try {
out = new FileOutputStream(dst).getChannel();
} catch (FileNotFoundException e1) {
log("out file not found", "e");
Toast.makeText(this, "out file not found", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
try
{
in.transferTo(0, in.size(), out);
String str = "log file copied to ";
str += path + File.separator + MainActivity.LOG_FILENAME;
log(str, "i");
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
clearLog();
} catch (IOException e) {
log("error copying log file", "e");
Toast.makeText(this, "error copying log file", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
finally
{
}
}
}
| changing service to not auto-start, not-sticky
affects #1
| src/com/shinymayhem/radiopresets/RadioPlayer.java | changing service to not auto-start, not-sticky | <ide><path>rc/com/shinymayhem/radiopresets/RadioPlayer.java
<ide> int preset = Integer.valueOf(intent.getIntExtra(MainActivity.EXTRA_STATION_PRESET, 0));
<ide> log("preset in action:" + String.valueOf(preset), "v");
<ide> play(preset);
<del> return START_REDELIVER_INTENT;
<add> //return START_REDELIVER_INTENT;
<add> return START_NOT_STICKY;
<ide> }
<ide> else if (action.equals(ACTION_NEXT.toString())) //Next preset intent
<ide> { |
|
Java | epl-1.0 | f402f608f7921b24791cb40be3c83e7ebfa63006 | 0 | Snickermicker/smarthome,Snickermicker/smarthome,Snickermicker/smarthome,Snickermicker/smarthome | /**
* Copyright (c) 2014,2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.config.discovery.internal.console;
import static org.eclipse.smarthome.config.discovery.inbox.InboxPredicates.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.eclipse.smarthome.config.discovery.DiscoveryResult;
import org.eclipse.smarthome.config.discovery.DiscoveryResultFlag;
import org.eclipse.smarthome.config.discovery.inbox.Inbox;
import org.eclipse.smarthome.config.discovery.internal.PersistentInbox;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.io.console.Console;
import org.eclipse.smarthome.io.console.extensions.AbstractConsoleCommandExtension;
import org.eclipse.smarthome.io.console.extensions.ConsoleCommandExtension;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* This class provides console commands around the inbox functionality.
*
* @author Kai Kreuzer - Initial contribution and API
*/
@Component(immediate = true, service = ConsoleCommandExtension.class)
public class InboxConsoleCommandExtension extends AbstractConsoleCommandExtension {
private static final String SUBCMD_APPROVE = "approve";
private static final String SUBCMD_IGNORE = "ignore";
private static final String SUBCMD_LIST = "list";
private static final String SUBCMD_LIST_IGNORED = "listignored";
private static final String SUBCMD_CLEAR = "clear";
private Inbox inbox;
public InboxConsoleCommandExtension() {
super("inbox", "Manage your inbox.");
}
@Override
public void execute(String[] args, Console console) {
if (args.length > 0) {
final String subCommand = args[0];
switch (subCommand) {
case SUBCMD_APPROVE:
if (args.length > 2) {
String label = args[2];
try {
ThingUID thingUID = new ThingUID(args[1]);
List<DiscoveryResult> results = inbox.stream().filter(forThingUID(thingUID))
.collect(Collectors.toList());
if (results.isEmpty()) {
console.println("No matching inbox entry could be found.");
return;
}
inbox.approve(thingUID, label);
} catch (Exception e) {
console.println(e.getMessage());
}
} else {
console.println("Specify thing id to approve: inbox approve <thingUID> <label>");
}
break;
case SUBCMD_IGNORE:
if (args.length > 1) {
try {
ThingUID thingUID = new ThingUID(args[1]);
PersistentInbox persistentInbox = (PersistentInbox) inbox;
persistentInbox.setFlag(thingUID, DiscoveryResultFlag.IGNORED);
} catch (IllegalArgumentException e) {
console.println("'" + args[1] + "' is no valid thing UID.");
}
} else {
console.println("Cannot approve thing as managed thing provider is missing.");
}
break;
case SUBCMD_LIST:
printInboxEntries(console,
inbox.stream().filter(withFlag((DiscoveryResultFlag.NEW))).collect(Collectors.toList()));
break;
case SUBCMD_LIST_IGNORED:
printInboxEntries(console, inbox.stream().filter(withFlag((DiscoveryResultFlag.IGNORED)))
.collect(Collectors.toList()));
break;
case SUBCMD_CLEAR:
clearInboxEntries(console, inbox.getAll());
break;
default:
printUsage(console);
break;
}
} else {
printInboxEntries(console,
inbox.stream().filter(withFlag((DiscoveryResultFlag.NEW))).collect(Collectors.toList()));
}
}
private void printInboxEntries(Console console, List<DiscoveryResult> discoveryResults) {
if (discoveryResults.isEmpty()) {
console.println("No inbox entries found.");
}
for (DiscoveryResult discoveryResult : discoveryResults) {
ThingTypeUID thingTypeUID = discoveryResult.getThingTypeUID();
ThingUID thingUID = discoveryResult.getThingUID();
String label = discoveryResult.getLabel();
DiscoveryResultFlag flag = discoveryResult.getFlag();
ThingUID bridgeId = discoveryResult.getBridgeUID();
Map<String, Object> properties = discoveryResult.getProperties();
String representationProperty = discoveryResult.getRepresentationProperty();
String timestamp = new Date(discoveryResult.getTimestamp()).toString();
String timeToLive = discoveryResult.getTimeToLive() == DiscoveryResult.TTL_UNLIMITED ? "UNLIMITED"
: "" + discoveryResult.getTimeToLive();
console.println(String.format(
"%s [%s]: %s [thingId=%s, bridgeId=%s, properties=%s, representationProperty=%s, timestamp=%s, timeToLive=%s]",
flag.name(), thingTypeUID, label, thingUID, bridgeId, properties, representationProperty, timestamp,
timeToLive));
}
}
private void clearInboxEntries(Console console, List<DiscoveryResult> discoveryResults) {
if (discoveryResults.isEmpty()) {
console.println("No inbox entries found.");
}
for (DiscoveryResult discoveryResult : discoveryResults) {
ThingTypeUID thingTypeUID = discoveryResult.getThingTypeUID();
ThingUID thingUID = discoveryResult.getThingUID();
String label = discoveryResult.getLabel();
DiscoveryResultFlag flag = discoveryResult.getFlag();
ThingUID bridgeId = discoveryResult.getBridgeUID();
Map<String, Object> properties = discoveryResult.getProperties();
console.println(String.format("REMOVED [%s]: %s [label=%s, thingId=%s, bridgeId=%s, properties=%s]",
flag.name(), thingTypeUID, label, thingUID, bridgeId, properties));
inbox.remove(thingUID);
}
}
@Override
public List<String> getUsages() {
return Arrays.asList(new String[] { buildCommandUsage("lists all current inbox entries"),
buildCommandUsage(SUBCMD_LIST, "lists all current inbox entries"),
buildCommandUsage(SUBCMD_LIST_IGNORED, "lists all ignored inbox entries"),
buildCommandUsage(SUBCMD_APPROVE + " <thingUID> <label>", "creates a thing for an inbox entry"),
buildCommandUsage(SUBCMD_CLEAR, "clears all current inbox entries"),
buildCommandUsage(SUBCMD_IGNORE + " <thingUID>", "ignores an inbox entry permanently") });
}
@Reference
protected void setInbox(Inbox inbox) {
this.inbox = inbox;
}
protected void unsetInbox(Inbox inbox) {
this.inbox = null;
}
}
| bundles/config/org.eclipse.smarthome.config.discovery/src/main/java/org/eclipse/smarthome/config/discovery/internal/console/InboxConsoleCommandExtension.java | /**
* Copyright (c) 2014,2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.config.discovery.internal.console;
import static org.eclipse.smarthome.config.discovery.inbox.InboxPredicates.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.eclipse.smarthome.config.discovery.DiscoveryResult;
import org.eclipse.smarthome.config.discovery.DiscoveryResultFlag;
import org.eclipse.smarthome.config.discovery.inbox.Inbox;
import org.eclipse.smarthome.config.discovery.internal.PersistentInbox;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.io.console.Console;
import org.eclipse.smarthome.io.console.extensions.AbstractConsoleCommandExtension;
import org.eclipse.smarthome.io.console.extensions.ConsoleCommandExtension;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* This class provides console commands around the inbox functionality
*
* @author Kai Kreuzer - Initial contribution and API
*/
@Component(immediate = true, service = ConsoleCommandExtension.class)
public class InboxConsoleCommandExtension extends AbstractConsoleCommandExtension {
private static final String SUBCMD_APPROVE = "approve";
private static final String SUBCMD_IGNORE = "ignore";
private static final String SUBCMD_LIST_IGNORED = "listignored";
private static final String SUBCMD_CLEAR = "clear";
private Inbox inbox;
public InboxConsoleCommandExtension() {
super("inbox", "Manage your inbox.");
}
@Override
public void execute(String[] args, Console console) {
if (args.length > 0) {
final String subCommand = args[0];
switch (subCommand) {
case SUBCMD_APPROVE:
if (args.length > 2) {
String label = args[2];
try {
ThingUID thingUID = new ThingUID(args[1]);
List<DiscoveryResult> results = inbox.stream().filter(forThingUID(thingUID))
.collect(Collectors.toList());
if (results.isEmpty()) {
console.println("No matching inbox entry could be found.");
return;
}
inbox.approve(thingUID, label);
} catch (Exception e) {
console.println(e.getMessage());
}
} else {
console.println("Specify thing id to approve: inbox approve <thingUID> <label>");
}
break;
case SUBCMD_IGNORE:
if (args.length > 1) {
try {
ThingUID thingUID = new ThingUID(args[1]);
PersistentInbox persistentInbox = (PersistentInbox) inbox;
persistentInbox.setFlag(thingUID, DiscoveryResultFlag.IGNORED);
} catch (IllegalArgumentException e) {
console.println("'" + args[1] + "' is no valid thing UID.");
}
} else {
console.println("Cannot approve thing as managed thing provider is missing.");
}
break;
case SUBCMD_LIST_IGNORED:
printInboxEntries(console, inbox.stream().filter(withFlag((DiscoveryResultFlag.IGNORED)))
.collect(Collectors.toList()));
break;
case SUBCMD_CLEAR:
clearInboxEntries(console, inbox.getAll());
break;
default:
break;
}
} else {
printInboxEntries(console,
inbox.stream().filter(withFlag((DiscoveryResultFlag.NEW))).collect(Collectors.toList()));
}
}
private void printInboxEntries(Console console, List<DiscoveryResult> discoveryResults) {
if (discoveryResults.isEmpty()) {
console.println("No inbox entries found.");
}
for (DiscoveryResult discoveryResult : discoveryResults) {
ThingTypeUID thingTypeUID = discoveryResult.getThingTypeUID();
ThingUID thingUID = discoveryResult.getThingUID();
String label = discoveryResult.getLabel();
DiscoveryResultFlag flag = discoveryResult.getFlag();
ThingUID bridgeId = discoveryResult.getBridgeUID();
Map<String, Object> properties = discoveryResult.getProperties();
String representationProperty = discoveryResult.getRepresentationProperty();
String timestamp = new Date(discoveryResult.getTimestamp()).toString();
String timeToLive = discoveryResult.getTimeToLive() == DiscoveryResult.TTL_UNLIMITED ? "UNLIMITED"
: "" + discoveryResult.getTimeToLive();
console.println(String.format(
"%s [%s]: %s [thingId=%s, bridgeId=%s, properties=%s, representationProperty=%s, timestamp=%s, timeToLive=%s]",
flag.name(), thingTypeUID, label, thingUID, bridgeId, properties, representationProperty, timestamp,
timeToLive));
}
}
private void clearInboxEntries(Console console, List<DiscoveryResult> discoveryResults) {
if (discoveryResults.isEmpty()) {
console.println("No inbox entries found.");
}
for (DiscoveryResult discoveryResult : discoveryResults) {
ThingTypeUID thingTypeUID = discoveryResult.getThingTypeUID();
ThingUID thingUID = discoveryResult.getThingUID();
String label = discoveryResult.getLabel();
DiscoveryResultFlag flag = discoveryResult.getFlag();
ThingUID bridgeId = discoveryResult.getBridgeUID();
Map<String, Object> properties = discoveryResult.getProperties();
console.println(String.format("REMOVED [%s]: %s [label=%s, thingId=%s, bridgeId=%s, properties=%s]",
flag.name(), thingTypeUID, label, thingUID, bridgeId, properties));
inbox.remove(thingUID);
}
}
@Override
public List<String> getUsages() {
return Arrays.asList(new String[] { buildCommandUsage("lists all current inbox entries"),
buildCommandUsage(SUBCMD_LIST_IGNORED, "lists all ignored inbox entries"),
buildCommandUsage(SUBCMD_APPROVE + " <thingUID> <label>", "creates a thing for an inbox entry"),
buildCommandUsage(SUBCMD_CLEAR, "clears all current inbox entries"),
buildCommandUsage(SUBCMD_IGNORE + " <thingUID>", "ignores an inbox entry permanently") });
}
@Reference
protected void setInbox(Inbox inbox) {
this.inbox = inbox;
}
protected void unsetInbox(Inbox inbox) {
this.inbox = null;
}
}
| Display usage help when entering non-existing inbox console command; add (#5588)
explicit list command for inbox console commands.
Signed-off-by: Henning Sudbrock <[email protected]> | bundles/config/org.eclipse.smarthome.config.discovery/src/main/java/org/eclipse/smarthome/config/discovery/internal/console/InboxConsoleCommandExtension.java | Display usage help when entering non-existing inbox console command; add (#5588) | <ide><path>undles/config/org.eclipse.smarthome.config.discovery/src/main/java/org/eclipse/smarthome/config/discovery/internal/console/InboxConsoleCommandExtension.java
<ide> import org.osgi.service.component.annotations.Reference;
<ide>
<ide> /**
<del> * This class provides console commands around the inbox functionality
<add> * This class provides console commands around the inbox functionality.
<ide> *
<ide> * @author Kai Kreuzer - Initial contribution and API
<ide> */
<ide>
<ide> private static final String SUBCMD_APPROVE = "approve";
<ide> private static final String SUBCMD_IGNORE = "ignore";
<add> private static final String SUBCMD_LIST = "list";
<ide> private static final String SUBCMD_LIST_IGNORED = "listignored";
<ide> private static final String SUBCMD_CLEAR = "clear";
<ide>
<ide> console.println("Cannot approve thing as managed thing provider is missing.");
<ide> }
<ide> break;
<add> case SUBCMD_LIST:
<add> printInboxEntries(console,
<add> inbox.stream().filter(withFlag((DiscoveryResultFlag.NEW))).collect(Collectors.toList()));
<add> break;
<ide> case SUBCMD_LIST_IGNORED:
<ide> printInboxEntries(console, inbox.stream().filter(withFlag((DiscoveryResultFlag.IGNORED)))
<ide> .collect(Collectors.toList()));
<ide> clearInboxEntries(console, inbox.getAll());
<ide> break;
<ide> default:
<add> printUsage(console);
<ide> break;
<ide> }
<ide> } else {
<ide> @Override
<ide> public List<String> getUsages() {
<ide> return Arrays.asList(new String[] { buildCommandUsage("lists all current inbox entries"),
<add> buildCommandUsage(SUBCMD_LIST, "lists all current inbox entries"),
<ide> buildCommandUsage(SUBCMD_LIST_IGNORED, "lists all ignored inbox entries"),
<ide> buildCommandUsage(SUBCMD_APPROVE + " <thingUID> <label>", "creates a thing for an inbox entry"),
<ide> buildCommandUsage(SUBCMD_CLEAR, "clears all current inbox entries"), |
|
Java | apache-2.0 | 981d94d96815b14c2f1ac940f45e38082876c4dc | 0 | anotherdev/robospice-fluent-request,anotherdev/robospice-fluent-request | package com.anotherdev.android.robospice;
import javax.annotation.Nullable;
abstract class Optional<T> {
public static <T> Optional<T> absent() {
return Absent.withType();
}
public static <T> Optional<T> from(@Nullable T nullableReference) {
return (nullableReference == null)
? Optional.<T>absent()
: new Present<>(nullableReference);
}
Optional() {}
public abstract boolean isPresent();
public abstract T get();
public abstract T or(T defaultValue);
public abstract Optional<T> or(Optional<? extends T> secondChoice);
@Nullable
public abstract T orNull();
protected static <R> R checkNotNull(R reference) {
return checkNotNull(reference, null);
}
protected static <R> R checkNotNull(R reference, @Nullable CharSequence errorMessage) {
if (reference == null) {
if (errorMessage == null) {
throw new NullPointerException();
} else {
throw new NullPointerException(String.valueOf(errorMessage));
}
}
return reference;
}
}
| library/src/main/java/com/anotherdev/android/robospice/Optional.java | package com.anotherdev.android.robospice;
import javax.annotation.Nullable;
abstract class Optional<T> {
public static <T> Optional<T> absent() {
return Absent.withType();
}
public static <T> Optional<T> from(@Nullable T nullableReference) {
return (nullableReference == null)
? Optional.<T>absent()
: new Present<>(nullableReference);
}
Optional() {}
public abstract boolean isPresent();
public abstract T get();
public abstract T or(T defaultValue);
@Nullable
public abstract T orNull();
protected T checkNotNull(T reference) {
return checkNotNull(reference, null);
}
protected T checkNotNull(T reference, @Nullable CharSequence errorMessage) {
if (reference == null) {
if (errorMessage == null) {
throw new NullPointerException();
} else {
throw new NullPointerException(String.valueOf(errorMessage));
}
}
return reference;
}
}
| don't use the same generic type
| library/src/main/java/com/anotherdev/android/robospice/Optional.java | don't use the same generic type | <ide><path>ibrary/src/main/java/com/anotherdev/android/robospice/Optional.java
<ide>
<ide> public abstract T or(T defaultValue);
<ide>
<add> public abstract Optional<T> or(Optional<? extends T> secondChoice);
<add>
<ide> @Nullable
<ide> public abstract T orNull();
<ide>
<del> protected T checkNotNull(T reference) {
<add>
<add> protected static <R> R checkNotNull(R reference) {
<ide> return checkNotNull(reference, null);
<ide> }
<ide>
<del> protected T checkNotNull(T reference, @Nullable CharSequence errorMessage) {
<add> protected static <R> R checkNotNull(R reference, @Nullable CharSequence errorMessage) {
<ide> if (reference == null) {
<ide> if (errorMessage == null) {
<ide> throw new NullPointerException(); |
|
JavaScript | mit | c114848a75d96f62c04d460ee12a506a2ca626d7 | 0 | JustinBeaudry/gulp-gitmodified,mikaelbr/gulp-gitmodified,denvo/gulp-gitmodified | /*global describe, it*/
"use strict";
var should = require("should"),
through = require("through2"),
fs = require("fs"),
join = require("path").join,
git = require("../lib/git");
require("mocha");
var filePath = join(__dirname, "./fixtures/*.txt"),
expectedFile = join(__dirname, "./fixtures/a.txt");
var gutil = require("gulp-util"),
gulp = require("gulp"),
gitmodified = require("../");
describe("gulp-gitmodified", function () {
it("should return a stream", function (done) {
var stream = gitmodified();
should.exist(stream.on);
should.exist(stream.write);
done();
});
it("should call git library with a tester", function (done) {
git.getStatusByMatcher = function (tester, cb) {
should.exist(tester);
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified());
});
it("should default to modified mode", function (done) {
git.getStatusByMatcher = function (tester, cb) {
tester.toString().should.equal("/^M\\s/i");
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified());
});
it("should map mode from named string to short hand", function (done) {
git.getStatusByMatcher = function (tester, cb) {
tester.toString().should.equal("/^M\\s/i");
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified("modified"));
});
it("should map deleted mode from named string to short hand", function (done) {
git.getStatusByMatcher = function (tester, cb) {
tester.toString().should.equal("/^D\\s/i");
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified("deleted"));
});
it("should return modified files", function (done) {
git.getStatusByMatcher = function (tester, cb) {
cb(null, ["a.txt"]);
};
var instream = gulp.src(filePath);
instream
.pipe(gitmodified("deleted"))
.pipe(through.obj(function(file, enc, cb) {
should.exist(file);
should.exist(file.path);
should.exist(file.contents);
file.path.should.equal(expectedFile);
done();
}));
});
it("should throw error when git returns error", function (done) {
git.getStatusByMatcher = function (tester, cb) {
return cb(new Error("new error"));
};
var instream = gulp.src(filePath);
var outstream = gitmodified();
instream
.pipe(gitmodified())
.on('error', function (err) {
should.exist(err);
err.message.should.equal("new error");
done();
});
});
it("should throw gulp specific error", function (done) {
git.getStatusByMatcher = function (tester, cb) {
return cb(new Error("new error"));
};
var instream = gulp.src(filePath);
var outstream = gitmodified();
instream
.pipe(gitmodified())
.on('error', function (err) {
should.exist(err.plugin);
err.plugin.should.equal("gulp-gitmodified");
done();
});
});
it("should pass on no files when no status is returned", function (done) {
var numFiles = 0;
git.getStatusByMatcher = function (tester, cb) {
cb(null, []);
};
var instream = gulp.src(filePath);
var outstream = gitmodified();
instream
.pipe(gitmodified("deleted"))
.pipe(through.obj(function(file, enc, cb) {
++numFiles;
done();
}, function (callback) {
numFiles.should.equal(0);
callback();
done();
}));
});
it('should handle streamed files', function (done) {
var streamedFile = new gutil.File({
path: "test/fixtures/a.txt",
cwd: "test/",
base: "test/fixtures/",
contents: fs.createReadStream(join(__dirname, "/fixtures/a.txt"))
});
git.getStatusByMatcher = function (tester, cb) {
cb(null, ["a.txt"]);
};
var outstream = gitmodified();
outstream.on('data', function(file) {
should.exist(file);
should.exist(file.path);
should.exist(file.contents);
should(file.isNull()).not.equal(true);
should.exist(file.isStream());
file.contents.should.equal(streamedFile.contents);
done();
});
outstream.write(streamedFile);
});
it('should handle folders', function (done) {
git.getStatusByMatcher = function (tester, cb) {
cb(null, ["fixtures/"]);
};
var instream = gulp.src(join(__dirname, "./fixtures"));
var outstream = gitmodified();
outstream.on('data', function(file) {
should.exist(file);
should.exist(file.path);
file.relative.should.equal('fixtures');
should.exist(file.isNull());
done();
});
instream.pipe(outstream);
});
});
| test/main.js | /*global describe, it*/
"use strict";
var should = require("should"),
through = require("through2"),
fs = require("fs"),
join = require("path").join,
git = require("../lib/git");
require("mocha");
var filePath = join(__dirname, "./fixtures/*.txt"),
expectedFile = join(__dirname, "./fixtures/a.txt");
var gutil = require("gulp-util"),
gulp = require("gulp"),
gitmodified = require("../");
describe("gulp-gitmodified", function () {
it("should return a stream", function (done) {
var stream = gitmodified();
should.exist(stream.on);
should.exist(stream.write);
done();
});
it("should call git library with a tester", function (done) {
git.getStatusByMatcher = function (tester, cb) {
should.exist(tester);
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified());
});
it("should default to modified mode", function (done) {
git.getStatusByMatcher = function (tester, cb) {
tester.toString().should.equal("/^M\\s/i");
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified());
});
it("should map mode from named string to short hand", function (done) {
git.getStatusByMatcher = function (tester, cb) {
tester.toString().should.equal("/^M\\s/i");
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified("modified"));
});
it("should map deleted mode from named string to short hand", function (done) {
git.getStatusByMatcher = function (tester, cb) {
tester.toString().should.equal("/^D\\s/i");
done();
};
var instream = gulp.src(filePath);
instream.pipe(gitmodified("deleted"));
});
it("should return modified files", function (done) {
git.getStatusByMatcher = function (tester, cb) {
cb(null, ["a.txt"]);
};
var instream = gulp.src(filePath);
instream
.pipe(gitmodified("deleted"))
.pipe(through.obj(function(file, enc, cb) {
should.exist(file);
should.exist(file.path);
should.exist(file.contents);
file.path.should.equal(expectedFile);
done();
}));
});
it("should throw error when git returns error", function (done) {
git.getStatusByMatcher = function (tester, cb) {
return cb(new Error("new error"));
};
var instream = gulp.src(filePath);
var outstream = gitmodified();
instream
.pipe(gitmodified())
.on('error', function (err) {
should.exist(err);
err.message.should.equal("new error");
done();
});
});
it("should throw gulp specific error", function (done) {
git.getStatusByMatcher = function (tester, cb) {
return cb(new Error("new error"));
};
var instream = gulp.src(filePath);
var outstream = gitmodified();
instream
.pipe(gitmodified())
.on('error', function (err) {
should.exist(err.plugin);
err.plugin.should.equal("gulp-gitmodified");
done();
});
});
it("should pass on no files when no status is returned", function (done) {
var numFiles = 0;
git.getStatusByMatcher = function (tester, cb) {
cb(null, []);
};
var instream = gulp.src(filePath);
var outstream = gitmodified();
instream
.pipe(gitmodified("deleted"))
.pipe(through.obj(function(file, enc, cb) {
++numFiles;
done();
}, function (callback) {
numFiles.should.equal(0);
callback();
done();
}));
});
it('should handle streamed files', function (done) {
var streamedFile = new gutil.File({
path: "test/fixtures/a.txt",
cwd: "test/",
base: "test/fixtures/",
contents: fs.createReadStream("test/fixtures/a.txt")
});
git.getStatusByMatcher = function (tester, cb) {
cb(null, ["a.txt"]);
};
var outstream = gitmodified();
outstream.on('data', function(file) {
should.exist(file);
should.exist(file.path);
should.exist(file.contents);
should.exist(file.isStream());
file.contents.should.equal(streamedFile.contents);
done();
});
outstream.write(streamedFile);
});
it('should handle folders', function (done) {
git.getStatusByMatcher = function (tester, cb) {
cb(null, ["fixtures/"]);
};
var instream = gulp.src(join(__dirname, "./fixtures"));
var outstream = gitmodified();
outstream.on('data', function(file) {
should.exist(file);
should.exist(file.path);
file.relative.should.equal('fixtures');
should.exist(file.isNull());
done();
});
instream.pipe(outstream);
});
});
| Adds assertion for if content is null on stream test.
| test/main.js | Adds assertion for if content is null on stream test. | <ide><path>est/main.js
<ide> path: "test/fixtures/a.txt",
<ide> cwd: "test/",
<ide> base: "test/fixtures/",
<del> contents: fs.createReadStream("test/fixtures/a.txt")
<add> contents: fs.createReadStream(join(__dirname, "/fixtures/a.txt"))
<ide> });
<ide>
<ide> git.getStatusByMatcher = function (tester, cb) {
<ide> should.exist(file);
<ide> should.exist(file.path);
<ide> should.exist(file.contents);
<add> should(file.isNull()).not.equal(true);
<ide> should.exist(file.isStream());
<ide> file.contents.should.equal(streamedFile.contents);
<ide> done(); |
|
Java | apache-2.0 | 83c941d5e5479e8792771b169cabfab0a9b1fe83 | 0 | apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.cxf;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.MessageContext;
import org.apache.cxf.Bus;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.transport.ConduitInitiator;
import org.apache.cxf.transport.Destination;
import org.apache.cxf.transport.MessageObserver;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.geronimo.webservices.WebServiceContainer;
import org.apache.geronimo.webservices.WebServiceContainer.Request;
import org.apache.geronimo.webservices.WebServiceContainer.Response;
public class GeronimoDestination extends AbstractHTTPDestination
implements Serializable {
private MessageObserver messageObserver;
public GeronimoDestination(Bus bus,
ConduitInitiator conduitInitiator,
EndpointInfo endpointInfo) throws IOException {
super(bus, conduitInitiator, endpointInfo, true);
}
public EndpointInfo getEndpointInfo() {
return this.endpointInfo;
}
public void invoke(Request request, Response response) throws Exception {
MessageImpl message = new MessageImpl();
message.setContent(InputStream.class, request.getInputStream());
message.setDestination(this);
message.put(Request.class, request);
message.put(Response.class, response);
HttpServletRequest servletRequest =
(HttpServletRequest)request.getAttribute(WebServiceContainer.SERVLET_REQUEST);
message.put(MessageContext.SERVLET_REQUEST, servletRequest);
HttpServletResponse servletResponse =
(HttpServletResponse)request.getAttribute(WebServiceContainer.SERVLET_RESPONSE);
message.put(MessageContext.SERVLET_RESPONSE, servletResponse);
ServletContext servletContext =
(ServletContext)request.getAttribute(WebServiceContainer.SERVLET_CONTEXT);
message.put(MessageContext.SERVLET_CONTEXT, servletContext);
// this calls copyRequestHeaders()
setHeaders(message);
message.put(Message.HTTP_REQUEST_METHOD, servletRequest.getMethod());
message.put(Message.PATH_INFO, servletRequest.getPathInfo());
message.put(Message.QUERY_STRING, servletRequest.getQueryString());
message.put(Message.CONTENT_TYPE, servletRequest.getContentType());
message.put(Message.ENCODING, getCharacterEncoding(servletRequest.getCharacterEncoding()));
messageObserver.onMessage(message);
}
private static String getCharacterEncoding(String encoding) {
if (encoding != null) {
encoding = encoding.trim();
// work around a bug with Jetty which results in the character
// encoding not being trimmed correctly:
// http://jira.codehaus.org/browse/JETTY-302
if (encoding.endsWith("\"")) {
encoding = encoding.substring(0, encoding.length() - 1);
}
}
return encoding;
}
protected void copyRequestHeaders(Message message, Map<String, List<String>> headers) {
HttpServletRequest servletRequest = (HttpServletRequest)message.get(MessageContext.SERVLET_REQUEST);
if (servletRequest != null) {
Enumeration names = servletRequest.getHeaderNames();
while(names.hasMoreElements()) {
String name = (String)names.nextElement();
List<String> headerValues = headers.get(name);
if (headerValues == null) {
headerValues = new ArrayList<String>();
headers.put(name, headerValues);
}
Enumeration values = servletRequest.getHeaders(name);
while(values.hasMoreElements()) {
String value = (String)values.nextElement();
headerValues.add(value);
}
}
}
}
public Logger getLogger() {
return Logger.getLogger(GeronimoDestination.class.getName());
}
public Conduit getInbuiltBackChannel(Message inMessage) {
return new BackChannelConduit(null, inMessage);
}
public Conduit getBackChannel(Message inMessage,
Message partialResponse,
EndpointReferenceType address) throws IOException {
Conduit backChannel = null;
if (address == null) {
backChannel = new BackChannelConduit(address, inMessage);
} else {
if (partialResponse != null) {
// setup the outbound message to for 202 Accepted
partialResponse.put(Message.RESPONSE_CODE,
HttpURLConnection.HTTP_ACCEPTED);
backChannel = new BackChannelConduit(address, inMessage);
} else {
backChannel = conduitInitiator.getConduit(endpointInfo, address);
// ensure decoupled back channel input stream is closed
backChannel.setMessageObserver(new MessageObserver() {
public void onMessage(Message m) {
if (m.getContentFormats().contains(InputStream.class)) {
InputStream is = m.getContent(InputStream.class);
try {
is.close();
} catch (Exception e) {
// ignore
}
}
}
});
}
}
return backChannel;
}
public void shutdown() {
}
public void setMessageObserver(MessageObserver messageObserver) {
this.messageObserver = messageObserver;
}
protected class BackChannelConduit implements Conduit {
protected Message request;
protected EndpointReferenceType target;
BackChannelConduit(EndpointReferenceType target, Message request) {
this.target = target;
this.request = request;
}
public void close(Message msg) throws IOException {
msg.getContent(OutputStream.class).close();
}
/**
* Register a message observer for incoming messages.
*
* @param observer the observer to notify on receipt of incoming
*/
public void setMessageObserver(MessageObserver observer) {
// shouldn't be called for a back channel conduit
}
public void prepare(Message message) throws IOException {
send(message);
}
/**
* Send an outbound message, assumed to contain all the name-value
* mappings of the corresponding input message (if any).
*
* @param message the message to be sent.
*/
public void send(Message message) throws IOException {
Response response = (Response)request.get(Response.class);
// handle response headers
updateResponseHeaders(message);
Map<String, List<String>> protocolHeaders =
(Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
// set headers of the HTTP response object
Iterator headers = protocolHeaders.entrySet().iterator();
while (headers.hasNext()) {
Map.Entry entry = (Map.Entry) headers.next();
String headerName = (String) entry.getKey();
String headerValue = getHeaderValue((List) entry.getValue());
response.setHeader(headerName, headerValue);
}
message.setContent(OutputStream.class, new WrappedOutputStream(message, response));
}
/**
* @return the reference associated with the target Destination
*/
public EndpointReferenceType getTarget() {
return target;
}
/**
* Retreive the back-channel Destination.
*
* @return the backchannel Destination (or null if the backchannel is
* built-in)
*/
public Destination getBackChannel() {
return null;
}
/**
* Close the conduit
*/
public void close() {
}
}
private String getHeaderValue(List<String> values) {
Iterator iter = values.iterator();
StringBuffer buf = new StringBuffer();
while(iter.hasNext()) {
buf.append(iter.next());
if (iter.hasNext()) {
buf.append(", ");
}
}
return buf.toString();
}
protected void setContentType(Message message, Response response) {
Map<String, List<String>> protocolHeaders =
(Map<String, List<String>>)message.get(Message.PROTOCOL_HEADERS);
if (protocolHeaders == null || !protocolHeaders.containsKey(Message.CONTENT_TYPE)) {
String ct = (String) message.get(Message.CONTENT_TYPE);
String enc = (String) message.get(Message.ENCODING);
if (null != ct) {
if (enc != null && ct.indexOf("charset=") == -1) {
ct = ct + "; charset=" + enc;
}
response.setContentType(ct);
} else if (enc != null) {
response.setContentType("text/xml; charset=" + enc);
}
}
}
private class WrappedOutputStream extends OutputStream {
private Message message;
private Response response;
private OutputStream rawOutputStream;
WrappedOutputStream(Message message, Response response) {
this.message = message;
this.response = response;
}
public void write(int b) throws IOException {
flushHeaders();
this.rawOutputStream.write(b);
}
public void write(byte b[]) throws IOException {
flushHeaders();
this.rawOutputStream.write(b);
}
public void write(byte b[], int off, int len) throws IOException {
flushHeaders();
this.rawOutputStream.write(b, off, len);
}
public void flush() throws IOException {
flushHeaders();
this.rawOutputStream.flush();
}
public void close() throws IOException {
flushHeaders();
this.rawOutputStream.close();
}
protected void flushHeaders() throws IOException {
if (this.rawOutputStream != null) {
return;
}
// set response code
Integer i = (Integer) this.message.get(Message.RESPONSE_CODE);
if (i != null) {
this.response.setStatusCode(i.intValue());
}
// set content-type
setContentType(this.message, this.response);
this.rawOutputStream = this.response.getOutputStream();
}
}
}
| modules/geronimo-cxf/src/main/java/org/apache/geronimo/cxf/GeronimoDestination.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.cxf;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.MessageContext;
import org.apache.cxf.Bus;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.transport.ConduitInitiator;
import org.apache.cxf.transport.Destination;
import org.apache.cxf.transport.MessageObserver;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.geronimo.webservices.WebServiceContainer;
import org.apache.geronimo.webservices.WebServiceContainer.Request;
import org.apache.geronimo.webservices.WebServiceContainer.Response;
public class GeronimoDestination extends AbstractHTTPDestination
implements Serializable {
private MessageObserver messageObserver;
public GeronimoDestination(Bus bus,
ConduitInitiator conduitInitiator,
EndpointInfo endpointInfo) throws IOException {
super(bus, conduitInitiator, endpointInfo, true);
}
public EndpointInfo getEndpointInfo() {
return this.endpointInfo;
}
public void invoke(Request request, Response response) throws Exception {
MessageImpl message = new MessageImpl();
message.setContent(InputStream.class, request.getInputStream());
message.setDestination(this);
message.put(Request.class, request);
message.put(Response.class, response);
HttpServletRequest servletRequest =
(HttpServletRequest)request.getAttribute(WebServiceContainer.SERVLET_REQUEST);
message.put(MessageContext.SERVLET_REQUEST, servletRequest);
HttpServletResponse servletResponse =
(HttpServletResponse)request.getAttribute(WebServiceContainer.SERVLET_RESPONSE);
message.put(MessageContext.SERVLET_RESPONSE, servletResponse);
ServletContext servletContext =
(ServletContext)request.getAttribute(WebServiceContainer.SERVLET_CONTEXT);
message.put(MessageContext.SERVLET_CONTEXT, servletContext);
// this calls copyRequestHeaders()
setHeaders(message);
message.put(Message.HTTP_REQUEST_METHOD, servletRequest.getMethod());
message.put(Message.PATH_INFO, servletRequest.getPathInfo());
message.put(Message.QUERY_STRING, servletRequest.getQueryString());
message.put(Message.CONTENT_TYPE, servletRequest.getContentType());
message.put(Message.ENCODING, getCharacterEncoding(servletRequest.getCharacterEncoding()));
messageObserver.onMessage(message);
}
private static String getCharacterEncoding(String encoding) {
if (encoding != null) {
encoding = encoding.trim();
// work around a bug with Jetty which results in the character
// encoding not being trimmed correctly:
// http://jira.codehaus.org/browse/JETTY-302
if (encoding.endsWith("\"")) {
encoding = encoding.substring(0, encoding.length() - 1);
}
}
return encoding;
}
protected void copyRequestHeaders(Message message, Map<String, List<String>> headers) {
HttpServletRequest servletRequest = (HttpServletRequest)message.get(MessageContext.SERVLET_REQUEST);
if (servletRequest != null) {
Enumeration names = servletRequest.getHeaderNames();
while(names.hasMoreElements()) {
String name = (String)names.nextElement();
List<String> headerValues = headers.get(name);
if (headerValues == null) {
headerValues = new ArrayList<String>();
headers.put(name, headerValues);
}
Enumeration values = servletRequest.getHeaders(name);
while(values.hasMoreElements()) {
String value = (String)values.nextElement();
headerValues.add(value);
}
}
}
}
public Logger getLogger() {
return Logger.getLogger(GeronimoDestination.class.getName());
}
public Conduit getInbuiltBackChannel(Message inMessage) {
return new BackChannelConduit(null, inMessage);
}
public Conduit getBackChannel(Message inMessage,
Message partialResponse,
EndpointReferenceType address) throws IOException {
Conduit backChannel = null;
if (address == null) {
backChannel = new BackChannelConduit(address, inMessage);
} else {
if (partialResponse != null) {
// setup the outbound message to for 202 Accepted
partialResponse.put(Message.RESPONSE_CODE,
HttpURLConnection.HTTP_ACCEPTED);
backChannel = new BackChannelConduit(address, inMessage);
} else {
backChannel = conduitInitiator.getConduit(endpointInfo, address);
// ensure decoupled back channel input stream is closed
backChannel.setMessageObserver(new MessageObserver() {
public void onMessage(Message m) {
if (m.getContentFormats().contains(InputStream.class)) {
InputStream is = m.getContent(InputStream.class);
try {
is.close();
} catch (Exception e) {
// ignore
}
}
}
});
}
}
return backChannel;
}
public void shutdown() {
}
public void setMessageObserver(MessageObserver messageObserver) {
this.messageObserver = messageObserver;
}
protected class BackChannelConduit implements Conduit {
protected Message request;
protected EndpointReferenceType target;
BackChannelConduit(EndpointReferenceType target, Message request) {
this.target = target;
this.request = request;
}
public void close(Message msg) throws IOException {
msg.getContent(OutputStream.class).close();
}
/**
* Register a message observer for incoming messages.
*
* @param observer the observer to notify on receipt of incoming
*/
public void setMessageObserver(MessageObserver observer) {
// shouldn't be called for a back channel conduit
}
public void prepare(Message message) throws IOException {
send(message);
}
/**
* Send an outbound message, assumed to contain all the name-value
* mappings of the corresponding input message (if any).
*
* @param message the message to be sent.
*/
public void send(Message message) throws IOException {
Response response = (Response)request.get(Response.class);
// 1. handle response code
Integer i = (Integer) message.get(Message.RESPONSE_CODE);
if (i != null) {
response.setStatusCode(i.intValue());
}
// 2. handle response headers
updateResponseHeaders(message);
Map<String, List<String>> protocolHeaders =
(Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
// set headers of the HTTP response object
Iterator headers = protocolHeaders.entrySet().iterator();
while (headers.hasNext()) {
Map.Entry entry = (Map.Entry) headers.next();
String headerName = (String) entry.getKey();
String headerValue = getHeaderValue((List) entry.getValue());
response.setHeader(headerName, headerValue);
}
message.setContent(OutputStream.class, new WrappedOutputStream(message, response));
}
/**
* @return the reference associated with the target Destination
*/
public EndpointReferenceType getTarget() {
return target;
}
/**
* Retreive the back-channel Destination.
*
* @return the backchannel Destination (or null if the backchannel is
* built-in)
*/
public Destination getBackChannel() {
return null;
}
/**
* Close the conduit
*/
public void close() {
}
}
private String getHeaderValue(List<String> values) {
Iterator iter = values.iterator();
StringBuffer buf = new StringBuffer();
while(iter.hasNext()) {
buf.append(iter.next());
if (iter.hasNext()) {
buf.append(", ");
}
}
return buf.toString();
}
protected void setContentType(Message message, Response response) {
Map<String, List<String>> protocolHeaders =
(Map<String, List<String>>)message.get(Message.PROTOCOL_HEADERS);
if (protocolHeaders == null || !protocolHeaders.containsKey(Message.CONTENT_TYPE)) {
String ct = (String) message.get(Message.CONTENT_TYPE);
String enc = (String) message.get(Message.ENCODING);
if (null != ct) {
if (enc != null && ct.indexOf("charset=") == -1) {
ct = ct + "; charset=" + enc;
}
response.setContentType(ct);
} else if (enc != null) {
response.setContentType("text/xml; charset=" + enc);
}
}
}
private class WrappedOutputStream extends OutputStream {
private Message message;
private Response response;
private OutputStream rawOutputStream;
WrappedOutputStream(Message message, Response response) {
this.message = message;
this.response = response;
}
public void write(int b) throws IOException {
flushHeaders();
this.rawOutputStream.write(b);
}
public void write(byte b[]) throws IOException {
flushHeaders();
this.rawOutputStream.write(b);
}
public void write(byte b[], int off, int len) throws IOException {
flushHeaders();
this.rawOutputStream.write(b, off, len);
}
public void flush() throws IOException {
flushHeaders();
this.rawOutputStream.flush();
}
public void close() throws IOException {
flushHeaders();
this.rawOutputStream.close();
}
protected void flushHeaders() throws IOException {
if (this.rawOutputStream != null) {
return;
}
setContentType(this.message, this.response);
this.rawOutputStream = this.response.getOutputStream();
}
}
} | delay setting of the response code
git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@531496 13f79535-47bb-0310-9956-ffa450edef68
| modules/geronimo-cxf/src/main/java/org/apache/geronimo/cxf/GeronimoDestination.java | delay setting of the response code | <ide><path>odules/geronimo-cxf/src/main/java/org/apache/geronimo/cxf/GeronimoDestination.java
<ide> public void send(Message message) throws IOException {
<ide> Response response = (Response)request.get(Response.class);
<ide>
<del> // 1. handle response code
<del> Integer i = (Integer) message.get(Message.RESPONSE_CODE);
<del> if (i != null) {
<del> response.setStatusCode(i.intValue());
<del> }
<del>
<del> // 2. handle response headers
<add> // handle response headers
<ide> updateResponseHeaders(message);
<ide>
<ide> Map<String, List<String>> protocolHeaders =
<ide> return;
<ide> }
<ide>
<add> // set response code
<add> Integer i = (Integer) this.message.get(Message.RESPONSE_CODE);
<add> if (i != null) {
<add> this.response.setStatusCode(i.intValue());
<add> }
<add>
<add> // set content-type
<ide> setContentType(this.message, this.response);
<del>
<add>
<ide> this.rawOutputStream = this.response.getOutputStream();
<ide> }
<ide> |
|
Java | mit | 794c2372988c998ed018a16e5157f094a1780cb8 | 0 | anagav/TinkerRocks | package com.tinkerrocks.process.traversal;
import com.tinkerrocks.index.RocksIndex;
import com.tinkerrocks.structure.RocksGraph;
import org.apache.tinkerpop.gremlin.process.traversal.Compare;
import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by ashishn on 8/15/15.
*/
public class RocksGraphStep<S extends Element> extends GraphStep<S> implements HasContainerHolder {
public final List<HasContainer> hasContainers = new ArrayList<>();
public RocksGraphStep(final GraphStep<S> originalGraphStep) {
super(originalGraphStep.getTraversal(), originalGraphStep.getReturnClass(), originalGraphStep.getIds());
originalGraphStep.getLabels().forEach(this::addLabel);
if ((this.ids.length == 0 || !(this.ids[0] instanceof Element))) {
this.setIteratorSupplier(() -> Vertex.class.isAssignableFrom(this.returnClass) ?
(Iterator) this.vertices() : (Iterator) this.edges());
}
}
private Iterator<? extends Edge> edges() {
final RocksGraph graph = (RocksGraph) this.getTraversal().getGraph().get();
final HasContainer indexedContainer = getIndexKey(Edge.class);
if (this.ids != null && this.ids.length > 0)
return this.iteratorList(graph.edges(this.ids));
else
return null == indexedContainer ?
this.iteratorList(graph.edges()) :
RocksIndex.queryEdgeIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue()).stream()
.filter(edge -> HasContainer.testAll(edge, this.hasContainers))
.collect(Collectors.<Edge>toList()).iterator();
}
private Iterator<? extends Vertex> vertices() {
final RocksGraph graph = (RocksGraph) this.getTraversal().getGraph().get();
final HasContainer indexedContainer = getIndexKey(Vertex.class);
if (this.ids != null && this.ids.length > 0)
return this.iteratorList(graph.vertices(this.ids));
else {
return null == indexedContainer ?
this.iteratorList(graph.vertices()) :
RocksIndex.queryVertexIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue())
.stream().filter(vertex -> HasContainer.testAll(vertex, this.hasContainers))
.collect(Collectors.<Vertex>toList()).iterator();
}
}
@SuppressWarnings("EqualsBetweenInconvertibleTypes")
private HasContainer getIndexKey(final Class<? extends Element> indexedClass) {
final Set<String> indexedKeys = ((RocksGraph) this.getTraversal().getGraph().get()).getIndexedKeys(indexedClass);
return this.hasContainers.stream()
.filter(c -> indexedKeys.contains(c.getKey()) && c.getPredicate().getBiPredicate().equals(Compare.eq))
.findAny()
.orElseGet(() -> null);
}
public String toString() {
if (this.hasContainers.isEmpty())
return super.toString();
else
return 0 == this.ids.length ?
StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), this.hasContainers) :
StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), Arrays.toString(this.ids), this.hasContainers);
}
private <E extends Element> Iterator<E> iteratorList(final Iterator<E> iterator) {
final List<E> list = new ArrayList<>();
while (iterator.hasNext()) {
final E e = iterator.next();
if (HasContainer.testAll(e, this.hasContainers))
list.add(e);
}
return list.iterator();
}
@Override
public List<HasContainer> getHasContainers() {
return this.hasContainers;
}
@Override
public void addHasContainer(final HasContainer hasContainer) {
this.hasContainers.add(hasContainer);
}
}
| src/main/java/com/tinkerrocks/process/traversal/RocksGraphStep.java | package com.tinkerrocks.process.traversal;
import com.tinkerrocks.index.RocksIndex;
import com.tinkerrocks.structure.RocksGraph;
import org.apache.tinkerpop.gremlin.process.traversal.Compare;
import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by ashishn on 8/15/15.
*/
public class RocksGraphStep<S extends Element> extends GraphStep<S> implements HasContainerHolder {
public final List<HasContainer> hasContainers = new ArrayList<>();
public RocksGraphStep(final GraphStep<S> originalGraphStep) {
super(originalGraphStep.getTraversal(), originalGraphStep.getReturnClass(), originalGraphStep.getIds());
originalGraphStep.getLabels().forEach(this::addLabel);
if ((this.ids.length == 0 || !(this.ids[0] instanceof Element))) {
this.setIteratorSupplier(() -> Vertex.class.isAssignableFrom(this.returnClass) ?
(Iterator) this.vertices() : (Iterator) this.edges());
}
}
private Iterator<? extends Edge> edges() {
final RocksGraph graph = (RocksGraph) this.getTraversal().getGraph().get();
final HasContainer indexedContainer = getIndexKey(Edge.class);
if (this.ids != null && this.ids.length > 0)
return this.iteratorList(graph.edges(this.ids));
else
return null == indexedContainer ?
this.iteratorList(graph.edges()) :
RocksIndex.queryEdgeIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue()).stream()
.filter(edge -> HasContainer.testAll(edge, this.hasContainers))
.collect(Collectors.<Edge>toList()).iterator();
}
private Iterator<? extends Vertex> vertices() {
final RocksGraph graph = (RocksGraph) this.getTraversal().getGraph().get();
final HasContainer indexedContainer = getIndexKey(Vertex.class);
if (this.ids != null && this.ids.length > 0)
return this.iteratorList(graph.vertices(this.ids));
else {
return null == indexedContainer ?
this.iteratorList(graph.vertices()) :
RocksIndex.queryVertexIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue())
.stream().filter(vertex -> HasContainer.testAll(vertex, this.hasContainers))
.collect(Collectors.<Vertex>toList()).iterator();
}
}
private HasContainer getIndexKey(final Class<? extends Element> indexedClass) {
final Set<String> indexedKeys = ((RocksGraph) this.getTraversal().getGraph().get()).getIndexedKeys(indexedClass);
return this.hasContainers.stream()
.filter(c -> indexedKeys.contains(c.getKey()) && c.getPredicate().getBiPredicate().equals(Compare.eq))
.findAny()
.orElseGet(() -> null);
}
public String toString() {
if (this.hasContainers.isEmpty())
return super.toString();
else
return 0 == this.ids.length ?
StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), this.hasContainers) :
StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), Arrays.toString(this.ids), this.hasContainers);
}
private <E extends Element> Iterator<E> iteratorList(final Iterator<E> iterator) {
final List<E> list = new ArrayList<>();
while (iterator.hasNext()) {
final E e = iterator.next();
if (HasContainer.testAll(e, this.hasContainers))
list.add(e);
}
return list.iterator();
}
@Override
public List<HasContainer> getHasContainers() {
return this.hasContainers;
}
@Override
public void addHasContainer(final HasContainer hasContainer) {
this.hasContainers.add(hasContainer);
}
}
| supress warnings
| src/main/java/com/tinkerrocks/process/traversal/RocksGraphStep.java | supress warnings | <ide><path>rc/main/java/com/tinkerrocks/process/traversal/RocksGraphStep.java
<ide>
<ide> }
<ide>
<add> @SuppressWarnings("EqualsBetweenInconvertibleTypes")
<ide> private HasContainer getIndexKey(final Class<? extends Element> indexedClass) {
<ide> final Set<String> indexedKeys = ((RocksGraph) this.getTraversal().getGraph().get()).getIndexedKeys(indexedClass);
<ide> |
|
Java | apache-2.0 | 9974591fdc894435a60627f9f12a5e674c029649 | 0 | tom-harwood/jburg3,tom-harwood/jburg3,tom-harwood/jburg3 | package jburg;
import java.util.*;
/**
* A State represents a vertex in the transition table.
* Vertices represent an equivalence class of input nodes,
* each of which has the same opcode/arity; an input node
* must match one of the pattern-matching productions in
* the state. The state may also be able to produce other
* nonterminals via nonterminal-to-nonterminal closures.
*
* <p>Store State objects in hashed associative containers;
* State objects' hash and equality semantics are set up
* to weed out duplicate states.
*/
class State<Nonterminal, NodeType>
{
/**
* The state's number. This number is set
* by the production table when it places
* a state in its table of unique states.
*/
int number = -1;
/** "Typedef" a map of costs by nonterminal. */
@SuppressWarnings("serial")
class CostMap extends HashMap<Nonterminal,Long> {}
/** "Typedef" a map of PatternMatchers keyed by Nonterminal. */
@SuppressWarnings("serial")
class PatternMap extends HashMap<Nonterminal, PatternMatcher<Nonterminal,NodeType>> {}
/** "Typedef" a map of Closures by Nonterminal. */
@SuppressWarnings("serial")
class ClosureMap extends HashMap<Nonterminal, Closure<Nonterminal>> {}
/**
* This state's pattern matching productions.
*/
private PatternMap patternMatchers = new PatternMap();
/**
* Cost of each pattern match.
*/
private CostMap patternCosts = new CostMap();
/**
* This state's closures, i.e., nonterminal-to-nonterminal productions.
*/
private ClosureMap closures = new ClosureMap();
/**
* The node type of this state; used while projecting
* representer states, which are unique for a particular
* tuple of (NodeType, nt=cost*).
*/
final NodeType nodeType;
/**
* Construct a state that characterizes non-null nodes.
* @param nodeType the node type of the nodes.
*/
State(NodeType nodeType)
{
this.nodeType = nodeType;
}
/**
* Construct a state that characterizes null pointers.
*/
State()
{
this.nodeType = null;
}
/**
* Add a pattern match to this state.
* @param p the pattern matching production.
* @param cost the cost of this production. The
* cost must be the best cost known so far.
*/
void setPatternMatcher(PatternMatcher<Nonterminal,NodeType> p, long cost)
{
assert(cost < getCost(p.target));
patternCosts.put(p.target, cost);
patternMatchers.put(p.target, p);
}
/**
* @return the number of pattern matching productions in this state.
*/
int size()
{
assert(patternMatchers.size() == patternCosts.size());
return patternMatchers.size();
}
/**
* @return true if this state has no pattern matching productions.
*/
boolean isEmpty()
{
return size() == 0;
}
/**
* Get the cost of a nonterminal; this may require
* navigation of a chain of closure productions back
* to the pattern-matching production.
* @return the aggregated cost of productions that
* produce the given nonterminal, or Integer.MAX_VALUE
* if there is no production for this nonterminal.
* Costs are returned as longs (and computed as longs)
* so that they don't overflow.
*/
long getCost(Nonterminal nt)
{
if (patternCosts.containsKey(nt)) {
return patternCosts.get(nt);
} else if (closures.containsKey(nt)) {
// Traverse the chain of closures.
Closure<Nonterminal> closure = closures.get(nt);
long closedCost = closure.ownCost + getCost(closure.source);
assert closedCost < Integer.MAX_VALUE;
return closedCost;
} else {
return Integer.MAX_VALUE;
}
}
/**
* Get the Production for a nonterminal.
* @param goal the Nonterminal to be produced.
* @return the corresponding Production, which
* may be a pattern matcher or a closure.
* @throws IllegalArgumentException if this state
* has no production for the specified nonterminal.
*/
Production<Nonterminal> getProduction(Nonterminal goal)
{
if (patternMatchers.containsKey(goal)) {
return patternMatchers.get(goal);
} else if (closures.containsKey(goal)) {
return closures.get(goal);
} else {
throw new IllegalArgumentException(String.format("State %d cannot produce %s", number, goal));
}
}
/**
* Add a closure to the closure map if it's the best alternative seen so far.
* @return true if the closure is added to the map.
*/
boolean addClosure(Closure<Nonterminal> closure)
{
// The cost of a closure is its own cost,
// plus the cost of producing its antecedent.
long closureCost = closure.ownCost + getCost(closure.source);
if (closureCost < this.getCost(closure.target)) {
closures.put(closure.target, closure);
return true;
} else {
return false;
}
}
/**
* Marshal nonterminals produced by both
* pattern matchers and closures.
* @return the set of nonterminals produced.
*/
Set<Nonterminal> getNonterminals()
{
// We could use a cheaper data structure, e.g.,
// List<Nonterminal>, but returning a set makes
// the semantics of this operation clear.
Set<Nonterminal> result = new HashSet<Nonterminal>();
for (Nonterminal patternNonterminal: patternMatchers.keySet()) {
result.add(patternNonterminal);
}
for (Nonterminal closureNonterminal: closures.keySet()) {
// A closure should never occlude a pattern match.
assert !result.contains(closureNonterminal);
result.add(closureNonterminal);
}
return result;
}
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append("State ");
buffer.append(String.valueOf(number));
buffer.append(" ");
buffer.append(this.nodeType);
if (patternMatchers.size() > 0) {
buffer.append("(patterns(");
boolean didFirst = false;
for (Nonterminal nt: patternMatchers.keySet()) {
PatternMatcher<Nonterminal, NodeType> p = patternMatchers.get(nt);
if (didFirst) {
buffer.append(",");
} else {
didFirst = true;
}
buffer.append(String.format("%s=%s", nt, p));
}
buffer.append(")");
if (closures.size() > 0) {
buffer.append(closures);
}
buffer.append(")");
}
return buffer.toString();
}
/**
* Dump an XML rendering of this state.
* @param out the output sink.
*/
void dump(java.io.PrintWriter out)
throws java.io.IOException
{
out.printf("<state number=\"%d\" nodeType=\"%s\">", number, nodeType);
if (patternMatchers.size() > 0) {
out.println("<patterns>");
for (Nonterminal nt: patternMatchers.keySet()) {
PatternMatcher<Nonterminal, NodeType> p = patternMatchers.get(nt);
out.printf("<pattern nt=\"%s\" pattern=\"%s\"/>\n", nt, p);
}
out.printf("</patterns>");
}
if (closures.size() > 0) {
out.println("<closures>");
for (Closure<Nonterminal> closure: closures.values()) {
out.printf(String.format("<closure nt=\"%s\" source=\"%s\"/>", closure.target, closure.source));
}
out.println("</closures>");
}
out.println("</state>");
}
/**
* Dump an abbreviated rendering of this state.
* @param out the output sink.
*/
void miniDump(java.io.PrintWriter out)
throws java.io.IOException
{
out.printf("<leaf state=\"%d\"/>\n", number);
}
/**
* Define a state's hash code in terms of its
* node type's hash code and its pattern map's
* hash code.
*
* <p> <strong>Using the cost map's hash code is invalid,</strong>
* since subsequent iterations may produce states that
* are identical except that they cost more due to closures,
* so computations based on the cost map diverge.
*
* <p>However, two states with the same pattern map
* will also have the same cost map after closure,
* so the pattern map is a valid choice for hashing.
*
* @return this state's node type's hashCode(),
* concatenated with the pattern map's hashCode().
*/
@Override
public int hashCode()
{
int nodeHash = nodeType != null? nodeType.hashCode(): 0;
return nodeHash * 31 + patternMatchers.hashCode();
}
/**
* Two states are equal if their node types
* and pattern maps are equal.
* @param o the object to compare against.
* @return true if o is a State and its node
* type and pattern map are equal to this
* state's corresponding members; false otherwise.
*/
@Override
@SuppressWarnings({"unchecked"})
public boolean equals(Object o)
{
if (o instanceof State) {
State<Nonterminal,NodeType> s = (State<Nonterminal,NodeType>)o;
if (this.nodeType == s.nodeType) {
return true;
} else if (this.nodeType != null && s.nodeType != null) {
return this.nodeType.equals(s.nodeType) && this.patternMatchers.equals(s.patternMatchers);
}
}
return false;
}
}
| src/java/jburg/State.java | package jburg;
import java.util.*;
/**
* A State represents a vertex in the transition table.
* Vertices represent an equivalence class of input nodes,
* each of which has the same opcode/arity; an input node
* must match one of the pattern-matching productions in
* the state. The state may also be able to produce other
* nonterminals via nonterminal-to-nonterminal closures.
*
* The State class is Comparable so that it can be
* sorted on its state number.
*/
class State<Nonterminal, NodeType> implements Comparable<State<Nonterminal,NodeType>>
{
/**
* The state's number. This number is set
* by the production table when it places
* a state in its table of unique states.
*/
int number = -1;
/** "Typedef" a map of costs by nonterminal. */
@SuppressWarnings("serial")
class CostMap extends HashMap<Nonterminal,Long> {}
/** "Typedef" a map of PatternMatchers keyed by Nonterminal. */
@SuppressWarnings("serial")
class PatternMap extends HashMap<Nonterminal, PatternMatcher<Nonterminal,NodeType>> {}
/** "Typedef" a map of Closures by Nonterminal. */
@SuppressWarnings("serial")
class ClosureMap extends HashMap<Nonterminal, Closure<Nonterminal>> {}
/**
* This state's pattern matching productions.
*/
private PatternMap patternMatchers = new PatternMap();
/**
* Cost of each pattern match.
*/
private CostMap patternCosts = new CostMap();
/**
* This state's closures, i.e., nonterminal-to-nonterminal productions.
*/
private ClosureMap closures = new ClosureMap();
/**
* The node type of this state; used while projecting
* representer states, which are unique for a particular
* tuple of (NodeType, nt=cost*).
*/
final NodeType nodeType;
State(NodeType nodeType)
{
this.nodeType = nodeType;
}
void setPatternMatcher(PatternMatcher<Nonterminal,NodeType> p, long cost)
{
assert(cost < getCost(p.target));
patternCosts.put(p.target, cost);
patternMatchers.put(p.target, p);
}
/**
* @return the number of pattern matching productions in this state.
*/
int size()
{
assert(patternMatchers.size() == patternCosts.size());
return patternMatchers.size();
}
/**
* @return true if this state has no pattern matching productions.
*/
boolean isEmpty()
{
return size() == 0;
}
/**
* Get the cost of a nonterminal; this may require
* navigation of a chain of closure productions back
* to the pattern-matching production.
* @return the aggregated cost of productions that
* produce the given nonterminal, or Integer.MAX_VALUE
* if there is no production for this nonterminal.
* Costs are returned as longs (and computed as longs)
* so that they don't overflow.
*/
long getCost(Nonterminal nt)
{
if (patternCosts.containsKey(nt)) {
return patternCosts.get(nt);
} else if (closures.containsKey(nt)) {
// Traverse the chain of closures.
Closure<Nonterminal> closure = closures.get(nt);
long closedCost = closure.ownCost + getCost(closure.source);
assert closedCost < Integer.MAX_VALUE;
return closedCost;
} else {
return Integer.MAX_VALUE;
}
}
/**
* Get the Production for a nonterminal.
* @param goal the Nonterminal to be produced.
* @return the corresponding Production, which
* may be a pattern matcher or a closure.
* @throws IllegalArgumentException if this state
* has no production for the specified nonterminal.
*/
Production<Nonterminal> getProduction(Nonterminal goal)
{
if (patternMatchers.containsKey(goal)) {
return patternMatchers.get(goal);
} else if (closures.containsKey(goal)) {
return closures.get(goal);
} else {
throw new IllegalArgumentException(String.format("State %d cannot produce %s", number, goal));
}
}
/**
* Add a closure to the closure map if it's the best alternative seen so far.
* @return true if the closure is added to the map.
*/
boolean addClosure(Closure<Nonterminal> closure)
{
// The cost of a closure is its own cost,
// plus the cost of producing its antecedent.
long closureCost = closure.ownCost + getCost(closure.source);
if (closureCost < this.getCost(closure.target)) {
closures.put(closure.target, closure);
return true;
} else {
return false;
}
}
/**
* Marshal nonterminals produced by both
* pattern matchers and closures.
* @return the set of nonterminals produced.
*/
Set<Nonterminal> getNonterminals()
{
// We could use a cheaper data structure, e.g.,
// List<Nonterminal>, but returning a set makes
// the semantics of this operation clear.
Set<Nonterminal> result = new HashSet<Nonterminal>();
for (Nonterminal patternNonterminal: patternMatchers.keySet()) {
result.add(patternNonterminal);
}
for (Nonterminal closureNonterminal: closures.keySet()) {
// A closure should never occlude a pattern match.
assert !result.contains(closureNonterminal);
result.add(closureNonterminal);
}
return result;
}
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append("State ");
buffer.append(String.valueOf(number));
buffer.append(" ");
buffer.append(this.nodeType);
if (patternMatchers.size() > 0) {
buffer.append("(patterns(");
boolean didFirst = false;
for (Nonterminal nt: patternMatchers.keySet()) {
PatternMatcher<Nonterminal, NodeType> p = patternMatchers.get(nt);
if (didFirst) {
buffer.append(",");
} else {
didFirst = true;
}
buffer.append(String.format("%s=%s", nt, p));
}
buffer.append(")");
if (closures.size() > 0) {
buffer.append(closures);
}
buffer.append(")");
}
return buffer.toString();
}
/**
* Dump an XML rendering of this state.
* @param out the output sink.
*/
void dump(java.io.PrintWriter out)
throws java.io.IOException
{
out.printf("<state number=\"%d\" nodeType=\"%s\">", number, nodeType);
if (patternMatchers.size() > 0) {
out.println("<patterns>");
for (Nonterminal nt: patternMatchers.keySet()) {
PatternMatcher<Nonterminal, NodeType> p = patternMatchers.get(nt);
out.printf("<pattern nt=\"%s\" pattern=\"%s\"/>\n", nt, p);
}
out.printf("</patterns>");
}
if (closures.size() > 0) {
out.println("<closures>");
for (Closure<Nonterminal> closure: closures.values()) {
out.printf(String.format("<closure nt=\"%s\" source=\"%s\"/>", closure.target, closure.source));
}
out.println("</closures>");
}
out.println("</state>");
}
/**
* Dump an abbreviated rendering of this state.
* @param out the output sink.
*/
void miniDump(java.io.PrintWriter out)
throws java.io.IOException
{
out.printf("<leaf state=\"%d\"/>\n", number);
}
/**
* Define a state's hash code in terms of its
* node type's hash code and its pattern map's
* hash code.
*
* <p> <strong> Using the cost map's hash code is invalid,</strong>
* since subsequent iterations may produce states that
* are identical except that they cost more due to closures,
* so computations based on the cost map diverge.
*
* <p>However, two states with the same pattern map
* will also have the same cost map after closure,
* so the pattern map is a valid choice for hashing.
*
* @return this state's node type's hashCode(),
* concatenated with the pattern map's hashCode().
*/
@Override
public int hashCode()
{
return nodeType.hashCode() * 31 + patternMatchers.hashCode();
}
/**
* Two states are equal if their node types
* and pattern maps are equal.
* @param o the object to compare against.
* @return true if o is a State and its node
* type and pattern map are equal to this
* state's corresponding members; false otherwise.
*/
@Override
@SuppressWarnings({"unchecked"})
public boolean equals(Object o)
{
if (o instanceof State) {
State<Nonterminal,NodeType> s = (State<Nonterminal,NodeType>)o;
return this.nodeType.equals(s.nodeType) && this.patternMatchers.equals(s.patternMatchers);
} else {
return false;
}
}
/**
* States are comparable on their state number;
* this is a convenience so that the state table,
* which is stored in hashed order, can be emitted
* in state number order.
* <p><strong>This ordering should not be used to
* store State objects in an associative container.</strong>
* Use hash-based associative containers to get
* correct semantics.
*/
@Override
public int compareTo(State<Nonterminal,NodeType> other)
{
assert this.number != -1 && other.number != -1;
return this.number - other.number;
}
}
| Remove State's Comparable semantics, add comments
| src/java/jburg/State.java | Remove State's Comparable semantics, add comments | <ide><path>rc/java/jburg/State.java
<ide> * the state. The state may also be able to produce other
<ide> * nonterminals via nonterminal-to-nonterminal closures.
<ide> *
<del> * The State class is Comparable so that it can be
<del> * sorted on its state number.
<add> * <p>Store State objects in hashed associative containers;
<add> * State objects' hash and equality semantics are set up
<add> * to weed out duplicate states.
<ide> */
<del>class State<Nonterminal, NodeType> implements Comparable<State<Nonterminal,NodeType>>
<add>class State<Nonterminal, NodeType>
<ide> {
<ide> /**
<ide> * The state's number. This number is set
<ide> */
<ide> final NodeType nodeType;
<ide>
<add> /**
<add> * Construct a state that characterizes non-null nodes.
<add> * @param nodeType the node type of the nodes.
<add> */
<ide> State(NodeType nodeType)
<ide> {
<ide> this.nodeType = nodeType;
<ide> }
<ide>
<add> /**
<add> * Construct a state that characterizes null pointers.
<add> */
<add> State()
<add> {
<add> this.nodeType = null;
<add> }
<add>
<add> /**
<add> * Add a pattern match to this state.
<add> * @param p the pattern matching production.
<add> * @param cost the cost of this production. The
<add> * cost must be the best cost known so far.
<add> */
<ide> void setPatternMatcher(PatternMatcher<Nonterminal,NodeType> p, long cost)
<ide> {
<ide> assert(cost < getCost(p.target));
<ide> * node type's hash code and its pattern map's
<ide> * hash code.
<ide> *
<del> * <p> <strong> Using the cost map's hash code is invalid,</strong>
<add> * <p> <strong>Using the cost map's hash code is invalid,</strong>
<ide> * since subsequent iterations may produce states that
<ide> * are identical except that they cost more due to closures,
<ide> * so computations based on the cost map diverge.
<ide> @Override
<ide> public int hashCode()
<ide> {
<del> return nodeType.hashCode() * 31 + patternMatchers.hashCode();
<add> int nodeHash = nodeType != null? nodeType.hashCode(): 0;
<add> return nodeHash * 31 + patternMatchers.hashCode();
<ide> }
<ide>
<ide> /**
<ide> {
<ide> if (o instanceof State) {
<ide> State<Nonterminal,NodeType> s = (State<Nonterminal,NodeType>)o;
<del> return this.nodeType.equals(s.nodeType) && this.patternMatchers.equals(s.patternMatchers);
<del>
<del> } else {
<del> return false;
<del> }
<del> }
<del>
<del> /**
<del> * States are comparable on their state number;
<del> * this is a convenience so that the state table,
<del> * which is stored in hashed order, can be emitted
<del> * in state number order.
<del> * <p><strong>This ordering should not be used to
<del> * store State objects in an associative container.</strong>
<del> * Use hash-based associative containers to get
<del> * correct semantics.
<del> */
<del> @Override
<del> public int compareTo(State<Nonterminal,NodeType> other)
<del> {
<del> assert this.number != -1 && other.number != -1;
<del> return this.number - other.number;
<add>
<add> if (this.nodeType == s.nodeType) {
<add> return true;
<add> } else if (this.nodeType != null && s.nodeType != null) {
<add> return this.nodeType.equals(s.nodeType) && this.patternMatchers.equals(s.patternMatchers);
<add> }
<add>
<add> }
<add>
<add> return false;
<ide> }
<ide> } |
|
Java | apache-2.0 | 93f02a8b3fa598a1996f3af15207e4ffb0fa29c7 | 0 | spiffyui/spiffyui,spiffyui/spiffyui,spiffyui/spiffyui | /*
* Copyright (c) 2010 Unpublished Work of Novell, Inc. All Rights Reserved.
*
* THIS WORK IS AN UNPUBLISHED WORK AND CONTAINS CONFIDENTIAL,
* PROPRIETARY AND TRADE SECRET INFORMATION OF NOVELL, INC. ACCESS TO
* THIS WORK IS RESTRICTED TO (I) NOVELL, INC. EMPLOYEES WHO HAVE A NEED
* TO KNOW HOW TO PERFORM TASKS WITHIN THE SCOPE OF THEIR ASSIGNMENTS AND
* (II) ENTITIES OTHER THAN NOVELL, INC. WHO HAVE ENTERED INTO
* APPROPRIATE LICENSE AGREEMENTS. NO PART OF THIS WORK MAY BE USED,
* PRACTICED, PERFORMED, COPIED, DISTRIBUTED, REVISED, MODIFIED,
* TRANSLATED, ABRIDGED, CONDENSED, EXPANDED, COLLECTED, COMPILED,
* LINKED, RECAST, TRANSFORMED OR ADAPTED WITHOUT THE PRIOR WRITTEN
* CONSENT OF NOVELL, INC. ANY USE OR EXPLOITATION OF THIS WORK WITHOUT
* AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL
* LIABILITY.
*
* ========================================================================
*/
package com.novell.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.novell.spiffyui.client.MessageUtil;
import com.novell.spiffyui.client.widgets.DatePickerTextBox;
import com.novell.spiffyui.client.widgets.LongMessage;
import com.novell.spiffyui.client.widgets.ProgressBar;
import com.novell.spiffyui.client.widgets.SlideDownPrefsPanel;
import com.novell.spiffyui.client.widgets.SlidingGridPanel;
import com.novell.spiffyui.client.widgets.SmallLoadingIndicator;
import com.novell.spiffyui.client.widgets.StatusIndicator;
import com.novell.spiffyui.client.widgets.TimePickerTextBox;
import com.novell.spiffyui.client.widgets.button.FancySaveButton;
import com.novell.spiffyui.client.widgets.button.RefreshAnchor;
import com.novell.spiffyui.client.widgets.button.SimpleButton;
import com.novell.spiffyui.client.widgets.dialog.ConfirmDialog;
import com.novell.spiffyui.client.widgets.dialog.Dialog;
import com.novell.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestBox;
import com.novell.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestRESTHelper;
/**
* This is the widgets sample panel
*
*/
public class WidgetsPanel extends HTMLPanel implements CloseHandler<PopupPanel>
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
private ConfirmDialog m_dlg;
private RefreshAnchor m_refresh;
private SlidingGridPanel m_slideGridPanel;
private static final int TALL = 1;
private static final int WIDE = 2;
private static final int BIG = 3;
/**
* Creates a new panel
*/
public WidgetsPanel()
{
super("div",
"<div id=\"WidgetsPrefsPanel\"></div><h1>Spiffy Widgets</h1>" +
STRINGS.WidgetsPanel_html() +
"<div id=\"WidgetsLongMessage\"></div><br /><br />" +
"<div id=\"WidgetsSlidingGrid\"></div>" +
"</div>");
getElement().setId("WidgetsPanel");
RootPanel.get("mainContent").add(this);
//Create the sliding grid and set it up for the rest of the controls
m_slideGridPanel = new SlidingGridPanel();
m_slideGridPanel.setGridOffset(225);
setVisible(false);
addLongMessage();
addNavPanelInfo();
addSlidingGrid();
/*
* Add widgets to the sliding grid in alphabetical order
*/
addDatePicker();
addFancyButton();
addMessageButton();
addLoginPanel();
addMultiValueAutoComplete();
addOptionsPanel();
addProgressBar();
addConfirmDialog();
addRefreshAnchor();
addSmallLoadingIndicator();
addStatusIndicators();
addSimpleButton();
addTimePicker();
/*
* Add the sliding grid here. This call must go last so that the onAttach of the SlidingGridPanel can do its thing.
*/
add(m_slideGridPanel, "WidgetsSlidingGrid");
}
/**
* Create the time picker control and add it to the sliding grid
*/
private void addTimePicker()
{
/*
* Add the time picker
*/
addToSlidingGrid(new TimePickerTextBox("timepicker"), "WidgetsTimePicker", "Time Picker",
"<p>" +
"Time Picker shows a time dropdown for easy selection. It is a wrapper for a " +
"<a href=\"http://code.google.com/p/jquery-timepicker/\">JQuery time picker</a>. " +
"The time step is set to 30 min but can be configured. It is localized. " +
"Try changing your browser locale and refreshing your browser." +
"</p>");
}
/**
* Create the status indicators and add them to the sliding grid
*/
private void addStatusIndicators()
{
/*
* Add 3 status indicators
*/
StatusIndicator status1 = new StatusIndicator(StatusIndicator.IN_PROGRESS);
StatusIndicator status2 = new StatusIndicator(StatusIndicator.SUCCEEDED);
StatusIndicator status3 = new StatusIndicator(StatusIndicator.FAILED);
HTMLPanel statusPanel = addToSlidingGrid(status1, "WidgetsStatus", "Status Indicator",
"<p>The status indicator shows valid, failed, and in progress status. It can be extended for others.</p>");
statusPanel.add(status2, "WidgetsStatus");
statusPanel.add(status3, "WidgetsStatus");
}
/**
* Create the small loading indicator and add it to the sliding grid
*/
private void addSmallLoadingIndicator()
{
/*
* Add a small loading indicator to our page
*/
SmallLoadingIndicator loading = new SmallLoadingIndicator();
addToSlidingGrid(loading, "WidgetsSmallLoading", "Small Loading Indicator", "<p>This indicator shows a loading status.</p>");
}
/**
* Create the refresh anchor and add it to the sliding grid
*/
private void addRefreshAnchor()
{
/*
* Add a refresh anchor to our page
*/
m_refresh = new RefreshAnchor("Widgets_refreshAnchor");
addToSlidingGrid(m_refresh, "WidgetsRefreshAnchor", "Refresh Anchor Confirm Dialog",
"<p>" +
"The refresh anchor shows an in progress status for refreshing items with an AJAX request. Click to show its in progress status and " +
"open an example of a confirm dialog." +
"</p>" +
"<p>" +
"Dialogs are keyboard accessible. They also support autohide and modal properties. You can also override the dialog class and " +
"supply your own implementation of the dialog." +
"</p>",
TALL);
m_refresh.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
m_refresh.setLoading(true);
m_dlg.center();
m_dlg.show();
event.preventDefault();
}
});
}
/**
* Create the confirm dialog and add it to the sliding grid
*/
private void addConfirmDialog()
{
/*
* Add the ConfirmDialog which will show up when refresh is clicked
*/
m_dlg = new ConfirmDialog("WidgetsConfirmDlg", "Sample Confirm");
m_dlg.hide();
m_dlg.addCloseHandler(this);
m_dlg.setText("Are you sure you want to refresh? (Doesn't make much sense as a confirm, but this is just a sample.)");
m_dlg.addButton("btn1", "Proceed", "OK");
m_dlg.addButton("btn2", "Cancel", "CANCEL");
}
/**
* Create the progress bar and add it to the sliding grid
*/
private void addProgressBar()
{
/*
* Add a progress bar to our page
*/
ProgressBar bar = new ProgressBar("WidgetsPanelProgressBar");
bar.setValue(65);
addToSlidingGrid(bar, "WidgetsProgressSpan", "Progress Bar",
"<p>" +
"This progress bar GWT control wraps the " +
"<a href=\"http://jqueryui.com/demos/progressbar/\">JQuery UI Progressbar</a>." +
"</p>");
}
/**
* Create the options panel and add it to the sliding grid
*/
private void addOptionsPanel()
{
/*
* Add the options slide down panel
*/
SlideDownPrefsPanel prefsPanel = new SlideDownPrefsPanel("WidgetsPrefs", "Slide Down Prefs Panel");
add(prefsPanel, "WidgetsPrefsPanel");
FlowPanel prefContents = new FlowPanel();
prefContents.add(new Label("Add display option labels and fields and an 'Apply' or 'Save' button."));
prefsPanel.setPanel(prefContents);
addToSlidingGrid(null, "WidgetsDisplayOptions", "Options Slide Down Panel",
"<p>" +
"Click the 'Slide Down Prefs Panel' slide-down tab at the top of the page to view an example of this widget." +
"</p>");
}
/**
* Create the mutli-value auto-complete field and add it to the sliding grid
*/
private void addMultiValueAutoComplete()
{
/*
* Add the multivalue suggest box
*/
MultivalueSuggestBox msb = new MultivalueSuggestBox(new MultivalueSuggestRESTHelper("TotalSize", "Options", "DisplayName", "Value") {
@Override
public String buildUrl(String q, int indexFrom, int indexTo)
{
return "multivaluesuggestboxexample/colors?q=" + q + "&indexFrom=" + indexFrom + "&indexTo=" + indexTo;
}
}, true);
msb.getFeedback().addStyleName("msg-feedback");
addToSlidingGrid(msb, "WidgetsSuggestBox", "Multi-Valued Suggest Box",
"<p>" +
"The multi-valued suggest box is an autocompleter that allows for multiple values and browsing. It uses REST to " +
"retrieve suggestions from the server. The full process is documented in " +
"<a href=\"http://www.zackgrossbart.com/hackito/gwt-rest-auto\">" +
"Creating a Multi-Valued Auto-Complete Field Using GWT SuggestBox and REST</a>." +
"</p>" +
"<p>" +
"Type blue, mac, or * to search for crayon colors." +
"</p>",
WIDE);
}
/**
* Create the date picker control and add it to the sliding grid
*/
private void addDatePicker()
{
/*
* Add the date picker
*/
addToSlidingGrid(new DatePickerTextBox("datepicker"), "WidgetsDatePicker", "Date Picker",
"<p>" +
"Spiffy UI's date picker shows a calendar for easy date selection. It wraps the <a href=\"http://jqueryui.com/demos/datepicker\">" +
"JQuery UI Date Picker</a> which is better tested, has more features, and is easier to style than the GWT date " +
"picker control. The JQuery Date Picker includes many features including the ablility to specify the minimum " +
"and maximum dates and changing the way to pick months and years." +
"</p>" +
"<p>" +
"The Spiffy UI Framework is localized into 53 languages. Try changing your browser locale and refreshing " +
"this page. In addition, since it is a GWT widget, you may get the selected date value as a java.util.Date." +
"</p>", TALL);
}
private void addNavPanelInfo()
{
Anchor css = new Anchor("CSS page", "CSSPanel");
css.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.CSS_NAV_ITEM_ID);
}
});
HTMLPanel panel = addToSlidingGrid(null, "NavPanelGridCell", "Navigation Bar",
"<p>" +
"The main navigation bar makes it easy to add styled navigation menus to your application with " +
"highlights, collapsible sections, and separators. These items navigate between different panels " +
"in your application, but can also navigate between different HTML pages." +
"</p>" +
"<p>" +
"The navigation menu also supports the back button when navigating between JavaScript panels in " +
"the same page. This makes it possible to support the back button, forward button, and browser " +
"history while maintaining the JavaScript state of your application and keeping very fast page loading." +
"</p>" +
"<p>" +
"The menus use CSS layout which supports a flexible layout. See the example on the " +
"<span id=\"cssPageWidgetsLink\"></span>." +
"</p>", TALL);
panel.add(css, "cssPageWidgetsLink");
}
/**
* Create the sliding grid
*/
private void addSlidingGrid()
{
/*
* Create the sliding grid and add its big cell
*/
addToSlidingGrid(null, "WidgetsSlidingGridCell", "Sliding Grid Panel",
"<p>" +
"All the cells here are layed out using the sliding grid panel. This panel is a wrapper for slidegrid.js, " +
"which automatically moves cells to fit nicely on the screen for any browser window size." +
"</p>" +
"<p>" +
"Resize your browser window to see it in action." +
"</p>" +
"<p>" +
"More information on the sliding grid can be found in <a href=\"http://www.zackgrossbart.com/hackito/slidegrid/\">" +
"Create Your Own Sliding Resizable Grid</a>." +
"</p>", TALL);
}
/**
* Create the long message control to the top of the page
*/
private void addLongMessage()
{
/*
* Add a long message to our page
*/
LongMessage message = new LongMessage("WidgetsLongMessageWidget");
add(message, "WidgetsLongMessage");
message.setHTML("<b>Long Message</b><br />" +
"Long messages are useful for showing information messages " +
"with more content than the standard messages but they are still " +
"transient messages.");
}
/**
* Create the simple button control and add it to the sliding grid
*/
private void addSimpleButton()
{
/*
* Add the simple button
*/
final SimpleButton simple = new SimpleButton("Simple Button");
simple.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
simple.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
simple.setInProgress(false);
}
};
t.schedule(2000);
}
});
addToSlidingGrid(simple, "WidgetsButton", "Simple Button",
"<p>" +
"All buttons get special styling from the Spiffy UI framework. Click to demonstrate its in progress status." +
"</p>");
}
/**
* Create the fancy button control and add it to the sliding grid
*/
private void addFancyButton()
{
/*
* Add the fancy button
*/
final FancySaveButton fancy = new FancySaveButton("Save");
fancy.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
fancy.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
fancy.setInProgress(false);
}
};
t.schedule(2000);
}
});
addToSlidingGrid(fancy, "WidgetsFancyButton", "Fancy Save Button",
"<p>" +
"Fancy buttons show an image and text with a disabled image and hover style. Click to demonstrate its in progress status." +
"</p>");
}
/**
* Create login panel and add it to the sliding grid
*/
private void addLoginPanel()
{
String buttonText = "";
if (Index.userLoggedIn()) {
buttonText = "Get More Secure Data";
} else {
buttonText = "Get Secure Data";
}
final SimpleButton doLoginButton = new SimpleButton(buttonText);
doLoginButton.getElement().setId("doLoginBtn");
doLoginButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
doLoginButton.setInProgress(true);
//a little timer to simulate time it takes to set in progress back to false
Timer t = new Timer() {
@Override
public void run()
{
doLoginButton.setInProgress(false);
}
};
t.schedule(2000);
// if (Index.userLoggedIn()) {
//SPSampleHeader.doLogout();
//} else {
AuthPanel.getData(true);
//}
}
});
HTMLPanel loginButtonPanel = addToSlidingGrid(doLoginButton, "WidgetsLoginPanel", "Login Panel",
"<p>" +
"A login dialog will display if you attempt to access secured information while unauthenticated. Click the button below to get secured data." +
"</p>" +
"<p>" +
"If you have a valid security token, the information will be returned immediately. Otherwise, it will be returned immediately after successful login. " +
"Once authenticated you may logout by clicking the link in the header." +
"</p>" +
"<p>Please visit the <span id=\"authPanelSpan\"></span> for more information on how Spiffy UI handles security.</p>"
, TALL);
loginButtonPanel.add((new HTML("<p><div id=\"loginResult\"></div>")), "WidgetsLoginPanel");
Anchor auth = new Anchor("Authentication page", "AuthPanel");
auth.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.AUTH_NAV_ITEM_ID);
}
});
loginButtonPanel.add(auth, "authPanelSpan");
}
/**
* A helper method that adds a widget and some HTML description to the sliding
* grid panel
*
* @param widget the widget to add
* @param id the ID of the new cell
* @param title the title of the new cell
* @param htmlText the HTML description of the widget
*
* @return the HTMLPanel used to add the contents to the new cell
*/
private HTMLPanel addToSlidingGrid(Widget widget, String id, String title, String htmlText)
{
return addToSlidingGrid(widget, id, title, htmlText, 0);
}
/**
* A helper method that adds a widget and some HTML description to the sliding
* grid panel
*
* @param widget the widget to add
* @param id the ID of the new cell
* @param title the title of the new cell
* @param htmlText the HTML description of the widget
* @param type the type of cell to add: TALL, BIG, or WIDE
*
* @return the HTMLPanel used to add the contents to the new cell
*/
private HTMLPanel addToSlidingGrid(Widget widget, String id, String title, String htmlText, int type)
{
HTMLPanel p = new HTMLPanel("div",
"<h3>" + title + "</h3>" +
htmlText +
"<span id=\"" + id + "\"></span>");
if (widget != null) {
p.add(widget, id);
}
switch (type) {
case WIDE:
m_slideGridPanel.addWide(p);
break;
case TALL:
m_slideGridPanel.addTall(p);
break;
case BIG:
m_slideGridPanel.addBig(p);
break;
default:
m_slideGridPanel.add(p);
break;
}
return p;
}
/**
* Add the message buttons to the sliding grid
*/
private void addMessageButton()
{
/*
* Add the message buttons
*/
Button b = new Button("Show Info Message");
HTMLPanel p = addToSlidingGrid(b, "WidgetsMessages", "Humanized Messages",
"<p>" +
"The Spiffy UI framework has an integrated message framework following the pattern of " +
"<a href=\"http://code.google.com/p/humanmsg/\">Humanized Messages</a>. " +
"These messages are non-modal and fade away without requiring further interaction. They " +
"include info messages, warnings, errors, and fatal errors. Errors and some warnings are sent to an error " +
"log at the bottom of the screen." +
"</p>",
TALL);
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showMessage("This is an information message");
}
});
b = new Button("Show Warning Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showWarning("This is a warning message", false);
}
});
b = new Button("Show Error Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showError("This is an error message");
}
});
b = new Button("Show Fatal Error Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showFatalError("This is a fatal error message");
}
});
}
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Dialog dlg = (Dialog) event.getSource();
String btn = dlg.getButtonClicked();
if (dlg == m_dlg && "OK".equals(btn)) {
MessageUtil.showMessage("Refreshing!");
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
m_refresh.setLoading(false);
}
};
t.schedule(2000);
} else {
m_refresh.setLoading(false);
}
}
}
| src/com/novell/spsample/client/WidgetsPanel.java | /*
* Copyright (c) 2010 Unpublished Work of Novell, Inc. All Rights Reserved.
*
* THIS WORK IS AN UNPUBLISHED WORK AND CONTAINS CONFIDENTIAL,
* PROPRIETARY AND TRADE SECRET INFORMATION OF NOVELL, INC. ACCESS TO
* THIS WORK IS RESTRICTED TO (I) NOVELL, INC. EMPLOYEES WHO HAVE A NEED
* TO KNOW HOW TO PERFORM TASKS WITHIN THE SCOPE OF THEIR ASSIGNMENTS AND
* (II) ENTITIES OTHER THAN NOVELL, INC. WHO HAVE ENTERED INTO
* APPROPRIATE LICENSE AGREEMENTS. NO PART OF THIS WORK MAY BE USED,
* PRACTICED, PERFORMED, COPIED, DISTRIBUTED, REVISED, MODIFIED,
* TRANSLATED, ABRIDGED, CONDENSED, EXPANDED, COLLECTED, COMPILED,
* LINKED, RECAST, TRANSFORMED OR ADAPTED WITHOUT THE PRIOR WRITTEN
* CONSENT OF NOVELL, INC. ANY USE OR EXPLOITATION OF THIS WORK WITHOUT
* AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL
* LIABILITY.
*
* ========================================================================
*/
package com.novell.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.novell.spiffyui.client.MessageUtil;
import com.novell.spiffyui.client.widgets.DatePickerTextBox;
import com.novell.spiffyui.client.widgets.LongMessage;
import com.novell.spiffyui.client.widgets.ProgressBar;
import com.novell.spiffyui.client.widgets.SlideDownPrefsPanel;
import com.novell.spiffyui.client.widgets.SlidingGridPanel;
import com.novell.spiffyui.client.widgets.SmallLoadingIndicator;
import com.novell.spiffyui.client.widgets.StatusIndicator;
import com.novell.spiffyui.client.widgets.TimePickerTextBox;
import com.novell.spiffyui.client.widgets.button.FancySaveButton;
import com.novell.spiffyui.client.widgets.button.RefreshAnchor;
import com.novell.spiffyui.client.widgets.button.SimpleButton;
import com.novell.spiffyui.client.widgets.dialog.ConfirmDialog;
import com.novell.spiffyui.client.widgets.dialog.Dialog;
import com.novell.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestBox;
import com.novell.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestRESTHelper;
/**
* This is the widgets sample panel
*
*/
public class WidgetsPanel extends HTMLPanel implements CloseHandler<PopupPanel>
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
private ConfirmDialog m_dlg;
private RefreshAnchor m_refresh;
private SlidingGridPanel m_slideGridPanel;
private static final int TALL = 1;
private static final int WIDE = 2;
private static final int BIG = 3;
/**
* Creates a new panel
*/
public WidgetsPanel()
{
super("div",
"<div id=\"WidgetsPrefsPanel\"></div><h1>Spiffy Widgets</h1>" +
STRINGS.WidgetsPanel_html() +
"<div id=\"WidgetsLongMessage\"></div><br /><br />" +
"<div id=\"WidgetsSlidingGrid\"></div>" +
"</div>");
getElement().setId("WidgetsPanel");
RootPanel.get("mainContent").add(this);
//Create the sliding grid and set it up for the rest of the controls
m_slideGridPanel = new SlidingGridPanel();
m_slideGridPanel.setGridOffset(225);
setVisible(false);
addLongMessage();
addNavPanelInfo();
addSlidingGrid();
/*
* Add widgets to the sliding grid in alphabetical order
*/
addDatePicker();
addFancyButton();
addLoginPanel();
addMessageButton();
addMultiValueAutoComplete();
addOptionsPanel();
addProgressBar();
addConfirmDialog();
addRefreshAnchor();
addSmallLoadingIndicator();
addStatusIndicators();
addSimpleButton();
addTimePicker();
/*
* Add the sliding grid here. This call must go last so that the onAttach of the SlidingGridPanel can do its thing.
*/
add(m_slideGridPanel, "WidgetsSlidingGrid");
}
/**
* Create the time picker control and add it to the sliding grid
*/
private void addTimePicker()
{
/*
* Add the time picker
*/
addToSlidingGrid(new TimePickerTextBox("timepicker"), "WidgetsTimePicker", "Time Picker",
"<p>" +
"Time Picker shows a time dropdown for easy selection. It is a wrapper for a " +
"<a href=\"http://code.google.com/p/jquery-timepicker/\">JQuery time picker</a>. " +
"The time step is set to 30 min but can be configured. It is localized. " +
"Try changing your browser locale and refreshing your browser." +
"</p>");
}
/**
* Create the status indicators and add them to the sliding grid
*/
private void addStatusIndicators()
{
/*
* Add 3 status indicators
*/
StatusIndicator status1 = new StatusIndicator(StatusIndicator.IN_PROGRESS);
StatusIndicator status2 = new StatusIndicator(StatusIndicator.SUCCEEDED);
StatusIndicator status3 = new StatusIndicator(StatusIndicator.FAILED);
HTMLPanel statusPanel = addToSlidingGrid(status1, "WidgetsStatus", "Status Indicator",
"<p>The status indicator shows valid, failed, and in progress status. It can be extended for others.</p>");
statusPanel.add(status2, "WidgetsStatus");
statusPanel.add(status3, "WidgetsStatus");
}
/**
* Create the small loading indicator and add it to the sliding grid
*/
private void addSmallLoadingIndicator()
{
/*
* Add a small loading indicator to our page
*/
SmallLoadingIndicator loading = new SmallLoadingIndicator();
addToSlidingGrid(loading, "WidgetsSmallLoading", "Small Loading Indicator", "<p>This indicator shows a loading status.</p>");
}
/**
* Create the refresh anchor and add it to the sliding grid
*/
private void addRefreshAnchor()
{
/*
* Add a refresh anchor to our page
*/
m_refresh = new RefreshAnchor("Widgets_refreshAnchor");
addToSlidingGrid(m_refresh, "WidgetsRefreshAnchor", "Refresh Anchor Confirm Dialog",
"<p>" +
"The refresh anchor shows an in progress status for refreshing items with an AJAX request. Click to show its in progress status and " +
"open an example of a confirm dialog." +
"</p>" +
"<p>" +
"Dialogs are keyboard accessible. They also support autohide and modal properties. You can also override the dialog class and " +
"supply your own implementation of the dialog." +
"</p>",
TALL);
m_refresh.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
m_refresh.setLoading(true);
m_dlg.center();
m_dlg.show();
event.preventDefault();
}
});
}
/**
* Create the confirm dialog and add it to the sliding grid
*/
private void addConfirmDialog()
{
/*
* Add the ConfirmDialog which will show up when refresh is clicked
*/
m_dlg = new ConfirmDialog("WidgetsConfirmDlg", "Sample Confirm");
m_dlg.hide();
m_dlg.addCloseHandler(this);
m_dlg.setText("Are you sure you want to refresh? (Doesn't make much sense as a confirm, but this is just a sample.)");
m_dlg.addButton("btn1", "Proceed", "OK");
m_dlg.addButton("btn2", "Cancel", "CANCEL");
}
/**
* Create the progress bar and add it to the sliding grid
*/
private void addProgressBar()
{
/*
* Add a progress bar to our page
*/
ProgressBar bar = new ProgressBar("WidgetsPanelProgressBar");
bar.setValue(65);
addToSlidingGrid(bar, "WidgetsProgressSpan", "Progress Bar",
"<p>" +
"This progress bar GWT control wraps the " +
"<a href=\"http://jqueryui.com/demos/progressbar/\">JQuery UI Progressbar</a>." +
"</p>");
}
/**
* Create the options panel and add it to the sliding grid
*/
private void addOptionsPanel()
{
/*
* Add the options slide down panel
*/
SlideDownPrefsPanel prefsPanel = new SlideDownPrefsPanel("WidgetsPrefs", "Slide Down Prefs Panel");
add(prefsPanel, "WidgetsPrefsPanel");
FlowPanel prefContents = new FlowPanel();
prefContents.add(new Label("Add display option labels and fields and an 'Apply' or 'Save' button."));
prefsPanel.setPanel(prefContents);
addToSlidingGrid(null, "WidgetsDisplayOptions", "Options Slide Down Panel",
"<p>" +
"Click the 'Slide Down Prefs Panel' slide-down tab at the top of the page to view an example of this widget." +
"</p>");
}
/**
* Create the mutli-value auto-complete field and add it to the sliding grid
*/
private void addMultiValueAutoComplete()
{
/*
* Add the multivalue suggest box
*/
MultivalueSuggestBox msb = new MultivalueSuggestBox(new MultivalueSuggestRESTHelper("TotalSize", "Options", "DisplayName", "Value") {
@Override
public String buildUrl(String q, int indexFrom, int indexTo)
{
return "multivaluesuggestboxexample/colors?q=" + q + "&indexFrom=" + indexFrom + "&indexTo=" + indexTo;
}
}, true);
msb.getFeedback().addStyleName("msg-feedback");
addToSlidingGrid(msb, "WidgetsSuggestBox", "Multivalue Suggest Box",
"<p>" +
"The Multivalue suggest box is an autocompleter that allows for multiple values and browsing. It uses REST to " +
"retrieve suggestions from the server. The full process is documented in " +
"<a href=\"http://www.zackgrossbart.com/hackito/gwt-rest-auto\">" +
"Creating a Multi-Valued Auto-Complete Field Using GWT SuggestBox and REST</a>." +
"</p>" +
"<p>" +
"Type blue, mac, or * to search for crayon colors." +
"</p>",
WIDE);
}
/**
* Create the date picker control and add it to the sliding grid
*/
private void addDatePicker()
{
/*
* Add the date picker
*/
addToSlidingGrid(new DatePickerTextBox("datepicker"), "WidgetsDatePicker", "Date Picker",
"<p>" +
"Spiffy UI's date picker shows a calendar for easy date selection. It wraps the <a href=\"http://jqueryui.com/demos/datepicker\">" +
"JQuery UI Date Picker</a> which is better tested, has more features, and is easier to style than the GWT date " +
"picker control. The JQuery Date Picker includes many features including the ablility to specify the minimum " +
"and maximum dates and changing the way to pick months and years." +
"</p>" +
"<p>" +
"The Spiffy UI Framework is localized into 53 languages. Try changing your browser locale and refreshing " +
"this page. In addition, since it is a GWT widget, you may get the selected date value as a java.util.Date." +
"</p>", TALL);
}
private void addNavPanelInfo()
{
Anchor css = new Anchor("CSS page", "CSSPanel");
css.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.CSS_NAV_ITEM_ID);
}
});
HTMLPanel panel = addToSlidingGrid(null, "NavPanelGridCell", "Navigation Bar",
"<p>" +
"The main navigation bar makes it easy to add styled navigation menus to your application with " +
"highlights, collapsible sections, and separators. These items navigate between different panels " +
"in your application, but can also navigate between different HTML pages." +
"</p>" +
"<p>" +
"The navigation menu also supports the back button when navigating between JavaScript panels in " +
"the same page. This makes it possible to support the back button, forward button, and browser " +
"history while maintaining the JavaScript state of your application and keeping very fast page loading." +
"</p>" +
"<p>" +
"The menus use CSS layout which supports a flexible layout. See the example on the " +
"<span id=\"cssPageWidgetsLink\"></span>." +
"</p>", TALL);
panel.add(css, "cssPageWidgetsLink");
}
/**
* Create the sliding grid
*/
private void addSlidingGrid()
{
/*
* Create the sliding grid and add its big cell
*/
addToSlidingGrid(null, "WidgetsSlidingGridCell", "Sliding Grid Panel",
"<p>" +
"All the cells here are layed out using the sliding grid panel. This panel is a wrapper for slidegrid.js, " +
"which automatically moves cells to fit nicely on the screen for any browser window size." +
"</p>" +
"<p>" +
"Resize your browser window to see it in action." +
"</p>" +
"<p>" +
"More information on the sliding grid can be found in <a href=\"http://www.zackgrossbart.com/hackito/slidegrid/\">" +
"Create Your Own Sliding Resizable Grid</a>." +
"</p>", TALL);
}
/**
* Create the long message control to the top of the page
*/
private void addLongMessage()
{
/*
* Add a long message to our page
*/
LongMessage message = new LongMessage("WidgetsLongMessageWidget");
add(message, "WidgetsLongMessage");
message.setHTML("<b>Long Message</b><br />" +
"Long messages are useful for showing information messages " +
"with more content than the standard messages but they are still " +
"transient messages.");
}
/**
* Create the simple button control and add it to the sliding grid
*/
private void addSimpleButton()
{
/*
* Add the simple button
*/
final SimpleButton simple = new SimpleButton("Simple Button");
simple.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
simple.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
simple.setInProgress(false);
}
};
t.schedule(2000);
}
});
addToSlidingGrid(simple, "WidgetsButton", "Simple Button",
"<p>" +
"All buttons get special styling from the Spiffy UI framework. Click to demonstrate its in progress status." +
"</p>");
}
/**
* Create the fancy button control and add it to the sliding grid
*/
private void addFancyButton()
{
/*
* Add the fancy button
*/
final FancySaveButton fancy = new FancySaveButton("Save");
fancy.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
fancy.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
fancy.setInProgress(false);
}
};
t.schedule(2000);
}
});
addToSlidingGrid(fancy, "WidgetsFancyButton", "Fancy Save Button",
"<p>" +
"Fancy buttons show an image and text with a disabled image and hover style. Click to demonstrate its in progress status." +
"</p>");
}
/**
* Create login panel and add it to the sliding grid
*/
private void addLoginPanel()
{
String buttonText = "";
if (Index.userLoggedIn()) {
buttonText = "Get More Secure Data";
} else {
buttonText = "Get Secure Data";
}
final SimpleButton doLoginButton = new SimpleButton(buttonText);
doLoginButton.getElement().setId("doLoginBtn");
doLoginButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
doLoginButton.setInProgress(true);
//a little timer to simulate time it takes to set in progress back to false
Timer t = new Timer() {
@Override
public void run()
{
doLoginButton.setInProgress(false);
}
};
t.schedule(2000);
// if (Index.userLoggedIn()) {
//SPSampleHeader.doLogout();
//} else {
AuthPanel.getData(true);
//}
}
});
HTMLPanel loginButtonPanel = addToSlidingGrid(doLoginButton, "WidgetsLoginPanel", "Login Panel",
"<p>" +
"Login Panel displays a login dialog. Click the button below to try to get some secure data. If you have not logged in before, the Login Panel will show for you to login. After login, you can get some secure data back." +
"</p>" +
"<p>Please visit the <span id=\"authPanelSpan\"></span> panel for more information on how Spiffy UI handles security.</p>"
, TALL);
loginButtonPanel.add((new HTML("<p><div id=\"loginResult\"></div>")), "WidgetsLoginPanel");
Anchor auth = new Anchor("Authentication", "#");
auth.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.AUTH_NAV_ITEM_ID);
}
});
loginButtonPanel.add(auth, "authPanelSpan");
}
/**
* A helper method that adds a widget and some HTML description to the sliding
* grid panel
*
* @param widget the widget to add
* @param id the ID of the new cell
* @param title the title of the new cell
* @param htmlText the HTML description of the widget
*
* @return the HTMLPanel used to add the contents to the new cell
*/
private HTMLPanel addToSlidingGrid(Widget widget, String id, String title, String htmlText)
{
return addToSlidingGrid(widget, id, title, htmlText, 0);
}
/**
* A helper method that adds a widget and some HTML description to the sliding
* grid panel
*
* @param widget the widget to add
* @param id the ID of the new cell
* @param title the title of the new cell
* @param htmlText the HTML description of the widget
* @param type the type of cell to add: TALL, BIG, or WIDE
*
* @return the HTMLPanel used to add the contents to the new cell
*/
private HTMLPanel addToSlidingGrid(Widget widget, String id, String title, String htmlText, int type)
{
HTMLPanel p = new HTMLPanel("div",
"<h3>" + title + "</h3>" +
htmlText +
"<span id=\"" + id + "\"></span>");
if (widget != null) {
p.add(widget, id);
}
switch (type) {
case WIDE:
m_slideGridPanel.addWide(p);
break;
case TALL:
m_slideGridPanel.addTall(p);
break;
case BIG:
m_slideGridPanel.addBig(p);
break;
default:
m_slideGridPanel.add(p);
break;
}
return p;
}
/**
* Add the message buttons to the sliding grid
*/
private void addMessageButton()
{
/*
* Add the message buttons
*/
Button b = new Button("Show Info Message");
HTMLPanel p = addToSlidingGrid(b, "WidgetsMessages", "Humanized Messages",
"<p>" +
"The Spiffy UI framework support has an integrated message framework following the pattern of " +
"<a href=\"http://code.google.com/p/humanmsg/\">Humanized Messages</a>. " +
"These messages are non-modal and fade away without requiring further interaction. They " +
"include info messages, warnings, errors, and fatal errors. Errors and some warnings are sent to an error " +
"log at the bottom of the screen." +
"</p>",
TALL);
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showMessage("This is an information message");
}
});
b = new Button("Show Warning Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showWarning("This is a warning message", false);
}
});
b = new Button("Show Error Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showError("This is an error message");
}
});
b = new Button("Show Fatal Error Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showFatalError("This is a fatal error message");
}
});
}
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Dialog dlg = (Dialog) event.getSource();
String btn = dlg.getButtonClicked();
if (dlg == m_dlg && "OK".equals(btn)) {
MessageUtil.showMessage("Refreshing!");
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
m_refresh.setLoading(false);
}
};
t.schedule(2000);
} else {
m_refresh.setLoading(false);
}
}
}
| text tweaks to widgets panel
| src/com/novell/spsample/client/WidgetsPanel.java | text tweaks to widgets panel | <ide><path>rc/com/novell/spsample/client/WidgetsPanel.java
<ide>
<ide> addFancyButton();
<ide>
<add> addMessageButton();
<add>
<ide> addLoginPanel();
<del>
<del> addMessageButton();
<ide>
<ide> addMultiValueAutoComplete();
<ide>
<ide> }
<ide> }, true);
<ide> msb.getFeedback().addStyleName("msg-feedback");
<del> addToSlidingGrid(msb, "WidgetsSuggestBox", "Multivalue Suggest Box",
<add> addToSlidingGrid(msb, "WidgetsSuggestBox", "Multi-Valued Suggest Box",
<ide> "<p>" +
<del> "The Multivalue suggest box is an autocompleter that allows for multiple values and browsing. It uses REST to " +
<add> "The multi-valued suggest box is an autocompleter that allows for multiple values and browsing. It uses REST to " +
<ide> "retrieve suggestions from the server. The full process is documented in " +
<ide> "<a href=\"http://www.zackgrossbart.com/hackito/gwt-rest-auto\">" +
<ide> "Creating a Multi-Valued Auto-Complete Field Using GWT SuggestBox and REST</a>." +
<ide>
<ide> HTMLPanel loginButtonPanel = addToSlidingGrid(doLoginButton, "WidgetsLoginPanel", "Login Panel",
<ide> "<p>" +
<del> "Login Panel displays a login dialog. Click the button below to try to get some secure data. If you have not logged in before, the Login Panel will show for you to login. After login, you can get some secure data back." +
<add> "A login dialog will display if you attempt to access secured information while unauthenticated. Click the button below to get secured data." +
<ide> "</p>" +
<del> "<p>Please visit the <span id=\"authPanelSpan\"></span> panel for more information on how Spiffy UI handles security.</p>"
<add> "<p>" +
<add> "If you have a valid security token, the information will be returned immediately. Otherwise, it will be returned immediately after successful login. " +
<add> "Once authenticated you may logout by clicking the link in the header." +
<add> "</p>" +
<add> "<p>Please visit the <span id=\"authPanelSpan\"></span> for more information on how Spiffy UI handles security.</p>"
<ide> , TALL);
<ide> loginButtonPanel.add((new HTML("<p><div id=\"loginResult\"></div>")), "WidgetsLoginPanel");
<ide>
<del> Anchor auth = new Anchor("Authentication", "#");
<add> Anchor auth = new Anchor("Authentication page", "AuthPanel");
<ide> auth.addClickHandler(new ClickHandler() {
<ide> @Override
<ide> public void onClick(ClickEvent event)
<ide> Button b = new Button("Show Info Message");
<ide> HTMLPanel p = addToSlidingGrid(b, "WidgetsMessages", "Humanized Messages",
<ide> "<p>" +
<del> "The Spiffy UI framework support has an integrated message framework following the pattern of " +
<add> "The Spiffy UI framework has an integrated message framework following the pattern of " +
<ide> "<a href=\"http://code.google.com/p/humanmsg/\">Humanized Messages</a>. " +
<ide> "These messages are non-modal and fade away without requiring further interaction. They " +
<ide> "include info messages, warnings, errors, and fatal errors. Errors and some warnings are sent to an error " + |
|
JavaScript | bsd-3-clause | 3519d16a73fbd3202c001bb4a358162435922491 | 0 | assetgraph/assetgraph-builder | var vm = require('vm'),
_ = require('underscore'),
memoizer = require('memoizer'),
uglify = require('uglify-js'),
uglifyAst = require('assetgraph/lib/util/uglifyAst'),
i18nTools = {};
// Helper for getting a prioritized list of relevant locale ids from a specific locale id.
// For instance, "en_US" produces ["en_US", "en"]
i18nTools.expandLocaleIdToPrioritizedList = memoizer(function (localeId) {
var localeIds = [localeId];
while (/_[^_]+$/.test(localeId)) {
localeId = localeId.replace(/_[^_]+$/, '');
localeIds.push(localeId);
}
return localeIds;
});
i18nTools.tokenizePattern = function (pattern) {
var tokens = [];
// Split pattern into tokens (return value of replace isn't used):
pattern.replace(/\{(\d+)\}|((?:[^\\\{]|\\[\\\{])+)/g, function ($0, placeHolderNumberStr, text) {
if (placeHolderNumberStr) {
tokens.push({
type: 'placeHolder',
value: parseInt(placeHolderNumberStr, 10)
});
} else {
tokens.push({
type: 'text',
value: text.replace(/\\([\{\}])/g, "$1")
});
}
});
return tokens;
};
i18nTools.patternToAst = function (pattern, placeHolderAsts) {
var ast;
i18nTools.tokenizePattern(pattern).forEach(function (token) {
var term;
if (token.type === 'placeHolder') {
term = placeHolderAsts[token.value];
} else {
term = ['string', token.value];
}
if (ast) {
ast = ['binary', '+', ast, term];
} else {
ast = term;
}
});
return ast || ['string', ''];
};
i18nTools.eachOneTrInAst = function (ast, lambda) {
var q = [ast];
while (q.length) {
var node = q.pop();
if (node[0] === 'call' && Array.isArray(node[1]) && node[1][0] === 'call' &&
Array.isArray(node[1][1]) && node[1][1][0] === 'dot' && Array.isArray(node[1][1][1]) &&
node[1][1][1][0] === 'name' && node[1][1][1][1] === 'one' &&
(node[1][1][2] === 'trPattern')) {
if (lambda('callTrPattern', node[1][2][0][1], node, node[1][2][1]) === false) { // type, key, node, defaultValueAst
return;
}
} else if (node[0] === 'call' && Array.isArray(node[1]) && node[1][0] === 'dot' &&
Array.isArray(node[1][1]) && node[1][1][0] === 'name' && node[1][1][1] === 'one' &&
(node[1][2] === 'tr' || node[1][2] === 'trPattern')) {
if (node[2].length === 0 || !Array.isArray(node[2][0]) || node[2][0][0] !== 'string') {
console.warn("Invalid one." + node[1][2] + " syntax: " + uglify.uglify.gen_code(node));
}
if (lambda(node[1][2], node[2][0][1], node, node[2][1]) === false) { // type, key, node, defaultValueAst
return;
}
}
for (var i = node.length - 1 ; i >= 1 ; i -= 1) {
if (Array.isArray(node[i])) {
q.push(node[i]);
}
}
}
};
i18nTools.getBootstrappedContext = function (assetGraph, htmlAsset) {
var context = vm.createContext();
context.window = context;
context.__defineSetter__('document', function () {});
context.__defineGetter__('document', function () {
htmlAsset.markDirty();
return htmlAsset.parseTree;
});
var bootstrapperRelations = assetGraph.findRelations({from: htmlAsset, node: {id: 'oneBootstrapper'}, to: {type: 'JavaScript'}});
if (bootstrapperRelations.length === 0) {
return context;
} else if (bootstrapperRelations.length > 1) {
throw new Error("i18nTools.getBootstrappedContext: Unexpected number of One bootstrapper relations found: " + bootstrapRelations.length);
}
new vm.Script(uglify.uglify.gen_code(bootstrapperRelations[0].to.parseTree), "bootstrap code for " + (htmlAsset.url || "inline")).runInContext(context);
return context;
};
// initialAsset must be Html or JavaScript
i18nTools.extractAllReachableKeys = function (assetGraph, initialAssets) {
if (!_.isArray(initialAssets)) {
initialAssets = [initialAssets];
}
var allKeys = {};
initialAssets.forEach(function (initialAsset) {
assetGraph.collectAssetsPostOrder(initialAsset, {type: ['HtmlScript', 'JavaScriptOneInclude']}).filter(function (asset) {
return asset.type === 'I18n';
}).forEach(function (i18nAsset) {
_.extend(allKeys, i18nAsset.parseTree);
});
});
return allKeys;
};
// initialAsset must be Html or JavaScript
i18nTools.extractAllReachableKeysForLocale = function (assetGraph, localeId, initialAsset) {
var allKeys = i18nTools.extractAllReachableKeys(assetGraph, initialAsset),
prioritizedLocaleIds = i18nTools.expandLocaleIdToPrioritizedList(localeId),
allKeysForLocale = {};
Object.keys(allKeys).forEach(function (key) {
var found = false;
for (var i = 0 ; i < prioritizedLocaleIds.length ; i += 1) {
if (prioritizedLocaleIds[i] in allKeys[key]) {
allKeysForLocale[key] = allKeys[key][prioritizedLocaleIds[i]];
found = true;
break;
}
}
if (!found) {
console.warn("i18nTools.extractAllReachableKeysForLocale: Key " + key + " not found for " + localeId);
}
});
return allKeysForLocale;
};
i18nTools.createOneTrReplacer = function (allKeys, localeId) { // localeId is optional and will only be used for warning messages
return function oneTrReplacer(type, key, node, defaultValueAst) {
var value = allKeys[key],
valueAst;
if (value === null || typeof value === 'undefined') {
// FIXME: Assumes that the defaultValueAst is in English, perhaps that should be configurable.
if (!localeId || !(/^en([\-_]|$)/.test(localeId) && defaultValueAst)) {
console.warn('oneTrReplacer: Key ' + key + ' not found' + (localeId ? ' in ' + localeId : ''));
}
if (defaultValueAst) {
valueAst = defaultValueAst;
} else {
valueAst = ['string', '[!' + key + '!]'];
}
} else {
valueAst = uglifyAst.objToAst(value);
}
if (type === 'callTrPattern') {
// Replace one.trPattern('keyName')(placeHolderValue, ...) with a string concatenation:
if (!Array.isArray(valueAst) || valueAst[0] !== 'string') {
console.warn("oneTrReplacer: Invalid one.trPattern syntax: " + value);
return;
}
Array.prototype.splice.apply(node, [0, node.length].concat(i18nTools.patternToAst(valueAst[1], node[2])));
} else if (type === 'tr') {
Array.prototype.splice.apply(node, [0, node.length].concat(valueAst));
} else if (type === 'trPattern') {
if (!Array.isArray(valueAst) || valueAst[0] !== 'string') {
console.warn("oneTrReplacer: Invalid one.trPattern syntax: " + value);
return;
}
var highestPlaceHolderNumber;
i18nTools.tokenizePattern(valueAst[1]).forEach(function (token) {
if (token.type === 'placeHolder' && (!highestPlaceHolderNumber || token.value > highestPlaceHolderNumber)) {
highestPlaceHolderNumber = token.value;
}
});
var argumentNames = [],
placeHolderAsts = [];
for (var j = 0 ; j <= highestPlaceHolderNumber ; j += 1) {
placeHolderAsts.push(['name', 'a' + j]);
argumentNames.push('a' + j);
}
var returnExpressionAst = i18nTools.patternToAst(valueAst[1], placeHolderAsts);
node.splice(0, node.length, 'function', null, argumentNames, [['return', returnExpressionAst]]);
}
};
};
// Get a object: key => array of "occurrence" objects: {asset: ..., type: ..., node, ..., defaultValueAst: ...}
i18nTools.findOneTrOccurrences = function (assetGraph, initialAssets) {
var oneTrOccurrencesByKey = {};
initialAssets.forEach(function (htmlAsset) {
assetGraph.collectAssetsPostOrder(htmlAsset, {type: ['HtmlScript', 'JavaScriptOneInclude']}).filter(function (asset) {
return asset.type === 'JavaScript';
}).forEach(function (javaScript) {
var hasOneTr = false;
i18nTools.eachOneTrInAst(javaScript.parseTree, function (type, key, node, defaultValueAst) {
hasOneTr = true;
(oneTrOccurrencesByKey[key] = oneTrOccurrencesByKey[key] || []).push({
asset: javaScript,
type: type,
node: node,
defaultValueAst: defaultValueAst
});
});
});
});
return oneTrOccurrencesByKey;
};
i18nTools.getOrCreateI18nAssetForKey = function (assetGraph, key, oneTrOccurrencesByKey) {
var i18nAssetsWithTheKey = [];
assetGraph.findAssets({type: 'I18n'}).forEach(function (i18nAsset) {
if (key in i18nAsset.parseTree) {
i18nAssetsWithTheKey.push(i18nAsset);
}
});
if (i18nAssetsWithTheKey.length > 1) {
throw new Error("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' was found in multiple I18n assets, cannot proceed");
}
if (i18nAssetsWithTheKey.length === 1) {
return i18nAssetsWithTheKey[0];
} else {
// Key isn't present in any I18n asset, try to work out from the one.tr occurrences where to put it
var addToI18nForJavaScriptAsset,
includingAssetsById = {};
if (!(key in oneTrOccurrencesByKey)) {
throw new Error("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' isn't used anywhere, cannot work out which .i18n file to add it to!");
}
oneTrOccurrencesByKey[key].forEach(function (occurrence) {
includingAssetsById[occurrence.asset.id] = occurrence.asset;
});
var includingAssets = _.values(includingAssetsById);
if (includingAssets.length === 0) {
throw new Error("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' isn't found in any I18n asset and isn't used in any one.tr statements");
}
if (includingAssets.length === 1) {
addToI18nForJavaScriptAsset = includingAssets[0];
} else {
console.warn("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' occurs in one.tr expressions in multiple JavaScript assets, arbitrarily choosing the last one seen");
addToI18nForJavaScriptAsset = includingAssets[includingAssets.length - 1];
}
var existingI18nRelations = assetGraph.findRelations({from: addToI18nForJavaScriptAsset, to: {type: 'I18n'}}),
i18nAsset;
if (existingI18nRelations.length === 0) {
i18nAsset = new assetGraph.constructor.assets.I18n({
isDirty: true,
parseTree: {}
});
var relation = new assetGraph.constructor.relations.JavaScriptOneInclude({
from: addToI18nForJavaScriptAsset,
to: i18nAsset
});
i18nAsset.url = (addToI18nForJavaScriptAsset.url || this.getBaseAssetForRelation(relation)).replace(/(?:\.js|\.html)?$/, ".i18n");
console.warn("i18nTools.getOrCreateI18nAssetForKey: Creating new I18n asset: " + i18nAsset.url);
assetGraph.addAsset(i18nAsset);
assetGraph.addRelation(relation);
} else {
if (existingI18nRelations.length > 1) {
console.warn("i18nTools.getOrCreateI18nAssetForKey: " + addToI18nForJavaScriptAsset + " has multiple I18n relations, choosing the first one");
}
i18nAsset = existingI18nRelations[0].to;
}
return i18nAsset;
}
};
_.extend(exports, i18nTools);
| lib/util/i18nTools.js | var vm = require('vm'),
_ = require('underscore'),
memoizer = require('memoizer'),
uglify = require('uglify-js'),
uglifyAst = require('assetgraph/lib/util/uglifyAst'),
i18nTools = {};
// Helper for getting a prioritized list of relevant locale ids from a specific locale id.
// For instance, "en_US" produces ["en_US", "en"]
i18nTools.expandLocaleIdToPrioritizedList = memoizer(function (localeId) {
var localeIds = [localeId];
while (/_[^_]+$/.test(localeId)) {
localeId = localeId.replace(/_[^_]+$/, '');
localeIds.push(localeId);
}
return localeIds;
});
i18nTools.tokenizePattern = function (pattern) {
var tokens = [];
// Split pattern into tokens (return value of replace isn't used):
pattern.replace(/\{(\d+)\}|((?:[^\\\{]|\\[\\\{])+)/g, function ($0, placeHolderNumberStr, text) {
if (placeHolderNumberStr) {
tokens.push({
type: 'placeHolder',
value: parseInt(placeHolderNumberStr, 10)
});
} else {
tokens.push({
type: 'text',
value: text.replace(/\\([\{\}])/g, "$1")
});
}
});
return tokens;
};
i18nTools.patternToAst = function (pattern, placeHolderAsts) {
var ast;
i18nTools.tokenizePattern(pattern).forEach(function (token) {
var term;
if (token.type === 'placeHolder') {
term = placeHolderAsts[token.value];
} else {
term = ['string', token.value];
}
if (ast) {
ast = ['binary', '+', ast, term];
} else {
ast = term;
}
});
return ast || ['string', ''];
};
i18nTools.eachOneTrInAst = function (ast, lambda) {
var q = [ast];
while (q.length) {
var node = q.pop();
if (node[0] === 'call' && Array.isArray(node[1]) && node[1][0] === 'call' &&
Array.isArray(node[1][1]) && node[1][1][0] === 'dot' && Array.isArray(node[1][1][1]) &&
node[1][1][1][0] === 'name' && node[1][1][1][1] === 'one' &&
(node[1][1][2] === 'trPattern')) {
if (lambda('callTrPattern', node[1][2][0][1], node, node[1][2][1]) === false) { // type, key, node, defaultValueAst
return;
}
} else if (node[0] === 'call' && Array.isArray(node[1]) && node[1][0] === 'dot' &&
Array.isArray(node[1][1]) && node[1][1][0] === 'name' && node[1][1][1] === 'one' &&
(node[1][2] === 'tr' || node[1][2] === 'trPattern')) {
if (node[2].length === 0 || !Array.isArray(node[2][0]) || node[2][0][0] !== 'string') {
console.warn("Invalid one." + node[1][2] + " syntax: " + uglify.uglify.gen_code(node));
}
if (lambda(node[1][2], node[2][0][1], node, node[2][1]) === false) { // type, key, node, defaultValueAst
return;
}
}
for (var i = 0 ; i < node.length ; i += 1) {
if (Array.isArray(node[i])) {
q.push(node[i]);
}
}
}
};
i18nTools.getBootstrappedContext = function (assetGraph, htmlAsset) {
var context = vm.createContext();
context.window = context;
context.__defineSetter__('document', function () {});
context.__defineGetter__('document', function () {
htmlAsset.markDirty();
return htmlAsset.parseTree;
});
var bootstrapperRelations = assetGraph.findRelations({from: htmlAsset, node: {id: 'oneBootstrapper'}, to: {type: 'JavaScript'}});
if (bootstrapperRelations.length === 0) {
return context;
} else if (bootstrapperRelations.length > 1) {
throw new Error("i18nTools.getBootstrappedContext: Unexpected number of One bootstrapper relations found: " + bootstrapRelations.length);
}
new vm.Script(uglify.uglify.gen_code(bootstrapperRelations[0].to.parseTree), "bootstrap code for " + (htmlAsset.url || "inline")).runInContext(context);
return context;
};
// initialAsset must be Html or JavaScript
i18nTools.extractAllReachableKeys = function (assetGraph, initialAssets) {
if (!_.isArray(initialAssets)) {
initialAssets = [initialAssets];
}
var allKeys = {};
initialAssets.forEach(function (initialAsset) {
assetGraph.collectAssetsPostOrder(initialAsset, {type: ['HtmlScript', 'JavaScriptOneInclude']}).filter(function (asset) {
return asset.type === 'I18n';
}).forEach(function (i18nAsset) {
_.extend(allKeys, i18nAsset.parseTree);
});
});
return allKeys;
};
// initialAsset must be Html or JavaScript
i18nTools.extractAllReachableKeysForLocale = function (assetGraph, localeId, initialAsset) {
var allKeys = i18nTools.extractAllReachableKeys(assetGraph, initialAsset),
prioritizedLocaleIds = i18nTools.expandLocaleIdToPrioritizedList(localeId),
allKeysForLocale = {};
Object.keys(allKeys).forEach(function (key) {
var found = false;
for (var i = 0 ; i < prioritizedLocaleIds.length ; i += 1) {
if (prioritizedLocaleIds[i] in allKeys[key]) {
allKeysForLocale[key] = allKeys[key][prioritizedLocaleIds[i]];
found = true;
break;
}
}
if (!found) {
console.warn("i18nTools.extractAllReachableKeysForLocale: Key " + key + " not found for " + localeId);
}
});
return allKeysForLocale;
};
i18nTools.createOneTrReplacer = function (allKeys, localeId) { // localeId is optional and will only be used for warning messages
return function oneTrReplacer(type, key, node, defaultValueAst) {
var value = allKeys[key],
valueAst;
if (value === null || typeof value === 'undefined') {
// FIXME: Assumes that the defaultValueAst is in English, perhaps that should be configurable.
if (!localeId || !(/^en([\-_]|$)/.test(localeId) && defaultValueAst)) {
console.warn('oneTrReplacer: Key ' + key + ' not found' + (localeId ? ' in ' + localeId : ''));
}
if (defaultValueAst) {
valueAst = defaultValueAst;
} else {
valueAst = ['string', '[!' + key + '!]'];
}
} else {
valueAst = uglifyAst.objToAst(value);
}
if (type === 'callTrPattern') {
// Replace one.trPattern('keyName')(placeHolderValue, ...) with a string concatenation:
if (!Array.isArray(valueAst) || valueAst[0] !== 'string') {
console.warn("oneTrReplacer: Invalid one.trPattern syntax: " + value);
return;
}
Array.prototype.splice.apply(node, [0, node.length].concat(i18nTools.patternToAst(valueAst[1], node[2])));
} else if (type === 'tr') {
Array.prototype.splice.apply(node, [0, node.length].concat(valueAst));
} else if (type === 'trPattern') {
if (!Array.isArray(valueAst) || valueAst[0] !== 'string') {
console.warn("oneTrReplacer: Invalid one.trPattern syntax: " + value);
return;
}
var highestPlaceHolderNumber;
i18nTools.tokenizePattern(valueAst[1]).forEach(function (token) {
if (token.type === 'placeHolder' && (!highestPlaceHolderNumber || token.value > highestPlaceHolderNumber)) {
highestPlaceHolderNumber = token.value;
}
});
var argumentNames = [],
placeHolderAsts = [];
for (var j = 0 ; j <= highestPlaceHolderNumber ; j += 1) {
placeHolderAsts.push(['name', 'a' + j]);
argumentNames.push('a' + j);
}
var returnExpressionAst = i18nTools.patternToAst(valueAst[1], placeHolderAsts);
node.splice(0, node.length, 'function', null, argumentNames, [['return', returnExpressionAst]]);
}
};
};
// Get a object: key => array of "occurrence" objects: {asset: ..., type: ..., node, ..., defaultValueAst: ...}
i18nTools.findOneTrOccurrences = function (assetGraph, initialAssets) {
var oneTrOccurrencesByKey = {};
initialAssets.forEach(function (htmlAsset) {
assetGraph.collectAssetsPostOrder(htmlAsset, {type: ['HtmlScript', 'JavaScriptOneInclude']}).filter(function (asset) {
return asset.type === 'JavaScript';
}).forEach(function (javaScript) {
var hasOneTr = false;
i18nTools.eachOneTrInAst(javaScript.parseTree, function (type, key, node, defaultValueAst) {
hasOneTr = true;
(oneTrOccurrencesByKey[key] = oneTrOccurrencesByKey[key] || []).push({
asset: javaScript,
type: type,
node: node,
defaultValueAst: defaultValueAst
});
});
});
});
return oneTrOccurrencesByKey;
};
i18nTools.getOrCreateI18nAssetForKey = function (assetGraph, key, oneTrOccurrencesByKey) {
var i18nAssetsWithTheKey = [];
assetGraph.findAssets({type: 'I18n'}).forEach(function (i18nAsset) {
if (key in i18nAsset.parseTree) {
i18nAssetsWithTheKey.push(i18nAsset);
}
});
if (i18nAssetsWithTheKey.length > 1) {
throw new Error("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' was found in multiple I18n assets, cannot proceed");
}
if (i18nAssetsWithTheKey.length === 1) {
return i18nAssetsWithTheKey[0];
} else {
// Key isn't present in any I18n asset, try to work out from the one.tr occurrences where to put it
var addToI18nForJavaScriptAsset,
includingAssetsById = {};
if (!(key in oneTrOccurrencesByKey)) {
throw new Error("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' isn't used anywhere, cannot work out which .i18n file to add it to!");
}
oneTrOccurrencesByKey[key].forEach(function (occurrence) {
includingAssetsById[occurrence.asset.id] = occurrence.asset;
});
var includingAssets = _.values(includingAssetsById);
if (includingAssets.length === 0) {
throw new Error("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' isn't found in any I18n asset and isn't used in any one.tr statements");
}
if (includingAssets.length === 1) {
addToI18nForJavaScriptAsset = includingAssets[0];
} else {
console.warn("i18nTools.getOrCreateI18nAssetForKey: The key '" + key + "' occurs in one.tr expressions in multiple JavaScript assets, arbitrarily choosing the last one seen");
addToI18nForJavaScriptAsset = includingAssets[includingAssets.length - 1];
}
var existingI18nRelations = assetGraph.findRelations({from: addToI18nForJavaScriptAsset, to: {type: 'I18n'}}),
i18nAsset;
if (existingI18nRelations.length === 0) {
i18nAsset = new assetGraph.constructor.assets.I18n({
isDirty: true,
parseTree: {}
});
var relation = new assetGraph.constructor.relations.JavaScriptOneInclude({
from: addToI18nForJavaScriptAsset,
to: i18nAsset
});
i18nAsset.url = (addToI18nForJavaScriptAsset.url || this.getBaseAssetForRelation(relation)).replace(/(?:\.js|\.html)?$/, ".i18n");
console.warn("i18nTools.getOrCreateI18nAssetForKey: Creating new I18n asset: " + i18nAsset.url);
assetGraph.addAsset(i18nAsset);
assetGraph.addRelation(relation);
} else {
if (existingI18nRelations.length > 1) {
console.warn("i18nTools.getOrCreateI18nAssetForKey: " + addToI18nForJavaScriptAsset + " has multiple I18n relations, choosing the first one");
}
i18nAsset = existingI18nRelations[0].to;
}
return i18nAsset;
}
};
_.extend(exports, i18nTools);
| i18nTools.eachOneTrInAst: Fixed traversal order.
| lib/util/i18nTools.js | i18nTools.eachOneTrInAst: Fixed traversal order. | <ide><path>ib/util/i18nTools.js
<ide> return;
<ide> }
<ide> }
<del> for (var i = 0 ; i < node.length ; i += 1) {
<add> for (var i = node.length - 1 ; i >= 1 ; i -= 1) {
<ide> if (Array.isArray(node[i])) {
<ide> q.push(node[i]);
<ide> } |
|
Java | mit | 8bad1102eae3bad7aed8114ed40736bba037662a | 0 | yeputons/spbau-java-course-torrent-term4,yeputons/spbau-java-course-torrent-term4 | package net.yeputons.spbau.spring2016.torrent.client;
import net.yeputons.spbau.spring2016.torrent.FileDescription;
import net.yeputons.spbau.spring2016.torrent.StateFileHolder;
import net.yeputons.spbau.spring2016.torrent.TorrentConnection;
import net.yeputons.spbau.spring2016.torrent.TrackerServer;
import net.yeputons.spbau.spring2016.torrent.protocol.FileEntry;
import net.yeputons.spbau.spring2016.torrent.protocol.ListRequest;
import net.yeputons.spbau.spring2016.torrent.protocol.UploadRequest;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
public class ConsoleClient implements Runnable {
private final int partSize;
private final Path storage = Paths.get("torrent-client-state.bin");
private final Deque<String> args;
private final StateFileHolder<ClientState> stateHolder;
public ConsoleClient(String[] args) {
this.args = new LinkedList<>(Arrays.asList(args));
stateHolder = new StateFileHolder<>(storage, new ClientState(Paths.get(".")));
partSize = Integer.parseInt(System.getProperty("torrent.part_size", "10485760"));
System.out.printf("torrent.part_size=%d\n", partSize);
}
@Override
public void run() {
if (args.size() < 2) {
help();
}
String operation = args.removeFirst();
InetSocketAddress addr = new InetSocketAddress(args.removeFirst(), TrackerServer.DEFAULT_PORT);
try (TorrentConnection connection = new TorrentConnection(addr)) {
switch (operation) {
case "list":
doList(connection);
break;
case "newfile":
doNewFile(connection);
break;
case "get":
doGet(connection);
break;
case "run":
doRun(connection);
break;
default:
help();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void help() {
System.err.println("Expected arguments: client (list|get|newfile|run) <tracker-address> [extra]");
System.err.println("Extra arguments for 'get': <file-id>");
System.err.println("Extra arguments for 'newfile': <file-path>");
System.err.println(
"Default file part size is 10485760 bytes, "
+ "can be modified with JVM property torrent.part_size");
System.exit(1);
}
private void doList(TorrentConnection connection) throws IOException {
if (args.size() != 0) {
help();
}
System.out.printf("%9s %19s %s\n", "ID", "SIZE", "NAME");
for (FileEntry e : connection.makeRequest(new ListRequest())) {
System.out.printf("%9d %19d %s\n", e.getId(), e.getSize(), e.getName());
}
}
private void doNewFile(TorrentConnection connection) throws IOException {
if (args.size() != 1) {
help();
}
Path p = Paths.get(args.removeFirst());
String fileName = p.getFileName().toString();
long size = Files.size(p);
System.out.printf("Adding file %s (%d bytes)... ", fileName, size);
int id = connection.makeRequest(new UploadRequest(fileName, size));
System.out.printf("id=%d\n", id);
ClientState state = stateHolder.getState();
FileDescription description = new FileDescription(new FileEntry(id, fileName, size), partSize);
description.getDownloaded().flip(0, description.getPartsCount());
state.getFiles().put(id, description);
stateHolder.save();
}
private void doGet(TorrentConnection connection) throws IOException {
if (args.size() != 1) {
help();
}
int id = Integer.parseInt(args.removeFirst());
ClientState state = stateHolder.getState();
if (state.getFiles().containsKey(id)) {
System.out.printf("File is already in the list: %s\n", state.getFiles().get(id));
return;
}
for (FileEntry e : connection.makeRequest(new ListRequest())) {
if (e.getId() == id) {
FileDescription description = new FileDescription(e, partSize);
state.getFiles().put(id, description);
stateHolder.save();
return;
}
}
System.err.println("File with id " + id + " was not found on the server");
System.exit(1);
}
private void doRun(TorrentConnection connection) throws IOException {
if (args.size() != 0) {
help();
}
TorrentClient client = new TorrentClient(connection, stateHolder);
client.start();
try {
client.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| src/main/java/net/yeputons/spbau/spring2016/torrent/client/ConsoleClient.java | package net.yeputons.spbau.spring2016.torrent.client;
import net.yeputons.spbau.spring2016.torrent.FileDescription;
import net.yeputons.spbau.spring2016.torrent.StateFileHolder;
import net.yeputons.spbau.spring2016.torrent.TorrentConnection;
import net.yeputons.spbau.spring2016.torrent.TrackerServer;
import net.yeputons.spbau.spring2016.torrent.protocol.FileEntry;
import net.yeputons.spbau.spring2016.torrent.protocol.ListRequest;
import net.yeputons.spbau.spring2016.torrent.protocol.UploadRequest;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
public class ConsoleClient implements Runnable {
private static final int PART_SIZE = 40;
private final Path storage = Paths.get("torrent-client-state.bin");
private final Deque<String> args;
private final StateFileHolder<ClientState> stateHolder;
public ConsoleClient(String[] args) {
this.args = new LinkedList<>(Arrays.asList(args));
stateHolder = new StateFileHolder<>(storage, new ClientState(Paths.get(".")));
}
@Override
public void run() {
if (args.size() < 2) {
help();
}
String operation = args.removeFirst();
InetSocketAddress addr = new InetSocketAddress(args.removeFirst(), TrackerServer.DEFAULT_PORT);
try (TorrentConnection connection = new TorrentConnection(addr)) {
switch (operation) {
case "list":
doList(connection);
break;
case "newfile":
doNewFile(connection);
break;
case "get":
doGet(connection);
break;
case "run":
doRun(connection);
break;
default:
help();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void help() {
System.err.println("Expected arguments: client (list|get|newfile|run) <tracker-address> [extra]");
System.err.println("Extra arguments for 'get': <file-id>");
System.err.println("Extra arguments for 'newfile': <file-path>");
System.exit(1);
}
private void doList(TorrentConnection connection) throws IOException {
if (args.size() != 0) {
help();
}
System.out.printf("%9s %19s %s\n", "ID", "SIZE", "NAME");
for (FileEntry e : connection.makeRequest(new ListRequest())) {
System.out.printf("%9d %19d %s\n", e.getId(), e.getSize(), e.getName());
}
}
private void doNewFile(TorrentConnection connection) throws IOException {
if (args.size() != 1) {
help();
}
Path p = Paths.get(args.removeFirst());
String fileName = p.getFileName().toString();
long size = Files.size(p);
System.out.printf("Adding file %s (%d bytes)... ", fileName, size);
int id = connection.makeRequest(new UploadRequest(fileName, size));
System.out.printf("id=%d\n", id);
ClientState state = stateHolder.getState();
FileDescription description = new FileDescription(new FileEntry(id, fileName, size), PART_SIZE);
description.getDownloaded().flip(0, description.getPartsCount());
state.getFiles().put(id, description);
stateHolder.save();
}
private void doGet(TorrentConnection connection) throws IOException {
if (args.size() != 1) {
help();
}
int id = Integer.parseInt(args.removeFirst());
ClientState state = stateHolder.getState();
if (state.getFiles().containsKey(id)) {
System.out.printf("File is already in the list: %s\n", state.getFiles().get(id));
return;
}
for (FileEntry e : connection.makeRequest(new ListRequest())) {
if (e.getId() == id) {
FileDescription description = new FileDescription(e, PART_SIZE);
state.getFiles().put(id, description);
stateHolder.save();
return;
}
}
System.err.println("File with id " + id + " was not found on the server");
System.exit(1);
}
private void doRun(TorrentConnection connection) throws IOException {
if (args.size() != 0) {
help();
}
TorrentClient client = new TorrentClient(connection, stateHolder);
client.start();
try {
client.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| ConsoleClient: make part size specifiable via system properties
| src/main/java/net/yeputons/spbau/spring2016/torrent/client/ConsoleClient.java | ConsoleClient: make part size specifiable via system properties | <ide><path>rc/main/java/net/yeputons/spbau/spring2016/torrent/client/ConsoleClient.java
<ide> import java.util.LinkedList;
<ide>
<ide> public class ConsoleClient implements Runnable {
<del> private static final int PART_SIZE = 40;
<add> private final int partSize;
<ide> private final Path storage = Paths.get("torrent-client-state.bin");
<ide> private final Deque<String> args;
<ide>
<ide> public ConsoleClient(String[] args) {
<ide> this.args = new LinkedList<>(Arrays.asList(args));
<ide> stateHolder = new StateFileHolder<>(storage, new ClientState(Paths.get(".")));
<add> partSize = Integer.parseInt(System.getProperty("torrent.part_size", "10485760"));
<add> System.out.printf("torrent.part_size=%d\n", partSize);
<ide> }
<ide>
<ide> @Override
<ide> System.err.println("Expected arguments: client (list|get|newfile|run) <tracker-address> [extra]");
<ide> System.err.println("Extra arguments for 'get': <file-id>");
<ide> System.err.println("Extra arguments for 'newfile': <file-path>");
<add> System.err.println(
<add> "Default file part size is 10485760 bytes, "
<add> + "can be modified with JVM property torrent.part_size");
<ide> System.exit(1);
<ide> }
<ide>
<ide> System.out.printf("id=%d\n", id);
<ide>
<ide> ClientState state = stateHolder.getState();
<del> FileDescription description = new FileDescription(new FileEntry(id, fileName, size), PART_SIZE);
<add> FileDescription description = new FileDescription(new FileEntry(id, fileName, size), partSize);
<ide> description.getDownloaded().flip(0, description.getPartsCount());
<ide> state.getFiles().put(id, description);
<ide> stateHolder.save();
<ide>
<ide> for (FileEntry e : connection.makeRequest(new ListRequest())) {
<ide> if (e.getId() == id) {
<del> FileDescription description = new FileDescription(e, PART_SIZE);
<add> FileDescription description = new FileDescription(e, partSize);
<ide> state.getFiles().put(id, description);
<ide> stateHolder.save();
<ide> return; |
|
Java | apache-2.0 | 938fffec543ce311635a8243506630de470ac911 | 0 | zhuyuqing/bestconf,zhuyuqing/bestconf | /**
* Copyright (c) 2017 Institute of Computing Technology, Chinese Academy of Sciences, 2017
* Institute of Computing Technology, Chinese Academy of Sciences contributors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package cn.ict.zyq.bestConf.cluster.InterfaceImpl;
import cn.ict.zyq.bestConf.cluster.Interface.ConfigReadin;
public class SparkConfigReadin implements ConfigReadin {
@Override
public void initial(String server, String username, String password, String localPath, String remotePath) {
// TODO Auto-generated method stub
}
@Override
public void downLoadConfigFile(String fileName) {
// TODO Auto-generated method stub
}
@Override
public HashMap modifyConfigFile(HashMap hm, String filepath) {
}
@Override
public HashMap modifyConfigFile(HashMap hm) {
}
}
| src/spark/cn/ict/zyq/bestConf/cluster/InterfaceImpl/SparkConfigReadin.java | /**
* Copyright (c) 2017 Institute of Computing Technology, Chinese Academy of Sciences, 2017
* Institute of Computing Technology, Chinese Academy of Sciences contributors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package cn.ict.zyq.bestConf.cluster.InterfaceImpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.ho.yaml.Yaml;
import ch.ethz.ssh2.Connection;
import cn.ict.zyq.bestConf.cluster.Interface.ConfigReadin;
import cn.ict.zyq.bestConf.cluster.Utils.PropertiesUtil;
public class SparkConfigReadin implements ConfigReadin {
private Connection connection;
private String server;
private String username;
private String password;
private String remotePath;
private String localPath;
private String filepath;
@Override
public void initial(String server, String username, String password, String localPath, String remotePath) {
// TODO Auto-generated method stub
this.server = server;
this.username = username;
this.password = password;
this.localPath = localPath;
this.remotePath = remotePath;
filepath = localPath + "/kmeans_defaults.yaml";
}
public Connection getConnection(){
try{
connection = new Connection(server);
connection.connect();
boolean isAuthenticated = connection.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
throw new IOException("Authentication failed...");
}
}catch (IOException e) {
e.printStackTrace();
}
return connection;
}
public void closeConnection() {
try {
if (connection.connect() != null) {
connection.close();
}
} catch (IOException e) {
} finally {
connection.close();
}
}
@Override
public void downLoadConfigFile(String fileName) {
// TODO Auto-generated method stub
}
public HashMap loadFileToHashMap(String filePath) {
HashMap hashmap = null;
File f = new File(filePath);
try {
Properties pps = PropertiesUtil.GetAllProperties(filePath);
hashmap = new HashMap((Map) pps);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hashmap;
}
public void modify(HashMap toModify, HashMap updatedValues) {
boolean flag;
Iterator itrUpdated = updatedValues.entrySet().iterator();
while(itrUpdated.hasNext()){
Map.Entry entUpdated = (Map.Entry)itrUpdated.next();
Object tempObj = toModify.get(entUpdated.getKey().toString());
if(tempObj!=null){
if (!entUpdated.getValue().toString().equals("NaN")) {
if (Double.parseDouble(entUpdated.getValue().toString()) < 1.0 && Double.parseDouble(entUpdated.getValue().toString()) != 0.0) {
toModify.put(entUpdated.getKey().toString(), entUpdated.getValue().toString());
} else if(Double.parseDouble(entUpdated.getValue().toString()) == 0.0){
toModify.put(entUpdated.getKey().toString(), Integer.parseInt("0"));
} else {
toModify.put(entUpdated.getKey().toString(), (int)Math.floor(Double.parseDouble(entUpdated.getValue().toString())));
}
}
}else
System.out.println(entUpdated.getKey().toString() + " doesn't exist in original list!");
}
}
@Override
public HashMap modifyConfigFile(HashMap hm, String filepath) {
HashMap ori = loadFileToHashMap(filepath);
modify(ori, hm);
return ori;
}
@Override
public HashMap modifyConfigFile(HashMap hm) {
HashMap ori = loadFileToHashMap(filepath);
modify(ori, hm);
return ori;
}
public static void main(String[] args){
SparkConfigReadin sparkR = new SparkConfigReadin();
SparkConfigWrite sparkW = new SparkConfigWrite();
String filepath = "data/spark/spark-defaults.conf";
HashMap hm = sparkR.loadFileToHashMap(filepath);
Iterator it = hm.entrySet().iterator();
sparkW.writetoConfigfile(hm);
while(it.hasNext()){
Map.Entry entry_hm_ori = (Map.Entry)it.next();
String key_hm_ori = entry_hm_ori.getKey().toString();
System.out.println("key is : " + key_hm_ori);
System.out.println("value is : " + entry_hm_ori.getValue());
}
}
}
| Update SparkConfigReadin.java | src/spark/cn/ict/zyq/bestConf/cluster/InterfaceImpl/SparkConfigReadin.java | Update SparkConfigReadin.java | <ide><path>rc/spark/cn/ict/zyq/bestConf/cluster/InterfaceImpl/SparkConfigReadin.java
<ide> * LICENSE file.
<ide> */
<ide> package cn.ict.zyq.bestConf.cluster.InterfaceImpl;
<del>
<del>import java.io.File;
<del>import java.io.FileInputStream;
<del>import java.io.FileNotFoundException;
<del>import java.io.IOException;
<del>import java.util.HashMap;
<del>import java.util.Iterator;
<del>import java.util.Map;
<del>import java.util.Properties;
<del>
<del>import org.ho.yaml.Yaml;
<del>
<del>import ch.ethz.ssh2.Connection;
<ide> import cn.ict.zyq.bestConf.cluster.Interface.ConfigReadin;
<del>import cn.ict.zyq.bestConf.cluster.Utils.PropertiesUtil;
<ide>
<ide> public class SparkConfigReadin implements ConfigReadin {
<del>
<del> private Connection connection;
<del> private String server;
<del> private String username;
<del> private String password;
<del> private String remotePath;
<del> private String localPath;
<del> private String filepath;
<del>
<add>
<ide> @Override
<ide> public void initial(String server, String username, String password, String localPath, String remotePath) {
<ide> // TODO Auto-generated method stub
<del> this.server = server;
<del> this.username = username;
<del> this.password = password;
<del> this.localPath = localPath;
<del> this.remotePath = remotePath;
<del> filepath = localPath + "/kmeans_defaults.yaml";
<del> }
<del> public Connection getConnection(){
<del> try{
<del> connection = new Connection(server);
<del> connection.connect();
<del> boolean isAuthenticated = connection.authenticateWithPassword(username, password);
<del> if (isAuthenticated == false) {
<del> throw new IOException("Authentication failed...");
<del> }
<del> }catch (IOException e) {
<del> e.printStackTrace();
<del> }
<del> return connection;
<add>
<ide> }
<ide>
<del> public void closeConnection() {
<del> try {
<del> if (connection.connect() != null) {
<del> connection.close();
<del> }
<del> } catch (IOException e) {
<del>
<del> } finally {
<del> connection.close();
<del> }
<del> }
<add>
<ide> @Override
<ide> public void downLoadConfigFile(String fileName) {
<ide> // TODO Auto-generated method stub
<ide>
<ide> }
<del> public HashMap loadFileToHashMap(String filePath) {
<del> HashMap hashmap = null;
<del> File f = new File(filePath);
<del> try {
<del> Properties pps = PropertiesUtil.GetAllProperties(filePath);
<del> hashmap = new HashMap((Map) pps);
<del> } catch (FileNotFoundException e) {
<del> e.printStackTrace();
<del> } catch (IOException e) {
<del> // TODO Auto-generated catch block
<del> e.printStackTrace();
<del> }
<del> return hashmap;
<del> }
<del> public void modify(HashMap toModify, HashMap updatedValues) {
<del> boolean flag;
<del> Iterator itrUpdated = updatedValues.entrySet().iterator();
<del> while(itrUpdated.hasNext()){
<del> Map.Entry entUpdated = (Map.Entry)itrUpdated.next();
<del> Object tempObj = toModify.get(entUpdated.getKey().toString());
<del> if(tempObj!=null){
<del> if (!entUpdated.getValue().toString().equals("NaN")) {
<del> if (Double.parseDouble(entUpdated.getValue().toString()) < 1.0 && Double.parseDouble(entUpdated.getValue().toString()) != 0.0) {
<del> toModify.put(entUpdated.getKey().toString(), entUpdated.getValue().toString());
<del> } else if(Double.parseDouble(entUpdated.getValue().toString()) == 0.0){
<del> toModify.put(entUpdated.getKey().toString(), Integer.parseInt("0"));
<del> } else {
<del> toModify.put(entUpdated.getKey().toString(), (int)Math.floor(Double.parseDouble(entUpdated.getValue().toString())));
<del> }
<del> }
<del> }else
<del> System.out.println(entUpdated.getKey().toString() + " doesn't exist in original list!");
<del> }
<del> }
<add>
<ide> @Override
<ide> public HashMap modifyConfigFile(HashMap hm, String filepath) {
<del> HashMap ori = loadFileToHashMap(filepath);
<del> modify(ori, hm);
<del> return ori;
<add>
<ide> }
<ide>
<ide> @Override
<ide> public HashMap modifyConfigFile(HashMap hm) {
<del> HashMap ori = loadFileToHashMap(filepath);
<del> modify(ori, hm);
<del> return ori;
<add>
<ide> }
<del> public static void main(String[] args){
<del> SparkConfigReadin sparkR = new SparkConfigReadin();
<del> SparkConfigWrite sparkW = new SparkConfigWrite();
<del> String filepath = "data/spark/spark-defaults.conf";
<del> HashMap hm = sparkR.loadFileToHashMap(filepath);
<del> Iterator it = hm.entrySet().iterator();
<del> sparkW.writetoConfigfile(hm);
<del> while(it.hasNext()){
<del> Map.Entry entry_hm_ori = (Map.Entry)it.next();
<del> String key_hm_ori = entry_hm_ori.getKey().toString();
<del> System.out.println("key is : " + key_hm_ori);
<del> System.out.println("value is : " + entry_hm_ori.getValue());
<del> }
<del> }
<add>
<ide> } |
|
Java | apache-2.0 | 17e0f147cc7849c4fd7612581c744fd760466f9d | 0 | powertac/powertac-server,powertac/powertac-server,powertac/powertac-server,powertac/powertac-server | /*
* Copyright (c) 2012 by the original author
*
* 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.powertac.genco;
import static org.junit.Assert.*;
import java.util.Collection;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powertac.common.config.Configurator;
import org.powertac.common.interfaces.ServerConfiguration;
import org.powertac.common.spring.SpringApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
/**
* @author jcollins
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-config.xml"})
@TestExecutionListeners(listeners = {
DependencyInjectionTestExecutionListener.class
})
public class GencoConfigTest
{
private Configuration config;
/**
*
*/
@Before
public void setUp () throws Exception
{
ApplicationContext context = SpringApplicationContext.getContext();
Resource props = context.getResource("genco-test.properties");
// this probably won't work if tests are packaged in a jarfile
config = new PropertiesConfiguration(props.getFile());
}
@Test
public void testConfigurator ()
{
Configurator processor = new Configurator();
processor.setConfiguration(config);
Collection<?> gencos = processor.configureInstances(Genco.class);
assertEquals("2 gencos generated", 2, gencos.size());
Genco nsp1 = null;
Genco nsp2 = null;
for (Object item : gencos) {
Genco genco = (Genco)item;
if ("nsp1".equals(genco.getUsername()))
nsp1 = genco;
else if ("nsp2".equals(genco.getUsername()))
nsp2 = genco;
}
assertNotNull("nsp1 created", nsp1);
assertEquals("nsp1 capacity", 20.0, nsp1.getNominalCapacity(), 1e-6);
assertEquals("nsp1 variability", 0.05, nsp1.getVariability(), 1e-6);
assertEquals("nsp1 reliability", 0.98, nsp1.getReliability(), 1e-6);
assertEquals("nsp1 cost", 20.0, nsp1.getCost(), 1e-6);
assertEquals("nsp1 emission", 1.0, nsp1.getCarbonEmissionRate(), 1e-6);
assertEquals("nsp1 leadtime", 8, nsp1.getCommitmentLeadtime());
assertNotNull("nsp2 created", nsp2);
assertEquals("nsp2 capacity", 30.0, nsp2.getNominalCapacity(), 1e-6);
assertEquals("nsp2 variability", 0.05, nsp2.getVariability(), 1e-6);
assertEquals("nsp2 reliability", 0.97, nsp2.getReliability(), 1e-6);
assertEquals("nsp2 cost", 30.0, nsp2.getCost(), 1e-6);
assertEquals("nsp2 emission", 0.95, nsp2.getCarbonEmissionRate(), 1e-6);
assertEquals("nsp2 leadtime", 6, nsp2.getCommitmentLeadtime());
}
}
| src/test/java/org/powertac/genco/GencoConfigTest.java | /*
* Copyright (c) 2012 by the original author
*
* 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.powertac.genco;
import static org.junit.Assert.*;
import java.util.Collection;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powertac.common.config.Configurator;
import org.powertac.common.interfaces.ServerConfiguration;
import org.powertac.common.spring.SpringApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author jcollins
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-config.xml"})
public class GencoConfigTest
{
private Configuration config;
/**
*
*/
@Before
public void setUp () throws Exception
{
ApplicationContext context = SpringApplicationContext.getContext();
Resource props = context.getResource("genco-test.properties");
// this probably won't work if tests are packaged in a jarfile
config = new PropertiesConfiguration(props.getFile());
}
@Test
public void testConfigurator ()
{
Configurator processor = new Configurator();
processor.setConfiguration(config);
Collection<?> gencos = processor.configureInstances(Genco.class);
assertEquals("2 gencos generated", 2, gencos.size());
Genco nsp1 = null;
Genco nsp2 = null;
for (Object item : gencos) {
Genco genco = (Genco)item;
if ("nsp1".equals(genco.getUsername()))
nsp1 = genco;
else if ("nsp2".equals(genco.getUsername()))
nsp2 = genco;
}
assertNotNull("nsp1 created", nsp1);
assertEquals("nsp1 capacity", 20.0, nsp1.getNominalCapacity(), 1e-6);
assertEquals("nsp1 variability", 0.05, nsp1.getVariability(), 1e-6);
assertEquals("nsp1 reliability", 0.98, nsp1.getReliability(), 1e-6);
assertEquals("nsp1 cost", 20.0, nsp1.getCost(), 1e-6);
assertEquals("nsp1 emission", 1.0, nsp1.getCarbonEmissionRate(), 1e-6);
assertEquals("nsp1 leadtime", 8, nsp1.getCommitmentLeadtime());
assertNotNull("nsp2 created", nsp2);
assertEquals("nsp2 capacity", 30.0, nsp2.getNominalCapacity(), 1e-6);
assertEquals("nsp2 variability", 0.05, nsp2.getVariability(), 1e-6);
assertEquals("nsp2 reliability", 0.97, nsp2.getReliability(), 1e-6);
assertEquals("nsp2 cost", 30.0, nsp2.getCost(), 1e-6);
assertEquals("nsp2 emission", 0.95, nsp2.getCarbonEmissionRate(), 1e-6);
assertEquals("nsp2 leadtime", 6, nsp2.getCommitmentLeadtime());
}
}
| Annotate SpringJUnit4ClassRunner tests with TestExecutionListeners
| src/test/java/org/powertac/genco/GencoConfigTest.java | Annotate SpringJUnit4ClassRunner tests with TestExecutionListeners | <ide><path>rc/test/java/org/powertac/genco/GencoConfigTest.java
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.TestExecutionListeners;
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<add>import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
<add>import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
<ide>
<ide> /**
<ide> * @author jcollins
<ide> */
<ide> @RunWith(SpringJUnit4ClassRunner.class)
<ide> @ContextConfiguration(locations = {"classpath:test-config.xml"})
<add>@TestExecutionListeners(listeners = {
<add> DependencyInjectionTestExecutionListener.class
<add>})
<ide> public class GencoConfigTest
<ide> {
<ide> private Configuration config; |
|
Java | agpl-3.0 | 809cdd84954ba2df1f06192ad5f5c3e4b33a9196 | 0 | jspacco/Knoxcraft,jspacco/Knoxcraft,jspacco/Knoxcraft,jspacco/Knoxcraft,jspacco/Knoxcraft | package org.knoxcraft.turtle3d;
import java.util.HashMap;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.CatalogTypes;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.type.BrickTypes;
import org.spongepowered.api.data.type.DirtTypes;
import org.spongepowered.api.data.type.DisguisedBlockTypes;
import org.spongepowered.api.data.type.DyeColors;
import org.spongepowered.api.data.type.PlantTypes;
import org.spongepowered.api.data.type.SandTypes;
import org.spongepowered.api.data.type.SandstoneTypes;
import org.spongepowered.api.data.type.SlabTypes;
import org.spongepowered.api.data.type.StoneTypes;
import org.spongepowered.api.data.type.TreeTypes;
public final class KCTBlockTypesBuilder {
private static class Metadata {
private BlockState block;
private int numID;
private int meta;
private String name;
private String textID;
public Metadata(int numID, int meta, String name, String textID, BlockState block) {
this.numID = numID;
this.meta = meta;
this.name = name;
this.textID = textID;
this.block = block;
}
public int getNumID() {
return numID;
}
public int getMetadata() {
return meta;
}
public String getName() {
return name;
}
public String getTextID() {
return textID;
}
public BlockState getBlock() {
return block;
}
}
private static final HashMap<KCTBlockTypes, Metadata> blocks = new HashMap<KCTBlockTypes, Metadata>();
/**
* Return the {@link BlockState} that corresponds to the given {@link KCTBlockType}.
* Basically, this converts between our own internal <tt>enum</tt> and a Sponge
* {@link BlockState}.
*
* <b>NOTE:</b>
*
* Using an initialize() method that gets called once, rather than a static initializer.
* The {@link BlockTypes} class dynamically creates placeholders where all methods throw
* UnsupportedOperationException. If you use any methods of a {@link BlockType} in a static
* initializer it will throw that UnsupportedOperationException. So we have to delay actually
* calling any methods on a {@link BlockType} until Sponge has actually initialized everything
* in {@link BlockTypes} with its real value.
*
* Sponge does eventually fill in the real {@link BlockType} instances in {@link BlockTypes}, probably
* using some design pattern that is related to {@link CatalogTypes} and {@link CatalogType}.
*
* We honestly don't understand how this process works, so we are just using the static
* initialize() method because it gets called late enough that it doesn't generate an exception.
* We don't know why this works.
*
* @param type
* @return
*/
public static BlockState getBlockState(KCTBlockTypes type) {
initialize();
return blocks.get(type).getBlock();
}
private static boolean isInitialized=false;
/**
* See {@link #getBlockState(KCTBlockTypes)} for more details about why we have this method
* instead of a static initializer.
*/
private static void initialize() {
// Ensure that we only call initialize once!
if (isInitialized){
return;
}
isInitialized=true;
blocks.put(KCTBlockTypes.AIR, new Metadata(0, 0, "AIR", "AIR",
BlockState.builder().build()));
blocks.put(KCTBlockTypes.STONE, new Metadata(1, 0, "STONE", "STONE",
BlockTypes.STONE.getDefaultState()));
blocks.put(KCTBlockTypes.GRANITE, new Metadata(1, 1, "GRANITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.GRANITE).get()));
blocks.put(KCTBlockTypes.POLISHED_GRANITE, new Metadata(1, 2, "POLISHED_GRANITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.SMOOTH_GRANITE).get()));
blocks.put(KCTBlockTypes.DIORITE, new Metadata(1, 3, "DIORITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.DIORITE).get()));
blocks.put(KCTBlockTypes.POLISHED_DIORITE, new Metadata(1, 4, "POLISHED_DIORITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.SMOOTH_DIORITE).get()));
blocks.put(KCTBlockTypes.ANDESITE, new Metadata(1, 5, "ANDESITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.ANDESITE).get()));
blocks.put(KCTBlockTypes.POLISHED_ANDESITE, new Metadata(1, 6, "POLISHED_ANDESITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.SMOOTH_ANDESITE).get()));
blocks.put(KCTBlockTypes.GRASS, new Metadata(2, 0, "GRASS", "GRASS",
BlockTypes.GRASS.getDefaultState()));
blocks.put(KCTBlockTypes.DIRT, new Metadata(3, 0, "DIRT", "DIRT",
BlockTypes.DIRT.getDefaultState()));
blocks.put(KCTBlockTypes.COARSE_DIRT, new Metadata(3, 1, "COARSE_DIRT", "DIRT",
BlockTypes.DIRT.getDefaultState().with(Keys.DIRT_TYPE, DirtTypes.COARSE_DIRT).get()));
blocks.put(KCTBlockTypes.PODZOL, new Metadata(3, 2, "PODZOL", "DIRT",
BlockTypes.DIRT.getDefaultState().with(Keys.DIRT_TYPE, DirtTypes.PODZOL).get()));
blocks.put(KCTBlockTypes.COBBLESTONE, new Metadata(4, 0, "COBBLESTONE", "COBBLESTONE",
BlockTypes.COBBLESTONE.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_WOOD_PLANK, new Metadata(5, 0, "OAK_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD_PLANK, new Metadata(5, 1, "SPRUCE_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_WOOD_PLANK, new Metadata(5, 2, "BIRCH_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD_PLANK, new Metadata(5, 3, "JUNGLE_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD_PLANK, new Metadata(5, 4, "ACACIA_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD_PLANK, new Metadata(5, 5, "DARK_OAK_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.OAK_SAPLING, new Metadata(6, 0, "OAK_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_SAPLING, new Metadata(6, 1, "SPRUCE_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_SAPLING, new Metadata(6, 2, "BIRCH_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_SAPLING, new Metadata(6, 3, "JUNGLE_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.ACACIA_SAPLING, new Metadata(6, 4, "ACACIA_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DARK_OAK_SAPLING, new Metadata(6, 5, "DARK_OAK_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.BEDROCK, new Metadata(7, 0, "BEDROCK", "BEDROCK",
BlockTypes.BEDROCK.getDefaultState()));
blocks.put(KCTBlockTypes.FLOWING_WATER, new Metadata(8, 0, "FLOWING_WATER", "FLOWING_WATER",
BlockTypes.FLOWING_WATER.getDefaultState()));
blocks.put(KCTBlockTypes.STILL_WATER, new Metadata(9, 0, "STILL_WATER", "WATER",
BlockTypes.WATER.getDefaultState()));
blocks.put(KCTBlockTypes.FLOWING_LAVA, new Metadata(10, 0, "FLOWING_LAVA", "FLOWING_LAVA",
BlockTypes.FLOWING_LAVA.getDefaultState()));
blocks.put(KCTBlockTypes.STILL_LAVA, new Metadata(11, 0, "STILL_LAVA", "LAVA",
BlockTypes.LAVA.getDefaultState()));
blocks.put(KCTBlockTypes.SAND, new Metadata(12, 0, "SAND", "SAND",
BlockTypes.SAND.getDefaultState()));
blocks.put(KCTBlockTypes.RED_SAND, new Metadata(12, 1, "RED_SAND", "SAND",
BlockTypes.SAND.getDefaultState().with(Keys.SAND_TYPE, SandTypes.RED).get()));
blocks.put(KCTBlockTypes.GRAVEL, new Metadata(13, 0, "GRAVEL", "GRAVEL",
BlockTypes.GRAVEL.getDefaultState()));
blocks.put(KCTBlockTypes.GOLD_ORE, new Metadata(14, 0, "GOLD_ORE", "GOLD_ORE",
BlockTypes.GOLD_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_ORE, new Metadata(15, 0, "IRON_ORE", "IRON_ORE",
BlockTypes.IRON_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.COAL_ORE, new Metadata(16, 0, "COAL_ORE", "COAL_ORE",
BlockTypes.COAL_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_WOOD, new Metadata(17, 0, "OAK_WOOD", "LOG",
BlockTypes.LOG.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD, new Metadata(17, 1, "SPRUCE_WOOD", "LOG",
BlockTypes.LOG.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_WOOD, new Metadata(17, 2, "BIRCH_WOOD", "LOG",
BlockTypes.LOG.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD, new Metadata(17, 3, "JUNGLE_WOOD", "LOG",
BlockTypes.LOG.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.OAK_LEAVES, new Metadata(18, 0, "OAK_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_LEAVES, new Metadata(18, 1, "SPRUCE_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_LEAVES, new Metadata(18, 2, "BIRCH_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_LEAVES, new Metadata(18, 3, "JUNGLE_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.SPONGE, new Metadata(19, 0, "SPONGE", "SPONGE",
BlockTypes.SPONGE.getDefaultState()));
blocks.put(KCTBlockTypes.WET_SPONGE, new Metadata(19, 1, "WET_SPONGE", "SPONGE",
BlockTypes.SPONGE.getDefaultState().with(Keys.IS_WET, true).get()));
blocks.put(KCTBlockTypes.GLASS, new Metadata(20, 0, "GLASS", "GLASS",
BlockTypes.GLASS.getDefaultState()));
blocks.put(KCTBlockTypes.LAPIS_LAZULI_ORE, new Metadata(21, 0, "LAPIS_LAZULI_ORE", "LAPIS_ORE",
BlockTypes.LAPIS_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.LAPIS_LAZULI_BLOCK, new Metadata(22, 0, "LAPIS_LAZULI_BLOCK", "LAPIS_BLOCK",
BlockTypes.LAPIS_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.DISPENSER, new Metadata(23, 0, "DISPENSER", "DISPENSER",
BlockTypes.DISPENSER.getDefaultState()));
blocks.put(KCTBlockTypes.SANDSTONE, new Metadata(24, 0, "SANDSTONE", "SANDSTONE",
BlockTypes.SANDSTONE.getDefaultState()));
blocks.put(KCTBlockTypes.CHISELED_SANDSTONE, new Metadata(24, 1, "CHISELED_SANDSTONE", "SANDSTONE",
BlockTypes.SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.SMOOTH_SANDSTONE, new Metadata(24, 2, "SMOOTH_SANDSTONE", "SANDSTONE",
BlockTypes.SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.SMOOTH).get()));
blocks.put(KCTBlockTypes.NOTE_BLOCK, new Metadata(25, 0, "NOTE_BLOCK", "NOTEBLOCK",
BlockTypes.NOTEBLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.BED, new Metadata(26, 0, "BED", "BED",
BlockTypes.BED.getDefaultState()));
blocks.put(KCTBlockTypes.POWERED_RAIL, new Metadata(27, 0, "POWERED_RAIL", "GOLDEN_RAIL",
BlockTypes.GOLDEN_RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.DETECTOR_RAIL, new Metadata(28, 0, "DETECTOR_RAIL", "DETECTOR_RAIL",
BlockTypes.DETECTOR_RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.STICKY_PISTON, new Metadata(29, 0, "STICKY_PISTON", "STICKY_PISTON",
BlockTypes.STICKY_PISTON.getDefaultState()));
blocks.put(KCTBlockTypes.COBWEB, new Metadata(30, 0, "COBWEB", "WEB",
BlockTypes.WEB.getDefaultState()));
blocks.put(KCTBlockTypes.DEAD_SHRUB, new Metadata(31, 0, "DEAD_SHRUB", "TALLGRASS",
BlockTypes.TALLGRASS.getDefaultState()));
// FIXME: doesn't exist?
// blocks.put(KCTBlockTypes.GRASS, new Metadata(31, 1, "GRASS", "TALLGRASS",
// BlockTypes.TALLGRASS.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.GRASS).get()));
//
// blocks.put(KCTBlockTypes.FERN, new Metadata(31, 2, "FERN", "TALLGRASS",
// BlockTypes.TALLGRASS.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.FERN).get()));
blocks.put(KCTBlockTypes.DEAD_BUSH, new Metadata(32, 0, "DEAD_BUSH", "DEADBUSH",
BlockTypes.DEADBUSH.getDefaultState()));
blocks.put(KCTBlockTypes.PISTON, new Metadata(33, 0, "PISTON", "PISTON",
BlockTypes.PISTON.getDefaultState()));
blocks.put(KCTBlockTypes.PISTON_HEAD, new Metadata(34, 0, "PISTON_HEAD", "PISTON_HEAD",
BlockTypes.PISTON_HEAD.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_WOOL, new Metadata(35, 0, "WHITE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_WOOL, new Metadata(35, 1, "ORANGE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_WOOL, new Metadata(35, 2, "MAGENTA_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_WOOL, new Metadata(35, 3, "LIGHT_BLUE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_WOOL, new Metadata(35, 4, "YELLOW_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_WOOL, new Metadata(35, 5, "LIME_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_WOOL, new Metadata(35, 6, "PINK_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_WOOL, new Metadata(35, 7, "GRAY_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_WOOL, new Metadata(35, 8, "LIGHT_GRAY_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_WOOL, new Metadata(35, 9, "CYAN_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_WOOL, new Metadata(35, 10, "PURPLE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_WOOL, new Metadata(35, 11, "BLUE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_WOOL, new Metadata(35, 12, "BROWN_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_WOOL, new Metadata(35, 13, "GREEN_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_WOOL, new Metadata(35, 14, "RED_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_WOOL, new Metadata(35, 15, "BLACK_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.DANDELION, new Metadata(37, 0, "DANDELION", "YELLOW_FLOWER",
BlockTypes.YELLOW_FLOWER.getDefaultState()));
blocks.put(KCTBlockTypes.POPPY, new Metadata(38, 0, "POPPY", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState()));
blocks.put(KCTBlockTypes.BLUE_ORCHID, new Metadata(38, 1, "BLUE_ORCHID", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.BLUE_ORCHID).get()));
blocks.put(KCTBlockTypes.ALLIUM, new Metadata(38, 2, "ALLIUM", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.ALLIUM).get()));
blocks.put(KCTBlockTypes.AZURE_BLUET, new Metadata(38, 3, "AZURE_BLUET", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.POPPY).get()));
blocks.put(KCTBlockTypes.RED_TULIP, new Metadata(38, 4, "RED_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.RED_TULIP).get()));
blocks.put(KCTBlockTypes.ORANGE_TULIP, new Metadata(38, 5, "ORANGE_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.ORANGE_TULIP).get()));
blocks.put(KCTBlockTypes.WHITE_TULIP, new Metadata(38, 6, "WHITE_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.WHITE_TULIP).get()));
blocks.put(KCTBlockTypes.PINK_TULIP, new Metadata(38, 7, "PINK_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.PINK_TULIP).get()));
blocks.put(KCTBlockTypes.OXEYE_DAISY, new Metadata(38, 8, "OXEYE_DAISY", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.OXEYE_DAISY).get()));
blocks.put(KCTBlockTypes.BROWN_MUSHROOM, new Metadata(39, 0, "BROWN_MUSHROOM", "BROWN_MUSHROOM",
BlockTypes.BROWN_MUSHROOM.getDefaultState()));
blocks.put(KCTBlockTypes.RED_MUSHROOM, new Metadata(40, 0, "RED_MUSHROOM", "RED_MUSHROOM",
BlockTypes.RED_MUSHROOM.getDefaultState()));
blocks.put(KCTBlockTypes.GOLD_BLOCK, new Metadata(41, 0, "GOLD_BLOCK", "GOLD_BLOCK",
BlockTypes.GOLD_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_BLOCK, new Metadata(42, 0, "IRON_BLOCK", "IRON_BLOCK",
BlockTypes.IRON_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_STONE_SLAB, new Metadata(43, 0, "DOUBLE_STONE_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_SANDSTONE_SLAB, new Metadata(43, 1, "DOUBLE_SANDSTONE_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SAND).get()));
blocks.put(KCTBlockTypes.DOUBLE_WOODEN_SLAB, new Metadata(43, 2, "DOUBLE_WOODEN_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.WOOD).get()));
blocks.put(KCTBlockTypes.DOUBLE_COBBLESTONE_SLAB, new Metadata(43, 3, "DOUBLE_COBBLESTONE_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.COBBLESTONE).get()));
blocks.put(KCTBlockTypes.DOUBLE_BRICK_SLAB, new Metadata(43, 4, "DOUBLE_BRICK_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.BRICK).get()));
blocks.put(KCTBlockTypes.DOUBLE_STONE_BRICK_SLAB, new Metadata(43, 5, "DOUBLE_STONE_BRICK_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SMOOTH_BRICK).get()));
blocks.put(KCTBlockTypes.DOUBLE_NETHER_BRICK_SLAB, new Metadata(43, 6, "DOUBLE_NETHER_BRICK_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.NETHERBRICK).get()));
blocks.put(KCTBlockTypes.DOUBLE_QUARTZ_SLAB, new Metadata(43, 7, "DOUBLE_QUARTZ_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.QUARTZ).get()));
blocks.put(KCTBlockTypes.STONE_SLAB, new Metadata(44, 0, "STONE_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.SANDSTONE_SLAB, new Metadata(44, 1, "SANDSTONE_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SAND).get()));
blocks.put(KCTBlockTypes.WOODEN_SLAB, new Metadata(44, 2, "WOODEN_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.WOOD).get()));
blocks.put(KCTBlockTypes.COBBLESTONE_SLAB, new Metadata(44, 3, "COBBLESTONE_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.STONE).get()));
blocks.put(KCTBlockTypes.BRICK_SLAB, new Metadata(44, 4, "BRICK_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.BRICK).get()));
blocks.put(KCTBlockTypes.STONE_BRICK_SLAB, new Metadata(44, 5, "STONE_BRICK_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SMOOTH_BRICK).get()));
blocks.put(KCTBlockTypes.NETHER_BRICK_SLAB, new Metadata(44, 6, "NETHER_BRICK_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.STONE).get()));
blocks.put(KCTBlockTypes.QUARTZ_SLAB, new Metadata(44, 7, "QUARTZ_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.QUARTZ).get()));
blocks.put(KCTBlockTypes.BRICKS, new Metadata(45, 0, "BRICKS", "BRICK_BLOCK",
BlockTypes.BRICK_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.TNT, new Metadata(46, 0, "TNT", "TNT",
BlockTypes.TNT.getDefaultState()));
blocks.put(KCTBlockTypes.BOOKSHELF, new Metadata(47, 0, "BOOKSHELF", "BOOKSHELF",
BlockTypes.BOOKSHELF.getDefaultState()));
blocks.put(KCTBlockTypes.MOSS_STONE, new Metadata(48, 0, "MOSS_STONE", "MOSSY_COBBLESTONE",
BlockTypes.MOSSY_COBBLESTONE.getDefaultState()));
blocks.put(KCTBlockTypes.OBSIDIAN, new Metadata(49, 0, "OBSIDIAN", "OBSIDIAN",
BlockTypes.OBSIDIAN.getDefaultState()));
blocks.put(KCTBlockTypes.TORCH, new Metadata(50, 0, "TORCH", "TORCH",
BlockTypes.TORCH.getDefaultState()));
blocks.put(KCTBlockTypes.FIRE, new Metadata(51, 0, "FIRE", "FIRE",
BlockTypes.FIRE.getDefaultState()));
blocks.put(KCTBlockTypes.MONSTER_SPAWNER, new Metadata(52, 0, "MONSTER_SPAWNER", "MOB_SPAWNER",
BlockTypes.MOB_SPAWNER.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_WOOD_STAIRS, new Metadata(53, 0, "OAK_WOOD_STAIRS", "OAK_STAIRS",
BlockTypes.OAK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.CHEST, new Metadata(54, 0, "CHEST", "CHEST",
BlockTypes.CHEST.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_WIRE, new Metadata(55, 0, "REDSTONE_WIRE", "REDSTONE_WIRE",
BlockTypes.REDSTONE_WIRE.getDefaultState()));
blocks.put(KCTBlockTypes.DIAMOND_ORE, new Metadata(56, 0, "DIAMOND_ORE", "DIAMOND_ORE",
BlockTypes.DIAMOND_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.DIAMOND_BLOCK, new Metadata(57, 0, "DIAMOND_BLOCK", "DIAMOND_BLOCK",
BlockTypes.DIAMOND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.CRAFTING_TABLE, new Metadata(58, 0, "CRAFTING_TABLE", "CRAFTING_TABLE",
BlockTypes.CRAFTING_TABLE.getDefaultState()));
blocks.put(KCTBlockTypes.WHEAT_CROPS, new Metadata(59, 0, "WHEAT_CROPS", "WHEAT",
BlockTypes.WHEAT.getDefaultState()));
blocks.put(KCTBlockTypes.FARMLAND, new Metadata(60, 0, "FARMLAND", "FARMLAND",
BlockTypes.FARMLAND.getDefaultState()));
blocks.put(KCTBlockTypes.FURNACE, new Metadata(61, 0, "FURNACE", "FURNACE",
BlockTypes.FURNACE.getDefaultState()));
blocks.put(KCTBlockTypes.BURNING_FURNACE, new Metadata(62, 0, "BURNING_FURNACE", "LIT_FURNACE",
BlockTypes.LIT_FURNACE.getDefaultState()));
blocks.put(KCTBlockTypes.STANDING_SIGN_BLOCK, new Metadata(63, 0, "STANDING_SIGN_BLOCK", "STANDING_SIGN",
BlockTypes.STANDING_SIGN.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_DOOR_BLOCK, new Metadata(64, 0, "OAK_DOOR_BLOCK", "WOODEN_DOOR",
BlockTypes.WOODEN_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.LADDER, new Metadata(65, 0, "LADDER", "LADDER",
BlockTypes.LADDER.getDefaultState()));
blocks.put(KCTBlockTypes.RAIL, new Metadata(66, 0, "RAIL", "RAIL",
BlockTypes.RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.COBBLESTONE_STAIRS, new Metadata(67, 0, "COBBLESTONE_STAIRS", "STONE_STAIRS",
BlockTypes.STONE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.WALL_MOUNTED_SIGN_BLOCK, new Metadata(68, 0, "WALL_MOUNTED_SIGN_BLOCK", "WALL_SIGN",
BlockTypes.WALL_SIGN.getDefaultState()));
blocks.put(KCTBlockTypes.LEVER, new Metadata(69, 0, "LEVER", "LEVER",
BlockTypes.LEVER.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_PRESSURE_PLATE, new Metadata(70, 0, "STONE_PRESSURE_PLATE", "STONE_PRESSURE_PLATE",
BlockTypes.STONE_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_DOOR_BLOCK, new Metadata(71, 0, "IRON_DOOR_BLOCK", "IRON_DOOR",
BlockTypes.IRON_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.WOODEN_PRESSURE_PLATE, new Metadata(72, 0, "WOODEN_PRESSURE_PLATE", "WOODEN_PRESSURE_PLATE",
BlockTypes.WOODEN_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_ORE, new Metadata(73, 0, "REDSTONE_ORE", "REDSTONE_ORE",
BlockTypes.REDSTONE_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.GLOWING_REDSTONE_ORE, new Metadata(74, 0, "GLOWING_REDSTONE_ORE", "LIT_REDSTONE_ORE",
BlockTypes.LIT_REDSTONE_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_TORCH_OFF, new Metadata(75, 0, "REDSTONE_TORCH_OFF", "UNLIT_REDSTONE_TORCH",
BlockTypes.UNLIT_REDSTONE_TORCH.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_TORCH_ON, new Metadata(76, 0, "REDSTONE_TORCH_ON", "REDSTONE_TORCH",
BlockTypes.REDSTONE_TORCH.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_BUTTON, new Metadata(77, 0, "STONE_BUTTON", "STONE_BUTTON",
BlockTypes.STONE_BUTTON.getDefaultState()));
blocks.put(KCTBlockTypes.SNOW, new Metadata(78, 0, "SNOW", "SNOW_LAYER",
BlockTypes.SNOW_LAYER.getDefaultState()));
blocks.put(KCTBlockTypes.ICE, new Metadata(79, 0, "ICE", "ICE",
BlockTypes.ICE.getDefaultState()));
blocks.put(KCTBlockTypes.SNOW_BLOCK, new Metadata(80, 0, "SNOW_BLOCK", "SNOW",
BlockTypes.SNOW.getDefaultState()));
blocks.put(KCTBlockTypes.CACTUS, new Metadata(81, 0, "CACTUS", "CACTUS",
BlockTypes.CACTUS.getDefaultState()));
blocks.put(KCTBlockTypes.CLAY, new Metadata(82, 0, "CLAY", "CLAY",
BlockTypes.CLAY.getDefaultState()));
blocks.put(KCTBlockTypes.SUGAR_CANES, new Metadata(83, 0, "SUGAR_CANES", "REEDS",
BlockTypes.REEDS.getDefaultState()));
blocks.put(KCTBlockTypes.JUKEBOX, new Metadata(84, 0, "JUKEBOX", "JUKEBOX",
BlockTypes.JUKEBOX.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_FENCE, new Metadata(85, 0, "OAK_FENCE", "FENCE",
BlockTypes.FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.PUMPKIN, new Metadata(86, 0, "PUMPKIN", "PUMPKIN",
BlockTypes.PUMPKIN.getDefaultState()));
blocks.put(KCTBlockTypes.NETHERRACK, new Metadata(87, 0, "NETHERRACK", "NETHERRACK",
BlockTypes.NETHERRACK.getDefaultState()));
blocks.put(KCTBlockTypes.SOUL_SAND, new Metadata(88, 0, "SOUL_SAND", "SOUL_SAND",
BlockTypes.SOUL_SAND.getDefaultState()));
blocks.put(KCTBlockTypes.GLOWSTONE, new Metadata(89, 0, "GLOWSTONE", "GLOWSTONE",
BlockTypes.GLOWSTONE.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_PORTAL, new Metadata(90, 0, "NETHER_PORTAL", "PORTAL",
BlockTypes.PORTAL.getDefaultState()));
blocks.put(KCTBlockTypes.JACK_OLANTERN, new Metadata(91, 0, "JACK_OLANTERN", "LIT_PUMPKIN",
BlockTypes.LIT_PUMPKIN.getDefaultState()));
blocks.put(KCTBlockTypes.CAKE_BLOCK, new Metadata(92, 0, "CAKE_BLOCK", "CAKE",
BlockTypes.CAKE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_REPEATER_BLOCK_OFF, new Metadata(93, 0, "REDSTONE_REPEATER_BLOCK_OFF", "UNPOWERED_REPEATER",
BlockTypes.UNPOWERED_REPEATER.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_REPEATER_BLOCK_ON, new Metadata(94, 0, "REDSTONE_REPEATER_BLOCK_ON", "POWERED_REPEATER",
BlockTypes.POWERED_REPEATER.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_STAINED_GLASS, new Metadata(95, 0, "WHITE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_STAINED_GLASS, new Metadata(95, 1, "ORANGE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_STAINED_GLASS, new Metadata(95, 2, "MAGENTA_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_STAINED_GLASS, new Metadata(95, 3, "LIGHT_BLUE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_STAINED_GLASS, new Metadata(95, 4, "YELLOW_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_STAINED_GLASS, new Metadata(95, 5, "LIME_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_STAINED_GLASS, new Metadata(95, 6, "PINK_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_STAINED_GLASS, new Metadata(95, 7, "GRAY_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_STAINED_GLASS, new Metadata(95, 8, "LIGHT_GRAY_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_STAINED_GLASS, new Metadata(95, 9, "CYAN_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_STAINED_GLASS, new Metadata(95, 10, "PURPLE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_STAINED_GLASS, new Metadata(95, 11, "BLUE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_STAINED_GLASS, new Metadata(95, 12, "BROWN_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_STAINED_GLASS, new Metadata(95, 13, "GREEN_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_STAINED_GLASS, new Metadata(95, 14, "RED_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_STAINED_GLASS, new Metadata(95, 15, "BLACK_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.WOODEN_TRAPDOOR, new Metadata(96, 0, "WOODEN_TRAPDOOR", "TRAPDOOR",
BlockTypes.TRAPDOOR.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_MONSTER_EGG, new Metadata(97, 0, "STONE_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState()));
blocks.put(KCTBlockTypes.COBBLESTONE_MONSTER_EGG, new Metadata(97, 1, "COBBLESTONE_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.COBBLESTONE).get()));
blocks.put(KCTBlockTypes.STONE_BRICK_MONSTER_EGG, new Metadata(97, 2, "STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.STONEBRICK).get()));
blocks.put(KCTBlockTypes.MOSSY_STONE_BRICK_MONSTER_EGG, new Metadata(97, 3, "MOSSY_STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.MOSSY_STONEBRICK).get()));
blocks.put(KCTBlockTypes.CRACKED_STONE_BRICK_MONSTER_EGG, new Metadata(97, 4, "CRACKED_STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.CRACKED_STONEBRICK).get()));
blocks.put(KCTBlockTypes.CHISELED_STONE_BRICK_MONSTER_EGG, new Metadata(97, 5, "CHISELED_STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.CHISELED_STONEBRICK).get()));
blocks.put(KCTBlockTypes.STONE_BRICKS, new Metadata(98, 0, "STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState()));
blocks.put(KCTBlockTypes.MOSSY_STONE_BRICKS, new Metadata(98, 1, "MOSSY_STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState().with(Keys.BRICK_TYPE, BrickTypes.MOSSY).get()));
blocks.put(KCTBlockTypes.CRACKED_STONE_BRICKS, new Metadata(98, 2, "CRACKED_STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState().with(Keys.BRICK_TYPE, BrickTypes.CRACKED).get()));
blocks.put(KCTBlockTypes.CHISELED_STONE_BRICKS, new Metadata(98, 3, "CHISELED_STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState().with(Keys.BRICK_TYPE, BrickTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.BROWN_MUSHROOM_BLOCK, new Metadata(99, 0, "BROWN_MUSHROOM_BLOCK", "BROWN_MUSHROOM_BLOCK",
BlockTypes.BROWN_MUSHROOM_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.RED_MUSHROOM_BLOCK, new Metadata(100, 0, "RED_MUSHROOM_BLOCK", "RED_MUSHROOM_BLOCK",
BlockTypes.RED_MUSHROOM_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_BARS, new Metadata(101, 0, "IRON_BARS", "IRON_BARS",
BlockTypes.IRON_BARS.getDefaultState()));
blocks.put(KCTBlockTypes.GLASS_PANE, new Metadata(102, 0, "GLASS_PANE", "GLASS_PANE",
BlockTypes.GLASS_PANE.getDefaultState()));
blocks.put(KCTBlockTypes.MELON_BLOCK, new Metadata(103, 0, "MELON_BLOCK", "MELON_BLOCK",
BlockTypes.MELON_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.PUMPKIN_STEM, new Metadata(104, 0, "PUMPKIN_STEM", "PUMPKIN_STEM",
BlockTypes.PUMPKIN_STEM.getDefaultState()));
blocks.put(KCTBlockTypes.MELON_STEM, new Metadata(105, 0, "MELON_STEM", "MELON_STEM",
BlockTypes.MELON_STEM.getDefaultState()));
blocks.put(KCTBlockTypes.VINES, new Metadata(106, 0, "VINES", "VINE",
BlockTypes.VINE.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_FENCE_GATE, new Metadata(107, 0, "OAK_FENCE_GATE", "FENCE_GATE",
BlockTypes.FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.BRICK_STAIRS, new Metadata(108, 0, "BRICK_STAIRS", "BRICK_STAIRS",
BlockTypes.BRICK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_BRICK_STAIRS, new Metadata(109, 0, "STONE_BRICK_STAIRS", "STONE_BRICK_STAIRS",
BlockTypes.STONE_BRICK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.MYCELIUM, new Metadata(110, 0, "MYCELIUM", "MYCELIUM",
BlockTypes.MYCELIUM.getDefaultState()));
blocks.put(KCTBlockTypes.LILY_PAD, new Metadata(111, 0, "LILY_PAD", "WATERLILY",
BlockTypes.WATERLILY.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_BRICK, new Metadata(112, 0, "NETHER_BRICK", "NETHER_BRICK",
BlockTypes.NETHER_BRICK.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_BRICK_FENCE, new Metadata(113, 0, "NETHER_BRICK_FENCE", "NETHER_BRICK_FENCE",
BlockTypes.NETHER_BRICK_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_BRICK_STAIRS, new Metadata(114, 0, "NETHER_BRICK_STAIRS", "NETHER_BRICK_STAIRS",
BlockTypes.NETHER_BRICK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_WART, new Metadata(115, 0, "NETHER_WART", "NETHER_WART",
BlockTypes.NETHER_WART.getDefaultState()));
/*
blocks.put(KCTBlockTypes.ENCHANTMENT_TABLE, new Metadata(116, 0, "ENCHANTMENT_TABLE", "ENCHANTING_TABLE",
BlockTypes.ENCHANTING_TABLE.getDefaultState()));
blocks.put(KCTBlockTypes.BREWING_STAND, new Metadata(117, 0, "BREWING_STAND", "BREWING_STAND",
BlockTypes.BREWING_STAND.getDefaultState()));
blocks.put(KCTBlockTypes.CAULDRON, new Metadata(118, 0, "CAULDRON", "CAULDRON",
BlockTypes.CAULDRON.getDefaultState()));
blocks.put(KCTBlockTypes.END_PORTAL, new Metadata(119, 0, "END_PORTAL", "END_PORTAL",
BlockTypes.END_PORTAL.getDefaultState()));
blocks.put(KCTBlockTypes.END_PORTAL_FRAME, new Metadata(120, 0, "END_PORTAL_FRAME", "END_PORTAL_FRAME",
BlockTypes.END_PORTAL_FRAME.getDefaultState()));
blocks.put(KCTBlockTypes.END_STONE, new Metadata(121, 0, "END_STONE", "END_STONE",
BlockTypes.END_STONE.getDefaultState()));
blocks.put(KCTBlockTypes.DRAGON_EGG, new Metadata(122, 0, "DRAGON_EGG", "DRAGON_EGG",
BlockTypes.DRAGON_EGG.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_LAMP_INACTIVE, new Metadata(123, 0, "REDSTONE_LAMP_INACTIVE", "REDSTONE_LAMP",
BlockTypes.REDSTONE_LAMP.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_LAMP_ACTIVE, new Metadata(124, 0, "REDSTONE_LAMP_ACTIVE", "LIT_REDSTONE_LAMP",
BlockTypes.LIT_REDSTONE_LAMP.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_OAK_WOOD_SLAB, new Metadata(125, 0, "DOUBLE_OAK_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_SPRUCE_WOOD_SLAB, new Metadata(125, 1, "DOUBLE_SPRUCE_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.DOUBLE_BIRCH_WOOD_SLAB, new Metadata(125, 2, "DOUBLE_BIRCH_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.DOUBLE_JUNGLE_WOOD_SLAB, new Metadata(125, 3, "DOUBLE_JUNGLE_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.DOUBLE_ACACIA_WOOD_SLAB, new Metadata(125, 4, "DOUBLE_ACACIA_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DOUBLE_DARK_OAK_WOOD_SLAB, new Metadata(125, 5, "DOUBLE_DARK_OAK_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.OAK).get()));
blocks.put(KCTBlockTypes.OAK_WOOD_SLAB, new Metadata(126, 0, "OAK_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD_SLAB, new Metadata(126, 1, "SPRUCE_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_WOOD_SLAB, new Metadata(126, 2, "BIRCH_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD_SLAB, new Metadata(126, 3, "JUNGLE_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD_SLAB, new Metadata(126, 4, "ACACIA_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD_SLAB, new Metadata(126, 5, "DARK_OAK_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.COCOA, new Metadata(127, 0, "COCOA", "COCOA",
BlockTypes.COCOA.getDefaultState()));
blocks.put(KCTBlockTypes.SANDSTONE_STAIRS, new Metadata(128, 0, "SANDSTONE_STAIRS", "SANDSTONE_STAIRS",
BlockTypes.SANDSTONE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.EMERALD_ORE, new Metadata(129, 0, "EMERALD_ORE", "EMERALD_ORE",
BlockTypes.EMERALD_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.ENDER_CHEST, new Metadata(130, 0, "ENDER_CHEST", "ENDER_CHEST",
BlockTypes.ENDER_CHEST.getDefaultState()));
blocks.put(KCTBlockTypes.TRIPWIRE_HOOK, new Metadata(131, 0, "TRIPWIRE_HOOK", "TRIPWIRE_HOOK",
BlockTypes.TRIPWIRE_HOOK.getDefaultState()));
blocks.put(KCTBlockTypes.TRIPWIRE, new Metadata(132, 0, "TRIPWIRE", "TRIPWIRE_HOOK",
BlockTypes.TRIPWIRE_HOOK.getDefaultState()));
blocks.put(KCTBlockTypes.EMERALD_BLOCK, new Metadata(133, 0, "EMERALD_BLOCK", "EMERALD_BLOCK",
BlockTypes.EMERALD_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD_STAIRS, new Metadata(134, 0, "SPRUCE_WOOD_STAIRS", "SPRUCE_STAIRS",
BlockTypes.SPRUCE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_WOOD_STAIRS, new Metadata(135, 0, "BIRCH_WOOD_STAIRS", "BIRCH_STAIRS",
BlockTypes.BIRCH_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD_STAIRS, new Metadata(136, 0, "JUNGLE_WOOD_STAIRS", "JUNGLE_STAIRS",
BlockTypes.JUNGLE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.COMMAND_BLOCK, new Metadata(137, 0, "COMMAND_BLOCK", "COMMAND_BLOCK",
BlockTypes.COMMAND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.BEACON, new Metadata(138, 0, "BEACON", "BEACON",
BlockTypes.BEACON.getDefaultState()));
blocks.put(KCTBlockTypes.COBBLESTONE_WALL, new Metadata(139, 0, "COBBLESTONE_WALL", "COBBLESTONE_WALL",
BlockTypes.COBBLESTONE_WALL.getDefaultState()));
blocks.put(KCTBlockTypes.MOSSY_COBBLESTONE_WALL, new Metadata(139, 1, "MOSSY_COBBLESTONE_WALL", "COBBLESTONE_WALL",
BlockTypes.COBBLESTONE_WALL.getDefaultState().with(Keys.WALL_TYPE, WallTypes.MOSSY).get()));
blocks.put(KCTBlockTypes.FLOWER_POT, new Metadata(140, 0, "FLOWER_POT", "FLOWER_POT",
BlockTypes.FLOWER_POT.getDefaultState()));
blocks.put(KCTBlockTypes.CARROTS, new Metadata(141, 0, "CARROTS", "CARROTS",
BlockTypes.CARROTS.getDefaultState()));
blocks.put(KCTBlockTypes.POTATOES, new Metadata(142, 0, "POTATOES", "POTATOES",
BlockTypes.POTATOES.getDefaultState()));
blocks.put(KCTBlockTypes.WOODEN_BUTTON, new Metadata(143, 0, "WOODEN_BUTTON", "WOODEN_BUTTON",
BlockTypes.WOODEN_BUTTON.getDefaultState()));
blocks.put(KCTBlockTypes.MOB_HEAD, new Metadata(144, 0, "MOB_HEAD", "SKULL",
BlockTypes.SKULL.getDefaultState()));
blocks.put(KCTBlockTypes.ANVIL, new Metadata(145, 0, "ANVIL", "ANVIL",
BlockTypes.ANVIL.getDefaultState()));
blocks.put(KCTBlockTypes.TRAPPED_CHEST, new Metadata(146, 0, "TRAPPED_CHEST", "TRAPPED_CHEST",
BlockTypes.TRAPPED_CHEST.getDefaultState()));
blocks.put(KCTBlockTypes.WEIGHTED_PRESSURE_PLATE_LIGHT, new Metadata(147, 0, "WEIGHTED_PRESSURE_PLATE_LIGHT", "LIGHT_WEIGHTED_PRESSURE_PLATE",
BlockTypes.LIGHT_WEIGHTED_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.WEIGHTED_PRESSURE_PLATE_HEAVY, new Metadata(148, 0, "WEIGHTED_PRESSURE_PLATE_HEAVY", "HEAVY_WEIGHTED_PRESSURE_PLATE",
BlockTypes.HEAVY_WEIGHTED_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_COMPARATOR_INACTIVE, new Metadata(149, 0, "REDSTONE_COMPARATOR_INACTIVE", "UNPOWERED_COMPARATOR",
BlockTypes.UNPOWERED_COMPARATOR.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_COMPARATOR_ACTIVE, new Metadata(150, 0, "REDSTONE_COMPARATOR_ACTIVE", "POWERED_COMPARATOR",
BlockTypes.POWERED_COMPARATOR.getDefaultState()));
blocks.put(KCTBlockTypes.DAYLIGHT_SENSOR, new Metadata(151, 0, "DAYLIGHT_SENSOR", "DAYLIGHT_DETECTOR",
BlockTypes.DAYLIGHT_DETECTOR.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_BLOCK, new Metadata(152, 0, "REDSTONE_BLOCK", "REDSTONE_BLOCK",
BlockTypes.REDSTONE_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_QUARTZ_ORE, new Metadata(153, 0, "NETHER_QUARTZ_ORE", "QUARTZ_ORE",
BlockTypes.QUARTZ_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.HOPPER, new Metadata(154, 0, "HOPPER", "HOPPER",
BlockTypes.HOPPER.getDefaultState()));
blocks.put(KCTBlockTypes.QUARTZ_BLOCK, new Metadata(155, 0, "QUARTZ_BLOCK", "QUARTZ_BLOCK",
BlockTypes.QUARTZ_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.CHISELED_QUARTZ_BLOCK, new Metadata(155, 1, "CHISELED_QUARTZ_BLOCK", "QUARTZ_BLOCK",
BlockTypes.QUARTZ_BLOCK.getDefaultState().with(Keys.QUARTZ_TYPE, QuartzTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.PILLAR_QUARTZ_BLOCK, new Metadata(155, 2, "PILLAR_QUARTZ_BLOCK", "QUARTZ_BLOCK",
BlockTypes.QUARTZ_BLOCK.getDefaultState().with(Keys.QUARTZ_TYPE, QuartzTypes.LINES_Y).get()));
blocks.put(KCTBlockTypes.QUARTZ_STAIRS, new Metadata(156, 0, "QUARTZ_STAIRS", "QUARTZ_STAIRS",
BlockTypes.QUARTZ_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.ACTIVATOR_RAIL, new Metadata(157, 0, "ACTIVATOR_RAIL", "ACTIVATOR_RAIL",
BlockTypes.ACTIVATOR_RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.DROPPER, new Metadata(158, 0, "DROPPER", "DROPPER",
BlockTypes.DROPPER.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_STAINED_CLAY, new Metadata(159, 0, "WHITE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_STAINED_CLAY, new Metadata(159, 1, "ORANGE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_STAINED_CLAY, new Metadata(159, 2, "MAGENTA_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_STAINED_CLAY, new Metadata(159, 3, "LIGHT_BLUE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_STAINED_CLAY, new Metadata(159, 4, "YELLOW_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_STAINED_CLAY, new Metadata(159, 5, "LIME_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_STAINED_CLAY, new Metadata(159, 6, "PINK_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_STAINED_CLAY, new Metadata(159, 7, "GRAY_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_STAINED_CLAY, new Metadata(159, 8, "LIGHT_GRAY_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_STAINED_CLAY, new Metadata(159, 9, "CYAN_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_STAINED_CLAY, new Metadata(159, 10, "PURPLE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_STAINED_CLAY, new Metadata(159, 11, "BLUE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_STAINED_CLAY, new Metadata(159, 12, "BROWN_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_STAINED_CLAY, new Metadata(159, 13, "GREEN_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_STAINED_CLAY, new Metadata(159, 14, "RED_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_STAINED_CLAY, new Metadata(159, 15, "BLACK_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.WHITE_STAINED_GLASS_PANE, new Metadata(160, 0, "WHITE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_STAINED_GLASS_PANE, new Metadata(160, 1, "ORANGE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_STAINED_GLASS_PANE, new Metadata(160, 2, "MAGENTA_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_STAINED_GLASS_PANE, new Metadata(160, 3, "LIGHT_BLUE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_STAINED_GLASS_PANE, new Metadata(160, 4, "YELLOW_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_STAINED_GLASS_PANE, new Metadata(160, 5, "LIME_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_STAINED_GLASS_PANE, new Metadata(160, 6, "PINK_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_STAINED_GLASS_PANE, new Metadata(160, 7, "GRAY_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_STAINED_GLASS_PANE, new Metadata(160, 8, "LIGHT_GRAY_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_STAINED_GLASS_PANE, new Metadata(160, 9, "CYAN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_STAINED_GLASS_PANE, new Metadata(160, 10, "PURPLE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_STAINED_GLASS_PANE, new Metadata(160, 11, "BLUE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_STAINED_GLASS_PANE, new Metadata(160, 12, "BROWN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_STAINED_GLASS_PANE, new Metadata(160, 13, "GREEN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_STAINED_GLASS_PANE, new Metadata(160, 14, "RED_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_STAINED_GLASS_PANE, new Metadata(160, 15, "BLACK_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.ACACIA_LEAVES, new Metadata(161, 0, "ACACIA_LEAVES", "LEAVES2",
BlockTypes.LEAVES2.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_LEAVES, new Metadata(161, 1, "DARK_OAK_LEAVES", "LEAVES2",
BlockTypes.LEAVES2.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD, new Metadata(162, 0, "ACACIA_WOOD", "LOG2",
BlockTypes.LOG2.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD, new Metadata(162, 1, "DARK_OAK_WOOD", "LOG2",
BlockTypes.LOG2.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD_STAIRS, new Metadata(163, 0, "ACACIA_WOOD_STAIRS", "ACACIA_STAIRS",
BlockTypes.ACACIA_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD_STAIRS, new Metadata(164, 0, "DARK_OAK_WOOD_STAIRS", "DARK_OAK_STAIRS",
BlockTypes.DARK_OAK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.SLIME_BLOCK, new Metadata(165, 0, "SLIME_BLOCK", "SLIME",
BlockTypes.SLIME.getDefaultState()));
blocks.put(KCTBlockTypes.BARRIER, new Metadata(166, 0, "BARRIER", "BARRIER",
BlockTypes.BARRIER.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_TRAPDOOR, new Metadata(167, 0, "IRON_TRAPDOOR", "IRON_TRAPDOOR",
BlockTypes.IRON_TRAPDOOR.getDefaultState()));
blocks.put(KCTBlockTypes.PRISMARINE, new Metadata(168, 0, "PRISMARINE", "PRISMARINE",
BlockTypes.PRISMARINE.getDefaultState()));
blocks.put(KCTBlockTypes.PRISMARINE_BRICKS, new Metadata(168, 1, "PRISMARINE_BRICKS", "PRISMARINE",
BlockTypes.PRISMARINE.getDefaultState().with(Keys.PRISMARINE_TYPE, PrismarineTypes.BRICKS).get()));
*/
/*
blocks.put(KCTBlockTypes.DARK_PRISMARINE, new Metadata(168, 2, "DARK_PRISMARINE", "PRISMARINE",
BlockTypes.PRISMARINE.getDefaultState().with(Keys.PRISMARINE_TYPE, PrismarineTypes.DARK).get()));
blocks.put(KCTBlockTypes.SEA_LANTERN, new Metadata(169, 0, "SEA_LANTERN", "SEA_LANTERN",
BlockTypes.SEA_LANTERN.getDefaultState()));
blocks.put(KCTBlockTypes.HAY_BALE, new Metadata(170, 0, "HAY_BALE", "HAY_BLOCK",
BlockTypes.HAY_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_CARPET, new Metadata(171, 0, "WHITE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_CARPET, new Metadata(171, 1, "ORANGE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_CARPET, new Metadata(171, 2, "MAGENTA_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_CARPET, new Metadata(171, 3, "LIGHT_BLUE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_CARPET, new Metadata(171, 4, "YELLOW_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_CARPET, new Metadata(171, 5, "LIME_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_CARPET, new Metadata(171, 6, "PINK_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_CARPET, new Metadata(171, 7, "GRAY_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_CARPET, new Metadata(171, 8, "LIGHT_GRAY_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_CARPET, new Metadata(171, 9, "CYAN_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_CARPET, new Metadata(171, 10, "PURPLE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_CARPET, new Metadata(171, 11, "BLUE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_CARPET, new Metadata(171, 12, "BROWN_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_CARPET, new Metadata(171, 13, "GREEN_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_CARPET, new Metadata(171, 14, "RED_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_CARPET, new Metadata(171, 15, "BLACK_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.HARDENED_CLAY, new Metadata(172, 0, "HARDENED_CLAY", "HARDENED_CLAY",
BlockTypes.HARDENED_CLAY.getDefaultState()));
blocks.put(KCTBlockTypes.BLOCK_OF_COAL, new Metadata(173, 0, "BLOCK_OF_COAL", "COAL_BLOCK",
BlockTypes.COAL_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.PACKED_ICE, new Metadata(174, 0, "PACKED_ICE", "PACKED_ICE",
BlockTypes.PACKED_ICE.getDefaultState()));
blocks.put(KCTBlockTypes.SUNFLOWER, new Metadata(175, 0, "SUNFLOWER", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState()));
blocks.put(KCTBlockTypes.LILAC, new Metadata(175, 1, "LILAC", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.SYRINGA).get()));
blocks.put(KCTBlockTypes.DOUBLE_TALLGRASS, new Metadata(175, 2, "DOUBLE_TALLGRASS", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.GRASS).get()));
blocks.put(KCTBlockTypes.LARGE_FERN, new Metadata(175, 3, "LARGE_FERN", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.FERN).get()));
blocks.put(KCTBlockTypes.ROSE_BUSH, new Metadata(175, 4, "ROSE_BUSH", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.ROSE).get()));
blocks.put(KCTBlockTypes.PEONY, new Metadata(175, 5, "PEONY", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.PAEONIA).get()));
blocks.put(KCTBlockTypes.FREE_STANDING_BANNER, new Metadata(176, 0, "FREE_STANDING_BANNER", "STANDING_BANNER",
BlockTypes.STANDING_BANNER.getDefaultState()));
blocks.put(KCTBlockTypes.WALL_MOUNTED_BANNER, new Metadata(177, 0, "WALL_MOUNTED_BANNER", "WALL_BANNER",
BlockTypes.WALL_BANNER.getDefaultState()));
blocks.put(KCTBlockTypes.INVERTED_DAYLIGHT_SENSOR, new Metadata(178, 0, "INVERTED_DAYLIGHT_SENSOR", "DAYLIGHT_DETECTOR_INVERTED",
BlockTypes.DAYLIGHT_DETECTOR_INVERTED.getDefaultState()));
blocks.put(KCTBlockTypes.RED_SANDSTONE, new Metadata(179, 0, "RED_SANDSTONE", "RED_SANDSTONE",
BlockTypes.RED_SANDSTONE.getDefaultState()));
blocks.put(KCTBlockTypes.CHISELED_RED_SANDSTONE, new Metadata(179, 1, "CHISELED_RED_SANDSTONE", "RED_SANDSTONE",
BlockTypes.RED_SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.SMOOTH_RED_SANDSTONE, new Metadata(179, 2, "SMOOTH_RED_SANDSTONE", "RED_SANDSTONE",
BlockTypes.RED_SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.SMOOTH).get()));
blocks.put(KCTBlockTypes.RED_SANDSTONE_STAIRS, new Metadata(180, 0, "RED_SANDSTONE_STAIRS", "RED_SANDSTONE_STAIRS",
BlockTypes.RED_SANDSTONE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_RED_SANDSTONE_SLAB, new Metadata(181, 0, "DOUBLE_RED_SANDSTONE_SLAB", "DOUBLE_STONE_SLAB2",
BlockTypes.DOUBLE_STONE_SLAB2.getDefaultState()));
blocks.put(KCTBlockTypes.RED_SANDSTONE_SLAB, new Metadata(182, 0, "RED_SANDSTONE_SLAB", "STONE_SLAB2",
BlockTypes.STONE_SLAB2.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_FENCE_GATE, new Metadata(183, 0, "SPRUCE_FENCE_GATE", "SPRUCE_FENCE_GATE",
BlockTypes.SPRUCE_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_FENCE_GATE, new Metadata(184, 0, "BIRCH_FENCE_GATE", "BIRCH_FENCE_GATE",
BlockTypes.BIRCH_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_FENCE_GATE, new Metadata(185, 0, "JUNGLE_FENCE_GATE", "JUNGLE_FENCE_GATE",
BlockTypes.JUNGLE_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_FENCE_GATE, new Metadata(186, 0, "DARK_OAK_FENCE_GATE", "DARK_OAK_FENCE_GATE",
BlockTypes.DARK_OAK_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.ACACIA_FENCE_GATE, new Metadata(187, 0, "ACACIA_FENCE_GATE", "ACACIA_FENCE_GATE",
BlockTypes.ACACIA_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_FENCE, new Metadata(188, 0, "SPRUCE_FENCE", "SPRUCE_FENCE",
BlockTypes.SPRUCE_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_FENCE, new Metadata(189, 0, "BIRCH_FENCE", "BIRCH_FENCE",
BlockTypes.BIRCH_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_FENCE, new Metadata(190, 0, "JUNGLE_FENCE", "JUNGLE_FENCE",
BlockTypes.JUNGLE_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_FENCE, new Metadata(191, 0, "DARK_OAK_FENCE", "DARK_OAK_FENCE",
BlockTypes.DARK_OAK_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.ACACIA_FENCE, new Metadata(192, 0, "ACACIA_FENCE", "ACACIA_FENCE",
BlockTypes.ACACIA_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_DOOR_BLOCK, new Metadata(193, 0, "SPRUCE_DOOR_BLOCK", "SPRUCE_DOOR",
BlockTypes.SPRUCE_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_DOOR_BLOCK, new Metadata(194, 0, "BIRCH_DOOR_BLOCK", "BIRCH_DOOR",
BlockTypes.BIRCH_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_DOOR_BLOCK, new Metadata(195, 0, "JUNGLE_DOOR_BLOCK", "JUNGLE_DOOR",
BlockTypes.JUNGLE_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.ACACIA_DOOR_BLOCK, new Metadata(196, 0, "ACACIA_DOOR_BLOCK", "ACACIA_DOOR",
BlockTypes.ACACIA_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_DOOR_BLOCK, new Metadata(197, 0, "DARK_OAK_DOOR_BLOCK", "DARK_OAK_DOOR",
BlockTypes.DARK_OAK_DOOR.getDefaultState()));
*/
/* Minecraft Blocks added after Version 1.9
blocks.put(KCTBlockTypes.END_ROD, new Metadata(198, 0, "END_ROD", "END_ROD",
BlockTypes.END_ROD.getDefaultState()));
blocks.put(KCTBlockTypes.CHORUS_PLANT, new Metadata(199, 0, "CHORUS_PLANT", "CHORUS_PLANT",
BlockTypes.CHORUS_PLANT.getDefaultState()));
blocks.put(KCTBlockTypes.CHORUS_FLOWER, new Metadata(200, 0, "CHORUS_FLOWER", "CHORUS_FLOWER",
BlockTypes.CHORUS_FLOWER.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_BLOCK, new Metadata(201, 0, "PURPUR_BLOCK", "PURPUR_BLOCK",
BlockTypes.PURPUR_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_PILLAR, new Metadata(202, 0, "PURPUR_PILLAR", "PURPUR_PILLAR",
BlockTypes.PURPUR_PILLAR.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_STAIRS, new Metadata(203, 0, "PURPUR_STAIRS", "PURPUR_STAIRS",
BlockTypes.PURPUR_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_DOUBLE_SLAB, new Metadata(204, 0, "PURPUR_DOUBLE_SLAB", "PURPUR_DOUBLE_SLAB",
BlockTypes.PURPUR_DOUBLE_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_SLAB, new Metadata(205, 0, "PURPUR_SLAB", "PURPUR_SLAB",
BlockTypes.PURPUR_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.END_STONE_BRICKS, new Metadata(206, 0, "END_STONE_BRICKS", "END_BRICKS",
BlockTypes.END_BRICKS.getDefaultState()));
blocks.put(KCTBlockTypes.BEETROOT_BLOCK, new Metadata(207, 0, "BEETROOT_BLOCK", "BEETROOTS",
BlockTypes.BEETROOTS.getDefaultState()));
blocks.put(KCTBlockTypes.GRASS_PATH, new Metadata(208, 0, "GRASS_PATH", "GRASS_PATH",
BlockTypes.GRASS_PATH.getDefaultState()));
blocks.put(KCTBlockTypes.END_GATEWAY, new Metadata(209, 0, "END_GATEWAY", "END_GATEWAY",
BlockTypes.END_GATEWAY.getDefaultState()));
blocks.put(KCTBlockTypes.REPEATING_COMMAND_BLOCK, new Metadata(210, 0, "REPEATING_COMMAND_BLOCK", "REPEATING_COMMAND_BLOCK",
BlockTypes.REPEATING_COMMAND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.CHAIN_COMMAND_BLOCK, new Metadata(211, 0, "CHAIN_COMMAND_BLOCK", "CHAIN_COMMAND_BLOCK",
BlockTypes.CHAIN_COMMAND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.FROSTED_ICE, new Metadata(212, 0, "FROSTED_ICE", "FROSTED_ICE",
BlockTypes.FROSTED_ICE.getDefaultState()));
blocks.put(KCTBlockTypes.STRUCTURE_BLOCK, new Metadata(255, 0, "STRUCTURE_BLOCK", "STRUCTURE_BLOCK",
BlockTypes.STRUCTURE_BLOCK.getDefaultState())); */
}
}
| TurtleSponge/src/main/java/org/knoxcraft/turtle3d/KCTBlockTypesBuilder.java | package org.knoxcraft.turtle3d;
import java.util.HashMap;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.type.BrickTypes;
import org.spongepowered.api.data.type.DirtTypes;
import org.spongepowered.api.data.type.DisguisedBlockTypes;
import org.spongepowered.api.data.type.DoublePlantTypes;
import org.spongepowered.api.data.type.DyeColors;
import org.spongepowered.api.data.type.PlantTypes;
import org.spongepowered.api.data.type.SandTypes;
import org.spongepowered.api.data.type.SandstoneTypes;
import org.spongepowered.api.data.type.SlabTypes;
import org.spongepowered.api.data.type.StoneTypes;
import org.spongepowered.api.data.type.TreeTypes;
public final class KCTBlockTypesBuilder {
private static class Metadata {
private BlockState block;
private int numID;
private int meta;
private String name;
private String textID;
public Metadata(int numID, int meta, String name, String textID, BlockState block) {
this.numID = numID;
this.meta = meta;
this.name = name;
this.textID = textID;
this.block = block;
}
public int getNumID() {
return numID;
}
public int getMetadata() {
return meta;
}
public String getName() {
return name;
}
public String getTextID() {
return textID;
}
public BlockState getBlock() {
return block;
}
}
private static final HashMap<KCTBlockTypes, Metadata> blocks = new HashMap<KCTBlockTypes, Metadata>();
public static BlockState getBlockState(KCTBlockTypes type) {
initialize();
return blocks.get(type).getBlock();
}
private static boolean isInitialized=false;
private static void initialize() {
if (isInitialized){
return;
}
isInitialized=true;
blocks.put(KCTBlockTypes.AIR, new Metadata(0, 0, "AIR", "AIR",
BlockState.builder().build()));
blocks.put(KCTBlockTypes.STONE, new Metadata(1, 0, "STONE", "STONE",
BlockTypes.STONE.getDefaultState()));
blocks.put(KCTBlockTypes.GRANITE, new Metadata(1, 1, "GRANITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.GRANITE).get()));
blocks.put(KCTBlockTypes.POLISHED_GRANITE, new Metadata(1, 2, "POLISHED_GRANITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.SMOOTH_GRANITE).get()));
blocks.put(KCTBlockTypes.DIORITE, new Metadata(1, 3, "DIORITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.DIORITE).get()));
blocks.put(KCTBlockTypes.POLISHED_DIORITE, new Metadata(1, 4, "POLISHED_DIORITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.SMOOTH_DIORITE).get()));
blocks.put(KCTBlockTypes.ANDESITE, new Metadata(1, 5, "ANDESITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.ANDESITE).get()));
blocks.put(KCTBlockTypes.POLISHED_ANDESITE, new Metadata(1, 6, "POLISHED_ANDESITE", "STONE",
BlockTypes.STONE.getDefaultState().with(Keys.STONE_TYPE, StoneTypes.SMOOTH_ANDESITE).get()));
blocks.put(KCTBlockTypes.GRASS, new Metadata(2, 0, "GRASS", "GRASS",
BlockTypes.GRASS.getDefaultState()));
blocks.put(KCTBlockTypes.DIRT, new Metadata(3, 0, "DIRT", "DIRT",
BlockTypes.DIRT.getDefaultState()));
blocks.put(KCTBlockTypes.COARSE_DIRT, new Metadata(3, 1, "COARSE_DIRT", "DIRT",
BlockTypes.DIRT.getDefaultState().with(Keys.DIRT_TYPE, DirtTypes.COARSE_DIRT).get()));
blocks.put(KCTBlockTypes.PODZOL, new Metadata(3, 2, "PODZOL", "DIRT",
BlockTypes.DIRT.getDefaultState().with(Keys.DIRT_TYPE, DirtTypes.PODZOL).get()));
blocks.put(KCTBlockTypes.COBBLESTONE, new Metadata(4, 0, "COBBLESTONE", "COBBLESTONE",
BlockTypes.COBBLESTONE.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_WOOD_PLANK, new Metadata(5, 0, "OAK_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD_PLANK, new Metadata(5, 1, "SPRUCE_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_WOOD_PLANK, new Metadata(5, 2, "BIRCH_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD_PLANK, new Metadata(5, 3, "JUNGLE_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD_PLANK, new Metadata(5, 4, "ACACIA_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD_PLANK, new Metadata(5, 5, "DARK_OAK_WOOD_PLANK", "PLANKS",
BlockTypes.PLANKS.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.OAK_SAPLING, new Metadata(6, 0, "OAK_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_SAPLING, new Metadata(6, 1, "SPRUCE_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_SAPLING, new Metadata(6, 2, "BIRCH_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_SAPLING, new Metadata(6, 3, "JUNGLE_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.ACACIA_SAPLING, new Metadata(6, 4, "ACACIA_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DARK_OAK_SAPLING, new Metadata(6, 5, "DARK_OAK_SAPLING", "SAPLING",
BlockTypes.SAPLING.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.BEDROCK, new Metadata(7, 0, "BEDROCK", "BEDROCK",
BlockTypes.BEDROCK.getDefaultState()));
blocks.put(KCTBlockTypes.FLOWING_WATER, new Metadata(8, 0, "FLOWING_WATER", "FLOWING_WATER",
BlockTypes.FLOWING_WATER.getDefaultState()));
blocks.put(KCTBlockTypes.STILL_WATER, new Metadata(9, 0, "STILL_WATER", "WATER",
BlockTypes.WATER.getDefaultState()));
blocks.put(KCTBlockTypes.FLOWING_LAVA, new Metadata(10, 0, "FLOWING_LAVA", "FLOWING_LAVA",
BlockTypes.FLOWING_LAVA.getDefaultState()));
blocks.put(KCTBlockTypes.STILL_LAVA, new Metadata(11, 0, "STILL_LAVA", "LAVA",
BlockTypes.LAVA.getDefaultState()));
blocks.put(KCTBlockTypes.SAND, new Metadata(12, 0, "SAND", "SAND",
BlockTypes.SAND.getDefaultState()));
blocks.put(KCTBlockTypes.RED_SAND, new Metadata(12, 1, "RED_SAND", "SAND",
BlockTypes.SAND.getDefaultState().with(Keys.SAND_TYPE, SandTypes.RED).get()));
blocks.put(KCTBlockTypes.GRAVEL, new Metadata(13, 0, "GRAVEL", "GRAVEL",
BlockTypes.GRAVEL.getDefaultState()));
blocks.put(KCTBlockTypes.GOLD_ORE, new Metadata(14, 0, "GOLD_ORE", "GOLD_ORE",
BlockTypes.GOLD_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_ORE, new Metadata(15, 0, "IRON_ORE", "IRON_ORE",
BlockTypes.IRON_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.COAL_ORE, new Metadata(16, 0, "COAL_ORE", "COAL_ORE",
BlockTypes.COAL_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_WOOD, new Metadata(17, 0, "OAK_WOOD", "LOG",
BlockTypes.LOG.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD, new Metadata(17, 1, "SPRUCE_WOOD", "LOG",
BlockTypes.LOG.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_WOOD, new Metadata(17, 2, "BIRCH_WOOD", "LOG",
BlockTypes.LOG.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD, new Metadata(17, 3, "JUNGLE_WOOD", "LOG",
BlockTypes.LOG.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.OAK_LEAVES, new Metadata(18, 0, "OAK_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_LEAVES, new Metadata(18, 1, "SPRUCE_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_LEAVES, new Metadata(18, 2, "BIRCH_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_LEAVES, new Metadata(18, 3, "JUNGLE_LEAVES", "LEAVES",
BlockTypes.LEAVES.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.SPONGE, new Metadata(19, 0, "SPONGE", "SPONGE",
BlockTypes.SPONGE.getDefaultState()));
blocks.put(KCTBlockTypes.WET_SPONGE, new Metadata(19, 1, "WET_SPONGE", "SPONGE",
BlockTypes.SPONGE.getDefaultState().with(Keys.IS_WET, true).get()));
blocks.put(KCTBlockTypes.GLASS, new Metadata(20, 0, "GLASS", "GLASS",
BlockTypes.GLASS.getDefaultState()));
blocks.put(KCTBlockTypes.LAPIS_LAZULI_ORE, new Metadata(21, 0, "LAPIS_LAZULI_ORE", "LAPIS_ORE",
BlockTypes.LAPIS_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.LAPIS_LAZULI_BLOCK, new Metadata(22, 0, "LAPIS_LAZULI_BLOCK", "LAPIS_BLOCK",
BlockTypes.LAPIS_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.DISPENSER, new Metadata(23, 0, "DISPENSER", "DISPENSER",
BlockTypes.DISPENSER.getDefaultState()));
blocks.put(KCTBlockTypes.SANDSTONE, new Metadata(24, 0, "SANDSTONE", "SANDSTONE",
BlockTypes.SANDSTONE.getDefaultState()));
blocks.put(KCTBlockTypes.CHISELED_SANDSTONE, new Metadata(24, 1, "CHISELED_SANDSTONE", "SANDSTONE",
BlockTypes.SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.SMOOTH_SANDSTONE, new Metadata(24, 2, "SMOOTH_SANDSTONE", "SANDSTONE",
BlockTypes.SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.SMOOTH).get()));
blocks.put(KCTBlockTypes.NOTE_BLOCK, new Metadata(25, 0, "NOTE_BLOCK", "NOTEBLOCK",
BlockTypes.NOTEBLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.BED, new Metadata(26, 0, "BED", "BED",
BlockTypes.BED.getDefaultState()));
blocks.put(KCTBlockTypes.POWERED_RAIL, new Metadata(27, 0, "POWERED_RAIL", "GOLDEN_RAIL",
BlockTypes.GOLDEN_RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.DETECTOR_RAIL, new Metadata(28, 0, "DETECTOR_RAIL", "DETECTOR_RAIL",
BlockTypes.DETECTOR_RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.STICKY_PISTON, new Metadata(29, 0, "STICKY_PISTON", "STICKY_PISTON",
BlockTypes.STICKY_PISTON.getDefaultState()));
blocks.put(KCTBlockTypes.COBWEB, new Metadata(30, 0, "COBWEB", "WEB",
BlockTypes.WEB.getDefaultState()));
blocks.put(KCTBlockTypes.DEAD_SHRUB, new Metadata(31, 0, "DEAD_SHRUB", "TALLGRASS",
BlockTypes.TALLGRASS.getDefaultState()));
// FIXME: doesn't exist?
// blocks.put(KCTBlockTypes.GRASS, new Metadata(31, 1, "GRASS", "TALLGRASS",
// BlockTypes.TALLGRASS.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.GRASS).get()));
//
// blocks.put(KCTBlockTypes.FERN, new Metadata(31, 2, "FERN", "TALLGRASS",
// BlockTypes.TALLGRASS.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.FERN).get()));
blocks.put(KCTBlockTypes.DEAD_BUSH, new Metadata(32, 0, "DEAD_BUSH", "DEADBUSH",
BlockTypes.DEADBUSH.getDefaultState()));
blocks.put(KCTBlockTypes.PISTON, new Metadata(33, 0, "PISTON", "PISTON",
BlockTypes.PISTON.getDefaultState()));
blocks.put(KCTBlockTypes.PISTON_HEAD, new Metadata(34, 0, "PISTON_HEAD", "PISTON_HEAD",
BlockTypes.PISTON_HEAD.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_WOOL, new Metadata(35, 0, "WHITE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_WOOL, new Metadata(35, 1, "ORANGE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_WOOL, new Metadata(35, 2, "MAGENTA_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_WOOL, new Metadata(35, 3, "LIGHT_BLUE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_WOOL, new Metadata(35, 4, "YELLOW_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_WOOL, new Metadata(35, 5, "LIME_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_WOOL, new Metadata(35, 6, "PINK_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_WOOL, new Metadata(35, 7, "GRAY_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_WOOL, new Metadata(35, 8, "LIGHT_GRAY_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_WOOL, new Metadata(35, 9, "CYAN_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_WOOL, new Metadata(35, 10, "PURPLE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_WOOL, new Metadata(35, 11, "BLUE_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_WOOL, new Metadata(35, 12, "BROWN_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_WOOL, new Metadata(35, 13, "GREEN_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_WOOL, new Metadata(35, 14, "RED_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_WOOL, new Metadata(35, 15, "BLACK_WOOL", "WOOL",
BlockTypes.WOOL.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.DANDELION, new Metadata(37, 0, "DANDELION", "YELLOW_FLOWER",
BlockTypes.YELLOW_FLOWER.getDefaultState()));
blocks.put(KCTBlockTypes.POPPY, new Metadata(38, 0, "POPPY", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState()));
blocks.put(KCTBlockTypes.BLUE_ORCHID, new Metadata(38, 1, "BLUE_ORCHID", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.BLUE_ORCHID).get()));
blocks.put(KCTBlockTypes.ALLIUM, new Metadata(38, 2, "ALLIUM", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.ALLIUM).get()));
blocks.put(KCTBlockTypes.AZURE_BLUET, new Metadata(38, 3, "AZURE_BLUET", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.POPPY).get()));
blocks.put(KCTBlockTypes.RED_TULIP, new Metadata(38, 4, "RED_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.RED_TULIP).get()));
blocks.put(KCTBlockTypes.ORANGE_TULIP, new Metadata(38, 5, "ORANGE_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.ORANGE_TULIP).get()));
blocks.put(KCTBlockTypes.WHITE_TULIP, new Metadata(38, 6, "WHITE_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.WHITE_TULIP).get()));
blocks.put(KCTBlockTypes.PINK_TULIP, new Metadata(38, 7, "PINK_TULIP", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.PINK_TULIP).get()));
blocks.put(KCTBlockTypes.OXEYE_DAISY, new Metadata(38, 8, "OXEYE_DAISY", "RED_FLOWER",
BlockTypes.RED_FLOWER.getDefaultState().with(Keys.PLANT_TYPE, PlantTypes.OXEYE_DAISY).get()));
blocks.put(KCTBlockTypes.BROWN_MUSHROOM, new Metadata(39, 0, "BROWN_MUSHROOM", "BROWN_MUSHROOM",
BlockTypes.BROWN_MUSHROOM.getDefaultState()));
blocks.put(KCTBlockTypes.RED_MUSHROOM, new Metadata(40, 0, "RED_MUSHROOM", "RED_MUSHROOM",
BlockTypes.RED_MUSHROOM.getDefaultState()));
blocks.put(KCTBlockTypes.GOLD_BLOCK, new Metadata(41, 0, "GOLD_BLOCK", "GOLD_BLOCK",
BlockTypes.GOLD_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_BLOCK, new Metadata(42, 0, "IRON_BLOCK", "IRON_BLOCK",
BlockTypes.IRON_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_STONE_SLAB, new Metadata(43, 0, "DOUBLE_STONE_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_SANDSTONE_SLAB, new Metadata(43, 1, "DOUBLE_SANDSTONE_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SAND).get()));
blocks.put(KCTBlockTypes.DOUBLE_WOODEN_SLAB, new Metadata(43, 2, "DOUBLE_WOODEN_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.WOOD).get()));
blocks.put(KCTBlockTypes.DOUBLE_COBBLESTONE_SLAB, new Metadata(43, 3, "DOUBLE_COBBLESTONE_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.COBBLESTONE).get()));
blocks.put(KCTBlockTypes.DOUBLE_BRICK_SLAB, new Metadata(43, 4, "DOUBLE_BRICK_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.BRICK).get()));
blocks.put(KCTBlockTypes.DOUBLE_STONE_BRICK_SLAB, new Metadata(43, 5, "DOUBLE_STONE_BRICK_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SMOOTH_BRICK).get()));
blocks.put(KCTBlockTypes.DOUBLE_NETHER_BRICK_SLAB, new Metadata(43, 6, "DOUBLE_NETHER_BRICK_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.NETHERBRICK).get()));
blocks.put(KCTBlockTypes.DOUBLE_QUARTZ_SLAB, new Metadata(43, 7, "DOUBLE_QUARTZ_SLAB", "DOUBLE_STONE_SLAB",
BlockTypes.DOUBLE_STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.QUARTZ).get()));
blocks.put(KCTBlockTypes.STONE_SLAB, new Metadata(44, 0, "STONE_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.SANDSTONE_SLAB, new Metadata(44, 1, "SANDSTONE_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SAND).get()));
blocks.put(KCTBlockTypes.WOODEN_SLAB, new Metadata(44, 2, "WOODEN_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.WOOD).get()));
blocks.put(KCTBlockTypes.COBBLESTONE_SLAB, new Metadata(44, 3, "COBBLESTONE_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.STONE).get()));
blocks.put(KCTBlockTypes.BRICK_SLAB, new Metadata(44, 4, "BRICK_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.BRICK).get()));
blocks.put(KCTBlockTypes.STONE_BRICK_SLAB, new Metadata(44, 5, "STONE_BRICK_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.SMOOTH_BRICK).get()));
blocks.put(KCTBlockTypes.NETHER_BRICK_SLAB, new Metadata(44, 6, "NETHER_BRICK_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.STONE).get()));
blocks.put(KCTBlockTypes.QUARTZ_SLAB, new Metadata(44, 7, "QUARTZ_SLAB", "STONE_SLAB",
BlockTypes.STONE_SLAB.getDefaultState().with(Keys.SLAB_TYPE, SlabTypes.QUARTZ).get()));
blocks.put(KCTBlockTypes.BRICKS, new Metadata(45, 0, "BRICKS", "BRICK_BLOCK",
BlockTypes.BRICK_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.TNT, new Metadata(46, 0, "TNT", "TNT",
BlockTypes.TNT.getDefaultState()));
blocks.put(KCTBlockTypes.BOOKSHELF, new Metadata(47, 0, "BOOKSHELF", "BOOKSHELF",
BlockTypes.BOOKSHELF.getDefaultState()));
blocks.put(KCTBlockTypes.MOSS_STONE, new Metadata(48, 0, "MOSS_STONE", "MOSSY_COBBLESTONE",
BlockTypes.MOSSY_COBBLESTONE.getDefaultState()));
blocks.put(KCTBlockTypes.OBSIDIAN, new Metadata(49, 0, "OBSIDIAN", "OBSIDIAN",
BlockTypes.OBSIDIAN.getDefaultState()));
blocks.put(KCTBlockTypes.TORCH, new Metadata(50, 0, "TORCH", "TORCH",
BlockTypes.TORCH.getDefaultState()));
blocks.put(KCTBlockTypes.FIRE, new Metadata(51, 0, "FIRE", "FIRE",
BlockTypes.FIRE.getDefaultState()));
blocks.put(KCTBlockTypes.MONSTER_SPAWNER, new Metadata(52, 0, "MONSTER_SPAWNER", "MOB_SPAWNER",
BlockTypes.MOB_SPAWNER.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_WOOD_STAIRS, new Metadata(53, 0, "OAK_WOOD_STAIRS", "OAK_STAIRS",
BlockTypes.OAK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.CHEST, new Metadata(54, 0, "CHEST", "CHEST",
BlockTypes.CHEST.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_WIRE, new Metadata(55, 0, "REDSTONE_WIRE", "REDSTONE_WIRE",
BlockTypes.REDSTONE_WIRE.getDefaultState()));
blocks.put(KCTBlockTypes.DIAMOND_ORE, new Metadata(56, 0, "DIAMOND_ORE", "DIAMOND_ORE",
BlockTypes.DIAMOND_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.DIAMOND_BLOCK, new Metadata(57, 0, "DIAMOND_BLOCK", "DIAMOND_BLOCK",
BlockTypes.DIAMOND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.CRAFTING_TABLE, new Metadata(58, 0, "CRAFTING_TABLE", "CRAFTING_TABLE",
BlockTypes.CRAFTING_TABLE.getDefaultState()));
blocks.put(KCTBlockTypes.WHEAT_CROPS, new Metadata(59, 0, "WHEAT_CROPS", "WHEAT",
BlockTypes.WHEAT.getDefaultState()));
blocks.put(KCTBlockTypes.FARMLAND, new Metadata(60, 0, "FARMLAND", "FARMLAND",
BlockTypes.FARMLAND.getDefaultState()));
blocks.put(KCTBlockTypes.FURNACE, new Metadata(61, 0, "FURNACE", "FURNACE",
BlockTypes.FURNACE.getDefaultState()));
blocks.put(KCTBlockTypes.BURNING_FURNACE, new Metadata(62, 0, "BURNING_FURNACE", "LIT_FURNACE",
BlockTypes.LIT_FURNACE.getDefaultState()));
blocks.put(KCTBlockTypes.STANDING_SIGN_BLOCK, new Metadata(63, 0, "STANDING_SIGN_BLOCK", "STANDING_SIGN",
BlockTypes.STANDING_SIGN.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_DOOR_BLOCK, new Metadata(64, 0, "OAK_DOOR_BLOCK", "WOODEN_DOOR",
BlockTypes.WOODEN_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.LADDER, new Metadata(65, 0, "LADDER", "LADDER",
BlockTypes.LADDER.getDefaultState()));
blocks.put(KCTBlockTypes.RAIL, new Metadata(66, 0, "RAIL", "RAIL",
BlockTypes.RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.COBBLESTONE_STAIRS, new Metadata(67, 0, "COBBLESTONE_STAIRS", "STONE_STAIRS",
BlockTypes.STONE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.WALL_MOUNTED_SIGN_BLOCK, new Metadata(68, 0, "WALL_MOUNTED_SIGN_BLOCK", "WALL_SIGN",
BlockTypes.WALL_SIGN.getDefaultState()));
blocks.put(KCTBlockTypes.LEVER, new Metadata(69, 0, "LEVER", "LEVER",
BlockTypes.LEVER.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_PRESSURE_PLATE, new Metadata(70, 0, "STONE_PRESSURE_PLATE", "STONE_PRESSURE_PLATE",
BlockTypes.STONE_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_DOOR_BLOCK, new Metadata(71, 0, "IRON_DOOR_BLOCK", "IRON_DOOR",
BlockTypes.IRON_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.WOODEN_PRESSURE_PLATE, new Metadata(72, 0, "WOODEN_PRESSURE_PLATE", "WOODEN_PRESSURE_PLATE",
BlockTypes.WOODEN_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_ORE, new Metadata(73, 0, "REDSTONE_ORE", "REDSTONE_ORE",
BlockTypes.REDSTONE_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.GLOWING_REDSTONE_ORE, new Metadata(74, 0, "GLOWING_REDSTONE_ORE", "LIT_REDSTONE_ORE",
BlockTypes.LIT_REDSTONE_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_TORCH_OFF, new Metadata(75, 0, "REDSTONE_TORCH_OFF", "UNLIT_REDSTONE_TORCH",
BlockTypes.UNLIT_REDSTONE_TORCH.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_TORCH_ON, new Metadata(76, 0, "REDSTONE_TORCH_ON", "REDSTONE_TORCH",
BlockTypes.REDSTONE_TORCH.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_BUTTON, new Metadata(77, 0, "STONE_BUTTON", "STONE_BUTTON",
BlockTypes.STONE_BUTTON.getDefaultState()));
blocks.put(KCTBlockTypes.SNOW, new Metadata(78, 0, "SNOW", "SNOW_LAYER",
BlockTypes.SNOW_LAYER.getDefaultState()));
blocks.put(KCTBlockTypes.ICE, new Metadata(79, 0, "ICE", "ICE",
BlockTypes.ICE.getDefaultState()));
blocks.put(KCTBlockTypes.SNOW_BLOCK, new Metadata(80, 0, "SNOW_BLOCK", "SNOW",
BlockTypes.SNOW.getDefaultState()));
blocks.put(KCTBlockTypes.CACTUS, new Metadata(81, 0, "CACTUS", "CACTUS",
BlockTypes.CACTUS.getDefaultState()));
blocks.put(KCTBlockTypes.CLAY, new Metadata(82, 0, "CLAY", "CLAY",
BlockTypes.CLAY.getDefaultState()));
blocks.put(KCTBlockTypes.SUGAR_CANES, new Metadata(83, 0, "SUGAR_CANES", "REEDS",
BlockTypes.REEDS.getDefaultState()));
blocks.put(KCTBlockTypes.JUKEBOX, new Metadata(84, 0, "JUKEBOX", "JUKEBOX",
BlockTypes.JUKEBOX.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_FENCE, new Metadata(85, 0, "OAK_FENCE", "FENCE",
BlockTypes.FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.PUMPKIN, new Metadata(86, 0, "PUMPKIN", "PUMPKIN",
BlockTypes.PUMPKIN.getDefaultState()));
blocks.put(KCTBlockTypes.NETHERRACK, new Metadata(87, 0, "NETHERRACK", "NETHERRACK",
BlockTypes.NETHERRACK.getDefaultState()));
blocks.put(KCTBlockTypes.SOUL_SAND, new Metadata(88, 0, "SOUL_SAND", "SOUL_SAND",
BlockTypes.SOUL_SAND.getDefaultState()));
blocks.put(KCTBlockTypes.GLOWSTONE, new Metadata(89, 0, "GLOWSTONE", "GLOWSTONE",
BlockTypes.GLOWSTONE.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_PORTAL, new Metadata(90, 0, "NETHER_PORTAL", "PORTAL",
BlockTypes.PORTAL.getDefaultState()));
blocks.put(KCTBlockTypes.JACK_OLANTERN, new Metadata(91, 0, "JACK_OLANTERN", "LIT_PUMPKIN",
BlockTypes.LIT_PUMPKIN.getDefaultState()));
blocks.put(KCTBlockTypes.CAKE_BLOCK, new Metadata(92, 0, "CAKE_BLOCK", "CAKE",
BlockTypes.CAKE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_REPEATER_BLOCK_OFF, new Metadata(93, 0, "REDSTONE_REPEATER_BLOCK_OFF", "UNPOWERED_REPEATER",
BlockTypes.UNPOWERED_REPEATER.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_REPEATER_BLOCK_ON, new Metadata(94, 0, "REDSTONE_REPEATER_BLOCK_ON", "POWERED_REPEATER",
BlockTypes.POWERED_REPEATER.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_STAINED_GLASS, new Metadata(95, 0, "WHITE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_STAINED_GLASS, new Metadata(95, 1, "ORANGE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_STAINED_GLASS, new Metadata(95, 2, "MAGENTA_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_STAINED_GLASS, new Metadata(95, 3, "LIGHT_BLUE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_STAINED_GLASS, new Metadata(95, 4, "YELLOW_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_STAINED_GLASS, new Metadata(95, 5, "LIME_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_STAINED_GLASS, new Metadata(95, 6, "PINK_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_STAINED_GLASS, new Metadata(95, 7, "GRAY_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_STAINED_GLASS, new Metadata(95, 8, "LIGHT_GRAY_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_STAINED_GLASS, new Metadata(95, 9, "CYAN_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_STAINED_GLASS, new Metadata(95, 10, "PURPLE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_STAINED_GLASS, new Metadata(95, 11, "BLUE_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_STAINED_GLASS, new Metadata(95, 12, "BROWN_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_STAINED_GLASS, new Metadata(95, 13, "GREEN_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_STAINED_GLASS, new Metadata(95, 14, "RED_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_STAINED_GLASS, new Metadata(95, 15, "BLACK_STAINED_GLASS", "STAINED_GLASS",
BlockTypes.STAINED_GLASS.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.WOODEN_TRAPDOOR, new Metadata(96, 0, "WOODEN_TRAPDOOR", "TRAPDOOR",
BlockTypes.TRAPDOOR.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_MONSTER_EGG, new Metadata(97, 0, "STONE_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState()));
blocks.put(KCTBlockTypes.COBBLESTONE_MONSTER_EGG, new Metadata(97, 1, "COBBLESTONE_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.COBBLESTONE).get()));
blocks.put(KCTBlockTypes.STONE_BRICK_MONSTER_EGG, new Metadata(97, 2, "STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.STONEBRICK).get()));
blocks.put(KCTBlockTypes.MOSSY_STONE_BRICK_MONSTER_EGG, new Metadata(97, 3, "MOSSY_STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.MOSSY_STONEBRICK).get()));
blocks.put(KCTBlockTypes.CRACKED_STONE_BRICK_MONSTER_EGG, new Metadata(97, 4, "CRACKED_STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.CRACKED_STONEBRICK).get()));
blocks.put(KCTBlockTypes.CHISELED_STONE_BRICK_MONSTER_EGG, new Metadata(97, 5, "CHISELED_STONE_BRICK_MONSTER_EGG", "MONSTER_EGG",
BlockTypes.MONSTER_EGG.getDefaultState().with(Keys.DISGUISED_BLOCK_TYPE, DisguisedBlockTypes.CHISELED_STONEBRICK).get()));
blocks.put(KCTBlockTypes.STONE_BRICKS, new Metadata(98, 0, "STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState()));
blocks.put(KCTBlockTypes.MOSSY_STONE_BRICKS, new Metadata(98, 1, "MOSSY_STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState().with(Keys.BRICK_TYPE, BrickTypes.MOSSY).get()));
blocks.put(KCTBlockTypes.CRACKED_STONE_BRICKS, new Metadata(98, 2, "CRACKED_STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState().with(Keys.BRICK_TYPE, BrickTypes.CRACKED).get()));
blocks.put(KCTBlockTypes.CHISELED_STONE_BRICKS, new Metadata(98, 3, "CHISELED_STONE_BRICKS", "STONEBRICK",
BlockTypes.STONEBRICK.getDefaultState().with(Keys.BRICK_TYPE, BrickTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.BROWN_MUSHROOM_BLOCK, new Metadata(99, 0, "BROWN_MUSHROOM_BLOCK", "BROWN_MUSHROOM_BLOCK",
BlockTypes.BROWN_MUSHROOM_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.RED_MUSHROOM_BLOCK, new Metadata(100, 0, "RED_MUSHROOM_BLOCK", "RED_MUSHROOM_BLOCK",
BlockTypes.RED_MUSHROOM_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_BARS, new Metadata(101, 0, "IRON_BARS", "IRON_BARS",
BlockTypes.IRON_BARS.getDefaultState()));
blocks.put(KCTBlockTypes.GLASS_PANE, new Metadata(102, 0, "GLASS_PANE", "GLASS_PANE",
BlockTypes.GLASS_PANE.getDefaultState()));
blocks.put(KCTBlockTypes.MELON_BLOCK, new Metadata(103, 0, "MELON_BLOCK", "MELON_BLOCK",
BlockTypes.MELON_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.PUMPKIN_STEM, new Metadata(104, 0, "PUMPKIN_STEM", "PUMPKIN_STEM",
BlockTypes.PUMPKIN_STEM.getDefaultState()));
blocks.put(KCTBlockTypes.MELON_STEM, new Metadata(105, 0, "MELON_STEM", "MELON_STEM",
BlockTypes.MELON_STEM.getDefaultState()));
blocks.put(KCTBlockTypes.VINES, new Metadata(106, 0, "VINES", "VINE",
BlockTypes.VINE.getDefaultState()));
blocks.put(KCTBlockTypes.OAK_FENCE_GATE, new Metadata(107, 0, "OAK_FENCE_GATE", "FENCE_GATE",
BlockTypes.FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.BRICK_STAIRS, new Metadata(108, 0, "BRICK_STAIRS", "BRICK_STAIRS",
BlockTypes.BRICK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.STONE_BRICK_STAIRS, new Metadata(109, 0, "STONE_BRICK_STAIRS", "STONE_BRICK_STAIRS",
BlockTypes.STONE_BRICK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.MYCELIUM, new Metadata(110, 0, "MYCELIUM", "MYCELIUM",
BlockTypes.MYCELIUM.getDefaultState()));
blocks.put(KCTBlockTypes.LILY_PAD, new Metadata(111, 0, "LILY_PAD", "WATERLILY",
BlockTypes.WATERLILY.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_BRICK, new Metadata(112, 0, "NETHER_BRICK", "NETHER_BRICK",
BlockTypes.NETHER_BRICK.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_BRICK_FENCE, new Metadata(113, 0, "NETHER_BRICK_FENCE", "NETHER_BRICK_FENCE",
BlockTypes.NETHER_BRICK_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_BRICK_STAIRS, new Metadata(114, 0, "NETHER_BRICK_STAIRS", "NETHER_BRICK_STAIRS",
BlockTypes.NETHER_BRICK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_WART, new Metadata(115, 0, "NETHER_WART", "NETHER_WART",
BlockTypes.NETHER_WART.getDefaultState()));
/*
blocks.put(KCTBlockTypes.ENCHANTMENT_TABLE, new Metadata(116, 0, "ENCHANTMENT_TABLE", "ENCHANTING_TABLE",
BlockTypes.ENCHANTING_TABLE.getDefaultState()));
blocks.put(KCTBlockTypes.BREWING_STAND, new Metadata(117, 0, "BREWING_STAND", "BREWING_STAND",
BlockTypes.BREWING_STAND.getDefaultState()));
blocks.put(KCTBlockTypes.CAULDRON, new Metadata(118, 0, "CAULDRON", "CAULDRON",
BlockTypes.CAULDRON.getDefaultState()));
blocks.put(KCTBlockTypes.END_PORTAL, new Metadata(119, 0, "END_PORTAL", "END_PORTAL",
BlockTypes.END_PORTAL.getDefaultState()));
blocks.put(KCTBlockTypes.END_PORTAL_FRAME, new Metadata(120, 0, "END_PORTAL_FRAME", "END_PORTAL_FRAME",
BlockTypes.END_PORTAL_FRAME.getDefaultState()));
blocks.put(KCTBlockTypes.END_STONE, new Metadata(121, 0, "END_STONE", "END_STONE",
BlockTypes.END_STONE.getDefaultState()));
blocks.put(KCTBlockTypes.DRAGON_EGG, new Metadata(122, 0, "DRAGON_EGG", "DRAGON_EGG",
BlockTypes.DRAGON_EGG.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_LAMP_INACTIVE, new Metadata(123, 0, "REDSTONE_LAMP_INACTIVE", "REDSTONE_LAMP",
BlockTypes.REDSTONE_LAMP.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_LAMP_ACTIVE, new Metadata(124, 0, "REDSTONE_LAMP_ACTIVE", "LIT_REDSTONE_LAMP",
BlockTypes.LIT_REDSTONE_LAMP.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_OAK_WOOD_SLAB, new Metadata(125, 0, "DOUBLE_OAK_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_SPRUCE_WOOD_SLAB, new Metadata(125, 1, "DOUBLE_SPRUCE_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.DOUBLE_BIRCH_WOOD_SLAB, new Metadata(125, 2, "DOUBLE_BIRCH_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.DOUBLE_JUNGLE_WOOD_SLAB, new Metadata(125, 3, "DOUBLE_JUNGLE_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.DOUBLE_ACACIA_WOOD_SLAB, new Metadata(125, 4, "DOUBLE_ACACIA_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DOUBLE_DARK_OAK_WOOD_SLAB, new Metadata(125, 5, "DOUBLE_DARK_OAK_WOOD_SLAB", "DOUBLE_WOODEN_SLAB",
BlockTypes.DOUBLE_WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.OAK).get()));
blocks.put(KCTBlockTypes.OAK_WOOD_SLAB, new Metadata(126, 0, "OAK_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD_SLAB, new Metadata(126, 1, "SPRUCE_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.SPRUCE).get()));
blocks.put(KCTBlockTypes.BIRCH_WOOD_SLAB, new Metadata(126, 2, "BIRCH_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.BIRCH).get()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD_SLAB, new Metadata(126, 3, "JUNGLE_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.JUNGLE).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD_SLAB, new Metadata(126, 4, "ACACIA_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.ACACIA).get()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD_SLAB, new Metadata(126, 5, "DARK_OAK_WOOD_SLAB", "WOODEN_SLAB",
BlockTypes.WOODEN_SLAB.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.COCOA, new Metadata(127, 0, "COCOA", "COCOA",
BlockTypes.COCOA.getDefaultState()));
blocks.put(KCTBlockTypes.SANDSTONE_STAIRS, new Metadata(128, 0, "SANDSTONE_STAIRS", "SANDSTONE_STAIRS",
BlockTypes.SANDSTONE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.EMERALD_ORE, new Metadata(129, 0, "EMERALD_ORE", "EMERALD_ORE",
BlockTypes.EMERALD_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.ENDER_CHEST, new Metadata(130, 0, "ENDER_CHEST", "ENDER_CHEST",
BlockTypes.ENDER_CHEST.getDefaultState()));
blocks.put(KCTBlockTypes.TRIPWIRE_HOOK, new Metadata(131, 0, "TRIPWIRE_HOOK", "TRIPWIRE_HOOK",
BlockTypes.TRIPWIRE_HOOK.getDefaultState()));
blocks.put(KCTBlockTypes.TRIPWIRE, new Metadata(132, 0, "TRIPWIRE", "TRIPWIRE_HOOK",
BlockTypes.TRIPWIRE_HOOK.getDefaultState()));
blocks.put(KCTBlockTypes.EMERALD_BLOCK, new Metadata(133, 0, "EMERALD_BLOCK", "EMERALD_BLOCK",
BlockTypes.EMERALD_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_WOOD_STAIRS, new Metadata(134, 0, "SPRUCE_WOOD_STAIRS", "SPRUCE_STAIRS",
BlockTypes.SPRUCE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_WOOD_STAIRS, new Metadata(135, 0, "BIRCH_WOOD_STAIRS", "BIRCH_STAIRS",
BlockTypes.BIRCH_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_WOOD_STAIRS, new Metadata(136, 0, "JUNGLE_WOOD_STAIRS", "JUNGLE_STAIRS",
BlockTypes.JUNGLE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.COMMAND_BLOCK, new Metadata(137, 0, "COMMAND_BLOCK", "COMMAND_BLOCK",
BlockTypes.COMMAND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.BEACON, new Metadata(138, 0, "BEACON", "BEACON",
BlockTypes.BEACON.getDefaultState()));
blocks.put(KCTBlockTypes.COBBLESTONE_WALL, new Metadata(139, 0, "COBBLESTONE_WALL", "COBBLESTONE_WALL",
BlockTypes.COBBLESTONE_WALL.getDefaultState()));
blocks.put(KCTBlockTypes.MOSSY_COBBLESTONE_WALL, new Metadata(139, 1, "MOSSY_COBBLESTONE_WALL", "COBBLESTONE_WALL",
BlockTypes.COBBLESTONE_WALL.getDefaultState().with(Keys.WALL_TYPE, WallTypes.MOSSY).get()));
blocks.put(KCTBlockTypes.FLOWER_POT, new Metadata(140, 0, "FLOWER_POT", "FLOWER_POT",
BlockTypes.FLOWER_POT.getDefaultState()));
blocks.put(KCTBlockTypes.CARROTS, new Metadata(141, 0, "CARROTS", "CARROTS",
BlockTypes.CARROTS.getDefaultState()));
blocks.put(KCTBlockTypes.POTATOES, new Metadata(142, 0, "POTATOES", "POTATOES",
BlockTypes.POTATOES.getDefaultState()));
blocks.put(KCTBlockTypes.WOODEN_BUTTON, new Metadata(143, 0, "WOODEN_BUTTON", "WOODEN_BUTTON",
BlockTypes.WOODEN_BUTTON.getDefaultState()));
blocks.put(KCTBlockTypes.MOB_HEAD, new Metadata(144, 0, "MOB_HEAD", "SKULL",
BlockTypes.SKULL.getDefaultState()));
blocks.put(KCTBlockTypes.ANVIL, new Metadata(145, 0, "ANVIL", "ANVIL",
BlockTypes.ANVIL.getDefaultState()));
blocks.put(KCTBlockTypes.TRAPPED_CHEST, new Metadata(146, 0, "TRAPPED_CHEST", "TRAPPED_CHEST",
BlockTypes.TRAPPED_CHEST.getDefaultState()));
blocks.put(KCTBlockTypes.WEIGHTED_PRESSURE_PLATE_LIGHT, new Metadata(147, 0, "WEIGHTED_PRESSURE_PLATE_LIGHT", "LIGHT_WEIGHTED_PRESSURE_PLATE",
BlockTypes.LIGHT_WEIGHTED_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.WEIGHTED_PRESSURE_PLATE_HEAVY, new Metadata(148, 0, "WEIGHTED_PRESSURE_PLATE_HEAVY", "HEAVY_WEIGHTED_PRESSURE_PLATE",
BlockTypes.HEAVY_WEIGHTED_PRESSURE_PLATE.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_COMPARATOR_INACTIVE, new Metadata(149, 0, "REDSTONE_COMPARATOR_INACTIVE", "UNPOWERED_COMPARATOR",
BlockTypes.UNPOWERED_COMPARATOR.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_COMPARATOR_ACTIVE, new Metadata(150, 0, "REDSTONE_COMPARATOR_ACTIVE", "POWERED_COMPARATOR",
BlockTypes.POWERED_COMPARATOR.getDefaultState()));
blocks.put(KCTBlockTypes.DAYLIGHT_SENSOR, new Metadata(151, 0, "DAYLIGHT_SENSOR", "DAYLIGHT_DETECTOR",
BlockTypes.DAYLIGHT_DETECTOR.getDefaultState()));
blocks.put(KCTBlockTypes.REDSTONE_BLOCK, new Metadata(152, 0, "REDSTONE_BLOCK", "REDSTONE_BLOCK",
BlockTypes.REDSTONE_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.NETHER_QUARTZ_ORE, new Metadata(153, 0, "NETHER_QUARTZ_ORE", "QUARTZ_ORE",
BlockTypes.QUARTZ_ORE.getDefaultState()));
blocks.put(KCTBlockTypes.HOPPER, new Metadata(154, 0, "HOPPER", "HOPPER",
BlockTypes.HOPPER.getDefaultState()));
blocks.put(KCTBlockTypes.QUARTZ_BLOCK, new Metadata(155, 0, "QUARTZ_BLOCK", "QUARTZ_BLOCK",
BlockTypes.QUARTZ_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.CHISELED_QUARTZ_BLOCK, new Metadata(155, 1, "CHISELED_QUARTZ_BLOCK", "QUARTZ_BLOCK",
BlockTypes.QUARTZ_BLOCK.getDefaultState().with(Keys.QUARTZ_TYPE, QuartzTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.PILLAR_QUARTZ_BLOCK, new Metadata(155, 2, "PILLAR_QUARTZ_BLOCK", "QUARTZ_BLOCK",
BlockTypes.QUARTZ_BLOCK.getDefaultState().with(Keys.QUARTZ_TYPE, QuartzTypes.LINES_Y).get()));
blocks.put(KCTBlockTypes.QUARTZ_STAIRS, new Metadata(156, 0, "QUARTZ_STAIRS", "QUARTZ_STAIRS",
BlockTypes.QUARTZ_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.ACTIVATOR_RAIL, new Metadata(157, 0, "ACTIVATOR_RAIL", "ACTIVATOR_RAIL",
BlockTypes.ACTIVATOR_RAIL.getDefaultState()));
blocks.put(KCTBlockTypes.DROPPER, new Metadata(158, 0, "DROPPER", "DROPPER",
BlockTypes.DROPPER.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_STAINED_CLAY, new Metadata(159, 0, "WHITE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_STAINED_CLAY, new Metadata(159, 1, "ORANGE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_STAINED_CLAY, new Metadata(159, 2, "MAGENTA_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_STAINED_CLAY, new Metadata(159, 3, "LIGHT_BLUE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_STAINED_CLAY, new Metadata(159, 4, "YELLOW_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_STAINED_CLAY, new Metadata(159, 5, "LIME_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_STAINED_CLAY, new Metadata(159, 6, "PINK_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_STAINED_CLAY, new Metadata(159, 7, "GRAY_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_STAINED_CLAY, new Metadata(159, 8, "LIGHT_GRAY_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_STAINED_CLAY, new Metadata(159, 9, "CYAN_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_STAINED_CLAY, new Metadata(159, 10, "PURPLE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_STAINED_CLAY, new Metadata(159, 11, "BLUE_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_STAINED_CLAY, new Metadata(159, 12, "BROWN_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_STAINED_CLAY, new Metadata(159, 13, "GREEN_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_STAINED_CLAY, new Metadata(159, 14, "RED_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_STAINED_CLAY, new Metadata(159, 15, "BLACK_STAINED_CLAY", "STAINED_HARDENED_CLAY",
BlockTypes.STAINED_HARDENED_CLAY.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.WHITE_STAINED_GLASS_PANE, new Metadata(160, 0, "WHITE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_STAINED_GLASS_PANE, new Metadata(160, 1, "ORANGE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_STAINED_GLASS_PANE, new Metadata(160, 2, "MAGENTA_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_STAINED_GLASS_PANE, new Metadata(160, 3, "LIGHT_BLUE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_STAINED_GLASS_PANE, new Metadata(160, 4, "YELLOW_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_STAINED_GLASS_PANE, new Metadata(160, 5, "LIME_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_STAINED_GLASS_PANE, new Metadata(160, 6, "PINK_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_STAINED_GLASS_PANE, new Metadata(160, 7, "GRAY_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_STAINED_GLASS_PANE, new Metadata(160, 8, "LIGHT_GRAY_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_STAINED_GLASS_PANE, new Metadata(160, 9, "CYAN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_STAINED_GLASS_PANE, new Metadata(160, 10, "PURPLE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_STAINED_GLASS_PANE, new Metadata(160, 11, "BLUE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_STAINED_GLASS_PANE, new Metadata(160, 12, "BROWN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_STAINED_GLASS_PANE, new Metadata(160, 13, "GREEN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_STAINED_GLASS_PANE, new Metadata(160, 14, "RED_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_STAINED_GLASS_PANE, new Metadata(160, 15, "BLACK_STAINED_GLASS_PANE", "STAINED_GLASS_PANE",
BlockTypes.STAINED_GLASS_PANE.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.ACACIA_LEAVES, new Metadata(161, 0, "ACACIA_LEAVES", "LEAVES2",
BlockTypes.LEAVES2.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_LEAVES, new Metadata(161, 1, "DARK_OAK_LEAVES", "LEAVES2",
BlockTypes.LEAVES2.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD, new Metadata(162, 0, "ACACIA_WOOD", "LOG2",
BlockTypes.LOG2.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD, new Metadata(162, 1, "DARK_OAK_WOOD", "LOG2",
BlockTypes.LOG2.getDefaultState().with(Keys.TREE_TYPE, TreeTypes.DARK_OAK).get()));
blocks.put(KCTBlockTypes.ACACIA_WOOD_STAIRS, new Metadata(163, 0, "ACACIA_WOOD_STAIRS", "ACACIA_STAIRS",
BlockTypes.ACACIA_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_WOOD_STAIRS, new Metadata(164, 0, "DARK_OAK_WOOD_STAIRS", "DARK_OAK_STAIRS",
BlockTypes.DARK_OAK_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.SLIME_BLOCK, new Metadata(165, 0, "SLIME_BLOCK", "SLIME",
BlockTypes.SLIME.getDefaultState()));
blocks.put(KCTBlockTypes.BARRIER, new Metadata(166, 0, "BARRIER", "BARRIER",
BlockTypes.BARRIER.getDefaultState()));
blocks.put(KCTBlockTypes.IRON_TRAPDOOR, new Metadata(167, 0, "IRON_TRAPDOOR", "IRON_TRAPDOOR",
BlockTypes.IRON_TRAPDOOR.getDefaultState()));
blocks.put(KCTBlockTypes.PRISMARINE, new Metadata(168, 0, "PRISMARINE", "PRISMARINE",
BlockTypes.PRISMARINE.getDefaultState()));
blocks.put(KCTBlockTypes.PRISMARINE_BRICKS, new Metadata(168, 1, "PRISMARINE_BRICKS", "PRISMARINE",
BlockTypes.PRISMARINE.getDefaultState().with(Keys.PRISMARINE_TYPE, PrismarineTypes.BRICKS).get()));
*/
/*
blocks.put(KCTBlockTypes.DARK_PRISMARINE, new Metadata(168, 2, "DARK_PRISMARINE", "PRISMARINE",
BlockTypes.PRISMARINE.getDefaultState().with(Keys.PRISMARINE_TYPE, PrismarineTypes.DARK).get()));
blocks.put(KCTBlockTypes.SEA_LANTERN, new Metadata(169, 0, "SEA_LANTERN", "SEA_LANTERN",
BlockTypes.SEA_LANTERN.getDefaultState()));
blocks.put(KCTBlockTypes.HAY_BALE, new Metadata(170, 0, "HAY_BALE", "HAY_BLOCK",
BlockTypes.HAY_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.WHITE_CARPET, new Metadata(171, 0, "WHITE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState()));
blocks.put(KCTBlockTypes.ORANGE_CARPET, new Metadata(171, 1, "ORANGE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.ORANGE).get()));
blocks.put(KCTBlockTypes.MAGENTA_CARPET, new Metadata(171, 2, "MAGENTA_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.MAGENTA).get()));
blocks.put(KCTBlockTypes.LIGHT_BLUE_CARPET, new Metadata(171, 3, "LIGHT_BLUE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIGHT_BLUE).get()));
blocks.put(KCTBlockTypes.YELLOW_CARPET, new Metadata(171, 4, "YELLOW_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.YELLOW).get()));
blocks.put(KCTBlockTypes.LIME_CARPET, new Metadata(171, 5, "LIME_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.LIME).get()));
blocks.put(KCTBlockTypes.PINK_CARPET, new Metadata(171, 6, "PINK_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PINK).get()));
blocks.put(KCTBlockTypes.GRAY_CARPET, new Metadata(171, 7, "GRAY_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.LIGHT_GRAY_CARPET, new Metadata(171, 8, "LIGHT_GRAY_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GRAY).get()));
blocks.put(KCTBlockTypes.CYAN_CARPET, new Metadata(171, 9, "CYAN_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.CYAN).get()));
blocks.put(KCTBlockTypes.PURPLE_CARPET, new Metadata(171, 10, "PURPLE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.PURPLE).get()));
blocks.put(KCTBlockTypes.BLUE_CARPET, new Metadata(171, 11, "BLUE_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLUE).get()));
blocks.put(KCTBlockTypes.BROWN_CARPET, new Metadata(171, 12, "BROWN_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BROWN).get()));
blocks.put(KCTBlockTypes.GREEN_CARPET, new Metadata(171, 13, "GREEN_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.GREEN).get()));
blocks.put(KCTBlockTypes.RED_CARPET, new Metadata(171, 14, "RED_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.RED).get()));
blocks.put(KCTBlockTypes.BLACK_CARPET, new Metadata(171, 15, "BLACK_CARPET", "CARPET",
BlockTypes.CARPET.getDefaultState().with(Keys.DYE_COLOR, DyeColors.BLACK).get()));
blocks.put(KCTBlockTypes.HARDENED_CLAY, new Metadata(172, 0, "HARDENED_CLAY", "HARDENED_CLAY",
BlockTypes.HARDENED_CLAY.getDefaultState()));
blocks.put(KCTBlockTypes.BLOCK_OF_COAL, new Metadata(173, 0, "BLOCK_OF_COAL", "COAL_BLOCK",
BlockTypes.COAL_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.PACKED_ICE, new Metadata(174, 0, "PACKED_ICE", "PACKED_ICE",
BlockTypes.PACKED_ICE.getDefaultState()));
blocks.put(KCTBlockTypes.SUNFLOWER, new Metadata(175, 0, "SUNFLOWER", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState()));
blocks.put(KCTBlockTypes.LILAC, new Metadata(175, 1, "LILAC", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.SYRINGA).get()));
blocks.put(KCTBlockTypes.DOUBLE_TALLGRASS, new Metadata(175, 2, "DOUBLE_TALLGRASS", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.GRASS).get()));
blocks.put(KCTBlockTypes.LARGE_FERN, new Metadata(175, 3, "LARGE_FERN", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.FERN).get()));
blocks.put(KCTBlockTypes.ROSE_BUSH, new Metadata(175, 4, "ROSE_BUSH", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.ROSE).get()));
blocks.put(KCTBlockTypes.PEONY, new Metadata(175, 5, "PEONY", "DOUBLE_PLANT",
BlockTypes.DOUBLE_PLANT.getDefaultState().with(Keys.DOUBLE_PLANT_TYPE, DoublePlantTypes.PAEONIA).get()));
blocks.put(KCTBlockTypes.FREE_STANDING_BANNER, new Metadata(176, 0, "FREE_STANDING_BANNER", "STANDING_BANNER",
BlockTypes.STANDING_BANNER.getDefaultState()));
blocks.put(KCTBlockTypes.WALL_MOUNTED_BANNER, new Metadata(177, 0, "WALL_MOUNTED_BANNER", "WALL_BANNER",
BlockTypes.WALL_BANNER.getDefaultState()));
blocks.put(KCTBlockTypes.INVERTED_DAYLIGHT_SENSOR, new Metadata(178, 0, "INVERTED_DAYLIGHT_SENSOR", "DAYLIGHT_DETECTOR_INVERTED",
BlockTypes.DAYLIGHT_DETECTOR_INVERTED.getDefaultState()));
blocks.put(KCTBlockTypes.RED_SANDSTONE, new Metadata(179, 0, "RED_SANDSTONE", "RED_SANDSTONE",
BlockTypes.RED_SANDSTONE.getDefaultState()));
blocks.put(KCTBlockTypes.CHISELED_RED_SANDSTONE, new Metadata(179, 1, "CHISELED_RED_SANDSTONE", "RED_SANDSTONE",
BlockTypes.RED_SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.CHISELED).get()));
blocks.put(KCTBlockTypes.SMOOTH_RED_SANDSTONE, new Metadata(179, 2, "SMOOTH_RED_SANDSTONE", "RED_SANDSTONE",
BlockTypes.RED_SANDSTONE.getDefaultState().with(Keys.SANDSTONE_TYPE, SandstoneTypes.SMOOTH).get()));
blocks.put(KCTBlockTypes.RED_SANDSTONE_STAIRS, new Metadata(180, 0, "RED_SANDSTONE_STAIRS", "RED_SANDSTONE_STAIRS",
BlockTypes.RED_SANDSTONE_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.DOUBLE_RED_SANDSTONE_SLAB, new Metadata(181, 0, "DOUBLE_RED_SANDSTONE_SLAB", "DOUBLE_STONE_SLAB2",
BlockTypes.DOUBLE_STONE_SLAB2.getDefaultState()));
blocks.put(KCTBlockTypes.RED_SANDSTONE_SLAB, new Metadata(182, 0, "RED_SANDSTONE_SLAB", "STONE_SLAB2",
BlockTypes.STONE_SLAB2.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_FENCE_GATE, new Metadata(183, 0, "SPRUCE_FENCE_GATE", "SPRUCE_FENCE_GATE",
BlockTypes.SPRUCE_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_FENCE_GATE, new Metadata(184, 0, "BIRCH_FENCE_GATE", "BIRCH_FENCE_GATE",
BlockTypes.BIRCH_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_FENCE_GATE, new Metadata(185, 0, "JUNGLE_FENCE_GATE", "JUNGLE_FENCE_GATE",
BlockTypes.JUNGLE_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_FENCE_GATE, new Metadata(186, 0, "DARK_OAK_FENCE_GATE", "DARK_OAK_FENCE_GATE",
BlockTypes.DARK_OAK_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.ACACIA_FENCE_GATE, new Metadata(187, 0, "ACACIA_FENCE_GATE", "ACACIA_FENCE_GATE",
BlockTypes.ACACIA_FENCE_GATE.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_FENCE, new Metadata(188, 0, "SPRUCE_FENCE", "SPRUCE_FENCE",
BlockTypes.SPRUCE_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_FENCE, new Metadata(189, 0, "BIRCH_FENCE", "BIRCH_FENCE",
BlockTypes.BIRCH_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_FENCE, new Metadata(190, 0, "JUNGLE_FENCE", "JUNGLE_FENCE",
BlockTypes.JUNGLE_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_FENCE, new Metadata(191, 0, "DARK_OAK_FENCE", "DARK_OAK_FENCE",
BlockTypes.DARK_OAK_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.ACACIA_FENCE, new Metadata(192, 0, "ACACIA_FENCE", "ACACIA_FENCE",
BlockTypes.ACACIA_FENCE.getDefaultState()));
blocks.put(KCTBlockTypes.SPRUCE_DOOR_BLOCK, new Metadata(193, 0, "SPRUCE_DOOR_BLOCK", "SPRUCE_DOOR",
BlockTypes.SPRUCE_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.BIRCH_DOOR_BLOCK, new Metadata(194, 0, "BIRCH_DOOR_BLOCK", "BIRCH_DOOR",
BlockTypes.BIRCH_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.JUNGLE_DOOR_BLOCK, new Metadata(195, 0, "JUNGLE_DOOR_BLOCK", "JUNGLE_DOOR",
BlockTypes.JUNGLE_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.ACACIA_DOOR_BLOCK, new Metadata(196, 0, "ACACIA_DOOR_BLOCK", "ACACIA_DOOR",
BlockTypes.ACACIA_DOOR.getDefaultState()));
blocks.put(KCTBlockTypes.DARK_OAK_DOOR_BLOCK, new Metadata(197, 0, "DARK_OAK_DOOR_BLOCK", "DARK_OAK_DOOR",
BlockTypes.DARK_OAK_DOOR.getDefaultState()));
*/
/* Minecraft Blocks added after Version 1.9
blocks.put(KCTBlockTypes.END_ROD, new Metadata(198, 0, "END_ROD", "END_ROD",
BlockTypes.END_ROD.getDefaultState()));
blocks.put(KCTBlockTypes.CHORUS_PLANT, new Metadata(199, 0, "CHORUS_PLANT", "CHORUS_PLANT",
BlockTypes.CHORUS_PLANT.getDefaultState()));
blocks.put(KCTBlockTypes.CHORUS_FLOWER, new Metadata(200, 0, "CHORUS_FLOWER", "CHORUS_FLOWER",
BlockTypes.CHORUS_FLOWER.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_BLOCK, new Metadata(201, 0, "PURPUR_BLOCK", "PURPUR_BLOCK",
BlockTypes.PURPUR_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_PILLAR, new Metadata(202, 0, "PURPUR_PILLAR", "PURPUR_PILLAR",
BlockTypes.PURPUR_PILLAR.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_STAIRS, new Metadata(203, 0, "PURPUR_STAIRS", "PURPUR_STAIRS",
BlockTypes.PURPUR_STAIRS.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_DOUBLE_SLAB, new Metadata(204, 0, "PURPUR_DOUBLE_SLAB", "PURPUR_DOUBLE_SLAB",
BlockTypes.PURPUR_DOUBLE_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.PURPUR_SLAB, new Metadata(205, 0, "PURPUR_SLAB", "PURPUR_SLAB",
BlockTypes.PURPUR_SLAB.getDefaultState()));
blocks.put(KCTBlockTypes.END_STONE_BRICKS, new Metadata(206, 0, "END_STONE_BRICKS", "END_BRICKS",
BlockTypes.END_BRICKS.getDefaultState()));
blocks.put(KCTBlockTypes.BEETROOT_BLOCK, new Metadata(207, 0, "BEETROOT_BLOCK", "BEETROOTS",
BlockTypes.BEETROOTS.getDefaultState()));
blocks.put(KCTBlockTypes.GRASS_PATH, new Metadata(208, 0, "GRASS_PATH", "GRASS_PATH",
BlockTypes.GRASS_PATH.getDefaultState()));
blocks.put(KCTBlockTypes.END_GATEWAY, new Metadata(209, 0, "END_GATEWAY", "END_GATEWAY",
BlockTypes.END_GATEWAY.getDefaultState()));
blocks.put(KCTBlockTypes.REPEATING_COMMAND_BLOCK, new Metadata(210, 0, "REPEATING_COMMAND_BLOCK", "REPEATING_COMMAND_BLOCK",
BlockTypes.REPEATING_COMMAND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.CHAIN_COMMAND_BLOCK, new Metadata(211, 0, "CHAIN_COMMAND_BLOCK", "CHAIN_COMMAND_BLOCK",
BlockTypes.CHAIN_COMMAND_BLOCK.getDefaultState()));
blocks.put(KCTBlockTypes.FROSTED_ICE, new Metadata(212, 0, "FROSTED_ICE", "FROSTED_ICE",
BlockTypes.FROSTED_ICE.getDefaultState()));
blocks.put(KCTBlockTypes.STRUCTURE_BLOCK, new Metadata(255, 0, "STRUCTURE_BLOCK", "STRUCTURE_BLOCK",
BlockTypes.STRUCTURE_BLOCK.getDefaultState())); */
}
}
| Added more detailed javadoc for initializing KCTBlockTypesBuilder | TurtleSponge/src/main/java/org/knoxcraft/turtle3d/KCTBlockTypesBuilder.java | Added more detailed javadoc for initializing KCTBlockTypesBuilder | <ide><path>urtleSponge/src/main/java/org/knoxcraft/turtle3d/KCTBlockTypesBuilder.java
<ide>
<ide> import java.util.HashMap;
<ide>
<add>import org.spongepowered.api.CatalogType;
<add>import org.spongepowered.api.CatalogTypes;
<ide> import org.spongepowered.api.block.BlockState;
<add>import org.spongepowered.api.block.BlockType;
<ide> import org.spongepowered.api.block.BlockTypes;
<ide> import org.spongepowered.api.data.key.Keys;
<ide> import org.spongepowered.api.data.type.BrickTypes;
<ide> import org.spongepowered.api.data.type.DirtTypes;
<ide> import org.spongepowered.api.data.type.DisguisedBlockTypes;
<del>import org.spongepowered.api.data.type.DoublePlantTypes;
<ide> import org.spongepowered.api.data.type.DyeColors;
<ide> import org.spongepowered.api.data.type.PlantTypes;
<ide> import org.spongepowered.api.data.type.SandTypes;
<ide>
<ide> private static final HashMap<KCTBlockTypes, Metadata> blocks = new HashMap<KCTBlockTypes, Metadata>();
<ide>
<add> /**
<add> * Return the {@link BlockState} that corresponds to the given {@link KCTBlockType}.
<add> * Basically, this converts between our own internal <tt>enum</tt> and a Sponge
<add> * {@link BlockState}.
<add> *
<add> * <b>NOTE:</b>
<add> *
<add> * Using an initialize() method that gets called once, rather than a static initializer.
<add> * The {@link BlockTypes} class dynamically creates placeholders where all methods throw
<add> * UnsupportedOperationException. If you use any methods of a {@link BlockType} in a static
<add> * initializer it will throw that UnsupportedOperationException. So we have to delay actually
<add> * calling any methods on a {@link BlockType} until Sponge has actually initialized everything
<add> * in {@link BlockTypes} with its real value.
<add> *
<add> * Sponge does eventually fill in the real {@link BlockType} instances in {@link BlockTypes}, probably
<add> * using some design pattern that is related to {@link CatalogTypes} and {@link CatalogType}.
<add> *
<add> * We honestly don't understand how this process works, so we are just using the static
<add> * initialize() method because it gets called late enough that it doesn't generate an exception.
<add> * We don't know why this works.
<add> *
<add> * @param type
<add> * @return
<add> */
<ide> public static BlockState getBlockState(KCTBlockTypes type) {
<ide> initialize();
<ide> return blocks.get(type).getBlock();
<ide> }
<ide> private static boolean isInitialized=false;
<ide>
<add> /**
<add> * See {@link #getBlockState(KCTBlockTypes)} for more details about why we have this method
<add> * instead of a static initializer.
<add> */
<ide> private static void initialize() {
<add> // Ensure that we only call initialize once!
<ide> if (isInitialized){
<ide> return;
<ide> } |
|
Java | apache-2.0 | c28774a7b2447303444c71352b0cc4f284294381 | 0 | mta452/Tehreer-Android,mta452/Tehreer-Android,mta452/Tehreer-Android | /*
* Copyright (C) 2018 Muhammad Tayyab Akram
*
* 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.mta.tehreer.layout;
import android.text.Spanned;
import com.mta.tehreer.internal.collections.SafeFloatList;
import com.mta.tehreer.internal.collections.SafeIntList;
import com.mta.tehreer.internal.collections.SafePointList;
import com.mta.tehreer.internal.layout.BreakResolver;
import com.mta.tehreer.internal.layout.ClusterMap;
import com.mta.tehreer.internal.layout.IntrinsicRun;
import com.mta.tehreer.internal.layout.ParagraphCollection;
import com.mta.tehreer.internal.layout.RunCollection;
import com.mta.tehreer.internal.util.StringUtils;
import com.mta.tehreer.unicode.BidiRun;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class LineResolver {
private Spanned mSpanned;
private ParagraphCollection mBidiParagraphs;
private RunCollection mIntrinsicRuns;
LineResolver() {
}
void reset(Spanned spanned, ParagraphCollection paragraphs, RunCollection runs) {
mSpanned = spanned;
mBidiParagraphs = paragraphs;
mIntrinsicRuns = runs;
}
static GlyphRun createGlyphRun(IntrinsicRun intrinsicRun, int charStart, int charEnd, Object[] spans) {
int glyphOffset = intrinsicRun.charGlyphStart(charStart);
int glyphCount = intrinsicRun.charGlyphEnd(charEnd - 1) - glyphOffset;
return new GlyphRun(charStart, charEnd, Arrays.asList(spans),
intrinsicRun.isBackward, intrinsicRun.bidiLevel,
intrinsicRun.writingDirection, intrinsicRun.typeface, intrinsicRun.typeSize,
intrinsicRun.ascent, intrinsicRun.descent, intrinsicRun.leading,
new SafeIntList(intrinsicRun.glyphIds, glyphOffset, glyphCount),
new SafePointList(intrinsicRun.glyphOffsets, glyphOffset, glyphCount),
new SafeFloatList(intrinsicRun.glyphAdvances, glyphOffset, glyphCount),
new ClusterMap(intrinsicRun.clusterMap,
charStart - intrinsicRun.charStart,
charEnd - charStart, glyphOffset));
}
static ComposedLine createComposedLine(CharSequence text, int charStart, int charEnd,
List<GlyphRun> runList, byte paragraphLevel) {
float lineAscent = 0.0f;
float lineDescent = 0.0f;
float lineLeading = 0.0f;
float lineExtent = 0.0f;
int trailingWhitespaceStart = StringUtils.getTrailingWhitespaceStart(text, charStart, charEnd);
float trailingWhitespaceExtent = 0.0f;
int runCount = runList.size();
for (int i = 0; i < runCount; i++) {
GlyphRun glyphRun = runList.get(i);
glyphRun.setOriginX(lineExtent);
float runAscent = glyphRun.getAscent();
float runDescent = glyphRun.getDescent();
float runLeading = glyphRun.getLeading();
int runCharStart = glyphRun.getCharStart();
int runCharEnd = glyphRun.getCharEnd();
int runGlyphCount = glyphRun.getGlyphCount();
float runExtent = glyphRun.computeTypographicExtent(0, runGlyphCount);
if (trailingWhitespaceStart >= runCharStart && trailingWhitespaceStart < runCharEnd) {
int whitespaceGlyphStart = glyphRun.getLeadingGlyphIndex(trailingWhitespaceStart);
int whitespaceGlyphEnd = glyphRun.getTrailingGlyphIndex(runCharEnd - 1);
float whitespaceExtent = glyphRun.computeTypographicExtent(whitespaceGlyphStart, whitespaceGlyphEnd);
trailingWhitespaceExtent += whitespaceExtent;
}
lineAscent = Math.max(lineAscent, runAscent);
lineDescent = Math.max(lineDescent, runDescent);
lineLeading = Math.max(lineLeading, runLeading);
lineExtent += runExtent;
}
return new ComposedLine(charStart, charEnd, paragraphLevel,
lineAscent, lineDescent, lineLeading, lineExtent,
trailingWhitespaceExtent, Collections.unmodifiableList(runList));
}
ComposedLine createSimpleLine(int start, int end) {
final List<GlyphRun> runList = new ArrayList<>();
mBidiParagraphs.forEachLineRun(start, end, new ParagraphCollection.RunConsumer() {
@Override
public void accept(BidiRun bidiRun) {
int visualStart = bidiRun.charStart;
int visualEnd = bidiRun.charEnd;
addVisualRuns(visualStart, visualEnd, runList);
}
});
return createComposedLine(mSpanned, start, end, runList,
mBidiParagraphs.charLevel(start));
}
ComposedLine createCompactLine(int start, int end, float extent, byte[] breaks, BreakMode mode,
TruncationPlace place, ComposedLine token) {
float tokenlessWidth = extent - token.getWidth();
switch (place) {
case START:
return createStartTruncatedLine(start, end, tokenlessWidth, breaks, mode, token);
case MIDDLE:
return createMiddleTruncatedLine(start, end, tokenlessWidth, breaks, mode, token);
case END:
return createEndTruncatedLine(start, end, tokenlessWidth, breaks, mode, token);
}
return null;
}
private class TruncationHandler implements ParagraphCollection.RunConsumer {
final int charStart;
final int charEnd;
final int skipStart;
final int skipEnd;
final List<GlyphRun> runList;
int leadingTokenIndex = -1;
int trailingTokenIndex = -1;
TruncationHandler(int charStart, int charEnd, int skipStart, int skipEnd, List<GlyphRun> runList) {
this.charStart = charStart;
this.charEnd = charEnd;
this.skipStart = skipStart;
this.skipEnd = skipEnd;
this.runList = runList;
}
@Override
public void accept(BidiRun bidiRun) {
int visualStart = bidiRun.charStart;
int visualEnd = bidiRun.charEnd;
if (bidiRun.isRightToLeft()) {
// Handle second part of characters.
if (visualEnd >= skipEnd) {
addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList);
if (visualStart < skipEnd) {
trailingTokenIndex = runList.size();
}
}
// Handle first part of characters.
if (visualStart <= skipStart) {
if (visualEnd > skipStart) {
leadingTokenIndex = runList.size();
}
addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList);
}
} else {
// Handle first part of characters.
if (visualStart <= skipStart) {
addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList);
if (visualEnd > skipStart) {
leadingTokenIndex = runList.size();
}
}
// Handle second part of characters.
if (visualEnd >= skipEnd) {
if (visualStart < skipEnd) {
trailingTokenIndex = runList.size();
}
addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList);
}
}
}
void addAllRuns() {
mBidiParagraphs.forEachLineRun(charStart, charEnd, this);
}
}
private ComposedLine createStartTruncatedLine(int start, int end, float tokenlessWidth,
byte[] breaks, BreakMode mode, ComposedLine token) {
int truncatedStart = BreakResolver.suggestBackwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, tokenlessWidth, mode);
if (truncatedStart > start) {
ArrayList<GlyphRun> runList = new ArrayList<>();
int tokenInsertIndex = 0;
if (truncatedStart < end) {
TruncationHandler truncationHandler = new TruncationHandler(start, end, start, truncatedStart, runList);
truncationHandler.addAllRuns();
tokenInsertIndex = truncationHandler.trailingTokenIndex;
}
addTokenRuns(token, runList, tokenInsertIndex);
return createComposedLine(mSpanned, truncatedStart, end, runList,
mBidiParagraphs.charLevel(truncatedStart));
}
return createSimpleLine(truncatedStart, end);
}
private ComposedLine createMiddleTruncatedLine(int start, int end, float tokenlessWidth,
byte[] breaks, BreakMode mode, ComposedLine token) {
float halfWidth = tokenlessWidth / 2.0f;
int firstMidEnd = BreakResolver.suggestForwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, halfWidth, mode);
int secondMidStart = BreakResolver.suggestBackwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, halfWidth, mode);
if (firstMidEnd < secondMidStart) {
// Exclude inner whitespaces as truncation token replaces them.
firstMidEnd = StringUtils.getTrailingWhitespaceStart(mSpanned, start, firstMidEnd);
secondMidStart = StringUtils.getLeadingWhitespaceEnd(mSpanned, secondMidStart, end);
ArrayList<GlyphRun> runList = new ArrayList<>();
int tokenInsertIndex = 0;
if (start < firstMidEnd || secondMidStart < end) {
TruncationHandler truncationHandler = new TruncationHandler(start, end, firstMidEnd, secondMidStart, runList);
truncationHandler.addAllRuns();
tokenInsertIndex = truncationHandler.leadingTokenIndex;
}
addTokenRuns(token, runList, tokenInsertIndex);
return createComposedLine(mSpanned, start, end, runList,
mBidiParagraphs.charLevel(start));
}
return createSimpleLine(start, end);
}
private ComposedLine createEndTruncatedLine(int start, int end, float tokenlessWidth,
byte[] breaks, BreakMode mode, ComposedLine token) {
int truncatedEnd = BreakResolver.suggestForwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, tokenlessWidth, mode);
if (truncatedEnd < end) {
// Exclude trailing whitespaces as truncation token replaces them.
truncatedEnd = StringUtils.getTrailingWhitespaceStart(mSpanned, start, truncatedEnd);
ArrayList<GlyphRun> runList = new ArrayList<>();
int tokenInsertIndex = 0;
if (start < truncatedEnd) {
TruncationHandler truncationHandler = new TruncationHandler(start, end, truncatedEnd, end, runList);
truncationHandler.addAllRuns();
tokenInsertIndex = truncationHandler.leadingTokenIndex;
}
addTokenRuns(token, runList, tokenInsertIndex);
return createComposedLine(mSpanned, start, truncatedEnd, runList,
mBidiParagraphs.charLevel(start));
}
return createSimpleLine(start, truncatedEnd);
}
private void addTokenRuns(ComposedLine token, List<GlyphRun> runList, int insertIndex) {
for (GlyphRun truncationRun : token.getRuns()) {
GlyphRun modifiedRun = new GlyphRun(truncationRun);
runList.add(insertIndex, modifiedRun);
insertIndex++;
}
}
private void addVisualRuns(int visualStart, int visualEnd, List<GlyphRun> runList) {
if (visualStart < visualEnd) {
// ASSUMPTIONS:
// - Visual range may fall in one or more glyph runs.
// - Consecutive intrinsic runs may have same bidi level.
int insertIndex = runList.size();
IntrinsicRun previousRun = null;
do {
int runIndex = mIntrinsicRuns.binarySearch(visualStart);
IntrinsicRun intrinsicRun = mIntrinsicRuns.get(runIndex);
int feasibleStart = Math.max(intrinsicRun.charStart, visualStart);
int feasibleEnd = Math.min(intrinsicRun.charEnd, visualEnd);
boolean forward = false;
if (previousRun != null) {
byte bidiLevel = intrinsicRun.bidiLevel;
if (bidiLevel != previousRun.bidiLevel || (bidiLevel & 1) == 0) {
insertIndex = runList.size();
forward = true;
}
}
int spanStart = feasibleStart;
while (spanStart < feasibleEnd) {
int spanEnd = mSpanned.nextSpanTransition(spanStart, feasibleEnd, Object.class);
Object[] spans = mSpanned.getSpans(spanStart, spanEnd, Object.class);
GlyphRun glyphRun = createGlyphRun(intrinsicRun, spanStart, spanEnd, spans);
runList.add(insertIndex, glyphRun);
if (forward) {
insertIndex++;
}
spanStart = spanEnd;
}
previousRun = intrinsicRun;
visualStart = feasibleEnd;
} while (visualStart != visualEnd);
}
}
}
| tehreer-android/src/main/java/com/mta/tehreer/layout/LineResolver.java | /*
* Copyright (C) 2018 Muhammad Tayyab Akram
*
* 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.mta.tehreer.layout;
import android.text.Spanned;
import com.mta.tehreer.internal.collections.SafeFloatList;
import com.mta.tehreer.internal.collections.SafeIntList;
import com.mta.tehreer.internal.collections.SafePointList;
import com.mta.tehreer.internal.layout.BreakResolver;
import com.mta.tehreer.internal.layout.ClusterMap;
import com.mta.tehreer.internal.layout.IntrinsicRun;
import com.mta.tehreer.internal.layout.ParagraphCollection;
import com.mta.tehreer.internal.layout.RunCollection;
import com.mta.tehreer.internal.util.StringUtils;
import com.mta.tehreer.unicode.BidiRun;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class LineResolver {
private Spanned mSpanned;
private ParagraphCollection mBidiParagraphs;
private RunCollection mIntrinsicRuns;
LineResolver() {
}
void reset(Spanned spanned, ParagraphCollection paragraphs, RunCollection runs) {
mSpanned = spanned;
mBidiParagraphs = paragraphs;
mIntrinsicRuns = runs;
}
static GlyphRun createGlyphRun(IntrinsicRun intrinsicRun, int charStart, int charEnd, Object[] spans) {
int glyphOffset = intrinsicRun.charGlyphStart(charStart);
int glyphCount = intrinsicRun.charGlyphEnd(charEnd - 1) - glyphOffset;
return new GlyphRun(charStart, charEnd, Arrays.asList(spans),
intrinsicRun.isBackward, intrinsicRun.bidiLevel,
intrinsicRun.typeface, intrinsicRun.typeSize, intrinsicRun.writingDirection,
new SafeIntList(intrinsicRun.glyphIds, glyphOffset, glyphCount),
new SafePointList(intrinsicRun.glyphOffsets, glyphOffset, glyphCount),
new SafeFloatList(intrinsicRun.glyphAdvances, glyphOffset, glyphCount),
new ClusterMap(intrinsicRun.clusterMap,
charStart - intrinsicRun.charStart,
charEnd - charStart, glyphOffset));
}
static ComposedLine createComposedLine(CharSequence text, int charStart, int charEnd,
List<GlyphRun> runList, byte paragraphLevel) {
float lineAscent = 0.0f;
float lineDescent = 0.0f;
float lineLeading = 0.0f;
float lineExtent = 0.0f;
int trailingWhitespaceStart = StringUtils.getTrailingWhitespaceStart(text, charStart, charEnd);
float trailingWhitespaceExtent = 0.0f;
int runCount = runList.size();
for (int i = 0; i < runCount; i++) {
GlyphRun glyphRun = runList.get(i);
glyphRun.setOriginX(lineExtent);
float runAscent = glyphRun.getAscent();
float runDescent = glyphRun.getDescent();
float runLeading = glyphRun.getLeading();
int runCharStart = glyphRun.getCharStart();
int runCharEnd = glyphRun.getCharEnd();
int runGlyphCount = glyphRun.getGlyphCount();
float runExtent = glyphRun.computeTypographicExtent(0, runGlyphCount);
if (trailingWhitespaceStart >= runCharStart && trailingWhitespaceStart < runCharEnd) {
int whitespaceGlyphStart = glyphRun.getLeadingGlyphIndex(trailingWhitespaceStart);
int whitespaceGlyphEnd = glyphRun.getTrailingGlyphIndex(runCharEnd - 1);
float whitespaceExtent = glyphRun.computeTypographicExtent(whitespaceGlyphStart, whitespaceGlyphEnd);
trailingWhitespaceExtent += whitespaceExtent;
}
lineAscent = Math.max(lineAscent, runAscent);
lineDescent = Math.max(lineDescent, runDescent);
lineLeading = Math.max(lineLeading, runLeading);
lineExtent += runExtent;
}
return new ComposedLine(charStart, charEnd, paragraphLevel,
lineAscent, lineDescent, lineLeading, lineExtent,
trailingWhitespaceExtent, Collections.unmodifiableList(runList));
}
ComposedLine createSimpleLine(int start, int end) {
final List<GlyphRun> runList = new ArrayList<>();
mBidiParagraphs.forEachLineRun(start, end, new ParagraphCollection.RunConsumer() {
@Override
public void accept(BidiRun bidiRun) {
int visualStart = bidiRun.charStart;
int visualEnd = bidiRun.charEnd;
addVisualRuns(visualStart, visualEnd, runList);
}
});
return createComposedLine(mSpanned, start, end, runList,
mBidiParagraphs.charLevel(start));
}
ComposedLine createCompactLine(int start, int end, float extent, byte[] breaks, BreakMode mode,
TruncationPlace place, ComposedLine token) {
float tokenlessWidth = extent - token.getWidth();
switch (place) {
case START:
return createStartTruncatedLine(start, end, tokenlessWidth, breaks, mode, token);
case MIDDLE:
return createMiddleTruncatedLine(start, end, tokenlessWidth, breaks, mode, token);
case END:
return createEndTruncatedLine(start, end, tokenlessWidth, breaks, mode, token);
}
return null;
}
private class TruncationHandler implements ParagraphCollection.RunConsumer {
final int charStart;
final int charEnd;
final int skipStart;
final int skipEnd;
final List<GlyphRun> runList;
int leadingTokenIndex = -1;
int trailingTokenIndex = -1;
TruncationHandler(int charStart, int charEnd, int skipStart, int skipEnd, List<GlyphRun> runList) {
this.charStart = charStart;
this.charEnd = charEnd;
this.skipStart = skipStart;
this.skipEnd = skipEnd;
this.runList = runList;
}
@Override
public void accept(BidiRun bidiRun) {
int visualStart = bidiRun.charStart;
int visualEnd = bidiRun.charEnd;
if (bidiRun.isRightToLeft()) {
// Handle second part of characters.
if (visualEnd >= skipEnd) {
addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList);
if (visualStart < skipEnd) {
trailingTokenIndex = runList.size();
}
}
// Handle first part of characters.
if (visualStart <= skipStart) {
if (visualEnd > skipStart) {
leadingTokenIndex = runList.size();
}
addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList);
}
} else {
// Handle first part of characters.
if (visualStart <= skipStart) {
addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList);
if (visualEnd > skipStart) {
leadingTokenIndex = runList.size();
}
}
// Handle second part of characters.
if (visualEnd >= skipEnd) {
if (visualStart < skipEnd) {
trailingTokenIndex = runList.size();
}
addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList);
}
}
}
void addAllRuns() {
mBidiParagraphs.forEachLineRun(charStart, charEnd, this);
}
}
private ComposedLine createStartTruncatedLine(int start, int end, float tokenlessWidth,
byte[] breaks, BreakMode mode, ComposedLine token) {
int truncatedStart = BreakResolver.suggestBackwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, tokenlessWidth, mode);
if (truncatedStart > start) {
ArrayList<GlyphRun> runList = new ArrayList<>();
int tokenInsertIndex = 0;
if (truncatedStart < end) {
TruncationHandler truncationHandler = new TruncationHandler(start, end, start, truncatedStart, runList);
truncationHandler.addAllRuns();
tokenInsertIndex = truncationHandler.trailingTokenIndex;
}
addTokenRuns(token, runList, tokenInsertIndex);
return createComposedLine(mSpanned, truncatedStart, end, runList,
mBidiParagraphs.charLevel(truncatedStart));
}
return createSimpleLine(truncatedStart, end);
}
private ComposedLine createMiddleTruncatedLine(int start, int end, float tokenlessWidth,
byte[] breaks, BreakMode mode, ComposedLine token) {
float halfWidth = tokenlessWidth / 2.0f;
int firstMidEnd = BreakResolver.suggestForwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, halfWidth, mode);
int secondMidStart = BreakResolver.suggestBackwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, halfWidth, mode);
if (firstMidEnd < secondMidStart) {
// Exclude inner whitespaces as truncation token replaces them.
firstMidEnd = StringUtils.getTrailingWhitespaceStart(mSpanned, start, firstMidEnd);
secondMidStart = StringUtils.getLeadingWhitespaceEnd(mSpanned, secondMidStart, end);
ArrayList<GlyphRun> runList = new ArrayList<>();
int tokenInsertIndex = 0;
if (start < firstMidEnd || secondMidStart < end) {
TruncationHandler truncationHandler = new TruncationHandler(start, end, firstMidEnd, secondMidStart, runList);
truncationHandler.addAllRuns();
tokenInsertIndex = truncationHandler.leadingTokenIndex;
}
addTokenRuns(token, runList, tokenInsertIndex);
return createComposedLine(mSpanned, start, end, runList,
mBidiParagraphs.charLevel(start));
}
return createSimpleLine(start, end);
}
private ComposedLine createEndTruncatedLine(int start, int end, float tokenlessWidth,
byte[] breaks, BreakMode mode, ComposedLine token) {
int truncatedEnd = BreakResolver.suggestForwardBreak(mSpanned, mIntrinsicRuns, breaks, start, end, tokenlessWidth, mode);
if (truncatedEnd < end) {
// Exclude trailing whitespaces as truncation token replaces them.
truncatedEnd = StringUtils.getTrailingWhitespaceStart(mSpanned, start, truncatedEnd);
ArrayList<GlyphRun> runList = new ArrayList<>();
int tokenInsertIndex = 0;
if (start < truncatedEnd) {
TruncationHandler truncationHandler = new TruncationHandler(start, end, truncatedEnd, end, runList);
truncationHandler.addAllRuns();
tokenInsertIndex = truncationHandler.leadingTokenIndex;
}
addTokenRuns(token, runList, tokenInsertIndex);
return createComposedLine(mSpanned, start, truncatedEnd, runList,
mBidiParagraphs.charLevel(start));
}
return createSimpleLine(start, truncatedEnd);
}
private void addTokenRuns(ComposedLine token, List<GlyphRun> runList, int insertIndex) {
for (GlyphRun truncationRun : token.getRuns()) {
GlyphRun modifiedRun = new GlyphRun(truncationRun);
runList.add(insertIndex, modifiedRun);
insertIndex++;
}
}
private void addVisualRuns(int visualStart, int visualEnd, List<GlyphRun> runList) {
if (visualStart < visualEnd) {
// ASSUMPTIONS:
// - Visual range may fall in one or more glyph runs.
// - Consecutive intrinsic runs may have same bidi level.
int insertIndex = runList.size();
IntrinsicRun previousRun = null;
do {
int runIndex = mIntrinsicRuns.binarySearch(visualStart);
IntrinsicRun intrinsicRun = mIntrinsicRuns.get(runIndex);
int feasibleStart = Math.max(intrinsicRun.charStart, visualStart);
int feasibleEnd = Math.min(intrinsicRun.charEnd, visualEnd);
boolean forward = false;
if (previousRun != null) {
byte bidiLevel = intrinsicRun.bidiLevel;
if (bidiLevel != previousRun.bidiLevel || (bidiLevel & 1) == 0) {
insertIndex = runList.size();
forward = true;
}
}
int spanStart = feasibleStart;
while (spanStart < feasibleEnd) {
int spanEnd = mSpanned.nextSpanTransition(spanStart, feasibleEnd, Object.class);
Object[] spans = mSpanned.getSpans(spanStart, spanEnd, Object.class);
GlyphRun glyphRun = createGlyphRun(intrinsicRun, spanStart, spanEnd, spans);
runList.add(insertIndex, glyphRun);
if (forward) {
insertIndex++;
}
spanStart = spanEnd;
}
previousRun = intrinsicRun;
visualStart = feasibleEnd;
} while (visualStart != visualEnd);
}
}
}
| [lib] Provided metrics to glyph run in line resolver...
| tehreer-android/src/main/java/com/mta/tehreer/layout/LineResolver.java | [lib] Provided metrics to glyph run in line resolver... | <ide><path>ehreer-android/src/main/java/com/mta/tehreer/layout/LineResolver.java
<ide>
<ide> return new GlyphRun(charStart, charEnd, Arrays.asList(spans),
<ide> intrinsicRun.isBackward, intrinsicRun.bidiLevel,
<del> intrinsicRun.typeface, intrinsicRun.typeSize, intrinsicRun.writingDirection,
<add> intrinsicRun.writingDirection, intrinsicRun.typeface, intrinsicRun.typeSize,
<add> intrinsicRun.ascent, intrinsicRun.descent, intrinsicRun.leading,
<ide> new SafeIntList(intrinsicRun.glyphIds, glyphOffset, glyphCount),
<ide> new SafePointList(intrinsicRun.glyphOffsets, glyphOffset, glyphCount),
<ide> new SafeFloatList(intrinsicRun.glyphAdvances, glyphOffset, glyphCount), |
|
Java | mit | error: pathspec 'src/com/javaquery/core/immutable/ImmutableClassLatLon.java' did not match any file(s) known to git
| d79a127c1f077a55e686da2581c52fb531ee3ecd | 1 | javaquery/Examples | package com.javaquery.core.immutable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Example of Immutable class in java.
* @author javaQuery
* @date 2019-12-10
* @Github: https://github.com/javaquery/Examples
*/
public final class ImmutableClassLatLon {
private final double latitude;
private final double longitude;
private final List<String> labels;
/**
* @param latitude
* @param longitude
* @param labels
*/
public ImmutableClassLatLon(double latitude, double longitude, List<String> labels) {
this.latitude = latitude;
this.longitude = longitude;
if(labels != null && !labels.isEmpty()){
this.labels = new ArrayList<>(labels);
}else{
this.labels = null;
}
}
/**
* Will return new copy of List rather returning reference to current list.
* @return
*/
public List<String> getLabels() {
return labels != null ? new ArrayList<>(labels) : null;
}
/**
* Get new object of ImmutableClassLatLon with updated label.
* @param label
* @return ImmutableClassLatLon
*/
public ImmutableClassLatLon addLabel(String label){
List<String> temporary = new ArrayList<>();
if(labels != null && !labels.isEmpty()){
temporary.addAll(labels);
}
temporary.add(label);
return new ImmutableClassLatLon(latitude, longitude, temporary);
}
public static void main(String[] args) {
ImmutableClassLatLon classLatLon = new ImmutableClassLatLon(23.0225, 72.5714, Arrays.asList("India"));
System.out.println("classLatLon address: " + classLatLon);
System.out.println("\n- classLatLon getLabels and add label -");
System.out.println("classLatLon labels before: " + classLatLon.getLabels());
/* classLatLon.getLabels() will return new copy of List rather returning reference to current list */
List<String> localLables = classLatLon.getLabels();
localLables.add("Hindi");
System.out.println("localLables: " + localLables);
System.out.println("classLatLon labels after: " + classLatLon.getLabels());
System.out.println("\n- add new label to classLatLon -");
System.out.println("classLatLon add label before: " + classLatLon.getLabels());
/* When new label is added it will return new object of ImmutableClassLatLon rather updating current object's list */
ImmutableClassLatLon classLatLonNewLabel = classLatLon.addLabel("Asia");
System.out.println("classLatLon add label after: " + classLatLon.getLabels());
System.out.println("classLatLonNewLabel address: " + classLatLonNewLabel);
System.out.println("classLatLonNewLabel labels: " + classLatLonNewLabel.getLabels());
}
}
| src/com/javaquery/core/immutable/ImmutableClassLatLon.java | immutable class example
| src/com/javaquery/core/immutable/ImmutableClassLatLon.java | immutable class example | <ide><path>rc/com/javaquery/core/immutable/ImmutableClassLatLon.java
<add>package com.javaquery.core.immutable;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>
<add>/**
<add> * Example of Immutable class in java.
<add> * @author javaQuery
<add> * @date 2019-12-10
<add> * @Github: https://github.com/javaquery/Examples
<add> */
<add>public final class ImmutableClassLatLon {
<add> private final double latitude;
<add> private final double longitude;
<add> private final List<String> labels;
<add>
<add> /**
<add> * @param latitude
<add> * @param longitude
<add> * @param labels
<add> */
<add> public ImmutableClassLatLon(double latitude, double longitude, List<String> labels) {
<add> this.latitude = latitude;
<add> this.longitude = longitude;
<add> if(labels != null && !labels.isEmpty()){
<add> this.labels = new ArrayList<>(labels);
<add> }else{
<add> this.labels = null;
<add> }
<add> }
<add>
<add> /**
<add> * Will return new copy of List rather returning reference to current list.
<add> * @return
<add> */
<add> public List<String> getLabels() {
<add> return labels != null ? new ArrayList<>(labels) : null;
<add> }
<add>
<add> /**
<add> * Get new object of ImmutableClassLatLon with updated label.
<add> * @param label
<add> * @return ImmutableClassLatLon
<add> */
<add> public ImmutableClassLatLon addLabel(String label){
<add> List<String> temporary = new ArrayList<>();
<add> if(labels != null && !labels.isEmpty()){
<add> temporary.addAll(labels);
<add> }
<add> temporary.add(label);
<add> return new ImmutableClassLatLon(latitude, longitude, temporary);
<add> }
<add>
<add> public static void main(String[] args) {
<add> ImmutableClassLatLon classLatLon = new ImmutableClassLatLon(23.0225, 72.5714, Arrays.asList("India"));
<add> System.out.println("classLatLon address: " + classLatLon);
<add>
<add> System.out.println("\n- classLatLon getLabels and add label -");
<add> System.out.println("classLatLon labels before: " + classLatLon.getLabels());
<add> /* classLatLon.getLabels() will return new copy of List rather returning reference to current list */
<add> List<String> localLables = classLatLon.getLabels();
<add> localLables.add("Hindi");
<add> System.out.println("localLables: " + localLables);
<add> System.out.println("classLatLon labels after: " + classLatLon.getLabels());
<add>
<add> System.out.println("\n- add new label to classLatLon -");
<add> System.out.println("classLatLon add label before: " + classLatLon.getLabels());
<add> /* When new label is added it will return new object of ImmutableClassLatLon rather updating current object's list */
<add> ImmutableClassLatLon classLatLonNewLabel = classLatLon.addLabel("Asia");
<add> System.out.println("classLatLon add label after: " + classLatLon.getLabels());
<add> System.out.println("classLatLonNewLabel address: " + classLatLonNewLabel);
<add> System.out.println("classLatLonNewLabel labels: " + classLatLonNewLabel.getLabels());
<add>
<add> }
<add>} |
|
Java | bsd-3-clause | e314755cc3311d8fca5fd1bb758f61ec6f40165f | 0 | wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy | /*
* Copyright (c) 2012, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.loop;
import java.util.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.Graph.DuplicationReplacement;
import com.oracle.graal.graph.iterators.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.PhiNode.PhiType;
import com.oracle.graal.nodes.VirtualState.NodeClosure;
import com.oracle.graal.nodes.VirtualState.VirtualClosure;
import com.oracle.graal.nodes.cfg.*;
public abstract class LoopFragment {
private final LoopEx loop;
private final LoopFragment original;
protected NodeBitMap nodes;
protected boolean nodesReady;
private Map<Node, Node> duplicationMap;
public LoopFragment(LoopEx loop) {
this(loop, null);
this.nodesReady = true;
}
public LoopFragment(LoopEx loop, LoopFragment original) {
this.loop = loop;
this.original = original;
this.nodesReady = false;
}
public LoopEx loop() {
return loop;
}
public abstract LoopFragment duplicate();
public abstract void insertBefore(LoopEx l);
public void disconnect() {
// TODO (gd) possibly abstract
}
public boolean contains(Node n) {
return nodes().contains(n);
}
@SuppressWarnings("unchecked")
public <New extends Node, Old extends New> New getDuplicatedNode(Old n) {
assert isDuplicate();
return (New) duplicationMap.get(n);
}
protected <New extends Node, Old extends New> void putDuplicatedNode(Old oldNode, New newNode) {
duplicationMap.put(oldNode, newNode);
}
public boolean isDuplicate() {
return original != null;
}
public LoopFragment original() {
return original;
}
public abstract NodeIterable<Node> nodes();
public StructuredGraph graph() {
LoopEx l;
if (isDuplicate()) {
l = original().loop();
} else {
l = loop();
}
return l.loopBegin().graph();
}
protected abstract DuplicationReplacement getDuplicationReplacement();
protected abstract void finishDuplication();
protected void patchNodes(final DuplicationReplacement dataFix) {
if (isDuplicate() && !nodesReady) {
assert !original.isDuplicate();
final DuplicationReplacement cfgFix = original().getDuplicationReplacement();
DuplicationReplacement dr;
if (cfgFix == null && dataFix != null) {
dr = dataFix;
} else if (cfgFix != null && dataFix == null) {
dr = cfgFix;
} else if (cfgFix != null && dataFix != null) {
dr = new DuplicationReplacement() {
@Override
public Node replacement(Node o) {
Node r1 = dataFix.replacement(o);
if (r1 != o) {
assert cfgFix.replacement(o) == o;
return r1;
}
Node r2 = cfgFix.replacement(o);
if (r2 != o) {
return r2;
}
return o;
}
};
} else {
dr = new DuplicationReplacement() {
@Override
public Node replacement(Node o) {
return o;
}
};
}
duplicationMap = graph().addDuplicates(original().nodes(), dr);
finishDuplication();
nodesReady = true;
} else {
// TODO (gd) apply fix ?
}
}
protected static NodeBitMap computeNodes(Graph graph, Iterable<AbstractBeginNode> blocks) {
return computeNodes(graph, blocks, Collections.<AbstractBeginNode> emptyList());
}
protected static NodeBitMap computeNodes(Graph graph, Iterable<AbstractBeginNode> blocks, Iterable<AbstractBeginNode> earlyExits) {
final NodeBitMap nodes = graph.createNodeBitMap(true);
for (AbstractBeginNode b : blocks) {
for (Node n : b.getBlockNodes()) {
if (n instanceof Invoke) {
nodes.mark(((Invoke) n).callTarget());
}
if (n instanceof StateSplit) {
FrameState stateAfter = ((StateSplit) n).stateAfter();
if (stateAfter != null) {
nodes.mark(stateAfter);
}
}
nodes.mark(n);
}
}
for (AbstractBeginNode earlyExit : earlyExits) {
FrameState stateAfter = earlyExit.stateAfter();
if (stateAfter != null) {
nodes.mark(stateAfter);
stateAfter.applyToVirtual(new VirtualClosure() {
@Override
public void apply(VirtualState node) {
nodes.mark(node);
}
});
}
nodes.mark(earlyExit);
for (ProxyNode proxy : earlyExit.proxies()) {
nodes.mark(proxy);
}
}
final NodeBitMap notloopNodes = graph.createNodeBitMap(true);
for (AbstractBeginNode b : blocks) {
for (Node n : b.getBlockNodes()) {
for (Node usage : n.usages()) {
markFloating(usage, nodes, notloopNodes);
}
}
}
return nodes;
}
private static boolean markFloating(Node n, NodeBitMap loopNodes, NodeBitMap notloopNodes) {
if (loopNodes.isMarked(n)) {
return true;
}
if (notloopNodes.isMarked(n)) {
return false;
}
if (n instanceof FixedNode) {
return false;
}
boolean mark = false;
if (n instanceof PhiNode) {
PhiNode phi = (PhiNode) n;
mark = loopNodes.isMarked(phi.merge());
if (mark) {
loopNodes.mark(n);
} else {
notloopNodes.mark(n);
return false;
}
}
for (Node usage : n.usages()) {
if (markFloating(usage, loopNodes, notloopNodes)) {
mark = true;
}
}
if (mark) {
loopNodes.mark(n);
return true;
}
notloopNodes.mark(n);
return false;
}
public static NodeIterable<AbstractBeginNode> toHirBlocks(final Iterable<Block> blocks) {
return new AbstractNodeIterable<AbstractBeginNode>() {
public Iterator<AbstractBeginNode> iterator() {
final Iterator<Block> it = blocks.iterator();
return new Iterator<AbstractBeginNode>() {
public void remove() {
throw new UnsupportedOperationException();
}
public AbstractBeginNode next() {
return it.next().getBeginNode();
}
public boolean hasNext() {
return it.hasNext();
}
};
}
};
}
/**
* Merges the early exits (i.e. loop exits) that were duplicated as part of this fragment, with
* the original fragment's exits.
*/
protected void mergeEarlyExits() {
assert isDuplicate();
StructuredGraph graph = graph();
for (AbstractBeginNode earlyExit : LoopFragment.toHirBlocks(original().loop().lirLoop().exits)) {
FixedNode next = earlyExit.next();
if (earlyExit.isDeleted() || !this.original().contains(earlyExit)) {
continue;
}
AbstractBeginNode newEarlyExit = getDuplicatedNode(earlyExit);
if (newEarlyExit == null) {
continue;
}
MergeNode merge = graph.add(new MergeNode());
AbstractEndNode originalEnd = graph.add(new EndNode());
AbstractEndNode newEnd = graph.add(new EndNode());
merge.addForwardEnd(originalEnd);
merge.addForwardEnd(newEnd);
earlyExit.setNext(originalEnd);
newEarlyExit.setNext(newEnd);
merge.setNext(next);
FrameState exitState = earlyExit.stateAfter();
FrameState state = null;
if (exitState != null) {
state = exitState;
exitState = exitState.duplicateWithVirtualState();
earlyExit.setStateAfter(exitState);
merge.setStateAfter(state);
}
for (Node anchored : earlyExit.anchored().snapshot()) {
anchored.replaceFirstInput(earlyExit, merge);
}
for (final ProxyNode vpn : earlyExit.proxies().snapshot()) {
final ValueNode replaceWith;
ProxyNode newVpn = getDuplicatedNode(vpn);
if (newVpn != null) {
PhiNode phi = graph.add(vpn.type() == PhiType.Value ? new PhiNode(vpn.kind(), merge) : new PhiNode(vpn.type(), merge, vpn.getIdentity()));
phi.addInput(vpn);
phi.addInput(newVpn);
replaceWith = phi;
} else {
replaceWith = vpn.value();
}
if (state != null) {
state.applyToNonVirtual(new NodeClosure<ValueNode>() {
@Override
public void apply(Node from, ValueNode node) {
if (node == vpn) {
from.replaceFirstInput(vpn, replaceWith);
}
}
});
}
for (Node usage : vpn.usages().snapshot()) {
if (!merge.isPhiAtMerge(usage)) {
if (usage instanceof VirtualState) {
VirtualState stateUsage = (VirtualState) usage;
if (exitState.isPartOfThisState(stateUsage)) {
continue;
}
}
usage.replaceFirstInput(vpn, replaceWith);
}
}
}
}
}
}
| graal/com.oracle.graal.loop/src/com/oracle/graal/loop/LoopFragment.java | /*
* Copyright (c) 2012, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.loop;
import java.util.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.Graph.DuplicationReplacement;
import com.oracle.graal.graph.iterators.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.PhiNode.PhiType;
import com.oracle.graal.nodes.VirtualState.NodeClosure;
import com.oracle.graal.nodes.VirtualState.VirtualClosure;
import com.oracle.graal.nodes.cfg.*;
public abstract class LoopFragment {
private final LoopEx loop;
private final LoopFragment original;
protected NodeBitMap nodes;
protected boolean nodesReady;
private Map<Node, Node> duplicationMap;
public LoopFragment(LoopEx loop) {
this(loop, null);
this.nodesReady = true;
}
public LoopFragment(LoopEx loop, LoopFragment original) {
this.loop = loop;
this.original = original;
this.nodesReady = false;
}
public LoopEx loop() {
return loop;
}
public abstract LoopFragment duplicate();
public abstract void insertBefore(LoopEx l);
public void disconnect() {
// TODO (gd) possibly abstract
}
public boolean contains(Node n) {
return nodes().contains(n);
}
@SuppressWarnings("unchecked")
public <New extends Node, Old extends New> New getDuplicatedNode(Old n) {
assert isDuplicate();
return (New) duplicationMap.get(n);
}
protected <New extends Node, Old extends New> void putDuplicatedNode(Old oldNode, New newNode) {
duplicationMap.put(oldNode, newNode);
}
public boolean isDuplicate() {
return original != null;
}
public LoopFragment original() {
return original;
}
public abstract NodeIterable<Node> nodes();
public StructuredGraph graph() {
LoopEx l;
if (isDuplicate()) {
l = original().loop();
} else {
l = loop();
}
return l.loopBegin().graph();
}
protected abstract DuplicationReplacement getDuplicationReplacement();
protected abstract void finishDuplication();
protected void patchNodes(final DuplicationReplacement dataFix) {
if (isDuplicate() && !nodesReady) {
assert !original.isDuplicate();
final DuplicationReplacement cfgFix = original().getDuplicationReplacement();
DuplicationReplacement dr;
if (cfgFix == null && dataFix != null) {
dr = dataFix;
} else if (cfgFix != null && dataFix == null) {
dr = cfgFix;
} else if (cfgFix != null && dataFix != null) {
dr = new DuplicationReplacement() {
@Override
public Node replacement(Node o) {
Node r1 = dataFix.replacement(o);
if (r1 != o) {
assert cfgFix.replacement(o) == o;
return r1;
}
Node r2 = cfgFix.replacement(o);
if (r2 != o) {
return r2;
}
return o;
}
};
} else {
dr = new DuplicationReplacement() {
@Override
public Node replacement(Node o) {
return o;
}
};
}
duplicationMap = graph().addDuplicates(original().nodes(), dr);
finishDuplication();
nodesReady = true;
} else {
// TODO (gd) apply fix ?
}
}
protected static NodeBitMap computeNodes(Graph graph, Collection<AbstractBeginNode> blocks) {
return computeNodes(graph, blocks, Collections.<AbstractBeginNode> emptyList());
}
protected static NodeBitMap computeNodes(Graph graph, Collection<AbstractBeginNode> blocks, Collection<AbstractBeginNode> earlyExits) {
final NodeBitMap nodes = graph.createNodeBitMap(true);
for (AbstractBeginNode b : blocks) {
for (Node n : b.getBlockNodes()) {
if (n instanceof Invoke) {
nodes.mark(((Invoke) n).callTarget());
}
if (n instanceof StateSplit) {
FrameState stateAfter = ((StateSplit) n).stateAfter();
if (stateAfter != null) {
nodes.mark(stateAfter);
}
}
nodes.mark(n);
}
}
for (AbstractBeginNode earlyExit : earlyExits) {
FrameState stateAfter = earlyExit.stateAfter();
if (stateAfter != null) {
nodes.mark(stateAfter);
stateAfter.applyToVirtual(new VirtualClosure() {
@Override
public void apply(VirtualState node) {
nodes.mark(node);
}
});
}
nodes.mark(earlyExit);
for (ProxyNode proxy : earlyExit.proxies()) {
nodes.mark(proxy);
}
}
final NodeBitMap notloopNodes = graph.createNodeBitMap(true);
for (AbstractBeginNode b : blocks) {
for (Node n : b.getBlockNodes()) {
for (Node usage : n.usages()) {
markFloating(usage, nodes, notloopNodes);
}
}
}
return nodes;
}
private static boolean markFloating(Node n, NodeBitMap loopNodes, NodeBitMap notloopNodes) {
if (loopNodes.isMarked(n)) {
return true;
}
if (notloopNodes.isMarked(n)) {
return false;
}
if (n instanceof FixedNode) {
return false;
}
boolean mark = false;
if (n instanceof PhiNode) {
PhiNode phi = (PhiNode) n;
mark = loopNodes.isMarked(phi.merge());
if (mark) {
loopNodes.mark(n);
} else {
notloopNodes.mark(n);
return false;
}
}
for (Node usage : n.usages()) {
if (markFloating(usage, loopNodes, notloopNodes)) {
mark = true;
}
}
if (mark) {
loopNodes.mark(n);
return true;
}
notloopNodes.mark(n);
return false;
}
public static Collection<AbstractBeginNode> toHirBlocks(Collection<Block> blocks) {
List<AbstractBeginNode> hir = new ArrayList<>(blocks.size());
for (Block b : blocks) {
hir.add(b.getBeginNode());
}
return hir;
}
/**
* Merges the early exits (i.e. loop exits) that were duplicated as part of this fragment, with
* the original fragment's exits.
*/
protected void mergeEarlyExits() {
assert isDuplicate();
StructuredGraph graph = graph();
for (AbstractBeginNode earlyExit : LoopFragment.toHirBlocks(original().loop().lirLoop().exits)) {
FixedNode next = earlyExit.next();
if (earlyExit.isDeleted() || !this.original().contains(earlyExit)) {
continue;
}
AbstractBeginNode newEarlyExit = getDuplicatedNode(earlyExit);
if (newEarlyExit == null) {
continue;
}
MergeNode merge = graph.add(new MergeNode());
AbstractEndNode originalEnd = graph.add(new EndNode());
AbstractEndNode newEnd = graph.add(new EndNode());
merge.addForwardEnd(originalEnd);
merge.addForwardEnd(newEnd);
earlyExit.setNext(originalEnd);
newEarlyExit.setNext(newEnd);
merge.setNext(next);
FrameState exitState = earlyExit.stateAfter();
FrameState state = null;
if (exitState != null) {
state = exitState;
exitState = exitState.duplicateWithVirtualState();
earlyExit.setStateAfter(exitState);
merge.setStateAfter(state);
}
for (Node anchored : earlyExit.anchored().snapshot()) {
anchored.replaceFirstInput(earlyExit, merge);
}
for (final ProxyNode vpn : earlyExit.proxies().snapshot()) {
final ValueNode replaceWith;
ProxyNode newVpn = getDuplicatedNode(vpn);
if (newVpn != null) {
PhiNode phi = graph.add(vpn.type() == PhiType.Value ? new PhiNode(vpn.kind(), merge) : new PhiNode(vpn.type(), merge, vpn.getIdentity()));
phi.addInput(vpn);
phi.addInput(newVpn);
replaceWith = phi;
} else {
replaceWith = vpn.value();
}
if (state != null) {
state.applyToNonVirtual(new NodeClosure<ValueNode>() {
@Override
public void apply(Node from, ValueNode node) {
if (node == vpn) {
from.replaceFirstInput(vpn, replaceWith);
}
}
});
}
for (Node usage : vpn.usages().snapshot()) {
if (!merge.isPhiAtMerge(usage)) {
if (usage instanceof VirtualState) {
VirtualState stateUsage = (VirtualState) usage;
if (exitState.isPartOfThisState(stateUsage)) {
continue;
}
}
usage.replaceFirstInput(vpn, replaceWith);
}
}
}
}
}
}
| use iterable for LoopFragment.toHirBlocks rather than reify collections
| graal/com.oracle.graal.loop/src/com/oracle/graal/loop/LoopFragment.java | use iterable for LoopFragment.toHirBlocks rather than reify collections | <ide><path>raal/com.oracle.graal.loop/src/com/oracle/graal/loop/LoopFragment.java
<ide> }
<ide> }
<ide>
<del> protected static NodeBitMap computeNodes(Graph graph, Collection<AbstractBeginNode> blocks) {
<add> protected static NodeBitMap computeNodes(Graph graph, Iterable<AbstractBeginNode> blocks) {
<ide> return computeNodes(graph, blocks, Collections.<AbstractBeginNode> emptyList());
<ide> }
<ide>
<del> protected static NodeBitMap computeNodes(Graph graph, Collection<AbstractBeginNode> blocks, Collection<AbstractBeginNode> earlyExits) {
<add> protected static NodeBitMap computeNodes(Graph graph, Iterable<AbstractBeginNode> blocks, Iterable<AbstractBeginNode> earlyExits) {
<ide> final NodeBitMap nodes = graph.createNodeBitMap(true);
<ide> for (AbstractBeginNode b : blocks) {
<ide> for (Node n : b.getBlockNodes()) {
<ide> return false;
<ide> }
<ide>
<del> public static Collection<AbstractBeginNode> toHirBlocks(Collection<Block> blocks) {
<del> List<AbstractBeginNode> hir = new ArrayList<>(blocks.size());
<del> for (Block b : blocks) {
<del> hir.add(b.getBeginNode());
<del> }
<del> return hir;
<add> public static NodeIterable<AbstractBeginNode> toHirBlocks(final Iterable<Block> blocks) {
<add> return new AbstractNodeIterable<AbstractBeginNode>() {
<add>
<add> public Iterator<AbstractBeginNode> iterator() {
<add> final Iterator<Block> it = blocks.iterator();
<add> return new Iterator<AbstractBeginNode>() {
<add>
<add> public void remove() {
<add> throw new UnsupportedOperationException();
<add> }
<add>
<add> public AbstractBeginNode next() {
<add> return it.next().getBeginNode();
<add> }
<add>
<add> public boolean hasNext() {
<add> return it.hasNext();
<add> }
<add> };
<add> }
<add>
<add> };
<ide> }
<ide>
<ide> /** |
|
Java | lgpl-2.1 | 894ac11171db15d730cae35545532ec55aea5d62 | 0 | nattaku/MineChem,pixlepix/MineChem,nattaku/MineChem | package ljdp.minechem.client;
import java.util.EnumSet;
import java.util.List;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.PotionInjector;
import ljdp.minechem.common.utils.ConstantValue;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraft.client.gui.Gui;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
// Thanks to thepers for teaching me rendering - Mandrake
public class TickHandler implements ITickHandler {
public void transmuteWaterToPortal(World world, int dx, int dy, int dz) {
int px = dx;
int pz = dz;
if (world.getBlockMaterial(px - 1, dy, pz) == Material.water) {
px--;
}
if (world.getBlockMaterial(px, dy, pz - 1) == Material.water) {
pz--;
}
world.setBlock(px + 0, dy, pz + 0, 1, 0, 2);
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
Minecraft mc = FMLClientHandler.instance().getClient();
if (mc.isSingleplayer()) {
EntityPlayer player = mc.thePlayer;
World world = mc.theWorld; // GuiIngame
if (player != null) {
if (world != null) {
}
double rangeToCheck = 32.0D;
List<EntityItem> itemList = world.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.expand(rangeToCheck, rangeToCheck, rangeToCheck));
for (EntityItem entityItem : itemList) {
if ((entityItem.getEntityItem().itemID == new ItemStack(MinechemItems.element, 1, EnumMolecule.potassiumNitrate.ordinal()).itemID && (world.isMaterialInBB(entityItem.boundingBox, Material.water)))) {
world.createExplosion(entityItem, entityItem.posX, entityItem.posY, entityItem.posZ, 0.9F, true);
int dx = MathHelper.floor_double(entityItem.posX);
int dy = MathHelper.floor_double(entityItem.posY);
int dz = MathHelper.floor_double(entityItem.posZ);
transmuteWaterToPortal(world, dx, dy, dz);
return;
}
}
}
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
}
public static void renderEffects() {
Minecraft mc = FMLClientHandler.instance().getClient();
if (mc.isSingleplayer()) {
EntityPlayer player = mc.thePlayer;
if (player instanceof EntityPlayer && player.isPotionActive(PotionInjector.atropineHigh)) {
PotionEffect DHigh = player.getActivePotionEffect(PotionInjector.atropineHigh);
int Multiplier = DHigh.getAmplifier();
if (Multiplier == 1 ){
RenderDelirium(10);}
else if (Multiplier == 2 ){
RenderDelirium(15);
}
else if (Multiplier == 3){
RenderDelirium(20);
}
else if (Multiplier == 4){
RenderDelirium(25);
}
else {
}
}
}
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.RENDER, TickType.CLIENT);
}
@Override
public String getLabel() {
return null;
}
/*
* // this is all unused code for a WIP gas system private void
* renderOverlays(float parialTickTime) { Minecraft mc =
* FMLClientHandler.instance().getClient(); if (mc.renderViewEntity != null
* && mc.gameSettings.thirdPersonView == 0 &&
* !mc.renderViewEntity.isPlayerSleeping() &&
* mc.thePlayer.isInsideOfMaterial(MinechemBlocks.materialGas)) {
* renderWarpedTextureOverlay(mc, new
* ResourceLocation(ConstantValue.MOD_ID,"/misc/water.png")); } }
*
*
* // Renders a texture that warps around based on the direction the player
* is looking. Texture needs to be bound before being called. Used for the
* water // overlay. Args: parialTickTime
*
* private void renderWarpedTextureOverlay(Minecraft mc, ResourceLocation
* texture) { int overlayTexture =
* mc.renderEngine.func_110581_b(texture).func_110552_b(); double tile =
* 4.0F; double yaw = -mc.thePlayer.rotationYaw / 64.0F; double pitch =
* mc.thePlayer.rotationPitch / 64.0F; double left = 0; double top = 0;
* double right = mc.displayWidth; double bot = mc.displayHeight; double z =
* -1; Tessellator ts = Tessellator.instance;
*
* GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.9F);
* GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND);
* GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
* GL11.glBindTexture(GL11.GL_TEXTURE_2D, overlayTexture);
* GL11.glPushMatrix();
*
* ts.startDrawingQuads(); ts.addVertexWithUV(left, bot, z, tile + yaw, tile
* + pitch); ts.addVertexWithUV(right, bot, z, yaw, tile + pitch);
* ts.addVertexWithUV(right, top, z, yaw, pitch); ts.addVertexWithUV(left,
* top, z, tile + yaw, pitch); ts.draw();
*
* GL11.glPopMatrix(); GL11.glDisable(GL11.GL_BLEND);
* GL11.glEnable(GL11.GL_ALPHA_TEST); }
*/
public static void RenderDelirium(int markiplier) {
ScaledResolution scale = new ScaledResolution(Minecraft.getMinecraft().gameSettings, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight);
int width = scale.getScaledWidth();
int height = scale.getScaledHeight();
Gui gui = new Gui();
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_ALPHA_TEST);
int color = (int) (220.0F * markiplier - 150) << 24 | 1052704;
gui.drawRect(0, 0, width, height, color);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
}
| src/ljdp/minechem/client/TickHandler.java | package ljdp.minechem.client;
import java.util.EnumSet;
import java.util.List;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.PotionInjector;
import ljdp.minechem.common.utils.ConstantValue;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraft.client.gui.Gui;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
// Thanks to thepers for teaching me rendering - Mandrake
public class TickHandler implements ITickHandler {
public void transmuteWaterToPortal(World world, int dx, int dy, int dz) {
int px = dx;
int pz = dz;
if (world.getBlockMaterial(px - 1, dy, pz) == Material.water) {
px--;
}
if (world.getBlockMaterial(px, dy, pz - 1) == Material.water) {
pz--;
}
world.setBlock(px + 0, dy, pz + 0, 1, 0, 2);
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
Minecraft mc = FMLClientHandler.instance().getClient();
if (mc.isSingleplayer()) {
EntityPlayer player = mc.thePlayer;
World world = mc.theWorld; // GuiIngame
if (player != null) {
if (world != null) {
}
double rangeToCheck = 32.0D;
List<EntityItem> itemList = world.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.expand(rangeToCheck, rangeToCheck, rangeToCheck));
for (EntityItem entityItem : itemList) {
if ((entityItem.getEntityItem().itemID == new ItemStack(MinechemItems.element, 1, EnumMolecule.potassiumNitrate.ordinal()).itemID && (world.isMaterialInBB(entityItem.boundingBox, Material.water)))) {
world.createExplosion(entityItem, entityItem.posX, entityItem.posY, entityItem.posZ, 0.9F, true);
int dx = MathHelper.floor_double(entityItem.posX);
int dy = MathHelper.floor_double(entityItem.posY);
int dz = MathHelper.floor_double(entityItem.posZ);
transmuteWaterToPortal(world, dx, dy, dz);
return;
}
}
}
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
}
public static void renderEffects() {
Minecraft mc = FMLClientHandler.instance().getClient();
if (mc.isSingleplayer()) {
EntityPlayer player = mc.thePlayer;
if (player instanceof EntityPlayer && player.isPotionActive(PotionInjector.atropineHigh)) {
PotionEffect DHigh = player.getActivePotionEffect(PotionInjector.atropineHigh);
int Multiplier = DHigh.getAmplifier();
if (Multiplier == 1 ){
RenderDelirium(10);}
else if (Multiplier == 2 ){
RenderDelirium(15);
}
else if (Multiplier == 3){
RenderDelirium(20);
}
else if (Multiplier == 4){
RenderDelirium(25);
}
else {
}
}
}
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.RENDER, TickType.CLIENT);
}
@Override
public String getLabel() {
return null;
}
/*
* // this is all unused code for a WIP gas system private void
* renderOverlays(float parialTickTime) { Minecraft mc =
* FMLClientHandler.instance().getClient(); if (mc.renderViewEntity != null
* && mc.gameSettings.thirdPersonView == 0 &&
* !mc.renderViewEntity.isPlayerSleeping() &&
* mc.thePlayer.isInsideOfMaterial(MinechemBlocks.materialGas)) {
* renderWarpedTextureOverlay(mc, new
* ResourceLocation(ConstantValue.MOD_ID,"/misc/water.png")); } }
*
*
* // Renders a texture that warps around based on the direction the player
* is looking. Texture needs to be bound before being called. Used for the
* water // overlay. Args: parialTickTime
*
* private void renderWarpedTextureOverlay(Minecraft mc, ResourceLocation
* texture) { int overlayTexture =
* mc.renderEngine.func_110581_b(texture).func_110552_b(); double tile =
* 4.0F; double yaw = -mc.thePlayer.rotationYaw / 64.0F; double pitch =
* mc.thePlayer.rotationPitch / 64.0F; double left = 0; double top = 0;
* double right = mc.displayWidth; double bot = mc.displayHeight; double z =
* -1; Tessellator ts = Tessellator.instance;
*
* GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.9F);
* GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND);
* GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
* GL11.glBindTexture(GL11.GL_TEXTURE_2D, overlayTexture);
* GL11.glPushMatrix();
*
* ts.startDrawingQuads(); ts.addVertexWithUV(left, bot, z, tile + yaw, tile
* + pitch); ts.addVertexWithUV(right, bot, z, yaw, tile + pitch);
* ts.addVertexWithUV(right, top, z, yaw, pitch); ts.addVertexWithUV(left,
* top, z, tile + yaw, pitch); ts.draw();
*
* GL11.glPopMatrix(); GL11.glDisable(GL11.GL_BLEND);
* GL11.glEnable(GL11.GL_ALPHA_TEST); }
*/
public static void RenderDelirium(int markiplier) {
ScaledResolution scale = new ScaledResolution(Minecraft.getMinecraft().gameSettings, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight);
int width = scale.getScaledWidth();
int height = scale.getScaledHeight();
Gui gui = new Gui();
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_ALPHA_TEST);
int color = (int) (220.0F * markiplier - 125) << 24 | 1052704;
gui.drawRect(0, 0, width, height, color);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
}
| Update TickHandler.java | src/ljdp/minechem/client/TickHandler.java | Update TickHandler.java | <ide><path>rc/ljdp/minechem/client/TickHandler.java
<ide> Gui gui = new Gui();
<ide> GL11.glDisable(GL11.GL_DEPTH_TEST);
<ide> GL11.glDisable(GL11.GL_ALPHA_TEST);
<del> int color = (int) (220.0F * markiplier - 125) << 24 | 1052704;
<add> int color = (int) (220.0F * markiplier - 150) << 24 | 1052704;
<ide> gui.drawRect(0, 0, width, height, color);
<ide> GL11.glEnable(GL11.GL_ALPHA_TEST);
<ide> GL11.glEnable(GL11.GL_DEPTH_TEST); |
|
Java | agpl-3.0 | fb9ca7d350831fe8511141eaaa7f0e82627b7f2b | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 780545b8-2e60-11e5-9284-b827eb9e62be | hello.java | 77ffc868-2e60-11e5-9284-b827eb9e62be | 780545b8-2e60-11e5-9284-b827eb9e62be | hello.java | 780545b8-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>77ffc868-2e60-11e5-9284-b827eb9e62be
<add>780545b8-2e60-11e5-9284-b827eb9e62be |
|
Java | mit | 68813255db10cb964178ffd36edc7a85e6b7eb26 | 0 | asafge/NewsBlurPlus | package com.noinnion.android.newsplus.extension.newsblurplus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.RemoteException;
import android.text.TextUtils;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.AQUtility;
import com.noinnion.android.reader.api.ReaderException;
import com.noinnion.android.reader.api.ReaderExtension;
import com.noinnion.android.reader.api.internal.IItemIdListHandler;
import com.noinnion.android.reader.api.internal.IItemListHandler;
import com.noinnion.android.reader.api.internal.ISubscriptionListHandler;
import com.noinnion.android.reader.api.internal.ITagListHandler;
import com.noinnion.android.reader.api.provider.IItem;
import com.noinnion.android.reader.api.provider.ISubscription;
import com.noinnion.android.reader.api.provider.ITag;
public class NewsBlurPlus extends ReaderExtension {
private List<ITag> tags;
private List<ISubscription> feeds;
private List<String> unread_hashes;
private ITag starredTag;
/*
* Main sync function to get folders, feeds, and counts.
* 1. Get the folders (tags) and their feeds.
* 2. Ask NewsBlur to Refresh feed counts + save to feeds.
* 3. Send handler the tags and feeds.
*/
@Override
public void handleReaderList(ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (APIHelper.isJSONResponseValid(json, status)) {
try {
JSONObject json_feeds = json.getJSONObject("feeds");
JSONObject json_folders = json.getJSONObject("flat_folders");
Iterator<?> keys = json_folders.keys();
if (keys.hasNext()) {
tags = new ArrayList<ITag>();
feeds = new ArrayList<ISubscription>();
if (starredTag == null) {
starredTag = APIHelper.createTag("Starred items", true);
tags.add(starredTag);
}
}
while (keys.hasNext()) {
String catName = ((String)keys.next());
JSONArray feedsPerFolder = json_folders.getJSONArray(catName);
catName = catName.trim();
ITag cat = APIHelper.createTag(catName, false); // TODO: Don't create when empty?
if (!TextUtils.isEmpty(catName))
tags.add(cat);
// Add all feeds in this category
for (int i=0; i<feedsPerFolder.length(); i++) {
ISubscription sub = new ISubscription();
String feedID = feedsPerFolder.getString(i);
JSONObject f = json_feeds.getJSONObject(feedID);
Calendar updateTime = Calendar.getInstance();
updateTime.add(Calendar.SECOND, (-1) * f.getInt("updated_seconds_ago"));
sub.newestItemTime = updateTime.getTimeInMillis() / 1000;
sub.uid = "FEED:" + APIHelper.getFeedUrlFromFeedId(feedID);
sub.title = f.getString("feed_title");
sub.htmlUrl = f.getString("feed_link");
sub.unreadCount = f.getInt("nt") + f.getInt("ps");
if (!TextUtils.isEmpty(catName))
sub.addCategory(cat.uid);
feeds.add(sub);
}
}
}
catch (JSONException e) {
AQUtility.report(e);
}
}
}
};
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
aq.ajax(APIHelper.API_URL_FOLDERS_AND_FEEDS, JSONObject.class, cb);
cb.block();
if ((APIHelper.isErrorCode(cb.getStatus().getCode())) || feeds.size() == 0)
throw new ReaderException("Network error");
updateFeedCounts();
try {
tagHandler.tags(tags);
subHandler.subscriptions(feeds);
}
catch (RemoteException e) {
throw new ReaderException(e);
}
}
/*
* Get a list of unread story IDS (URLs), UI will mark all other as read.
* This really speeds up the sync process.
*/
@Override
public void handleItemIdList(final IItemIdListHandler handler, long syncTime) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try {
if (APIHelper.isJSONResponseValid(json, status)) {
List<String> unread = new ArrayList<String>();
JSONArray arr = json.getJSONArray("stories");
for (int i=0; i<arr.length(); i++) {
JSONObject story = arr.getJSONObject(i);
unread.add(story.getString("id"));
}
handler.items(unread);
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
};
getUnreadHashes();
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
String url = APIHelper.API_URL_RIVER;
for (String h : unread_hashes)
url += "h=" + h + "&";
//aq.ajax(url + "read_filter=unread", JSONObject.class, cb);
//cb.block();
}
/*
* Get all the unread story hashes at once
*/
private void getUnreadHashes() {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
unread_hashes = new ArrayList<String>();
cb.url(APIHelper.API_URL_UNREAD_HASHES).type(JSONObject.class);
aq.sync(cb);
JSONObject json = cb.getResult();
AjaxStatus status = cb.getStatus();
if (APIHelper.isJSONResponseValid(json, status)) {
try {
JSONObject json_folders = json.getJSONObject("unread_feed_story_hashes");
Iterator<?> keys = json_folders.keys();
while (keys.hasNext()) {
JSONArray items = json_folders.getJSONArray((String)keys.next());
for (int i=0; i<items.length(); i++)
unread_hashes.add(items.getString(i));
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
}
/*
* Call for an update on all feeds' unread counters, and store the result
*/
private void updateFeedCounts() {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
cb.url(APIHelper.API_URL_REFRESH_FEEDS).type(JSONObject.class);
aq.sync(cb);
JSONObject json = cb.getResult();
AjaxStatus status = cb.getStatus();
if (APIHelper.isJSONResponseValid(json, status)) {
try {
JSONObject json_feeds = json.getJSONObject("feeds");
for (ISubscription sub : feeds) {
JSONObject f = json_feeds.getJSONObject(APIHelper.getFeedIdFromFeedUrl(sub.uid));
sub.unreadCount = f.getInt("ps") + f.getInt("nt");
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
}
/*
* Handle a single item list (a feed or a folder).
* This functions calls the parseItemList function.
*/
@Override
public void handleItemList(IItemListHandler handler, long syncTime) throws IOException, ReaderException {
try {
if ((tags != null) && (feeds != null)) {
String uid = handler.stream();
if (uid.equals(ReaderExtension.STATE_READING_LIST)) {
for (ISubscription sub : feeds)
if (sub.unreadCount > 0 && !handler.excludedStreams().contains(sub.uid))
parseItemList(sub.uid.replace("FEED:", ""), handler, sub.getCategories());
}
else if (uid.startsWith("FOL:")) {
for (ISubscription sub : feeds)
if (sub.unreadCount > 0 && sub.getCategories().contains(uid) && !handler.excludedStreams().contains(sub.uid))
parseItemList(sub.uid.replace("FEED:", ""), handler, sub.getCategories());
}
else if (uid.startsWith("FEED:")) {
if (!handler.excludedStreams().contains(uid))
parseItemList(handler.stream().replace("FEED:", ""), handler, Arrays.asList(""));
}
else if (uid.startsWith(ReaderExtension.STATE_STARRED)) {
parseItemList(APIHelper.API_URL_STARRED_ITEMS, handler, Arrays.asList(""));
}
}
}
catch (RemoteException e) {
throw new ReaderException(e);
}
}
/*
* Get the content of a single feed
*
* API call: https://www.newsblur.com/reader/feeds
* Result:
* feeds/[ID]/feed_address (http://feeds.feedburner.com/codinghorror - rss file)
* feeds/[ID]/feed_title ("Coding Horror")
* feeds/[ID]/feed_link (http://www.codinghorror.com/blog/ - site's link)
*/
public void parseItemList(String url, final IItemListHandler handler, final List<String> categories) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try {
if (APIHelper.isJSONResponseValid(json, status)) {
List<IItem> items = new ArrayList<IItem>();
JSONArray arr = json.getJSONArray("stories");
int length = 0;
for (int i=0; i<arr.length(); i++) {
JSONObject story = arr.getJSONObject(i);
IItem item = new IItem();
item.subUid = "FEED:" + url;
item.title = story.getString("story_title");
item.link = story.getString("story_permalink");
item.uid = story.getString("id");
item.author = story.getString("story_authors");
item.updatedTime = story.getLong("story_timestamp");
item.publishedTime = story.getLong("story_timestamp");
item.read = (story.getInt("read_status") == 1);
item.content = story.getString("story_content");
if (story.has("starred") && story.getString("starred") == "true") {
item.starred = true;
item.addCategory(starredTag.uid);
}
for (String cat : categories)
item.addCategory(cat);
items.add(item);
// Handle TransactionTooLargeException, based on Noin's recommendation
length += item.getLength();
if (items.size() % 200 == 0 || length > 300000) {
handler.items(items);
items.clear();
length = 0;
}
}
handler.items(items);
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
};
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
aq.ajax(url, JSONObject.class, cb);
cb.block();
}
/*
* Main function for marking stories (and their feeds) as read/unread.
*/
private boolean markAs(boolean read, String[] itemUids, String[] subUIds) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (APIHelper.isJSONResponseValid(json, status)) {
try {
if (!json.getString("result").startsWith("ok"))
throw new ReaderException("Failed marking as read");
}
catch (Exception e) {
AQUtility.report(e);
}
}
}
};
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
if (itemUids == null && subUIds == null) {
aq.ajax(APIHelper.API_URL_MARK_ALL_AS_READ, JSONObject.class, cb);
cb.block();
}
else {
if (itemUids == null) {
Map<String, Object> params = new HashMap<String, Object>();
for (String sub : subUIds)
params.put("feed_id", APIHelper.getFeedIdFromFeedUrl(sub));
aq.ajax(APIHelper.API_URL_MARK_FEED_AS_READ, params, JSONObject.class, cb);
cb.block();
}
else {
String url = read ? APIHelper.API_URL_MARK_STORY_AS_READ : APIHelper.API_URL_MARK_STORY_AS_UNREAD;
Map<String, Object> params = new HashMap<String, Object>();
for (int i=0; i<itemUids.length; i++) {
params.put("story_id", itemUids[i]);
params.put("feed_id", APIHelper.getFeedIdFromFeedUrl(subUIds[i]));
}
aq.ajax(url, params, JSONObject.class, cb);
cb.block();
}
}
return true; // TODO: Return some real feedback
}
/*
* Mark a list of stories (and their feeds) as read
*/
@Override
public boolean markAsRead(String[] itemUids, String[] subUIds) throws IOException, ReaderException {
return this.markAs(true, itemUids, subUIds);
}
/*
* Mark a list of stories (and their feeds) as unread
*/
@Override
public boolean markAsUnread(String[] itemUids, String[] subUids, boolean keepUnread) throws IOException, ReaderException {
return this.markAs(false, itemUids, subUids);
}
/*
* Mark all stories on all feeds as read.
* Note: S = subscription (feed), t = tag
*/
@Override
public boolean markAllAsRead(String s, String t, long syncTime) throws IOException, ReaderException {
if (s == null && t == null)
return this.markAs(true, null, null);
else if (s.startsWith("FEED:")) {
String[] feed = { APIHelper.getFeedIdFromFeedUrl(s) };
return this.markAs(true, null, feed);
}
else if (s.startsWith("FOL:")) {
List<String> subUIDs = new ArrayList<String>();
for (ISubscription sub : feeds)
if (sub.getCategories().contains(s))
subUIDs.add(sub.uid);
if (subUIDs.size() > 0)
return this.markAs(true, null, (String[])subUIDs.toArray());
return true;
}
else
return false; // Can't mark a folder/tag as read
}
//TODO: Tag/Folder handling
@Override
public boolean editItemTag(String[] itemUids, String[] subUids, String[] addTags, String[] removeTags) throws IOException, ReaderException {
return false;
}
@Override
public boolean editSubscription(String uid, String title, String url, String[] tag, int action, long syncTime) throws IOException, ReaderException {
return false;
}
@Override
public boolean renameTag(String tagUid, String oldLabel, String newLabel) throws IOException, ReaderException {
return false;
}
@Override
public boolean disableTag(String tagUid, String label) throws IOException, ReaderException {
return false;
}
}
| newsplus/extensions/NewsblurExtension/src/com/noinnion/android/newsplus/extension/newsblurplus/NewsBlurPlus.java | package com.noinnion.android.newsplus.extension.newsblurplus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.RemoteException;
import android.text.TextUtils;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.AQUtility;
import com.noinnion.android.reader.api.ReaderException;
import com.noinnion.android.reader.api.ReaderExtension;
import com.noinnion.android.reader.api.internal.IItemIdListHandler;
import com.noinnion.android.reader.api.internal.IItemListHandler;
import com.noinnion.android.reader.api.internal.ISubscriptionListHandler;
import com.noinnion.android.reader.api.internal.ITagListHandler;
import com.noinnion.android.reader.api.provider.IItem;
import com.noinnion.android.reader.api.provider.ISubscription;
import com.noinnion.android.reader.api.provider.ITag;
public class NewsBlurPlus extends ReaderExtension {
private List<ITag> tags;
private List<ISubscription> feeds;
private List<String> unread_hashes;
private ITag starredTag;
/*
* Main sync function to get folders, feeds, and counts.
* 1. Get the folders (tags) and their feeds.
* 2. Ask NewsBlur to Refresh feed counts + save to feeds.
* 3. Send handler the tags and feeds.
*/
@Override
public void handleReaderList(ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (APIHelper.isJSONResponseValid(json, status)) {
try {
JSONObject json_feeds = json.getJSONObject("feeds");
JSONObject json_folders = json.getJSONObject("flat_folders");
Iterator<?> keys = json_folders.keys();
if (keys.hasNext()) {
tags = new ArrayList<ITag>();
feeds = new ArrayList<ISubscription>();
if (starredTag == null) {
starredTag = APIHelper.createTag("Starred items", true);
tags.add(starredTag);
}
}
while (keys.hasNext()) {
String catName = ((String)keys.next());
JSONArray feedsPerFolder = json_folders.getJSONArray(catName);
catName = catName.trim();
ITag cat = APIHelper.createTag(catName, false); // TODO: Don't create when empty?
if (!TextUtils.isEmpty(catName))
tags.add(cat);
// Add all feeds in this category
for (int i=0; i<feedsPerFolder.length(); i++) {
ISubscription sub = new ISubscription();
String feedID = feedsPerFolder.getString(i);
JSONObject f = json_feeds.getJSONObject(feedID);
Calendar updateTime = Calendar.getInstance();
updateTime.add(Calendar.SECOND, (-1) * f.getInt("updated_seconds_ago"));
sub.newestItemTime = updateTime.getTimeInMillis() / 1000;
sub.uid = "FEED:" + APIHelper.getFeedUrlFromFeedId(feedID);
sub.title = f.getString("feed_title");
sub.htmlUrl = f.getString("feed_link");
sub.unreadCount = f.getInt("nt") + f.getInt("ps");
if (!TextUtils.isEmpty(catName))
sub.addCategory(cat.uid);
feeds.add(sub);
}
}
}
catch (JSONException e) {
AQUtility.report(e);
}
}
}
};
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
aq.ajax(APIHelper.API_URL_FOLDERS_AND_FEEDS, JSONObject.class, cb);
cb.block();
if ((APIHelper.isErrorCode(cb.getStatus().getCode())) || feeds.size() == 0)
throw new ReaderException("Network error");
updateFeedCounts();
try {
tagHandler.tags(tags);
subHandler.subscriptions(feeds);
}
catch (RemoteException e) {
throw new ReaderException(e);
}
}
/*
* Get a list of unread story IDS (URLs), UI will mark all other as read.
* This really speeds up the sync process.
*/
@Override
public void handleItemIdList(final IItemIdListHandler handler, long syncTime) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try {
if (APIHelper.isJSONResponseValid(json, status)) {
List<String> unread = new ArrayList<String>();
JSONArray arr = json.getJSONArray("stories");
for (int i=0; i<arr.length(); i++) {
JSONObject story = arr.getJSONObject(i);
unread.add(story.getString("id"));
}
handler.items(unread);
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
};
getUnreadHashes();
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
String url = APIHelper.API_URL_RIVER;
for (String h : unread_hashes)
url += "h=" + h + "&";
//aq.ajax(url + "read_filter=unread", JSONObject.class, cb);
//cb.block();
}
/*
* Get all the unread story hashes at once
*/
private void getUnreadHashes() {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
unread_hashes = new ArrayList<String>();
cb.url(APIHelper.API_URL_UNREAD_HASHES).type(JSONObject.class);
aq.sync(cb);
JSONObject json = cb.getResult();
AjaxStatus status = cb.getStatus();
if (APIHelper.isJSONResponseValid(json, status)) {
try {
JSONObject json_folders = json.getJSONObject("unread_feed_story_hashes");
Iterator<?> keys = json_folders.keys();
while (keys.hasNext()) {
JSONArray items = json_folders.getJSONArray((String)keys.next());
for (int i=0; i<items.length(); i++)
unread_hashes.add(items.getString(i));
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
}
/*
* Call for an update on all feeds' unread counters, and store the result
*/
private void updateFeedCounts() {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
cb.url(APIHelper.API_URL_REFRESH_FEEDS).type(JSONObject.class);
aq.sync(cb);
JSONObject json = cb.getResult();
AjaxStatus status = cb.getStatus();
if (APIHelper.isJSONResponseValid(json, status)) {
try {
JSONObject json_feeds = json.getJSONObject("feeds");
for (ISubscription sub : feeds) {
JSONObject f = json_feeds.getJSONObject(APIHelper.getFeedIdFromFeedUrl(sub.uid));
sub.unreadCount = f.getInt("ps") + f.getInt("nt");
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
}
/*
* Handle a single item list (a feed or a folder).
* This functions calls the parseItemList function.
*/
@Override
public void handleItemList(IItemListHandler handler, long syncTime) throws IOException, ReaderException {
try {
if ((tags != null) && (feeds != null)) {
String uid = handler.stream();
if (uid.equals(ReaderExtension.STATE_READING_LIST)) {
for (ISubscription sub : feeds)
if (sub.unreadCount > 0 && !handler.excludedStreams().contains(sub.uid))
parseItemList(sub.uid.replace("FEED:", ""), handler, sub.getCategories());
}
else if (uid.startsWith("FOL:")) {
for (ISubscription sub : feeds)
if (sub.unreadCount > 0 && sub.getCategories().contains(uid) && !handler.excludedStreams().contains(sub.uid))
parseItemList(sub.uid.replace("FEED:", ""), handler, sub.getCategories());
}
else if (uid.startsWith("FEED:")) {
if (!handler.excludedStreams().contains(uid))
parseItemList(handler.stream().replace("FEED:", ""), handler, Arrays.asList(""));
}
else if (uid.startsWith(ReaderExtension.STATE_STARRED)) {
parseItemList(APIHelper.API_URL_STARRED_ITEMS, handler, Arrays.asList(""));
}
}
}
catch (RemoteException e) {
throw new ReaderException(e);
}
}
/*
* Get the content of a single feed
*
* API call: https://www.newsblur.com/reader/feeds
* Result:
* feeds/[ID]/feed_address (http://feeds.feedburner.com/codinghorror - rss file)
* feeds/[ID]/feed_title ("Coding Horror")
* feeds/[ID]/feed_link (http://www.codinghorror.com/blog/ - site's link)
*/
public void parseItemList(String url, final IItemListHandler handler, final List<String> categories) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try {
if (APIHelper.isJSONResponseValid(json, status)) {
List<IItem> items = new ArrayList<IItem>();
JSONArray arr = json.getJSONArray("stories");
int length = 0;
for (int i=0; i<arr.length(); i++) {
JSONObject story = arr.getJSONObject(i);
IItem item = new IItem();
item.subUid = "FEED:" + url;
item.title = story.getString("story_title");
item.link = story.getString("story_permalink");
item.uid = story.getString("id");
item.author = story.getString("story_authors");
item.updatedTime = story.getLong("story_timestamp");
item.publishedTime = story.getLong("story_timestamp");
item.read = (story.getInt("read_status") == 1);
item.content = story.getString("story_content");
if (story.has("starred") && story.getString("starred") == "true") {
item.starred = true;
item.addCategory(starredTag.uid);
}
for (String cat : categories)
item.addCategory(cat);
items.add(item);
// Handle TransactionTooLargeException, based on Noin's recommendation
length += item.getLength();
if (items.size() % 200 == 0 || length > 300000) {
handler.items(items);
items.clear();
length = 0;
}
}
handler.items(items);
}
}
catch (Exception e) {
AQUtility.report(e);
}
}
};
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
aq.ajax(url, JSONObject.class, cb);
cb.block();
}
/*
* Main function for marking stories (and their feeds) as read/unread.
*/
private boolean markAs(boolean read, String[] itemUids, String[] subUIds) throws IOException, ReaderException {
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (APIHelper.isJSONResponseValid(json, status)) {
try {
if (!json.getString("result").startsWith("ok"))
throw new ReaderException("Failed marking as read");
}
catch (Exception e) {
AQUtility.report(e);
}
}
}
};
final AQuery aq = new AQuery(this);
final Context c = getApplicationContext();
APIHelper.wrapCallback(c, cb);
if (itemUids == null && subUIds == null) {
aq.ajax(APIHelper.API_URL_MARK_ALL_AS_READ, JSONObject.class, cb);
cb.block();
}
else {
if (itemUids == null) {
Map<String, Object> params = new HashMap<String, Object>();
for (String sub : subUIds)
params.put("feed_id", APIHelper.getFeedIdFromFeedUrl(sub));
aq.ajax(APIHelper.API_URL_MARK_FEED_AS_READ, params, JSONObject.class, cb);
cb.block();
}
else {
String url = read ? APIHelper.API_URL_MARK_STORY_AS_READ : APIHelper.API_URL_MARK_STORY_AS_UNREAD;
Map<String, Object> params = new HashMap<String, Object>();
for (int i=0; i<itemUids.length; i++) {
params.put("story_id", itemUids[i]);
params.put("feed_id", APIHelper.getFeedIdFromFeedUrl(subUIds[i]));
}
aq.ajax(url, params, JSONObject.class, cb);
cb.block();
}
}
return true; // TODO: Return some real feedback
}
/*
* Mark a list of stories (and their feeds) as read
*/
@Override
public boolean markAsRead(String[] itemUids, String[] subUIds) throws IOException, ReaderException {
return this.markAs(true, itemUids, subUIds);
}
/*
* Mark a list of stories (and their feeds) as unread
*/
@Override
public boolean markAsUnread(String[] itemUids, String[] subUids, boolean keepUnread) throws IOException, ReaderException {
return this.markAs(false, itemUids, subUids);
}
/*
* Mark all stories on all feeds as read.
* Note: S = subscription (feed), t = tag
*/
@Override
public boolean markAllAsRead(String s, String t, long syncTime) throws IOException, ReaderException {
if (s == null && t == null)
return this.markAs(true, null, null);
else if (s.startsWith("FEED:")) {
String[] feed = { APIHelper.getFeedIdFromFeedUrl(s) };
return this.markAs(true, null, feed);
}
else if (s.startsWith("FOL:")) {
List<String> subUIDs = new ArrayList<String>();
for (ISubscription sub : feeds)
if (sub.getCategories().contains(s))
subUIDs.add(sub.uid);
if (subUIDs.size() > 0)
return this.markAs(true, null, (String[])subUIDs.toArray());
return true;
}
else
return false; // Can't mark a folder/tag as read
}
//TODO: Tag/Folder handling
@Override
public boolean editItemTag(String[] itemUids, String[] subUids, String[] addTags, String[] removeTags) throws IOException, ReaderException {
return false;
}
@Override
public boolean editSubscription(String uid, String title, String url, String[] tag, int action, long syncTime) throws IOException, ReaderException {
return false;
}
@Override
public boolean renameTag(String tagUid, String oldLabel, String newLabel) throws IOException, ReaderException {
return false;
}
@Override
public boolean disableTag(String tagUid, String label) throws IOException, ReaderException {
return false;
}
}
| Remove spaces
| newsplus/extensions/NewsblurExtension/src/com/noinnion/android/newsplus/extension/newsblurplus/NewsBlurPlus.java | Remove spaces | <ide><path>ewsplus/extensions/NewsblurExtension/src/com/noinnion/android/newsplus/extension/newsblurplus/NewsBlurPlus.java
<ide> }
<ide> }
<ide>
<del>
<ide> /*
<ide> * Get the content of a single feed
<ide> *
<ide> return true; // TODO: Return some real feedback
<ide> }
<ide>
<del>
<ide> /*
<ide> * Mark a list of stories (and their feeds) as read
<ide> */
<ide> return this.markAs(true, itemUids, subUIds);
<ide> }
<ide>
<del>
<ide> /*
<ide> * Mark a list of stories (and their feeds) as unread
<ide> */
<ide> return this.markAs(false, itemUids, subUids);
<ide> }
<ide>
<del>
<ide> /*
<ide> * Mark all stories on all feeds as read.
<ide> * Note: S = subscription (feed), t = tag |
|
JavaScript | mit | b1d28a3f6acba13b000b6b7ee8f0a783badefb1e | 0 | wpfpizicai/knowledge,wpfpizicai/knowledge,wpfpizicai/knowledge | /**
* controller
* @return
*/
module.exports = Controller("Home/BaseController", function(){
"use strict";
var courses = [{name:"创造力提升",id:"creativedad",detail:"",source:"UNAM",time:"永久开放",img:"1.jpg"},{name:"跨领域医疗信息学",id:"creativedad",detail:"",source:"Minnesota",time:"永久开放",img:"2.png"},{name:"微观经济学",id:"creativedad",detail:"",source:"Illinois",time:"Dec 22nd",img:"3.jpg"},{name:"遗传学与进化概论",id:"creativedad",detail:"",source:"Duke",time:"Jan 1st",img:"4.jpg"},{name:"探索性数据分析",id:"creativedad",detail:"",source:"约翰霍普金斯大学",time:"3月 2日",img:"5.jpg"},{name:"统计推断",id:"creativedad",detail:"",source:"斯坦福大学",time:"永久开放",img:"6.jpg"}];
var c_data = {
navLinks : navLinks,
section : 'home'
};
return {
indexAction: function(){
this.assign(extend({
courses:courses,
title : "首页",
userInfo : D('User').where({ //根据用户邮箱和密码查询符合条件的数据
email: "[email protected]",
pwd: md5("admin")
}).find()
},c_data))
this.display();
}
};
}); | App/Lib/Controller/Home/IndexController.js | /**
* controller
* @return
*/
module.exports = Controller("Home/BaseController", function(){
"use strict";
var courses = [{name:"创造力提升",id:"creativedad",detail:"",source:"UNAM",time:"永久开放",img:"1.jpg"},{name:"跨领域医疗信息学",id:"creativedad",detail:"",source:"Minnesota",time:"永久开放",img:"2.png"},{name:"微观经济学",id:"creativedad",detail:"",source:"Illinois",time:"Dec 22nd",img:"3.jpg"},{name:"遗传学与进化概论",id:"creativedad",detail:"",source:"Duke",time:"Jan 1st",img:"4.jpg"},{name:"探索性数据分析",id:"creativedad",detail:"",source:"约翰霍普金斯大学",time:"3月 2日",img:"5.jpg"},{name:"统计推断",id:"creativedad",detail:"",source:"斯坦福大学",time:"永久开放",img:"6.jpg"}];
var c_data = {
navLinks : navLinks,
section : 'home'
};
return {
indexAction: function(){
this.assign(extend({
courses:courses,
title : "首页",
userInfo : this.userInfo
},c_data))
this.display();
}
};
}); | add files by wangpengfei
| App/Lib/Controller/Home/IndexController.js | add files by wangpengfei | <ide><path>pp/Lib/Controller/Home/IndexController.js
<ide> this.assign(extend({
<ide> courses:courses,
<ide> title : "首页",
<del> userInfo : this.userInfo
<add> userInfo : D('User').where({ //根据用户邮箱和密码查询符合条件的数据
<add> email: "[email protected]",
<add> pwd: md5("admin")
<add> }).find()
<ide> },c_data))
<ide> this.display();
<ide> } |
|
Java | apache-2.0 | 1461f42d0ebd90f714482c2cb018a8d82f9aa1fb | 0 | blademainer/intellij-community,holmes/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,holmes/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,dslomov/intellij-community,caot/intellij-community,signed/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,izonder/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,da1z/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,semonte/intellij-community,retomerz/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,adedayo/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,consulo/consulo,petteyg/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,FHannes/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,holmes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,caot/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,dslomov/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,izonder/intellij-community,caot/intellij-community,kool79/intellij-community,ibinti/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,apixandru/intellij-community,supersven/intellij-community,blademainer/intellij-community,jexp/idea2,TangHao1987/intellij-community,robovm/robovm-studio,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,ftomassetti/intellij-community,ernestp/consulo,diorcety/intellij-community,vladmm/intellij-community,slisson/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,amith01994/intellij-community,diorcety/intellij-community,supersven/intellij-community,supersven/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,slisson/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,jexp/idea2,gnuhub/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,petteyg/intellij-community,kdwink/intellij-community,adedayo/intellij-community,allotria/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,signed/intellij-community,consulo/consulo,TangHao1987/intellij-community,kdwink/intellij-community,slisson/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,FHannes/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,ernestp/consulo,alphafoobar/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,fitermay/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,consulo/consulo,xfournet/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,holmes/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,samthor/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,consulo/consulo,FHannes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,kool79/intellij-community,xfournet/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,slisson/intellij-community,da1z/intellij-community,izonder/intellij-community,clumsy/intellij-community,joewalnes/idea-community,amith01994/intellij-community,retomerz/intellij-community,blademainer/intellij-community,fnouama/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,da1z/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,allotria/intellij-community,Lekanich/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,hurricup/intellij-community,apixandru/intellij-community,kool79/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,izonder/intellij-community,allotria/intellij-community,slisson/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,diorcety/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,jexp/idea2,alphafoobar/intellij-community,amith01994/intellij-community,robovm/robovm-studio,jexp/idea2,dslomov/intellij-community,FHannes/intellij-community,ryano144/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,jexp/idea2,gnuhub/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,signed/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,hurricup/intellij-community,blademainer/intellij-community,samthor/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,semonte/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,FHannes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,FHannes/intellij-community,izonder/intellij-community,dslomov/intellij-community,allotria/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ernestp/consulo,orekyuu/intellij-community,supersven/intellij-community,asedunov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,adedayo/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,samthor/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,robovm/robovm-studio,jagguli/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,vladmm/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,clumsy/intellij-community,jagguli/intellij-community,samthor/intellij-community,holmes/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,semonte/intellij-community,samthor/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,jagguli/intellij-community,diorcety/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,slisson/intellij-community,allotria/intellij-community,da1z/intellij-community,retomerz/intellij-community,slisson/intellij-community,kdwink/intellij-community,ryano144/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,allotria/intellij-community,izonder/intellij-community,Lekanich/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,jagguli/intellij-community,hurricup/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,holmes/intellij-community,FHannes/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,semonte/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,xfournet/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,jexp/idea2,Lekanich/intellij-community,signed/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,fitermay/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,apixandru/intellij-community,samthor/intellij-community,caot/intellij-community,asedunov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,holmes/intellij-community,ryano144/intellij-community,consulo/consulo,retomerz/intellij-community,fitermay/intellij-community,FHannes/intellij-community,dslomov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,consulo/consulo,nicolargo/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,jexp/idea2,youdonghai/intellij-community,semonte/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ernestp/consulo,gnuhub/intellij-community,supersven/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,ibinti/intellij-community,signed/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,da1z/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,blademainer/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,robovm/robovm-studio,da1z/intellij-community,retomerz/intellij-community,fnouama/intellij-community,kool79/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,slisson/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,holmes/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,petteyg/intellij-community,amith01994/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,apixandru/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,caot/intellij-community,vladmm/intellij-community,fitermay/intellij-community,signed/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ryano144/intellij-community,slisson/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,jexp/idea2,semonte/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,blademainer/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,izonder/intellij-community,retomerz/intellij-community,da1z/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,samthor/intellij-community,caot/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ernestp/consulo,ibinti/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community | package com.intellij.codeInsight.highlighting;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx;
import com.intellij.openapi.editor.ex.FocusChangeListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NotNull;
public class BraceHighlighter implements ProjectComponent {
private final Project myProject;
private final Alarm myAlarm = new Alarm();
private CaretListener myCaretListener;
private SelectionListener mySelectionListener;
private DocumentListener myDocumentListener;
private FocusChangeListener myFocusChangeListener;
private boolean myIsDisposed = false;
public BraceHighlighter(Project project) {
myProject = project;
}
@NotNull
public String getComponentName() {
return "BraceHighlighter";
}
public void initComponent() { }
public void disposeComponent() {
myIsDisposed = true;
}
public void projectOpened() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
myCaretListener = new CaretListener() {
public void caretPositionChanged(CaretEvent e) {
myAlarm.cancelAllRequests();
Editor editor = e.getEditor();
if (editor.getProject() == myProject) {
updateBraces(editor);
}
}
};
eventMulticaster.addCaretListener(myCaretListener);
mySelectionListener = new SelectionListener() {
public void selectionChanged(SelectionEvent e) {
myAlarm.cancelAllRequests();
Editor editor = e.getEditor();
if (editor.getProject() == myProject) {
updateBraces(editor);
}
}
};
eventMulticaster.addSelectionListener(mySelectionListener);
myDocumentListener = new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
Editor[] editors = EditorFactory.getInstance().getEditors(e.getDocument(), myProject);
for (Editor editor : editors) {
updateBraces(editor);
}
}
};
eventMulticaster.addDocumentListener(myDocumentListener);
myFocusChangeListener = new FocusChangeListener() {
public void focusLost(Editor editor) {
clearBraces(editor);
}
public void focusGained(Editor editor) {
updateBraces(editor);
}
};
((EditorEventMulticasterEx)eventMulticaster).addFocusChangeListner(myFocusChangeListener);
final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
fileEditorManager.addFileEditorManagerListener(
new FileEditorManagerAdapter() {
public void selectionChanged(FileEditorManagerEvent e) {
myAlarm.cancelAllRequests();
}
}
);
}
});
}
private void updateBraces(final Editor editor) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Project project = editor.getProject();
if (project != null && !project.isDisposed() && !myIsDisposed && !myProject.isDisposed() && editor.getComponent().isShowing() && !editor.isViewer()) {
new BraceHighlightingHandler(project, editor, myAlarm).updateBraces();
}
}
}, ModalityState.stateForComponent(editor.getComponent()));
}
private void clearBraces(final Editor editor) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Project project = editor.getProject();
if (project != null && !project.isDisposed() && !myIsDisposed && editor.getComponent().isShowing()) {
new BraceHighlightingHandler(project, editor, myAlarm).clearBraceHighlighters();
}
}
}, ModalityState.stateForComponent(editor.getComponent()));
}
public void projectClosed() {
EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
eventMulticaster.removeCaretListener(myCaretListener);
eventMulticaster.removeSelectionListener(mySelectionListener);
eventMulticaster.removeDocumentListener(myDocumentListener);
((EditorEventMulticasterEx)eventMulticaster).removeFocusChangeListner(myFocusChangeListener);
}
}
| codeInsight/impl/com/intellij/codeInsight/highlighting/BraceHighlighter.java | package com.intellij.codeInsight.highlighting;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx;
import com.intellij.openapi.editor.ex.FocusChangeListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NotNull;
public class BraceHighlighter implements ProjectComponent {
private final Project myProject;
private final Alarm myAlarm = new Alarm();
private CaretListener myCaretListener;
private SelectionListener mySelectionListener;
private DocumentListener myDocumentListener;
private FocusChangeListener myFocusChangeListener;
private boolean myIsDisposed = false;
public BraceHighlighter(Project project) {
myProject = project;
}
@NotNull
public String getComponentName() {
return "BraceHighlighter";
}
public void initComponent() { }
public void disposeComponent() {
myIsDisposed = true;
}
public void projectOpened() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
myCaretListener = new CaretListener() {
public void caretPositionChanged(CaretEvent e) {
myAlarm.cancelAllRequests();
Editor editor = e.getEditor();
if (editor.getProject() == myProject) {
updateBraces(editor);
}
}
};
eventMulticaster.addCaretListener(myCaretListener);
mySelectionListener = new SelectionListener() {
public void selectionChanged(SelectionEvent e) {
myAlarm.cancelAllRequests();
Editor editor = e.getEditor();
if (editor.getProject() == myProject) {
updateBraces(editor);
}
}
};
eventMulticaster.addSelectionListener(mySelectionListener);
myDocumentListener = new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
Editor[] editors = EditorFactory.getInstance().getEditors(e.getDocument(), myProject);
for (Editor editor : editors) {
updateBraces(editor);
}
}
};
eventMulticaster.addDocumentListener(myDocumentListener);
myFocusChangeListener = new FocusChangeListener() {
public void focusLost(Editor editor) {
clearBraces(editor);
}
public void focusGained(Editor editor) {
updateBraces(editor);
}
};
((EditorEventMulticasterEx)eventMulticaster).addFocusChangeListner(myFocusChangeListener);
final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
fileEditorManager.addFileEditorManagerListener(
new FileEditorManagerAdapter() {
public void selectionChanged(FileEditorManagerEvent e) {
myAlarm.cancelAllRequests();
}
}
);
}
});
}
private void updateBraces(final Editor editor) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (!myIsDisposed && !myProject.isDisposed() && editor.getComponent().isShowing() && !editor.isViewer()) {
new BraceHighlightingHandler(myProject, editor, myAlarm).updateBraces();
}
}
}, ModalityState.stateForComponent(editor.getComponent()));
}
private void clearBraces(final Editor editor) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (!myIsDisposed && editor.getComponent().isShowing()) {
new BraceHighlightingHandler(myProject, editor, myAlarm).clearBraceHighlighters();
}
}
}, ModalityState.stateForComponent(editor.getComponent()));
}
public void projectClosed() {
EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
eventMulticaster.removeCaretListener(myCaretListener);
eventMulticaster.removeSelectionListener(mySelectionListener);
eventMulticaster.removeDocumentListener(myDocumentListener);
((EditorEventMulticasterEx)eventMulticaster).removeFocusChangeListner(myFocusChangeListener);
}
}
| avoid accessing PSI from within alien project
| codeInsight/impl/com/intellij/codeInsight/highlighting/BraceHighlighter.java | avoid accessing PSI from within alien project | <ide><path>odeInsight/impl/com/intellij/codeInsight/highlighting/BraceHighlighter.java
<ide> private void updateBraces(final Editor editor) {
<ide> ApplicationManager.getApplication().invokeLater(new Runnable() {
<ide> public void run() {
<del> if (!myIsDisposed && !myProject.isDisposed() && editor.getComponent().isShowing() && !editor.isViewer()) {
<del> new BraceHighlightingHandler(myProject, editor, myAlarm).updateBraces();
<add> Project project = editor.getProject();
<add> if (project != null && !project.isDisposed() && !myIsDisposed && !myProject.isDisposed() && editor.getComponent().isShowing() && !editor.isViewer()) {
<add> new BraceHighlightingHandler(project, editor, myAlarm).updateBraces();
<ide> }
<ide> }
<ide> }, ModalityState.stateForComponent(editor.getComponent()));
<ide> private void clearBraces(final Editor editor) {
<ide> ApplicationManager.getApplication().invokeLater(new Runnable() {
<ide> public void run() {
<del> if (!myIsDisposed && editor.getComponent().isShowing()) {
<del> new BraceHighlightingHandler(myProject, editor, myAlarm).clearBraceHighlighters();
<add> Project project = editor.getProject();
<add> if (project != null && !project.isDisposed() && !myIsDisposed && editor.getComponent().isShowing()) {
<add> new BraceHighlightingHandler(project, editor, myAlarm).clearBraceHighlighters();
<ide> }
<ide> }
<ide> }, ModalityState.stateForComponent(editor.getComponent()));
<ide> eventMulticaster.removeDocumentListener(myDocumentListener);
<ide> ((EditorEventMulticasterEx)eventMulticaster).removeFocusChangeListner(myFocusChangeListener);
<ide> }
<del>
<ide> } |
|
Java | bsd-3-clause | c4298f70cba07972b4d7fc9bd567f4554a83ed87 | 0 | GuacoIV/VisEQ,GuacoIV/VisEQ,GuacoIV/VisEQ | /*
Copyright (c) 2012, Spotify AB
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Spotify AB nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SPOTIFY AB BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* The player view and playlist logic put together.
*
* The logic should be put in the service-layer but currently its here
*/
package com.lsu.vizeq;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.content.pm.PackageManager;
import com.lsu.vizeq.R.color;
import com.lsu.vizeq.ServiceBinder.ServiceBinderDelegate;
import com.lsu.vizeq.SpotifyService.PlayerUpdateDelegate;
public class PlayerActivity extends Activity {
private ServiceBinder mBinder;
private WebService mWebservice;
private boolean mIsStarred;
// Disable the ui until a track has been loaded
private boolean mIsTrackLoaded;
private ArrayList<Track> mTracks = new ArrayList<Track>();
private String mAlbumUri;
private int mIndex = 0;
MyApplication myapp;
public static Camera cam;
private static MyApplication MyApp;
static RelativeLayout playerBackground;
static int flash = 0;
public static void SendBeat(String data) {
byte[] sendData = new byte[7];
try {
DatagramSocket sendSocket = new DatagramSocket();
sendData = data.getBytes();
Iterator it = MyApp.connectedUsers.entrySet().iterator();
while (it.hasNext())
{
Log.d("sendbeat", "hey");
Map.Entry pairs= (Map.Entry) it.next();
InetAddress IPAddress = (InetAddress) pairs.getValue();
String test = "name: " + pairs.getKey() + " ip: " + pairs.getValue();
Log.d("UDP",test);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7770);
sendSocket.send(sendPacket);
}
sendSocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public InetAddress getBroadcastAddress() throws IOException
{
WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for(int k = 0; k < 4; k++)
{
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
}
return InetAddress.getByAddress(quads);
}
private final PlayerUpdateDelegate playerPositionDelegate = new PlayerUpdateDelegate() {
@Override
public void onPlayerPositionChanged(float pos) {
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setProgress((int) (pos * seekBar.getMax()));
}
@Override
public void onEndOfTrack() {
playNext();
}
@Override
public void onPlayerPause() {
ImageView image = (ImageView) findViewById(R.id.player_play_pause_image);
image.setBackgroundResource(R.drawable.player_play_state);
}
@Override
public void onPlayerPlay() {
ImageView image = (ImageView) findViewById(R.id.player_play_pause_image);
image.setBackgroundResource(R.drawable.player_pause_state);
}
@Override
public void onTrackStarred() {
ImageView view = (ImageView) findViewById(R.id.star_image);
view.setBackgroundResource(R.drawable.star_state);
mIsStarred = true;
}
@Override
public void onTrackUnStarred() {
ImageView view = (ImageView) findViewById(R.id.star_image);
view.setBackgroundResource(R.drawable.star_disabled_state);
mIsStarred = false;
}
};
public void star() {
if (mTracks.size() == 0 || !mIsTrackLoaded)
return;
if (mIsStarred) {
mBinder.getService().unStar();
} else {
mBinder.getService().star();
}
}
public void togglePlay() {
if (mTracks.size() == 0)
return;
Track track = mTracks.get(mIndex);
mBinder.getService().togglePlay(track.getSpotifyUri(), playerPositionDelegate);
}
public void playNext() {
if (mTracks.size() == 0)
return;
mIndex++;
if (mIndex >= mTracks.size())
mIndex = 0;
mBinder.getService().playNext(mTracks.get(mIndex).getSpotifyUri(), playerPositionDelegate);
updateTrackState();
}
public void playPrev() {
if (mTracks.size() == 0)
return;
Log.i("", "Play previous song");
mIndex--;
if (mIndex < 0)
mIndex = mTracks.size() - 1;
mBinder.getService().playNext(mTracks.get(mIndex).getSpotifyUri(), playerPositionDelegate);
updateTrackState();
}
public void updateTrackState() {
ImageView view = (ImageView) findViewById(R.id.star_image);
view.setBackgroundResource(R.drawable.star_disabled_state);
if (mTracks.size() > 0)
{
((TextView) findViewById(R.id.track_info)).setText(mTracks.get(mIndex).getTrackInfo());
((TextView) findViewById(R.id.track_name)).setText(mTracks.get(mIndex).getTrackName());
}
}
protected void onNewIntent(Intent intent) {
int keycode = intent.getIntExtra("keycode", -1);
//if (keycode == -1)
//throw new RuntimeException("Could not identify the keycode");
if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keycode == KeyEvent.KEYCODE_HEADSETHOOK
|| keycode == KeyEvent.KEYCODE_MEDIA_PLAY || keycode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
togglePlay();
} else if (keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
playNext();
} else if (keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
star();
}
};
@Override
protected void onResume() {
// Register media buttons
AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// Start listening for button presses
am.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
super.onResume();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LightGreen)));
//Makes volume buttons control music stream even when nothing playing
setVolumeControlStream(AudioManager.STREAM_MUSIC);
myapp = (MyApplication) this.getApplicationContext();
MyApp = myapp;
playerBackground = (RelativeLayout) findViewById(R.id.PlayerLayout);
// //light sending stuff
// new Thread( new Runnable()
// {
// public void run()
// {
// try {
//
// DatagramSocket sendSocket = new DatagramSocket();
// int count = 0;
// while(true)
// {
// byte[] sendData = new byte[7];
// String data = "#FF0000";
// if (count%2==0)
// {
// data = "#000000";
// try
// {
// if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
// {
// cam = Camera.open();
// Parameters p = cam.getParameters();
// p.setFlashMode(Parameters.FLASH_MODE_TORCH);
// cam.setParameters(p);
// cam.startPreview();
// }
// }
// catch (Exception e) {
// e.printStackTrace();
// Log.d("Flashlight", "Exception flashLightOn");
// }
// }
// else
// {
// try
// {
// if (getPackageManager().hasSystemFeature(
// PackageManager.FEATURE_CAMERA_FLASH)) {
// cam.stopPreview();
// cam.release();
// cam = null;
// }
// }
// catch (Exception e)
// {
// e.printStackTrace();
// Log.d("Flashlight", "Exception flashLightOff");
// }
// }
// sendData = data.getBytes();
// Iterator it = myapp.connectedUsers.entrySet().iterator();
// while (it.hasNext())
// {
// Map.Entry pairs= (Map.Entry) it.next();
// InetAddress IPAddress = InetAddress.getByName((String) pairs.getValue());
// String test = "name: " + pairs.getKey() + " ip: " + pairs.getValue();
// Log.d("UDP",test);
// DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7770);
// sendSocket.send(sendPacket);
// //Log.d("UDP","Sent! "+ (String) pairs.getValue());
// }
// Log.d("UDP","Sent!");
// Thread.sleep(500);
// count++;
// if(count == 2000) break;
// }
// sendSocket.close();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }).start();
//end light sending stuff
new Thread( new Runnable()
{
public void run()
{
while (true)
{
flashOwnScreen();
try
{
Thread.sleep(150);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(300);
mBinder = new ServiceBinder(this);
mBinder.bindService(new ServiceBinderDelegate() {
@Override
public void onIsBound() {
}
});
Log.e("", "Your login id is " + Installation.id(this));
mWebservice = new WebService(Installation.id(this));
mWebservice.loadAlbum(new WebService.TracksLoadedDelegate() {
public void onTracksLoaded(ArrayList<Track> tracks, String albumUri, String imageUri) {
mTracks = tracks;
mAlbumUri = albumUri;
// Set the data of the first track
mIndex = 0;
updateTrackState();
AsyncTask<String, Integer, Bitmap> coverLoader = new AsyncTask<String, Integer, Bitmap>() {
@Override
protected Bitmap doInBackground(String... uris) {
try {
URL url = new URL(uris[0]);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
} catch (MalformedURLException e) {
throw new RuntimeException("Cannot load cover image", e);
} catch (IOException e) {
throw new RuntimeException("Cannot load cover image", e);
}
}
protected void onPostExecute(Bitmap bmp) {
((ImageView) findViewById(R.id.cover_image)).setImageBitmap(bmp);
}
};
coverLoader.execute(new String[] { imageUri });
// load the track
//mBinder.getService().playNext(mTracks.get(mIndex).getSpotifyUri(), playerPositionDelegate); //had getSpotifyUri
// track might not be loaded yet but assume it is
mIsTrackLoaded = true;
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mIsTrackLoaded)
mBinder.getService().seek((float) seekBar.getProgress() / seekBar.getMax());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
});
findViewById(R.id.player_prev).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playPrev();
}
});
findViewById(R.id.player_next).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playNext();
}
});
findViewById(R.id.player_play_pause).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
togglePlay();
}
});
findViewById(R.id.player_star).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
star();
}
});
findViewById(R.id.player_next_album).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mTracks.size() == 0 || mAlbumUri == null)
return;
AlertDialog.Builder builder = new AlertDialog.Builder(PlayerActivity.this);
builder.setMessage("Are you sure you want to skip to the next Album?").setTitle("Alert");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mWebservice.loadNextAlbum(Installation.id(PlayerActivity.this), mAlbumUri);
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
LibSpotifyWrapper.BeginPolling();
Log.d("what", "up");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_player, menu);
return true;
}
@Override
public void finish() {
mBinder.getService().destroy();
super.finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
Process.killProcess(Process.myPid());
mBinder.getService().destroy();
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void flashOwnScreen()
{
if (flash==1)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
playerBackground.setBackgroundColor(Color.BLUE);
}
});
flash = 0;
}
else
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
playerBackground.setBackgroundColor(Color.BLACK);
}
});
}
}
}
| src/com/lsu/vizeq/PlayerActivity.java | /*
Copyright (c) 2012, Spotify AB
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Spotify AB nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SPOTIFY AB BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* The player view and playlist logic put together.
*
* The logic should be put in the service-layer but currently its here
*/
package com.lsu.vizeq;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.content.pm.PackageManager;
import com.lsu.vizeq.R.color;
import com.lsu.vizeq.ServiceBinder.ServiceBinderDelegate;
import com.lsu.vizeq.SpotifyService.PlayerUpdateDelegate;
public class PlayerActivity extends Activity {
private ServiceBinder mBinder;
private WebService mWebservice;
private boolean mIsStarred;
// Disable the ui until a track has been loaded
private boolean mIsTrackLoaded;
private ArrayList<Track> mTracks = new ArrayList<Track>();
private String mAlbumUri;
private int mIndex = 0;
MyApplication myapp;
public static Camera cam;
private static MyApplication MyApp;
static RelativeLayout playerBackground;
static int flash = 0;
public static void SendBeat(String data) {
byte[] sendData = new byte[7];
try {
DatagramSocket sendSocket = new DatagramSocket();
sendData = data.getBytes();
Iterator it = MyApp.connectedUsers.entrySet().iterator();
while (it.hasNext())
{
Log.d("sendbeat", "hey");
Map.Entry pairs= (Map.Entry) it.next();
InetAddress IPAddress = (InetAddress) pairs.getValue();
String test = "name: " + pairs.getKey() + " ip: " + pairs.getValue();
Log.d("UDP",test);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7770);
sendSocket.send(sendPacket);
}
sendSocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public InetAddress getBroadcastAddress() throws IOException
{
WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for(int k = 0; k < 4; k++)
{
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
}
return InetAddress.getByAddress(quads);
}
private final PlayerUpdateDelegate playerPositionDelegate = new PlayerUpdateDelegate() {
@Override
public void onPlayerPositionChanged(float pos) {
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setProgress((int) (pos * seekBar.getMax()));
}
@Override
public void onEndOfTrack() {
playNext();
}
@Override
public void onPlayerPause() {
ImageView image = (ImageView) findViewById(R.id.player_play_pause_image);
image.setBackgroundResource(R.drawable.player_play_state);
}
@Override
public void onPlayerPlay() {
ImageView image = (ImageView) findViewById(R.id.player_play_pause_image);
image.setBackgroundResource(R.drawable.player_pause_state);
}
@Override
public void onTrackStarred() {
ImageView view = (ImageView) findViewById(R.id.star_image);
view.setBackgroundResource(R.drawable.star_state);
mIsStarred = true;
}
@Override
public void onTrackUnStarred() {
ImageView view = (ImageView) findViewById(R.id.star_image);
view.setBackgroundResource(R.drawable.star_disabled_state);
mIsStarred = false;
}
};
public void star() {
if (mTracks.size() == 0 || !mIsTrackLoaded)
return;
if (mIsStarred) {
mBinder.getService().unStar();
} else {
mBinder.getService().star();
}
}
public void togglePlay() {
if (mTracks.size() == 0)
return;
Track track = mTracks.get(mIndex);
mBinder.getService().togglePlay(track.getSpotifyUri(), playerPositionDelegate);
}
public void playNext() {
if (mTracks.size() == 0)
return;
mIndex++;
if (mIndex >= mTracks.size())
mIndex = 0;
mBinder.getService().playNext(mTracks.get(mIndex).getSpotifyUri(), playerPositionDelegate);
updateTrackState();
}
public void playPrev() {
if (mTracks.size() == 0)
return;
Log.i("", "Play previous song");
mIndex--;
if (mIndex < 0)
mIndex = mTracks.size() - 1;
mBinder.getService().playNext(mTracks.get(mIndex).getSpotifyUri(), playerPositionDelegate);
updateTrackState();
}
public void updateTrackState() {
ImageView view = (ImageView) findViewById(R.id.star_image);
view.setBackgroundResource(R.drawable.star_disabled_state);
if (mTracks.size() > 0)
{
((TextView) findViewById(R.id.track_info)).setText(mTracks.get(mIndex).getTrackInfo());
((TextView) findViewById(R.id.track_name)).setText(mTracks.get(mIndex).getTrackName());
}
}
protected void onNewIntent(Intent intent) {
int keycode = intent.getIntExtra("keycode", -1);
//if (keycode == -1)
//throw new RuntimeException("Could not identify the keycode");
if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keycode == KeyEvent.KEYCODE_HEADSETHOOK
|| keycode == KeyEvent.KEYCODE_MEDIA_PLAY || keycode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
togglePlay();
} else if (keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
playNext();
} else if (keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
star();
}
};
@Override
protected void onResume() {
// Register media buttons
AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
// Start listening for button presses
am.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
super.onResume();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LightGreen)));
//Makes volume buttons control music stream even when nothing playing
setVolumeControlStream(AudioManager.STREAM_MUSIC);
myapp = (MyApplication) this.getApplicationContext();
MyApp = myapp;
playerBackground = (RelativeLayout) findViewById(R.id.PlayerLayout);
// //light sending stuff
new Thread( new Runnable()
{
public void run()
{
try {
DatagramSocket sendSocket = new DatagramSocket();
int count = 0;
while(true)
{
byte[] sendData = new byte[7];
String data = "#FF0000";
if (count%2==0)
{
data = "#000000";
try
{
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
}
catch (Exception e) {
e.printStackTrace();
Log.d("Flashlight", "Exception flashLightOn");
}
}
else
{
try
{
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam.stopPreview();
cam.release();
cam = null;
}
}
catch (Exception e)
{
e.printStackTrace();
Log.d("Flashlight", "Exception flashLightOff");
}
}
sendData = data.getBytes();
Iterator it = myapp.connectedUsers.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs= (Map.Entry) it.next();
InetAddress IPAddress = InetAddress.getByName((String) pairs.getValue());
String test = "name: " + pairs.getKey() + " ip: " + pairs.getValue();
Log.d("UDP",test);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7770);
sendSocket.send(sendPacket);
//Log.d("UDP","Sent! "+ (String) pairs.getValue());
}
Log.d("UDP","Sent!");
Thread.sleep(500);
count++;
if(count == 2000) break;
}
sendSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//end light sending stuff
new Thread( new Runnable()
{
public void run()
{
while (true)
{
flashOwnScreen();
try
{
Thread.sleep(150);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(300);
mBinder = new ServiceBinder(this);
mBinder.bindService(new ServiceBinderDelegate() {
@Override
public void onIsBound() {
}
});
Log.e("", "Your login id is " + Installation.id(this));
mWebservice = new WebService(Installation.id(this));
mWebservice.loadAlbum(new WebService.TracksLoadedDelegate() {
public void onTracksLoaded(ArrayList<Track> tracks, String albumUri, String imageUri) {
mTracks = tracks;
mAlbumUri = albumUri;
// Set the data of the first track
mIndex = 0;
updateTrackState();
AsyncTask<String, Integer, Bitmap> coverLoader = new AsyncTask<String, Integer, Bitmap>() {
@Override
protected Bitmap doInBackground(String... uris) {
try {
URL url = new URL(uris[0]);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
} catch (MalformedURLException e) {
throw new RuntimeException("Cannot load cover image", e);
} catch (IOException e) {
throw new RuntimeException("Cannot load cover image", e);
}
}
protected void onPostExecute(Bitmap bmp) {
((ImageView) findViewById(R.id.cover_image)).setImageBitmap(bmp);
}
};
coverLoader.execute(new String[] { imageUri });
// load the track
//mBinder.getService().playNext(mTracks.get(mIndex).getSpotifyUri(), playerPositionDelegate); //had getSpotifyUri
// track might not be loaded yet but assume it is
mIsTrackLoaded = true;
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mIsTrackLoaded)
mBinder.getService().seek((float) seekBar.getProgress() / seekBar.getMax());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
});
findViewById(R.id.player_prev).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playPrev();
}
});
findViewById(R.id.player_next).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playNext();
}
});
findViewById(R.id.player_play_pause).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
togglePlay();
}
});
findViewById(R.id.player_star).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
star();
}
});
findViewById(R.id.player_next_album).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mTracks.size() == 0 || mAlbumUri == null)
return;
AlertDialog.Builder builder = new AlertDialog.Builder(PlayerActivity.this);
builder.setMessage("Are you sure you want to skip to the next Album?").setTitle("Alert");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mWebservice.loadNextAlbum(Installation.id(PlayerActivity.this), mAlbumUri);
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
LibSpotifyWrapper.BeginPolling();
Log.d("what", "up");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_player, menu);
return true;
}
@Override
public void finish() {
mBinder.getService().destroy();
super.finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
Process.killProcess(Process.myPid());
mBinder.getService().destroy();
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void flashOwnScreen()
{
if (flash==1)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
playerBackground.setBackgroundColor(Color.BLUE);
}
});
flash = 0;
}
else
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
playerBackground.setBackgroundColor(Color.BLACK);
}
});
}
}
}
| hotfix
| src/com/lsu/vizeq/PlayerActivity.java | hotfix | <ide><path>rc/com/lsu/vizeq/PlayerActivity.java
<ide> playerBackground = (RelativeLayout) findViewById(R.id.PlayerLayout);
<ide>
<ide> // //light sending stuff
<del> new Thread( new Runnable()
<del> {
<del> public void run()
<del> {
<del> try {
<del>
<del> DatagramSocket sendSocket = new DatagramSocket();
<del> int count = 0;
<del> while(true)
<del> {
<del> byte[] sendData = new byte[7];
<del> String data = "#FF0000";
<del> if (count%2==0)
<del> {
<del> data = "#000000";
<del> try
<del> {
<del> if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
<del> {
<del> cam = Camera.open();
<del> Parameters p = cam.getParameters();
<del> p.setFlashMode(Parameters.FLASH_MODE_TORCH);
<del> cam.setParameters(p);
<del> cam.startPreview();
<del> }
<del> }
<del> catch (Exception e) {
<del> e.printStackTrace();
<del> Log.d("Flashlight", "Exception flashLightOn");
<del> }
<del> }
<del> else
<del> {
<del> try
<del> {
<del> if (getPackageManager().hasSystemFeature(
<del> PackageManager.FEATURE_CAMERA_FLASH)) {
<del> cam.stopPreview();
<del> cam.release();
<del> cam = null;
<del> }
<del> }
<del> catch (Exception e)
<del> {
<del> e.printStackTrace();
<del> Log.d("Flashlight", "Exception flashLightOff");
<del> }
<del> }
<del> sendData = data.getBytes();
<del> Iterator it = myapp.connectedUsers.entrySet().iterator();
<del> while (it.hasNext())
<del> {
<del> Map.Entry pairs= (Map.Entry) it.next();
<del> InetAddress IPAddress = InetAddress.getByName((String) pairs.getValue());
<del> String test = "name: " + pairs.getKey() + " ip: " + pairs.getValue();
<del> Log.d("UDP",test);
<del> DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7770);
<del> sendSocket.send(sendPacket);
<del> //Log.d("UDP","Sent! "+ (String) pairs.getValue());
<del> }
<del> Log.d("UDP","Sent!");
<del> Thread.sleep(500);
<del> count++;
<del> if(count == 2000) break;
<del> }
<del> sendSocket.close();
<del> } catch (Exception e) {
<del> // TODO Auto-generated catch block
<del> e.printStackTrace();
<del> }
<del> }
<del> }).start();
<add>// new Thread( new Runnable()
<add>// {
<add>// public void run()
<add>// {
<add>// try {
<add>//
<add>// DatagramSocket sendSocket = new DatagramSocket();
<add>// int count = 0;
<add>// while(true)
<add>// {
<add>// byte[] sendData = new byte[7];
<add>// String data = "#FF0000";
<add>// if (count%2==0)
<add>// {
<add>// data = "#000000";
<add>// try
<add>// {
<add>// if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
<add>// {
<add>// cam = Camera.open();
<add>// Parameters p = cam.getParameters();
<add>// p.setFlashMode(Parameters.FLASH_MODE_TORCH);
<add>// cam.setParameters(p);
<add>// cam.startPreview();
<add>// }
<add>// }
<add>// catch (Exception e) {
<add>// e.printStackTrace();
<add>// Log.d("Flashlight", "Exception flashLightOn");
<add>// }
<add>// }
<add>// else
<add>// {
<add>// try
<add>// {
<add>// if (getPackageManager().hasSystemFeature(
<add>// PackageManager.FEATURE_CAMERA_FLASH)) {
<add>// cam.stopPreview();
<add>// cam.release();
<add>// cam = null;
<add>// }
<add>// }
<add>// catch (Exception e)
<add>// {
<add>// e.printStackTrace();
<add>// Log.d("Flashlight", "Exception flashLightOff");
<add>// }
<add>// }
<add>// sendData = data.getBytes();
<add>// Iterator it = myapp.connectedUsers.entrySet().iterator();
<add>// while (it.hasNext())
<add>// {
<add>// Map.Entry pairs= (Map.Entry) it.next();
<add>// InetAddress IPAddress = InetAddress.getByName((String) pairs.getValue());
<add>// String test = "name: " + pairs.getKey() + " ip: " + pairs.getValue();
<add>// Log.d("UDP",test);
<add>// DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7770);
<add>// sendSocket.send(sendPacket);
<add>// //Log.d("UDP","Sent! "+ (String) pairs.getValue());
<add>// }
<add>// Log.d("UDP","Sent!");
<add>// Thread.sleep(500);
<add>// count++;
<add>// if(count == 2000) break;
<add>// }
<add>// sendSocket.close();
<add>// } catch (Exception e) {
<add>// // TODO Auto-generated catch block
<add>// e.printStackTrace();
<add>// }
<add>// }
<add>// }).start();
<ide> //end light sending stuff
<ide>
<ide> new Thread( new Runnable() |
|
Java | apache-2.0 | be4c48fb07a0359f3d18ffdc29898af7fc4f358d | 0 | chirino/fabric8v2,KurtStam/fabric8,chirino/fabric8v2,rhuss/fabric8,KurtStam/fabric8,rhuss/fabric8,KurtStam/fabric8,rhuss/fabric8,dhirajsb/fabric8,dhirajsb/fabric8,dhirajsb/fabric8,rhuss/fabric8,chirino/fabric8v2,dhirajsb/fabric8,KurtStam/fabric8,chirino/fabric8v2 | /**
* Copyright 2005-2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.kubernetes.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.fabric8.kubernetes.api.extensions.Templates;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ReplicationControllerSpec;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretVolumeSource;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceAccount;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.extensions.DaemonSet;
import io.fabric8.kubernetes.api.model.extensions.Ingress;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.ClientOperation;
import io.fabric8.kubernetes.client.dsl.ClientResource;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.ImageStream;
import io.fabric8.openshift.api.model.OAuthClient;
import io.fabric8.openshift.api.model.Route;
import io.fabric8.openshift.api.model.Template;
import io.fabric8.openshift.client.DefaultOpenShiftClient;
import io.fabric8.openshift.client.OpenShiftClient;
import io.fabric8.openshift.client.OpenShiftNotAvailableException;
import io.fabric8.utils.Files;
import io.fabric8.utils.IOHelpers;
import io.fabric8.utils.Objects;
import io.fabric8.utils.Strings;
import io.fabric8.utils.Systems;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import static io.fabric8.kubernetes.api.KubernetesHelper.getKind;
import static io.fabric8.kubernetes.api.KubernetesHelper.getName;
import static io.fabric8.kubernetes.api.KubernetesHelper.getObjectId;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateAnnotations;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateLabels;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateMetadata;
import static io.fabric8.kubernetes.api.KubernetesHelper.loadJson;
import static io.fabric8.kubernetes.api.KubernetesHelper.summaryText;
import static io.fabric8.kubernetes.api.KubernetesHelper.toItemList;
/**
* Applies DTOs to the current Kubernetes master
*/
public class Controller {
private static final transient Logger LOG = LoggerFactory.getLogger(Controller.class);
private final KubernetesClient kubernetesClient;
private boolean throwExceptionOnError = true;
private boolean allowCreate = true;
private boolean recreateMode;
private boolean servicesOnlyMode;
private boolean ignoreServiceMode;
private boolean ignoreRunningOAuthClients = true;
private boolean rollingUpgrade;
private boolean processTemplatesLocally;
private File logJsonDir;
private File basedir;
private boolean failOnMissingParameterValue;
private boolean supportOAuthClients;
private boolean deletePodsOnReplicationControllerUpdate = true;
private String namesapce = KubernetesHelper.defaultNamespace();
private boolean requireSecretsCreatedBeforeReplicationControllers;
private boolean rollingUpgradePreserveScale = true;
public Controller() {
this(new DefaultKubernetesClient());
}
public Controller(KubernetesClient kubernetesClient) {
this.kubernetesClient = kubernetesClient;
}
public String apply(File file) throws Exception {
String ext = Files.getFileExtension(file);
if ("yaml".equalsIgnoreCase(ext)) {
return applyYaml(file);
} else if ("json".equalsIgnoreCase(ext)) {
return applyJson(file);
} else {
throw new IllegalArgumentException("Unknown file type " + ext);
}
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(byte[] json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(String json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(File json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given YAML to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyYaml(String yaml) throws Exception {
String json = convertYamlToJson(yaml);
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given YAML to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyYaml(File yaml) throws Exception {
String json = convertYamlToJson(yaml);
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
private String convertYamlToJson(String yamlString) throws FileNotFoundException {
Yaml yaml = new Yaml();
Map<String, Object> map = (Map<String, Object>) yaml.load(yamlString);
JSONObject jsonObject = new JSONObject(map);
return jsonObject.toString();
}
private String convertYamlToJson(File yamlFile) throws FileNotFoundException {
Yaml yaml = new Yaml();
FileInputStream fstream = new FileInputStream(yamlFile);
Map<String, Object> map = (Map<String, Object>) yaml.load(fstream);
JSONObject jsonObject = new JSONObject(map);
return jsonObject.toString();
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(InputStream json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given DTOs onto the Kubernetes master
*/
public void apply(Object dto, String sourceName) throws Exception {
if (dto instanceof List) {
List list = (List) dto;
for (Object element : list) {
if (dto == element) {
LOG.warn("Found recursive nested object for " + dto + " of class: " + dto.getClass().getName());
continue;
}
apply(element, sourceName);
}
} else if (dto instanceof KubernetesList) {
applyList((KubernetesList) dto, sourceName);
} else if (dto != null) {
applyEntity(dto, sourceName);
}
}
/**
* Applies the given DTOs onto the Kubernetes master
*/
public void applyEntity(Object dto, String sourceName) throws Exception {
if (dto instanceof Pod) {
applyPod((Pod) dto, sourceName);
} else if (dto instanceof ReplicationController) {
applyReplicationController((ReplicationController) dto, sourceName);
} else if (dto instanceof Service) {
applyService((Service) dto, sourceName);
} else if (dto instanceof Namespace) {
applyNamespace((Namespace) dto);
} else if (dto instanceof Route) {
applyRoute((Route) dto, sourceName);
} else if (dto instanceof BuildConfig) {
applyBuildConfig((BuildConfig) dto, sourceName);
} else if (dto instanceof DeploymentConfig) {
applyDeploymentConfig((DeploymentConfig) dto, sourceName);
} else if (dto instanceof ImageStream) {
applyImageStream((ImageStream) dto, sourceName);
} else if (dto instanceof OAuthClient) {
applyOAuthClient((OAuthClient) dto, sourceName);
} else if (dto instanceof PersistentVolumeClaim) {
applyResource((PersistentVolumeClaim) dto, sourceName, kubernetesClient.persistentVolumeClaims());
} else if (dto instanceof Template) {
applyTemplate((Template) dto, sourceName);
} else if (dto instanceof ServiceAccount) {
applyServiceAccount((ServiceAccount) dto, sourceName);
} else if (dto instanceof Secret) {
applySecret((Secret) dto, sourceName);
} else if (dto instanceof DaemonSet) {
applyResource((DaemonSet) dto, sourceName, kubernetesClient.extensions().daemonSets());
} else if (dto instanceof Ingress) {
applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
} else {
throw new IllegalArgumentException("Unknown entity type " + dto);
}
}
public void applyOAuthClient(OAuthClient entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
if (supportOAuthClients) {
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring OAuthClient: " + id);
return;
}
OAuthClient old = openShiftClient.oAuthClients().withName(id).get();
if (isRunning(old)) {
if (isIgnoreRunningOAuthClients()) {
LOG.info("Not updating the OAuthClient which are shared across namespaces as its already running");
return;
}
if (UserConfigurationCompare.configEqual(entity, old)) {
LOG.info("OAuthClient has not changed so not doing anything");
} else {
if (isRecreateMode()) {
openShiftClient.oAuthClients().withName(id).delete();
doCreateOAuthClient(entity, sourceName);
} else {
try {
Object answer = openShiftClient.oAuthClients().withName(id).replace(entity);
LOG.info("Updated OAuthClient result: " + answer);
} catch (Exception e) {
onApplyError("Failed to update OAuthClient from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating an OAuthClient from " + sourceName + " name " + getName(entity));
} else {
doCreateOAuthClient(entity, sourceName);
}
}
}
}
}
protected void doCreateOAuthClient(OAuthClient entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
Object result = null;
try {
result = openShiftClient.oAuthClients().create(entity);
} catch (Exception e) {
onApplyError("Failed to create OAuthClient from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
/**
* Creates/updates the template and processes it returning the processed DTOs
*/
public Object applyTemplate(Template entity, String sourceName) throws Exception {
installTemplate(entity, sourceName);
return processTemplate(entity, sourceName);
}
/**
* Installs the template into the namespace without processing it
*/
public void installTemplate(Template entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient == null) {
// lets not install the template on Kubernetes!
return;
}
if (!isProcessTemplatesLocally()) {
String namespace = getNamespace();
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
Template old = openShiftClient.templates().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
LOG.info("Template has not changed so not doing anything");
} else {
boolean recreateMode = isRecreateMode();
// TODO seems you can't update templates right now
recreateMode = true;
if (recreateMode) {
openShiftClient.templates().inNamespace(namespace).withName(id).delete();
doCreateTemplate(entity, namespace, sourceName);
} else {
LOG.info("Updating a Template from " + sourceName);
try {
Object answer = openShiftClient.templates().inNamespace(namespace).withName(id).replace(entity);
LOG.info("Updated Template: " + answer);
} catch (Exception e) {
onApplyError("Failed to update Template from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateTemplate(entity, namespace, sourceName);
}
}
}
}
public OpenShiftClient getOpenShiftClientOrNull() {
OpenShiftClient openShiftClient = null;
try {
openShiftClient = kubernetesClient.adapt(OpenShiftClient.class);
} catch (OpenShiftNotAvailableException e) {
// ignore
}
return openShiftClient;
}
public OpenShiftClient getOpenShiftClientOrJenkinshift() {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient == null) {
// lets try talk to the jenkinshift service which provides a BuildConfig REST API based on Jenkins
// for when using vanilla Kubernetes
String jenkinshiftUrl = Systems.getEnvVar("JENKINSHIFT_URL", "http://jenkinshift/");
openShiftClient = new DefaultOpenShiftClient(jenkinshiftUrl);
}
return openShiftClient;
}
protected void doCreateTemplate(Template entity, String namespace, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
LOG.info("Creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
try {
Object answer = openShiftClient.templates().inNamespace(namespace).create(entity);
logGeneratedEntity("Created Template: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to Template entity from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
/**
* Creates/updates a service account and processes it returning the processed DTOs
*/
public void applyServiceAccount(ServiceAccount serviceAccount, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(serviceAccount);
Objects.notNull(id, "No name for " + serviceAccount + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring ServiceAccount: " + id);
return;
}
ServiceAccount old = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(serviceAccount, old)) {
LOG.info("ServiceAccount has not changed so not doing anything");
} else {
if (isRecreateMode()) {
kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).delete();
doCreateServiceAccount(serviceAccount, namespace, sourceName);
} else {
LOG.info("Updating a ServiceAccount from " + sourceName);
try {
Object answer = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).replace(serviceAccount);
logGeneratedEntity("Updated ServiceAccount: ", namespace, serviceAccount, answer);
} catch (Exception e) {
onApplyError("Failed to update ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName(serviceAccount));
} else {
doCreateServiceAccount(serviceAccount, namespace, sourceName);
}
}
}
protected void doCreateServiceAccount(ServiceAccount serviceAccount, String namespace, String sourceName) {
LOG.info("Creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName
(serviceAccount));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.serviceAccounts().inNamespace(namespace).create(serviceAccount);
} else {
answer = kubernetesClient.serviceAccounts().inNamespace(getNamespace()).create(serviceAccount);
}
logGeneratedEntity("Created ServiceAccount: ", namespace, serviceAccount, answer);
} catch (Exception e) {
onApplyError("Failed to create ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
}
}
public void applySecret(Secret secret, String sourceName) throws Exception {
String namespace = getNamespace(secret);
String id = getName(secret);
Objects.notNull(id, "No name for " + secret + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring Secrets: " + id);
return;
}
Secret old = kubernetesClient.secrets().inNamespace(namespace).withName(id).get();
// check if the secret already exists or not
if (isRunning(old)) {
// if the secret already exists and is the same, then do nothing
if (UserConfigurationCompare.configEqual(secret, old)) {
LOG.info("Secret has not changed so not doing anything");
return;
} else {
if (isRecreateMode()) {
kubernetesClient.secrets().inNamespace(namespace).withName(id).delete();
doCreateSecret(secret, namespace, sourceName);
} else {
LOG.info("Updating a Secret from " + sourceName);
try {
Object answer = kubernetesClient.secrets().inNamespace(namespace).withName(id).replace(secret);
logGeneratedEntity("Updated Secret:", namespace, secret, answer);
} catch (Exception e) {
onApplyError("Failed to update secret from " + sourceName + ". " + e + ". " + secret, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a Secret from " + sourceName + " namespace " + namespace + " name " + getName(secret));
} else {
doCreateSecret(secret, namespace, sourceName);
}
}
}
protected void doCreateSecret(Secret secret, String namespace, String sourceName) {
LOG.info("Creating a Secret from " + sourceName + " namespace " + namespace + " name " + getName(secret));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.secrets().inNamespace(namespace).create(secret);
} else {
answer = kubernetesClient.secrets().inNamespace(getNamespace()).create(secret);
}
logGeneratedEntity("Created Secret: ", namespace, secret, answer);
} catch (Exception e) {
onApplyError("Failed to create Secret from " + sourceName + ". " + e + ". " + secret, e);
}
}
protected void logGeneratedEntity(String message, String namespace, HasMetadata entity, Object result) {
if (logJsonDir != null) {
File namespaceDir = new File(logJsonDir, namespace);
namespaceDir.mkdirs();
String kind = getKind(entity);
String name = KubernetesHelper.getName(entity);
if (Strings.isNotBlank(kind)) {
name = kind.toLowerCase() + "-" + name;
}
if (Strings.isNullOrBlank(name)) {
LOG.warn("No name for the entity " + entity);
} else {
String fileName = name + ".json";
File file = new File(namespaceDir, fileName);
if (file.exists()) {
int idx = 1;
while (true) {
fileName = name + "-" + idx++ + ".json";
file = new File(namespaceDir, fileName);
if (!file.exists()) {
break;
}
}
}
String text;
if (result instanceof String) {
text = result.toString();
} else {
try {
text = KubernetesHelper.toJson(result);
} catch (JsonProcessingException e) {
LOG.warn("Cannot convert " + result + " to JSON: " + e, e);
if (result != null) {
text = result.toString();
} else {
text = "null";
}
}
}
try {
IOHelpers.writeFully(file, text);
Object fileLocation = file;
if (basedir != null) {
String path = Files.getRelativePath(basedir, file);
if (path != null) {
fileLocation = Strings.stripPrefix(path, "/");
}
}
LOG.info(message + fileLocation);
} catch (IOException e) {
LOG.warn("Failed to write to file " + file + ". " + e, e);
}
return;
}
}
LOG.info(message + result);
}
public Object processTemplate(Template entity, String sourceName) {
try {
return Templates.processTemplatesLocally(entity, failOnMissingParameterValue);
} catch (IOException e) {
onApplyError("Failed to process template " + sourceName + ". " + e + ". " + entity, e);
return null;
}
/* Let's do it in the client side.
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
LOG.info("Creating Template " + namespace + ":" + id + " " + summaryText(entity));
Object result = null;
try {
Template response = kubernetes.templates().inNamespace(namespace).create(entity);
String json = OBJECT_MAPPER.writeValueAsString(response);
logGeneratedEntity("Template processed into: ", namespace, entity, json);
result = loadJson(json);
printSummary(result);
} catch (Exception e) {
onApplyError("Failed to create controller from " + sourceName + ". " + e + ". " + entity, e);
}
return result;
*/
}
protected void printSummary(Object kubeResource) throws IOException {
if (kubeResource != null) {
LOG.debug(" " + kubeResource.getClass().getSimpleName() + " " + kubeResource);
}
if (kubeResource instanceof Template) {
Template template = (Template) kubeResource;
String id = getName(template);
LOG.info(" Template " + id + " " + summaryText(template));
printSummary(template.getObjects());
return;
}
List<HasMetadata> list = toItemList(kubeResource);
for (HasMetadata object : list) {
if (object != null) {
if (object == list) {
LOG.debug("Ignoring recursive list " + list);
continue;
} else if (object instanceof List) {
printSummary(object);
} else {
String kind = object.getClass().getSimpleName();
String id = getObjectId(object);
LOG.info(" " + kind + " " + id + " " + summaryText(object));
}
}
}
}
public void applyRoute(Route entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (Strings.isNullOrBlank(namespace)) {
namespace = getNamespace();
}
Route route = openShiftClient.routes().inNamespace(namespace).withName(id).get();
if (route == null) {
try {
LOG.info("Creating Route " + namespace + ":" + id + " " + KubernetesHelper.summaryText(entity));
openShiftClient.routes().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create Route from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
}
public void applyBuildConfig(BuildConfig entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinshift();
if (openShiftClient != null) {
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (Strings.isNullOrBlank(namespace)) {
namespace = getNamespace();
}
applyNamespace(namespace);
BuildConfig old = openShiftClient.buildConfigs().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
LOG.info("BuildConfig has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting BuildConfig: " + id);
openShiftClient.buildConfigs().inNamespace(namespace).withName(id).delete();
doCreateBuildConfig(entity, namespace, sourceName);
} else {
LOG.info("Updating BuildConfig from " + sourceName);
try {
String resourceVersion = KubernetesHelper.getResourceVersion(old);
ObjectMeta metadata = KubernetesHelper.getOrCreateMetadata(entity);
metadata.setNamespace(namespace);
metadata.setResourceVersion(resourceVersion);
Object answer = openShiftClient.buildConfigs().inNamespace(namespace).withName(id).replace(entity);
logGeneratedEntity("Updated BuildConfig: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to update BuildConfig from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating BuildConfig from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateBuildConfig(entity, namespace, sourceName);
}
}
}
}
public void doCreateBuildConfig(BuildConfig entity, String namespace ,String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinshift();
if (openShiftClient != null) {
try {
openShiftClient.buildConfigs().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create BuildConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyDeploymentConfig(DeploymentConfig entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
try {
openShiftClient.deploymentConfigs().inNamespace(getNamespace()).create(entity);
} catch (Exception e) {
onApplyError("Failed to create DeploymentConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyImageStream(ImageStream entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
try {
openShiftClient.imageStreams().inNamespace(getNamespace()).create(entity);
} catch (Exception e) {
onApplyError("Failed to create BuildConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyList(KubernetesList list, String sourceName) throws Exception {
List<HasMetadata> entities = list.getItems();
if (entities != null) {
for (Object entity : entities) {
applyEntity(entity, sourceName);
}
}
}
public void applyService(Service service, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(service);
Objects.notNull(id, "No name for " + service + " " + sourceName);
if (isIgnoreServiceMode()) {
LOG.debug("Ignoring Service: " + namespace + ":" + id);
return;
}
Service old = kubernetesClient.services().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(service, old)) {
LOG.info("Service has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting Service: " + id);
kubernetesClient.services().inNamespace(namespace).withName(id).delete();
doCreateService(service, namespace, sourceName);
} else {
LOG.info("Updating a Service from " + sourceName);
try {
Object answer = kubernetesClient.services().inNamespace(namespace).withName(id).replace(service);
logGeneratedEntity("Updated Service: ", namespace, service, answer);
} catch (Exception e) {
onApplyError("Failed to update Service from " + sourceName + ". " + e + ". " + service, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a Service from " + sourceName + " namespace " + namespace + " name " + getName(service));
} else {
doCreateService(service, namespace, sourceName);
}
}
}
public <T extends HasMetadata,L,D> void applyResource(T resource, String sourceName, ClientOperation<T, L, D, ClientResource<T, D>> resources) throws Exception {
String namespace = getNamespace();
String id = getName(resource);
String kind = getKind(resource);
Objects.notNull(id, "No name for " + resource + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Ignoring " + kind + ": " + namespace + ":" + id);
return;
}
T old = resources.inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(resource, old)) {
LOG.info(kind + " has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting " + kind + ": " + id);
resources.inNamespace(namespace).withName(id).delete();
doCreateResource(resource, namespace, sourceName, resources);
} else {
LOG.info("Updating " + kind + " from " + sourceName);
try {
Object answer = resources.inNamespace(namespace).withName(id).replace(resource);
logGeneratedEntity("Updated " + kind + ": ", namespace, resource, answer);
} catch (Exception e) {
onApplyError("Failed to update " + kind + " from " + sourceName + ". " + e + ". " + resource, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a " + kind + " from " + sourceName + " namespace " + namespace + " name " + getName(resource));
} else {
doCreateResource(resource, namespace, sourceName, resources);
}
}
}
protected <T extends HasMetadata,L,D> void doCreateResource(T resource, String namespace ,String sourceName, ClientOperation<T, L, D, ClientResource<T, D>> resources) throws Exception {
String kind = getKind(resource);
LOG.info("Creating a " + kind + " from " + sourceName + " namespace " + namespace + " name " + getName(resource));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = resources.inNamespace(namespace).create(resource);
} else {
answer = resources.inNamespace(getNamespace()).create(resource);
}
logGeneratedEntity("Created " + kind + ": ", namespace, resource, answer);
} catch (Exception e) {
onApplyError("Failed to create " + kind + " from " + sourceName + ". " + e + ". " + resource, e);
}
}
protected void doCreateService(Service service, String namespace, String sourceName) {
LOG.info("Creating a Service from " + sourceName + " namespace " + namespace + " name " + getName(service));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.services().inNamespace(namespace).create(service);
} else {
answer = kubernetesClient.services().inNamespace(getNamespace()).create(service);
}
logGeneratedEntity("Created Service: ", namespace, service, answer);
} catch (Exception e) {
onApplyError("Failed to create Service from " + sourceName + ". " + e + ". " + service, e);
}
}
public void applyNamespace(String namespaceName) {
Namespace entity = new Namespace();
ObjectMeta metadata = getOrCreateMetadata(entity);
metadata.setName(namespaceName);
String namespace = kubernetesClient.getNamespace();
if (Strings.isNotBlank(namespace)) {
// lets associate this new namespace with the project that it was created from
getOrCreateLabels(entity).put("project", namespace);
}
applyNamespace(entity);
}
/**
* Returns true if the namespace is created
*/
public boolean applyNamespace(Namespace entity) {
String namespace = getOrCreateMetadata(entity).getName();
LOG.info("Using namespace: " + namespace);
String name = getName(entity);
Objects.notNull(name, "No name for " + entity );
Namespace old = kubernetesClient.namespaces().withName(name).get();
if (!isRunning(old)) {
try {
Object answer = kubernetesClient.namespaces().create(entity);
logGeneratedEntity("Created namespace: ", namespace, entity, answer);
return true;
} catch (Exception e) {
onApplyError("Failed to create namespace: " + name + " due " + e.getMessage(), e);
}
}
return false;
}
public void applyReplicationController(ReplicationController replicationController, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(replicationController);
Objects.notNull(id, "No name for " + replicationController + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring ReplicationController: " + namespace + ":" + id);
return;
}
ReplicationController old = kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(replicationController, old)) {
LOG.info("ReplicationController has not changed so not doing anything");
} else {
ReplicationControllerSpec newSpec = replicationController.getSpec();
ReplicationControllerSpec oldSpec = old.getSpec();
if (rollingUpgrade) {
LOG.info("Rolling upgrade of the ReplicationController: " + namespace + "/" + id);
// lets preserve the number of replicas currently running in the environment we are about to upgrade
if (rollingUpgradePreserveScale && newSpec != null && oldSpec != null) {
Integer replicas = oldSpec.getReplicas();
if (replicas != null) {
newSpec.setReplicas(replicas);
}
}
LOG.info("rollingUpgradePreserveScale " + rollingUpgradePreserveScale + " new replicas is " + (newSpec != null ? newSpec.getReplicas() : "<null>"));
kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).rolling().replace(replicationController);
} else if (isRecreateMode()) {
LOG.info("Deleting ReplicationController: " + id);
kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).delete();
doCreateReplicationController(replicationController, namespace, sourceName);
} else {
LOG.info("Updating ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
try {
Object answer = kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).replace(replicationController);
logGeneratedEntity("Updated replicationController: ", namespace, replicationController, answer);
if (deletePodsOnReplicationControllerUpdate) {
kubernetesClient.pods().inNamespace(namespace).withLabels(newSpec.getSelector()).delete();
LOG.info("Deleting any pods for the replication controller to ensure they use the new configuration");
} else {
LOG.info("Warning not deleted any pods so they could well be running with the old configuration!");
}
} catch (Exception e) {
onApplyError("Failed to update ReplicationController from " + sourceName + ". " + e + ". " + replicationController, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
} else {
doCreateReplicationController(replicationController, namespace, sourceName);
}
}
}
protected void doCreateReplicationController(ReplicationController replicationController, String namespace, String sourceName) {
LOG.info("Creating a ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
try {
// lets check that if secrets are required they exist
ReplicationControllerSpec spec = replicationController.getSpec();
if (spec != null) {
PodTemplateSpec template = spec.getTemplate();
if (template != null) {
PodSpec podSpec = template.getSpec();
validatePodSpec(podSpec, namespace);
}
}
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.replicationControllers().inNamespace(namespace).create(replicationController);
} else {
answer = kubernetesClient.replicationControllers().inNamespace(getNamespace()).create(replicationController);
}
logGeneratedEntity("Created ReplicationController: ", namespace, replicationController, answer);
} catch (Exception e) {
onApplyError("Failed to create ReplicationController from " + sourceName + ". " + e + ". " + replicationController, e);
}
}
/**
* Lets verify that any dependencies are available; such as volumes or secrets
*/
protected void validatePodSpec(PodSpec podSpec, String namespace) {
if (requireSecretsCreatedBeforeReplicationControllers) {
List<Volume> volumes = podSpec.getVolumes();
if (volumes != null) {
for (Volume volume : volumes) {
SecretVolumeSource secret = volume.getSecret();
if (secret != null) {
String secretName = secret.getSecretName();
if (Strings.isNotBlank(secretName)) {
KubernetesHelper.validateSecretExists(kubernetesClient, namespace, secretName);
}
}
}
}
}
}
public void applyPod(Pod pod, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(pod);
Objects.notNull(id, "No name for " + pod + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring Pod: " + namespace + ":" + id);
return;
}
Pod old = kubernetesClient.pods().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(pod, old)) {
LOG.info("Pod has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting Pod: " + id);
kubernetesClient.pods().inNamespace(namespace).withName(id).delete();
doCreatePod(pod, namespace, sourceName);
} else {
LOG.info("Updating a Pod from " + sourceName + " namespace " + namespace + " name " + getName(pod));
try {
Object answer = kubernetesClient.pods().inNamespace(namespace).withName(id).replace(pod);
LOG.info("Updated Pod result: " + answer);
} catch (Exception e) {
onApplyError("Failed to update Pod from " + sourceName + ". " + e + ". " + pod, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a pod from " + sourceName + " namespace " + namespace + " name " + getName(pod));
} else {
doCreatePod(pod, namespace, sourceName);
}
}
}
protected void doCreatePod(Pod pod, String namespace, String sourceName) {
LOG.info("Creating a Pod from " + sourceName + " namespace " + namespace + " name " + getName(pod));
try {
PodSpec podSpec = pod.getSpec();
if (podSpec != null) {
validatePodSpec(podSpec, namespace);
}
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.pods().inNamespace(namespace).create(pod);
} else {
answer = kubernetesClient.pods().inNamespace(getNamespace()).create(pod);
}
LOG.info("Created Pod result: " + answer);
} catch (Exception e) {
onApplyError("Failed to create Pod from " + sourceName + ". " + e + ". " + pod, e);
}
}
public String getNamespace() {
return namesapce;
}
/**
* Returns the namespace defined in the entity or the configured namespace
*/
protected String getNamespace(HasMetadata entity) {
String answer = KubernetesHelper.getNamespace(entity);
if (Strings.isNullOrBlank(answer)) {
answer = getNamespace();
}
// lest make sure the namespace exists
applyNamespace(answer);
return answer;
}
public void setNamespace(String namespace) {
this.namesapce = namespace;
}
public boolean isThrowExceptionOnError() {
return throwExceptionOnError;
}
public void setThrowExceptionOnError(boolean throwExceptionOnError) {
this.throwExceptionOnError = throwExceptionOnError;
}
public boolean isProcessTemplatesLocally() {
return processTemplatesLocally;
}
public void setProcessTemplatesLocally(boolean processTemplatesLocally) {
this.processTemplatesLocally = processTemplatesLocally;
}
public boolean isDeletePodsOnReplicationControllerUpdate() {
return deletePodsOnReplicationControllerUpdate;
}
public void setDeletePodsOnReplicationControllerUpdate(boolean deletePodsOnReplicationControllerUpdate) {
this.deletePodsOnReplicationControllerUpdate = deletePodsOnReplicationControllerUpdate;
}
public File getLogJsonDir() {
return logJsonDir;
}
/**
* Lets you configure the directory where JSON logging files should go
*/
public void setLogJsonDir(File logJsonDir) {
this.logJsonDir = logJsonDir;
}
public File getBasedir() {
return basedir;
}
public void setBasedir(File basedir) {
this.basedir = basedir;
}
protected boolean isRunning(HasMetadata entity) {
return entity != null;
}
/**
* Logs an error applying some JSON to Kubernetes and optionally throws an exception
*/
protected void onApplyError(String message, Exception e) {
LOG.error(message, e);
if (throwExceptionOnError) {
throw new RuntimeException(message, e);
}
}
/**
* Returns true if this controller allows new resources to be created in the given namespace
*/
public boolean isAllowCreate() {
return allowCreate;
}
public void setAllowCreate(boolean allowCreate) {
this.allowCreate = allowCreate;
}
/**
* If enabled then updates are performed by deleting the resource first then creating it
*/
public boolean isRecreateMode() {
return recreateMode;
}
public void setRecreateMode(boolean recreateMode) {
this.recreateMode = recreateMode;
}
public void setServicesOnlyMode(boolean servicesOnlyMode) {
this.servicesOnlyMode = servicesOnlyMode;
}
/**
* If enabled then only services are created/updated to allow services to be created/updated across
* a number of apps before any pods/replication controllers are updated
*/
public boolean isServicesOnlyMode() {
return servicesOnlyMode;
}
/**
* If enabled then all services are ignored to avoid them being recreated. This is useful if you want to
* recreate ReplicationControllers and Pods but leave Services as they are to avoid the portalIP addresses
* changing
*/
public boolean isIgnoreServiceMode() {
return ignoreServiceMode;
}
public void setIgnoreServiceMode(boolean ignoreServiceMode) {
this.ignoreServiceMode = ignoreServiceMode;
}
public boolean isIgnoreRunningOAuthClients() {
return ignoreRunningOAuthClients;
}
public void setIgnoreRunningOAuthClients(boolean ignoreRunningOAuthClients) {
this.ignoreRunningOAuthClients = ignoreRunningOAuthClients;
}
public boolean isFailOnMissingParameterValue() {
return failOnMissingParameterValue;
}
public void setFailOnMissingParameterValue(boolean failOnMissingParameterValue) {
this.failOnMissingParameterValue = failOnMissingParameterValue;
}
public boolean isSupportOAuthClients() {
return supportOAuthClients;
}
public void setSupportOAuthClients(boolean supportOAuthClients) {
this.supportOAuthClients = supportOAuthClients;
}
public boolean isRequireSecretsCreatedBeforeReplicationControllers() {
return requireSecretsCreatedBeforeReplicationControllers;
}
public void setRequireSecretsCreatedBeforeReplicationControllers(boolean requireSecretsCreatedBeforeReplicationControllers) {
this.requireSecretsCreatedBeforeReplicationControllers = requireSecretsCreatedBeforeReplicationControllers;
}
public boolean isRollingUpgrade() {
return rollingUpgrade;
}
public void setRollingUpgrade(boolean rollingUpgrade) {
this.rollingUpgrade = rollingUpgrade;
}
public boolean isRollingUpgradePreserveScale() {
return rollingUpgradePreserveScale;
}
public void setRollingUpgradePreserveScale(boolean rollingUpgradePreserveScale) {
this.rollingUpgradePreserveScale = rollingUpgradePreserveScale;
}
}
| components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/Controller.java | /**
* Copyright 2005-2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.kubernetes.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.fabric8.kubernetes.api.extensions.Templates;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ReplicationControllerSpec;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretVolumeSource;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceAccount;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.extensions.DaemonSet;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.ClientOperation;
import io.fabric8.kubernetes.client.dsl.ClientResource;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.ImageStream;
import io.fabric8.openshift.api.model.OAuthClient;
import io.fabric8.openshift.api.model.Route;
import io.fabric8.openshift.api.model.Template;
import io.fabric8.openshift.client.DefaultOpenShiftClient;
import io.fabric8.openshift.client.OpenShiftClient;
import io.fabric8.openshift.client.OpenShiftNotAvailableException;
import io.fabric8.utils.Files;
import io.fabric8.utils.IOHelpers;
import io.fabric8.utils.Objects;
import io.fabric8.utils.Strings;
import io.fabric8.utils.Systems;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import static io.fabric8.kubernetes.api.KubernetesHelper.getKind;
import static io.fabric8.kubernetes.api.KubernetesHelper.getName;
import static io.fabric8.kubernetes.api.KubernetesHelper.getObjectId;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateAnnotations;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateLabels;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateMetadata;
import static io.fabric8.kubernetes.api.KubernetesHelper.loadJson;
import static io.fabric8.kubernetes.api.KubernetesHelper.summaryText;
import static io.fabric8.kubernetes.api.KubernetesHelper.toItemList;
/**
* Applies DTOs to the current Kubernetes master
*/
public class Controller {
private static final transient Logger LOG = LoggerFactory.getLogger(Controller.class);
private final KubernetesClient kubernetesClient;
private boolean throwExceptionOnError = true;
private boolean allowCreate = true;
private boolean recreateMode;
private boolean servicesOnlyMode;
private boolean ignoreServiceMode;
private boolean ignoreRunningOAuthClients = true;
private boolean rollingUpgrade;
private boolean processTemplatesLocally;
private File logJsonDir;
private File basedir;
private boolean failOnMissingParameterValue;
private boolean supportOAuthClients;
private boolean deletePodsOnReplicationControllerUpdate = true;
private String namesapce = KubernetesHelper.defaultNamespace();
private boolean requireSecretsCreatedBeforeReplicationControllers;
private boolean rollingUpgradePreserveScale = true;
public Controller() {
this(new DefaultKubernetesClient());
}
public Controller(KubernetesClient kubernetesClient) {
this.kubernetesClient = kubernetesClient;
}
public String apply(File file) throws Exception {
String ext = Files.getFileExtension(file);
if ("yaml".equalsIgnoreCase(ext)) {
return applyYaml(file);
} else if ("json".equalsIgnoreCase(ext)) {
return applyJson(file);
} else {
throw new IllegalArgumentException("Unknown file type " + ext);
}
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(byte[] json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(String json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(File json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given YAML to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyYaml(String yaml) throws Exception {
String json = convertYamlToJson(yaml);
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given YAML to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyYaml(File yaml) throws Exception {
String json = convertYamlToJson(yaml);
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
private String convertYamlToJson(String yamlString) throws FileNotFoundException {
Yaml yaml = new Yaml();
Map<String, Object> map = (Map<String, Object>) yaml.load(yamlString);
JSONObject jsonObject = new JSONObject(map);
return jsonObject.toString();
}
private String convertYamlToJson(File yamlFile) throws FileNotFoundException {
Yaml yaml = new Yaml();
FileInputStream fstream = new FileInputStream(yamlFile);
Map<String, Object> map = (Map<String, Object>) yaml.load(fstream);
JSONObject jsonObject = new JSONObject(map);
return jsonObject.toString();
}
/**
* Applies the given JSON to the underlying REST APIs in a single operation without needing to explicitly parse first.
*/
public String applyJson(InputStream json) throws Exception {
Object dto = loadJson(json);
apply(dto, "REST call");
return "";
}
/**
* Applies the given DTOs onto the Kubernetes master
*/
public void apply(Object dto, String sourceName) throws Exception {
if (dto instanceof List) {
List list = (List) dto;
for (Object element : list) {
if (dto == element) {
LOG.warn("Found recursive nested object for " + dto + " of class: " + dto.getClass().getName());
continue;
}
apply(element, sourceName);
}
} else if (dto instanceof KubernetesList) {
applyList((KubernetesList) dto, sourceName);
} else if (dto != null) {
applyEntity(dto, sourceName);
}
}
/**
* Applies the given DTOs onto the Kubernetes master
*/
public void applyEntity(Object dto, String sourceName) throws Exception {
if (dto instanceof Pod) {
applyPod((Pod) dto, sourceName);
} else if (dto instanceof ReplicationController) {
applyReplicationController((ReplicationController) dto, sourceName);
} else if (dto instanceof Service) {
applyService((Service) dto, sourceName);
} else if (dto instanceof Namespace) {
applyNamespace((Namespace) dto);
} else if (dto instanceof Route) {
applyRoute((Route) dto, sourceName);
} else if (dto instanceof BuildConfig) {
applyBuildConfig((BuildConfig) dto, sourceName);
} else if (dto instanceof DeploymentConfig) {
applyDeploymentConfig((DeploymentConfig) dto, sourceName);
} else if (dto instanceof ImageStream) {
applyImageStream((ImageStream) dto, sourceName);
} else if (dto instanceof OAuthClient) {
applyOAuthClient((OAuthClient) dto, sourceName);
} else if (dto instanceof PersistentVolumeClaim) {
applyResource((PersistentVolumeClaim) dto, sourceName, kubernetesClient.persistentVolumeClaims());
} else if (dto instanceof Template) {
applyTemplate((Template) dto, sourceName);
} else if (dto instanceof ServiceAccount) {
applyServiceAccount((ServiceAccount) dto, sourceName);
} else if (dto instanceof Secret) {
applySecret((Secret) dto, sourceName);
} else if (dto instanceof DaemonSet) {
applyResource((DaemonSet) dto, sourceName, kubernetesClient.extensions().daemonSets());
} else {
throw new IllegalArgumentException("Unknown entity type " + dto);
}
}
public void applyOAuthClient(OAuthClient entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
if (supportOAuthClients) {
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring OAuthClient: " + id);
return;
}
OAuthClient old = openShiftClient.oAuthClients().withName(id).get();
if (isRunning(old)) {
if (isIgnoreRunningOAuthClients()) {
LOG.info("Not updating the OAuthClient which are shared across namespaces as its already running");
return;
}
if (UserConfigurationCompare.configEqual(entity, old)) {
LOG.info("OAuthClient has not changed so not doing anything");
} else {
if (isRecreateMode()) {
openShiftClient.oAuthClients().withName(id).delete();
doCreateOAuthClient(entity, sourceName);
} else {
try {
Object answer = openShiftClient.oAuthClients().withName(id).replace(entity);
LOG.info("Updated OAuthClient result: " + answer);
} catch (Exception e) {
onApplyError("Failed to update OAuthClient from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating an OAuthClient from " + sourceName + " name " + getName(entity));
} else {
doCreateOAuthClient(entity, sourceName);
}
}
}
}
}
protected void doCreateOAuthClient(OAuthClient entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
Object result = null;
try {
result = openShiftClient.oAuthClients().create(entity);
} catch (Exception e) {
onApplyError("Failed to create OAuthClient from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
/**
* Creates/updates the template and processes it returning the processed DTOs
*/
public Object applyTemplate(Template entity, String sourceName) throws Exception {
installTemplate(entity, sourceName);
return processTemplate(entity, sourceName);
}
/**
* Installs the template into the namespace without processing it
*/
public void installTemplate(Template entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient == null) {
// lets not install the template on Kubernetes!
return;
}
if (!isProcessTemplatesLocally()) {
String namespace = getNamespace();
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
Template old = openShiftClient.templates().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
LOG.info("Template has not changed so not doing anything");
} else {
boolean recreateMode = isRecreateMode();
// TODO seems you can't update templates right now
recreateMode = true;
if (recreateMode) {
openShiftClient.templates().inNamespace(namespace).withName(id).delete();
doCreateTemplate(entity, namespace, sourceName);
} else {
LOG.info("Updating a Template from " + sourceName);
try {
Object answer = openShiftClient.templates().inNamespace(namespace).withName(id).replace(entity);
LOG.info("Updated Template: " + answer);
} catch (Exception e) {
onApplyError("Failed to update Template from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateTemplate(entity, namespace, sourceName);
}
}
}
}
public OpenShiftClient getOpenShiftClientOrNull() {
OpenShiftClient openShiftClient = null;
try {
openShiftClient = kubernetesClient.adapt(OpenShiftClient.class);
} catch (OpenShiftNotAvailableException e) {
// ignore
}
return openShiftClient;
}
public OpenShiftClient getOpenShiftClientOrJenkinshift() {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient == null) {
// lets try talk to the jenkinshift service which provides a BuildConfig REST API based on Jenkins
// for when using vanilla Kubernetes
String jenkinshiftUrl = Systems.getEnvVar("JENKINSHIFT_URL", "http://jenkinshift/");
openShiftClient = new DefaultOpenShiftClient(jenkinshiftUrl);
}
return openShiftClient;
}
protected void doCreateTemplate(Template entity, String namespace, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
LOG.info("Creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
try {
Object answer = openShiftClient.templates().inNamespace(namespace).create(entity);
logGeneratedEntity("Created Template: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to Template entity from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
/**
* Creates/updates a service account and processes it returning the processed DTOs
*/
public void applyServiceAccount(ServiceAccount serviceAccount, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(serviceAccount);
Objects.notNull(id, "No name for " + serviceAccount + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring ServiceAccount: " + id);
return;
}
ServiceAccount old = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(serviceAccount, old)) {
LOG.info("ServiceAccount has not changed so not doing anything");
} else {
if (isRecreateMode()) {
kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).delete();
doCreateServiceAccount(serviceAccount, namespace, sourceName);
} else {
LOG.info("Updating a ServiceAccount from " + sourceName);
try {
Object answer = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).replace(serviceAccount);
logGeneratedEntity("Updated ServiceAccount: ", namespace, serviceAccount, answer);
} catch (Exception e) {
onApplyError("Failed to update ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName(serviceAccount));
} else {
doCreateServiceAccount(serviceAccount, namespace, sourceName);
}
}
}
protected void doCreateServiceAccount(ServiceAccount serviceAccount, String namespace, String sourceName) {
LOG.info("Creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName
(serviceAccount));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.serviceAccounts().inNamespace(namespace).create(serviceAccount);
} else {
answer = kubernetesClient.serviceAccounts().inNamespace(getNamespace()).create(serviceAccount);
}
logGeneratedEntity("Created ServiceAccount: ", namespace, serviceAccount, answer);
} catch (Exception e) {
onApplyError("Failed to create ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
}
}
public void applySecret(Secret secret, String sourceName) throws Exception {
String namespace = getNamespace(secret);
String id = getName(secret);
Objects.notNull(id, "No name for " + secret + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring Secrets: " + id);
return;
}
Secret old = kubernetesClient.secrets().inNamespace(namespace).withName(id).get();
// check if the secret already exists or not
if (isRunning(old)) {
// if the secret already exists and is the same, then do nothing
if (UserConfigurationCompare.configEqual(secret, old)) {
LOG.info("Secret has not changed so not doing anything");
return;
} else {
if (isRecreateMode()) {
kubernetesClient.secrets().inNamespace(namespace).withName(id).delete();
doCreateSecret(secret, namespace, sourceName);
} else {
LOG.info("Updating a Secret from " + sourceName);
try {
Object answer = kubernetesClient.secrets().inNamespace(namespace).withName(id).replace(secret);
logGeneratedEntity("Updated Secret:", namespace, secret, answer);
} catch (Exception e) {
onApplyError("Failed to update secret from " + sourceName + ". " + e + ". " + secret, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a Secret from " + sourceName + " namespace " + namespace + " name " + getName(secret));
} else {
doCreateSecret(secret, namespace, sourceName);
}
}
}
protected void doCreateSecret(Secret secret, String namespace, String sourceName) {
LOG.info("Creating a Secret from " + sourceName + " namespace " + namespace + " name " + getName(secret));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.secrets().inNamespace(namespace).create(secret);
} else {
answer = kubernetesClient.secrets().inNamespace(getNamespace()).create(secret);
}
logGeneratedEntity("Created Secret: ", namespace, secret, answer);
} catch (Exception e) {
onApplyError("Failed to create Secret from " + sourceName + ". " + e + ". " + secret, e);
}
}
protected void logGeneratedEntity(String message, String namespace, HasMetadata entity, Object result) {
if (logJsonDir != null) {
File namespaceDir = new File(logJsonDir, namespace);
namespaceDir.mkdirs();
String kind = getKind(entity);
String name = KubernetesHelper.getName(entity);
if (Strings.isNotBlank(kind)) {
name = kind.toLowerCase() + "-" + name;
}
if (Strings.isNullOrBlank(name)) {
LOG.warn("No name for the entity " + entity);
} else {
String fileName = name + ".json";
File file = new File(namespaceDir, fileName);
if (file.exists()) {
int idx = 1;
while (true) {
fileName = name + "-" + idx++ + ".json";
file = new File(namespaceDir, fileName);
if (!file.exists()) {
break;
}
}
}
String text;
if (result instanceof String) {
text = result.toString();
} else {
try {
text = KubernetesHelper.toJson(result);
} catch (JsonProcessingException e) {
LOG.warn("Cannot convert " + result + " to JSON: " + e, e);
if (result != null) {
text = result.toString();
} else {
text = "null";
}
}
}
try {
IOHelpers.writeFully(file, text);
Object fileLocation = file;
if (basedir != null) {
String path = Files.getRelativePath(basedir, file);
if (path != null) {
fileLocation = Strings.stripPrefix(path, "/");
}
}
LOG.info(message + fileLocation);
} catch (IOException e) {
LOG.warn("Failed to write to file " + file + ". " + e, e);
}
return;
}
}
LOG.info(message + result);
}
public Object processTemplate(Template entity, String sourceName) {
try {
return Templates.processTemplatesLocally(entity, failOnMissingParameterValue);
} catch (IOException e) {
onApplyError("Failed to process template " + sourceName + ". " + e + ". " + entity, e);
return null;
}
/* Let's do it in the client side.
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
LOG.info("Creating Template " + namespace + ":" + id + " " + summaryText(entity));
Object result = null;
try {
Template response = kubernetes.templates().inNamespace(namespace).create(entity);
String json = OBJECT_MAPPER.writeValueAsString(response);
logGeneratedEntity("Template processed into: ", namespace, entity, json);
result = loadJson(json);
printSummary(result);
} catch (Exception e) {
onApplyError("Failed to create controller from " + sourceName + ". " + e + ". " + entity, e);
}
return result;
*/
}
protected void printSummary(Object kubeResource) throws IOException {
if (kubeResource != null) {
LOG.debug(" " + kubeResource.getClass().getSimpleName() + " " + kubeResource);
}
if (kubeResource instanceof Template) {
Template template = (Template) kubeResource;
String id = getName(template);
LOG.info(" Template " + id + " " + summaryText(template));
printSummary(template.getObjects());
return;
}
List<HasMetadata> list = toItemList(kubeResource);
for (HasMetadata object : list) {
if (object != null) {
if (object == list) {
LOG.debug("Ignoring recursive list " + list);
continue;
} else if (object instanceof List) {
printSummary(object);
} else {
String kind = object.getClass().getSimpleName();
String id = getObjectId(object);
LOG.info(" " + kind + " " + id + " " + summaryText(object));
}
}
}
}
public void applyRoute(Route entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (Strings.isNullOrBlank(namespace)) {
namespace = getNamespace();
}
Route route = openShiftClient.routes().inNamespace(namespace).withName(id).get();
if (route == null) {
try {
LOG.info("Creating Route " + namespace + ":" + id + " " + KubernetesHelper.summaryText(entity));
openShiftClient.routes().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create Route from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
}
public void applyBuildConfig(BuildConfig entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinshift();
if (openShiftClient != null) {
String id = getName(entity);
Objects.notNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (Strings.isNullOrBlank(namespace)) {
namespace = getNamespace();
}
applyNamespace(namespace);
BuildConfig old = openShiftClient.buildConfigs().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
LOG.info("BuildConfig has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting BuildConfig: " + id);
openShiftClient.buildConfigs().inNamespace(namespace).withName(id).delete();
doCreateBuildConfig(entity, namespace, sourceName);
} else {
LOG.info("Updating BuildConfig from " + sourceName);
try {
String resourceVersion = KubernetesHelper.getResourceVersion(old);
ObjectMeta metadata = KubernetesHelper.getOrCreateMetadata(entity);
metadata.setNamespace(namespace);
metadata.setResourceVersion(resourceVersion);
Object answer = openShiftClient.buildConfigs().inNamespace(namespace).withName(id).replace(entity);
logGeneratedEntity("Updated BuildConfig: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to update BuildConfig from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating BuildConfig from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateBuildConfig(entity, namespace, sourceName);
}
}
}
}
public void doCreateBuildConfig(BuildConfig entity, String namespace ,String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinshift();
if (openShiftClient != null) {
try {
openShiftClient.buildConfigs().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create BuildConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyDeploymentConfig(DeploymentConfig entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
try {
openShiftClient.deploymentConfigs().inNamespace(getNamespace()).create(entity);
} catch (Exception e) {
onApplyError("Failed to create DeploymentConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyImageStream(ImageStream entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
if (openShiftClient != null) {
try {
openShiftClient.imageStreams().inNamespace(getNamespace()).create(entity);
} catch (Exception e) {
onApplyError("Failed to create BuildConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyList(KubernetesList list, String sourceName) throws Exception {
List<HasMetadata> entities = list.getItems();
if (entities != null) {
for (Object entity : entities) {
applyEntity(entity, sourceName);
}
}
}
public void applyService(Service service, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(service);
Objects.notNull(id, "No name for " + service + " " + sourceName);
if (isIgnoreServiceMode()) {
LOG.debug("Ignoring Service: " + namespace + ":" + id);
return;
}
Service old = kubernetesClient.services().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(service, old)) {
LOG.info("Service has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting Service: " + id);
kubernetesClient.services().inNamespace(namespace).withName(id).delete();
doCreateService(service, namespace, sourceName);
} else {
LOG.info("Updating a Service from " + sourceName);
try {
Object answer = kubernetesClient.services().inNamespace(namespace).withName(id).replace(service);
logGeneratedEntity("Updated Service: ", namespace, service, answer);
} catch (Exception e) {
onApplyError("Failed to update Service from " + sourceName + ". " + e + ". " + service, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a Service from " + sourceName + " namespace " + namespace + " name " + getName(service));
} else {
doCreateService(service, namespace, sourceName);
}
}
}
public <T extends HasMetadata,L,D> void applyResource(T resource, String sourceName, ClientOperation<T, L, D, ClientResource<T, D>> resources) throws Exception {
String namespace = getNamespace();
String id = getName(resource);
String kind = getKind(resource);
Objects.notNull(id, "No name for " + resource + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Ignoring " + kind + ": " + namespace + ":" + id);
return;
}
T old = resources.inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(resource, old)) {
LOG.info(kind + " has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting " + kind + ": " + id);
resources.inNamespace(namespace).withName(id).delete();
doCreateResource(resource, namespace, sourceName, resources);
} else {
LOG.info("Updating " + kind + " from " + sourceName);
try {
Object answer = resources.inNamespace(namespace).withName(id).replace(resource);
logGeneratedEntity("Updated " + kind + ": ", namespace, resource, answer);
} catch (Exception e) {
onApplyError("Failed to update " + kind + " from " + sourceName + ". " + e + ". " + resource, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a " + kind + " from " + sourceName + " namespace " + namespace + " name " + getName(resource));
} else {
doCreateResource(resource, namespace, sourceName, resources);
}
}
}
protected <T extends HasMetadata,L,D> void doCreateResource(T resource, String namespace ,String sourceName, ClientOperation<T, L, D, ClientResource<T, D>> resources) throws Exception {
String kind = getKind(resource);
LOG.info("Creating a " + kind + " from " + sourceName + " namespace " + namespace + " name " + getName(resource));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = resources.inNamespace(namespace).create(resource);
} else {
answer = resources.inNamespace(getNamespace()).create(resource);
}
logGeneratedEntity("Created " + kind + ": ", namespace, resource, answer);
} catch (Exception e) {
onApplyError("Failed to create " + kind + " from " + sourceName + ". " + e + ". " + resource, e);
}
}
protected void doCreateService(Service service, String namespace, String sourceName) {
LOG.info("Creating a Service from " + sourceName + " namespace " + namespace + " name " + getName(service));
try {
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.services().inNamespace(namespace).create(service);
} else {
answer = kubernetesClient.services().inNamespace(getNamespace()).create(service);
}
logGeneratedEntity("Created Service: ", namespace, service, answer);
} catch (Exception e) {
onApplyError("Failed to create Service from " + sourceName + ". " + e + ". " + service, e);
}
}
public void applyNamespace(String namespaceName) {
Namespace entity = new Namespace();
ObjectMeta metadata = getOrCreateMetadata(entity);
metadata.setName(namespaceName);
String namespace = kubernetesClient.getNamespace();
if (Strings.isNotBlank(namespace)) {
// lets associate this new namespace with the project that it was created from
getOrCreateLabels(entity).put("project", namespace);
}
applyNamespace(entity);
}
/**
* Returns true if the namespace is created
*/
public boolean applyNamespace(Namespace entity) {
String namespace = getOrCreateMetadata(entity).getName();
LOG.info("Using namespace: " + namespace);
String name = getName(entity);
Objects.notNull(name, "No name for " + entity );
Namespace old = kubernetesClient.namespaces().withName(name).get();
if (!isRunning(old)) {
try {
Object answer = kubernetesClient.namespaces().create(entity);
logGeneratedEntity("Created namespace: ", namespace, entity, answer);
return true;
} catch (Exception e) {
onApplyError("Failed to create namespace: " + name + " due " + e.getMessage(), e);
}
}
return false;
}
public void applyReplicationController(ReplicationController replicationController, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(replicationController);
Objects.notNull(id, "No name for " + replicationController + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring ReplicationController: " + namespace + ":" + id);
return;
}
ReplicationController old = kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(replicationController, old)) {
LOG.info("ReplicationController has not changed so not doing anything");
} else {
ReplicationControllerSpec newSpec = replicationController.getSpec();
ReplicationControllerSpec oldSpec = old.getSpec();
if (rollingUpgrade) {
LOG.info("Rolling upgrade of the ReplicationController: " + namespace + "/" + id);
// lets preserve the number of replicas currently running in the environment we are about to upgrade
if (rollingUpgradePreserveScale && newSpec != null && oldSpec != null) {
Integer replicas = oldSpec.getReplicas();
if (replicas != null) {
newSpec.setReplicas(replicas);
}
}
LOG.info("rollingUpgradePreserveScale " + rollingUpgradePreserveScale + " new replicas is " + (newSpec != null ? newSpec.getReplicas() : "<null>"));
kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).rolling().replace(replicationController);
} else if (isRecreateMode()) {
LOG.info("Deleting ReplicationController: " + id);
kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).delete();
doCreateReplicationController(replicationController, namespace, sourceName);
} else {
LOG.info("Updating ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
try {
Object answer = kubernetesClient.replicationControllers().inNamespace(namespace).withName(id).replace(replicationController);
logGeneratedEntity("Updated replicationController: ", namespace, replicationController, answer);
if (deletePodsOnReplicationControllerUpdate) {
kubernetesClient.pods().inNamespace(namespace).withLabels(newSpec.getSelector()).delete();
LOG.info("Deleting any pods for the replication controller to ensure they use the new configuration");
} else {
LOG.info("Warning not deleted any pods so they could well be running with the old configuration!");
}
} catch (Exception e) {
onApplyError("Failed to update ReplicationController from " + sourceName + ". " + e + ". " + replicationController, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
} else {
doCreateReplicationController(replicationController, namespace, sourceName);
}
}
}
protected void doCreateReplicationController(ReplicationController replicationController, String namespace, String sourceName) {
LOG.info("Creating a ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
try {
// lets check that if secrets are required they exist
ReplicationControllerSpec spec = replicationController.getSpec();
if (spec != null) {
PodTemplateSpec template = spec.getTemplate();
if (template != null) {
PodSpec podSpec = template.getSpec();
validatePodSpec(podSpec, namespace);
}
}
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.replicationControllers().inNamespace(namespace).create(replicationController);
} else {
answer = kubernetesClient.replicationControllers().inNamespace(getNamespace()).create(replicationController);
}
logGeneratedEntity("Created ReplicationController: ", namespace, replicationController, answer);
} catch (Exception e) {
onApplyError("Failed to create ReplicationController from " + sourceName + ". " + e + ". " + replicationController, e);
}
}
/**
* Lets verify that any dependencies are available; such as volumes or secrets
*/
protected void validatePodSpec(PodSpec podSpec, String namespace) {
if (requireSecretsCreatedBeforeReplicationControllers) {
List<Volume> volumes = podSpec.getVolumes();
if (volumes != null) {
for (Volume volume : volumes) {
SecretVolumeSource secret = volume.getSecret();
if (secret != null) {
String secretName = secret.getSecretName();
if (Strings.isNotBlank(secretName)) {
KubernetesHelper.validateSecretExists(kubernetesClient, namespace, secretName);
}
}
}
}
}
}
public void applyPod(Pod pod, String sourceName) throws Exception {
String namespace = getNamespace();
String id = getName(pod);
Objects.notNull(id, "No name for " + pod + " " + sourceName);
if (isServicesOnlyMode()) {
LOG.debug("Only processing Services right now so ignoring Pod: " + namespace + ":" + id);
return;
}
Pod old = kubernetesClient.pods().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(pod, old)) {
LOG.info("Pod has not changed so not doing anything");
} else {
if (isRecreateMode()) {
LOG.info("Deleting Pod: " + id);
kubernetesClient.pods().inNamespace(namespace).withName(id).delete();
doCreatePod(pod, namespace, sourceName);
} else {
LOG.info("Updating a Pod from " + sourceName + " namespace " + namespace + " name " + getName(pod));
try {
Object answer = kubernetesClient.pods().inNamespace(namespace).withName(id).replace(pod);
LOG.info("Updated Pod result: " + answer);
} catch (Exception e) {
onApplyError("Failed to update Pod from " + sourceName + ". " + e + ". " + pod, e);
}
}
}
} else {
if (!isAllowCreate()) {
LOG.warn("Creation disabled so not creating a pod from " + sourceName + " namespace " + namespace + " name " + getName(pod));
} else {
doCreatePod(pod, namespace, sourceName);
}
}
}
protected void doCreatePod(Pod pod, String namespace, String sourceName) {
LOG.info("Creating a Pod from " + sourceName + " namespace " + namespace + " name " + getName(pod));
try {
PodSpec podSpec = pod.getSpec();
if (podSpec != null) {
validatePodSpec(podSpec, namespace);
}
Object answer;
if (Strings.isNotBlank(namespace)) {
answer = kubernetesClient.pods().inNamespace(namespace).create(pod);
} else {
answer = kubernetesClient.pods().inNamespace(getNamespace()).create(pod);
}
LOG.info("Created Pod result: " + answer);
} catch (Exception e) {
onApplyError("Failed to create Pod from " + sourceName + ". " + e + ". " + pod, e);
}
}
public String getNamespace() {
return namesapce;
}
/**
* Returns the namespace defined in the entity or the configured namespace
*/
protected String getNamespace(HasMetadata entity) {
String answer = KubernetesHelper.getNamespace(entity);
if (Strings.isNullOrBlank(answer)) {
answer = getNamespace();
}
// lest make sure the namespace exists
applyNamespace(answer);
return answer;
}
public void setNamespace(String namespace) {
this.namesapce = namespace;
}
public boolean isThrowExceptionOnError() {
return throwExceptionOnError;
}
public void setThrowExceptionOnError(boolean throwExceptionOnError) {
this.throwExceptionOnError = throwExceptionOnError;
}
public boolean isProcessTemplatesLocally() {
return processTemplatesLocally;
}
public void setProcessTemplatesLocally(boolean processTemplatesLocally) {
this.processTemplatesLocally = processTemplatesLocally;
}
public boolean isDeletePodsOnReplicationControllerUpdate() {
return deletePodsOnReplicationControllerUpdate;
}
public void setDeletePodsOnReplicationControllerUpdate(boolean deletePodsOnReplicationControllerUpdate) {
this.deletePodsOnReplicationControllerUpdate = deletePodsOnReplicationControllerUpdate;
}
public File getLogJsonDir() {
return logJsonDir;
}
/**
* Lets you configure the directory where JSON logging files should go
*/
public void setLogJsonDir(File logJsonDir) {
this.logJsonDir = logJsonDir;
}
public File getBasedir() {
return basedir;
}
public void setBasedir(File basedir) {
this.basedir = basedir;
}
protected boolean isRunning(HasMetadata entity) {
return entity != null;
}
/**
* Logs an error applying some JSON to Kubernetes and optionally throws an exception
*/
protected void onApplyError(String message, Exception e) {
LOG.error(message, e);
if (throwExceptionOnError) {
throw new RuntimeException(message, e);
}
}
/**
* Returns true if this controller allows new resources to be created in the given namespace
*/
public boolean isAllowCreate() {
return allowCreate;
}
public void setAllowCreate(boolean allowCreate) {
this.allowCreate = allowCreate;
}
/**
* If enabled then updates are performed by deleting the resource first then creating it
*/
public boolean isRecreateMode() {
return recreateMode;
}
public void setRecreateMode(boolean recreateMode) {
this.recreateMode = recreateMode;
}
public void setServicesOnlyMode(boolean servicesOnlyMode) {
this.servicesOnlyMode = servicesOnlyMode;
}
/**
* If enabled then only services are created/updated to allow services to be created/updated across
* a number of apps before any pods/replication controllers are updated
*/
public boolean isServicesOnlyMode() {
return servicesOnlyMode;
}
/**
* If enabled then all services are ignored to avoid them being recreated. This is useful if you want to
* recreate ReplicationControllers and Pods but leave Services as they are to avoid the portalIP addresses
* changing
*/
public boolean isIgnoreServiceMode() {
return ignoreServiceMode;
}
public void setIgnoreServiceMode(boolean ignoreServiceMode) {
this.ignoreServiceMode = ignoreServiceMode;
}
public boolean isIgnoreRunningOAuthClients() {
return ignoreRunningOAuthClients;
}
public void setIgnoreRunningOAuthClients(boolean ignoreRunningOAuthClients) {
this.ignoreRunningOAuthClients = ignoreRunningOAuthClients;
}
public boolean isFailOnMissingParameterValue() {
return failOnMissingParameterValue;
}
public void setFailOnMissingParameterValue(boolean failOnMissingParameterValue) {
this.failOnMissingParameterValue = failOnMissingParameterValue;
}
public boolean isSupportOAuthClients() {
return supportOAuthClients;
}
public void setSupportOAuthClients(boolean supportOAuthClients) {
this.supportOAuthClients = supportOAuthClients;
}
public boolean isRequireSecretsCreatedBeforeReplicationControllers() {
return requireSecretsCreatedBeforeReplicationControllers;
}
public void setRequireSecretsCreatedBeforeReplicationControllers(boolean requireSecretsCreatedBeforeReplicationControllers) {
this.requireSecretsCreatedBeforeReplicationControllers = requireSecretsCreatedBeforeReplicationControllers;
}
public boolean isRollingUpgrade() {
return rollingUpgrade;
}
public void setRollingUpgrade(boolean rollingUpgrade) {
this.rollingUpgrade = rollingUpgrade;
}
public boolean isRollingUpgradePreserveScale() {
return rollingUpgradePreserveScale;
}
public void setRollingUpgradePreserveScale(boolean rollingUpgradePreserveScale) {
this.rollingUpgradePreserveScale = rollingUpgradePreserveScale;
}
}
| add support for Ingress
| components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/Controller.java | add support for Ingress | <ide><path>omponents/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/Controller.java
<ide> import io.fabric8.kubernetes.api.model.ServiceAccount;
<ide> import io.fabric8.kubernetes.api.model.Volume;
<ide> import io.fabric8.kubernetes.api.model.extensions.DaemonSet;
<add>import io.fabric8.kubernetes.api.model.extensions.Ingress;
<ide> import io.fabric8.kubernetes.client.DefaultKubernetesClient;
<ide> import io.fabric8.kubernetes.client.KubernetesClient;
<ide> import io.fabric8.kubernetes.client.dsl.ClientOperation;
<ide> applySecret((Secret) dto, sourceName);
<ide> } else if (dto instanceof DaemonSet) {
<ide> applyResource((DaemonSet) dto, sourceName, kubernetesClient.extensions().daemonSets());
<add> } else if (dto instanceof Ingress) {
<add> applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
<ide> } else {
<ide> throw new IllegalArgumentException("Unknown entity type " + dto);
<ide> } |
|
Java | apache-2.0 | f2bf2f7b9d42680398cab1461bf9d26d9b1870a2 | 0 | apache/lenya,apache/lenya,apache/lenya,apache/lenya | /*
* DocumentTypeBuilder.java
*
* Created on 9. April 2003, 10:11
*/
package org.apache.lenya.cms.publication;
import java.io.File;
import org.apache.lenya.xml.DocumentHelper;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* A builder for document types.
*
* @author <a href="mailto:[email protected]">Andreas Hartmann</a>
*/
public class DocumentTypeBuilder {
/** Creates a new instance of DocumentTypeBuilder */
public DocumentTypeBuilder() {
}
/**
* The default document types configuration directory, relative to the publication directory.
*/
public static final String DOCTYPE_DIRECTORY
= "config/doctypes".replace('/', File.separatorChar);
/*
* The default document types configuration file, relative to the publication directory.
*/
public static final String CONFIG_FILE
= "doctypes.xconf".replace('/', File.separatorChar);
/**
* Builds a document type for a given name.
*
* @param name A string value.
* @param publication The publication the document type belongs to.
* @return A document type object.
*/
public DocumentType buildDocumentType(String name, Publication publication)
throws DocumentTypeBuildException {
File configDirectory = new File(publication.getDirectory(), DOCTYPE_DIRECTORY);
File configFile = new File(configDirectory, CONFIG_FILE);
try {
Document document = DocumentHelper.readDocument(configFile);
DocumentHelper helper = new DocumentHelper();
String xPath = "doctypes/doc[@type = '" + name + "']";
Node doctypeNode = XPathAPI.selectSingleNode(document, xPath);
// TODO add doctype initialization code
}
catch (Exception e) {
throw new DocumentTypeBuildException(e);
}
DocumentType type = new DocumentType(name);
return type;
}
}
| src/java/org/apache/lenya/cms/publication/DocumentTypeBuilder.java | /*
* DocumentTypeBuilder.java
*
* Created on 9. April 2003, 10:11
*/
package org.apache.lenya.cms.publication;
import java.io.File;
import org.apache.lenya.xml.DocumentHelper;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* A builder for document types.
*
* @author <a href="mailto:[email protected]">Andreas Hartmann</a>
*/
public class DocumentTypeBuilder {
/** Creates a new instance of DocumentTypeBuilder */
public DocumentTypeBuilder() {
}
/**
* The default document types configuration file, relative to the publication directory.
*/
public static final String CONFIG_FILE
= "config/doctypes/doctypes.xconf".replace('/', File.separatorChar);
/**
* Builds a document type for a given name.
*
* @param name A string value.
* @param publication The publication the document type belongs to.
* @return A document type object.
*/
public DocumentType buildDocumentType(String name, Publication publication)
throws DocumentTypeBuildException {
File configFile = new File(publication.getDirectory(), CONFIG_FILE);
try {
Document document = DocumentHelper.readDocument(configFile);
DocumentHelper helper = new DocumentHelper();
String xPath = "doctypes/doc[@type = '" + name + "']";
Node doctypeNode = XPathAPI.selectSingleNode(document, xPath);
// TODO add doctype initialization code
}
catch (Exception e) {
throw new DocumentTypeBuildException(e);
}
DocumentType type = new DocumentType(name);
return type;
}
}
| added DOCTYPE_DIRECTORY field
git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@39731 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lenya/cms/publication/DocumentTypeBuilder.java | added DOCTYPE_DIRECTORY field | <ide><path>rc/java/org/apache/lenya/cms/publication/DocumentTypeBuilder.java
<ide> public DocumentTypeBuilder() {
<ide> }
<ide>
<add>
<ide> /**
<add> * The default document types configuration directory, relative to the publication directory.
<add> */
<add> public static final String DOCTYPE_DIRECTORY
<add> = "config/doctypes".replace('/', File.separatorChar);
<add> /*
<ide> * The default document types configuration file, relative to the publication directory.
<ide> */
<ide> public static final String CONFIG_FILE
<del> = "config/doctypes/doctypes.xconf".replace('/', File.separatorChar);
<add> = "doctypes.xconf".replace('/', File.separatorChar);
<add>
<ide>
<ide> /**
<ide> * Builds a document type for a given name.
<ide> public DocumentType buildDocumentType(String name, Publication publication)
<ide> throws DocumentTypeBuildException {
<ide>
<del> File configFile = new File(publication.getDirectory(), CONFIG_FILE);
<add> File configDirectory = new File(publication.getDirectory(), DOCTYPE_DIRECTORY);
<add> File configFile = new File(configDirectory, CONFIG_FILE);
<ide>
<ide> try {
<ide> Document document = DocumentHelper.readDocument(configFile); |
|
JavaScript | apache-2.0 | a23075140553a6ebf52622627ecab75ecfeddd84 | 0 | jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2 | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.graphics',
name: 'TreeNode',
extends: 'foam.graphics.Box',
requires: [
'foam.graphics.Box',
'foam.graphics.CView',
'foam.graphics.Label',
'foam.graphics.Line'
],
imports: [
'formatNode',
'graph',
'parentNode?',
'relationship',
'isAutoExpandedByDefault',
'childNodesForAutoExpansion'
],
exports: ['as parentNode'],
properties: [
'data',
[ 'height', 155 ],
[ 'width', 60 ],
[ 'padding', 30 ],
[ 'lineWidth', 0.5 ],
[ 'border', 'gray' ],
[ 'color', 'white' ],
{
name: 'outline',
documentation: `
An array containing the max left ( left edge plus padding of the leftmost node)
and max right ( right edge plus padding of the rightmost node) values per level
of the tree where index 0 is the root
`,
expression: function (x, width, expanded, childNodes, padding) {
var outlineBelowRoot = [];
/**
* We need to check the outlines of each child node against eachother regardless
* of overlap so that we get actual max left and max right of each level,
* overlap and corresponding adjustments are dealt with in the @layout method
*/
for (let i = 0; i < childNodes.length && expanded; i++) {
var childOutline = childNodes[i].outline.map(o => ({
left: o.left + x,
right: o.right + x,
}));
for (var j = 0; j < childOutline.length; j++) {
outlineBelowRoot[j] = outlineBelowRoot[j] || {
left: Number.MAX_SAFE_INTEGER,
right: Number.MIN_SAFE_INTEGER
};
outlineBelowRoot[j].left = Math.min(childOutline[j].left, outlineBelowRoot[j].left);
outlineBelowRoot[j].right = Math.max(childOutline[j].right, outlineBelowRoot[j].right);
}
}
var rootLevelOutline = [
{
left: x - width / 2 - padding / 2,
right: x + width / 2 + padding / 2
}
]
return rootLevelOutline.concat(outlineBelowRoot);
}
},
{
name: 'childNodes',
factory: function () { return []; }
},
{
name: 'x',
documentation: `
The x value of a node's position relative to their parent
`,
expression: function(neighborX, centerX) {
return neighborX + centerX;
}
},
{
class: 'Float',
name: 'neighborX',
documentation: `
The relative position of the current node's right neighbor
`
},
{
class: 'Float',
name: 'centerX',
documentation: `
The adjustment to the current node's x to properly
center the current node above their children
`
},
{
class: 'Boolean',
name: 'expanded',
expression: function(isAutoExpandedByDefault, childNodesForAutoExpansion, childNodes) {
if ( isAutoExpandedByDefault ) {
return childNodes.length < childNodesForAutoExpansion;
}
return false;
},
postSet: function() {
this.graph.doLayout();
}
}
],
methods: [
function initCView() {
this.SUPER();
this.formatNode();
if (this.relationship) {
this.data[this.relationship.forwardName].select(childData => {
this.addChildNode({
data: childData,
width: this.width,
height: this.height,
padding: this.padding,
lineWidth: this.lineWidth
});
});
}
this.canvas.on('click', (e) => {
var p = this.parent;
while ( this.cls_.isInstance(p) ) {
if ( ! p.expanded ) return;
p = p.parent;
}
var point = this.globalToLocalCoordinates({
w: 1,
x: e.offsetX,
y: e.offsetY,
});
/**
* need to adjust the x-value to the middle of the node and not the far left edge
* so that the pointer click registers correctly when clicking any part of the node
*/
point.x += this.width / 2;
if ( this.hitTest(point) ) {
this.expanded = ! this.expanded;
}
});
},
function paint(x) {
if ( ! this.parentNode || this.parentNode.expanded ) this.SUPER(x);
},
function paintSelf(x) {
x.save();
x.translate(-this.width / 2, 0);
this.SUPER(x);
x.restore();
this.paintConnectors(x);
},
function paintConnectors(x) {
function line(x1, y1, x2, y2) {
x.beginPath();
x.moveTo(x1, y1);
x.lineTo(x2, y2);
x.stroke();
}
// Paint lines to childNodes
x.lineWidth = this.lineWidth;
x.strokeStyle = this.border;
if (this.expanded && this.childNodes.length) {
var h = this.childNodes[0].y * 3 / 4;
var l = this.childNodes.length;
line(0, this.height, 0, h);
for (var i = 0; i < l; i++) {
var c = this.childNodes[i];
line(0, h, c.x, h);
line(c.x, h, c.x, c.y);
}
}
// Paint expand/collapse arrow
x.lineWidth = this.borderWidth;
if (this.childNodes.length) {
var d = this.expanded ? 5 : -5;
var y = this.height - 8;
line(-5, y, 0, y + d);
line(0, y + d, 5, y);
}
},
function addChildNode(args) {
var node = this.cls_.create(args, this);
node.y = this.height * 2;
this.add(node);
this.childNodes = this.childNodes.concat(node);
node.outline$.sub(() => {
/**
* Here we are forcing a recalculation of the outline b/c there is no way to subscribe
* to all children outlines via an expression since outline is an array
*/
this.outline = [];
this.outline = undefined
});
return this;
},
function distanceTo(node) {
minLevels = Math.min(this.outline.length, node.outline.length);
var minDistance = Number.MAX_SAFE_INTEGER;
for (var i = 0; i < minLevels; i++) {
var overlapDistance = node.outline[i].left - this.outline[i].right;
minDistance = Math.min(minDistance, overlapDistance);
}
return minDistance;
},
/**
* We need to first ensure that there are no overlaps between subtrees
* and then we can take care of subtrees being too far apart because
* otherwise they will conflict with eachother and go into an infinite loop
* since nodes can have be a positive distance away from each other and be properly spaced (i.e. higher levels in the tree)
* whereas nodes cannot be a negative distance since that means an overlap has occured
* once the above is done we can finally center the nodes
*/
function layout() {
var moved = false;
for ( var i = 0; i < this.childNodes.length; i++ ) {
var n1 = this.childNodes[i];
for ( var j = i + 1; j < this.childNodes.length; j++ ){
var n2 = this.childNodes[j];
var distance = n1.distanceTo(n2);
if ( distance < 0 ) {
n2.neighborX -= distance;
moved = true;
}
}
}
for ( var i = 0; i < this.childNodes.length - 1; i++ ) {
var n1 = this.childNodes[i];
var n2 = this.childNodes[i + 1];
var distance = n1.distanceTo(n2);
if ( distance > 0 ) {
for ( var j = 0; j < i; j++ ) {
var n3 = this.childNodes[j];
distance = Math.min(distance, n3.distanceTo(n2));
}
if ( distance ) {
n2.neighborX -= distance;
moved = true;
}
}
}
for ( var i = 0; i < this.childNodes.length; i++ ){
if ( this.childNodes[i].layout() ) moved = true;
}
if ( this.outline[1] ) {
var rootLevelWidth = this.outline[0].right - this.outline[0].left;
var childLevelWidth = this.outline[1].right - this.outline[1].left;
var d = - (childLevelWidth - rootLevelWidth) / 2;
this.childNodes.forEach(c => {
if ( c.centerX != d ) {
c.centerX = d;
moved = true;
}
})
}
return moved;
},
function findNode(id){
if (this.data.id === id) {
return this;
}
for (var i = 0; i < this.childNodes.length; i++) {
var foundNode = this.childNodes[i].findNode(id);
if (foundNode) {
return foundNode;
}
}
}
]
})
| src/foam/graphics/TreeNode.js | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.graphics',
name: 'TreeNode',
extends: 'foam.graphics.Box',
requires: [
'foam.graphics.Box',
'foam.graphics.CView',
'foam.graphics.Label',
'foam.graphics.Line'
],
imports: [
'formatNode',
'graph',
'parentNode?',
'relationship',
'isAutoExpandedByDefault',
'childNodesForAutoExpansion'
],
exports: ['as parentNode'],
properties: [
'data',
[ 'height', 155 ],
[ 'width', 60 ],
[ 'padding', 30 ],
[ 'lineWidth', 0.5 ],
[ 'border', 'gray' ],
[ 'color', 'white' ],
{
name: 'outline',
documentation: `
An array containing the max left ( left edge plus padding of the leftmost node)
and max right ( right edge plus padding of the rightmost node) values per level
of the tree where index 0 is the root
`,
expression: function (x, width, expanded, childNodes, padding) {
var outlineBelowRoot = [];
/**
* We need to check the outlines of each child node against eachother regardless
* of overlap so that we get actual max left and max right of each level,
* overlap and corresponding adjustments are dealt with in the @layout method
*/
for (let i = 0; i < childNodes.length && expanded; i++) {
var childOutline = childNodes[i].outline.map(o => ({
left: o.left + x,
right: o.right + x,
}));
for (var j = 0; j < childOutline.length; j++) {
outlineBelowRoot[j] = outlineBelowRoot[j] || {
left: Number.MAX_SAFE_INTEGER,
right: Number.MIN_SAFE_INTEGER
};
outlineBelowRoot[j].left = Math.min(childOutline[j].left, outlineBelowRoot[j].left);
outlineBelowRoot[j].right = Math.max(childOutline[j].right, outlineBelowRoot[j].right);
}
}
var rootLevelOutline = [
{
left: x - width / 2 - padding / 2,
right: x + width / 2 + padding / 2
}
]
return rootLevelOutline.concat(outlineBelowRoot);
}
},
{
name: 'childNodes',
factory: function () { return []; }
},
{
name: 'x',
documentation: `
The x value of a node's position relative to their parent
`,
expression: function(neighborX, centerX) {
return neighborX + centerX;
}
},
{
class: 'Float',
name: 'neighborX',
documentation: `
The relative position of the current node's right neighbor
`
},
{
class: 'Float',
name: 'centerX',
documentation: `
The adjustment to the current node's x to properly
center the current node above their children
`
},
{
class: 'Boolean',
name: 'expanded',
expression: function(isAutoExpandedByDefault, childNodesForAutoExpansion, childNodes) {
if ( isAutoExpandedByDefault ) {
return childNodes < childNodesForAutoExpansion;
}
return false;
},
postSet: function() {
this.graph.doLayout();
}
}
],
methods: [
function initCView() {
this.SUPER();
this.formatNode();
if (this.relationship) {
this.data[this.relationship.forwardName].select(childData => {
this.addChildNode({
data: childData,
width: this.width,
height: this.height,
padding: this.padding,
lineWidth: this.lineWidth
});
});
}
this.canvas.on('click', (e) => {
var p = this.parent;
while ( this.cls_.isInstance(p) ) {
if ( ! p.expanded ) return;
p = p.parent;
}
var point = this.globalToLocalCoordinates({
w: 1,
x: e.offsetX,
y: e.offsetY,
});
/**
* need to adjust the x-value to the middle of the node and not the far left edge
* so that the pointer click registers correctly when clicking any part of the node
*/
point.x += this.width / 2;
if ( this.hitTest(point) ) {
this.expanded = ! this.expanded;
}
});
},
function paint(x) {
if ( ! this.parentNode || this.parentNode.expanded ) this.SUPER(x);
},
function paintSelf(x) {
x.save();
x.translate(-this.width / 2, 0);
this.SUPER(x);
x.restore();
this.paintConnectors(x);
},
function paintConnectors(x) {
function line(x1, y1, x2, y2) {
x.beginPath();
x.moveTo(x1, y1);
x.lineTo(x2, y2);
x.stroke();
}
// Paint lines to childNodes
x.lineWidth = this.lineWidth;
x.strokeStyle = this.border;
if (this.expanded && this.childNodes.length) {
var h = this.childNodes[0].y * 3 / 4;
var l = this.childNodes.length;
line(0, this.height, 0, h);
for (var i = 0; i < l; i++) {
var c = this.childNodes[i];
line(0, h, c.x, h);
line(c.x, h, c.x, c.y);
}
}
// Paint expand/collapse arrow
x.lineWidth = this.borderWidth;
if (this.childNodes.length) {
var d = this.expanded ? 5 : -5;
var y = this.height - 8;
line(-5, y, 0, y + d);
line(0, y + d, 5, y);
}
},
function addChildNode(args) {
var node = this.cls_.create(args, this);
node.y = this.height * 2;
this.add(node);
this.childNodes = this.childNodes.concat(node);
node.outline$.sub(() => {
/**
* Here we are forcing a recalculation of the outline b/c there is no way to subscribe
* to all children outlines via an expression since outline is an array
*/
this.outline = [];
this.outline = undefined
});
return this;
},
function distanceTo(node) {
minLevels = Math.min(this.outline.length, node.outline.length);
var minDistance = Number.MAX_SAFE_INTEGER;
for (var i = 0; i < minLevels; i++) {
var overlapDistance = node.outline[i].left - this.outline[i].right;
minDistance = Math.min(minDistance, overlapDistance);
}
return minDistance;
},
/**
* We need to first ensure that there are no overlaps between subtrees
* and then we can take care of subtrees being too far apart because
* otherwise they will conflict with eachother and go into an infinite loop
* since nodes can have be a positive distance away from each other and be properly spaced (i.e. higher levels in the tree)
* whereas nodes cannot be a negative distance since that means an overlap has occured
* once the above is done we can finally center the nodes
*/
function layout() {
var moved = false;
for ( var i = 0; i < this.childNodes.length; i++ ) {
var n1 = this.childNodes[i];
for ( var j = i + 1; j < this.childNodes.length; j++ ){
var n2 = this.childNodes[j];
var distance = n1.distanceTo(n2);
if ( distance < 0 ) {
n2.neighborX -= distance;
moved = true;
}
}
}
for ( var i = 0; i < this.childNodes.length - 1; i++ ) {
var n1 = this.childNodes[i];
var n2 = this.childNodes[i + 1];
var distance = n1.distanceTo(n2);
if ( distance > 0 ) {
for ( var j = 0; j < i; j++ ) {
var n3 = this.childNodes[j];
distance = Math.min(distance, n3.distanceTo(n2));
}
if ( distance ) {
n2.neighborX -= distance;
moved = true;
}
}
}
for ( var i = 0; i < this.childNodes.length; i++ ){
if ( this.childNodes[i].layout() ) moved = true;
}
if ( this.outline[1] ) {
var rootLevelWidth = this.outline[0].right - this.outline[0].left;
var childLevelWidth = this.outline[1].right - this.outline[1].left;
var d = - (childLevelWidth - rootLevelWidth) / 2;
this.childNodes.forEach(c => {
if ( c.centerX != d ) {
c.centerX = d;
moved = true;
}
})
}
return moved;
},
function findNode(id){
if (this.data.id === id) {
return this;
}
for (var i = 0; i < this.childNodes.length; i++) {
var foundNode = this.childNodes[i].findNode(id);
if (foundNode) {
return foundNode;
}
}
}
]
})
| basically forgot about a .length
| src/foam/graphics/TreeNode.js | basically forgot about a .length | <ide><path>rc/foam/graphics/TreeNode.js
<ide> name: 'expanded',
<ide> expression: function(isAutoExpandedByDefault, childNodesForAutoExpansion, childNodes) {
<ide> if ( isAutoExpandedByDefault ) {
<del> return childNodes < childNodesForAutoExpansion;
<add> return childNodes.length < childNodesForAutoExpansion;
<ide> }
<ide> return false;
<ide> }, |
|
Java | mit | d86ff6ee371e7aa010f9c7994539de67996dde06 | 0 | brianbolze/VoogaSalad_Final_Project,brianbolze/VoogaSalad_Final_Project,gregory-lyons/CS308-final-project,gregory-lyons/CS308-final-project,Chase-M/voogasalad_LosTorres,thefreshduke/voogasalad,thefreshduke/voogasalad,Chase-M/Tower-Defense-Game-Engine,Chase-M/Tower-Defense-Game-Engine,Chase-M/voogasalad_LosTorres,akyker20/TD_Game_Engine | package gamePlayer.mainClasses.welcomeScreen.availableGames;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.image.ImageView;
import utilities.JavaFXutilities.imageView.StringToImageViewConverter;
public class GameDescriptionLoader {
private static String GAMES_DIRECTORY = "./Games/";
public List<GameDescription> getDescriptions() {
File[] games = new File(GAMES_DIRECTORY).listFiles();
List<GameDescription> list = new ArrayList<GameDescription>();
//step through each game and create game description
for (File file:games) {
ImageView gameImage = StringToImageViewConverter.getImageView
(GameDescription.WIDTH, GameDescription.GAME_IMAGE_HEIGHT, file.getAbsolutePath()+"/background/Map1.jpg");
list.add(new GameDescription(gameImage,file.getName(),file.getAbsolutePath()));
}
return list;
}
}
| src/gamePlayer/mainClasses/welcomeScreen/availableGames/GameDescriptionLoader.java | package gamePlayer.mainClasses.welcomeScreen.availableGames;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.image.ImageView;
import utilities.JavaFXutilities.imageView.StringToImageViewConverter;
public class GameDescriptionLoader {
private static String GAMES_DIRECTORY = "./Games/";
public List<GameDescription> getDescriptions() {
File[] games = new File(GAMES_DIRECTORY).listFiles();
List<GameDescription> list = new ArrayList<GameDescription>();
//step through each game and create game description
for (File file:games) {
ImageView gameImage = StringToImageViewConverter.getImageView
(GameDescription.WIDTH, GameDescription.GAME_IMAGE_HEIGHT, file.getAbsolutePath()+"/background/Map1.jpg");
list.add(new GameDescription(gameImage,"Awesome Game",file.getAbsolutePath()));
}
return list;
}
}
| modified s-player game description
| src/gamePlayer/mainClasses/welcomeScreen/availableGames/GameDescriptionLoader.java | modified s-player game description | <ide><path>rc/gamePlayer/mainClasses/welcomeScreen/availableGames/GameDescriptionLoader.java
<ide> for (File file:games) {
<ide> ImageView gameImage = StringToImageViewConverter.getImageView
<ide> (GameDescription.WIDTH, GameDescription.GAME_IMAGE_HEIGHT, file.getAbsolutePath()+"/background/Map1.jpg");
<del> list.add(new GameDescription(gameImage,"Awesome Game",file.getAbsolutePath()));
<add> list.add(new GameDescription(gameImage,file.getName(),file.getAbsolutePath()));
<ide> }
<ide>
<ide> return list; |
|
Java | apache-2.0 | 78a63c00c1dac7cc87125c07a63d41232592ab7b | 0 | apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,kalaspuffar/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.text;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.StringWriter;
import java.io.Writer;
import java.text.Bidi;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.pagenavigation.PDThreadBead;
import org.apache.pdfbox.util.QuickSort;
/**
* This class will take a pdf document and strip out all of the text and ignore the formatting and such. Please note; it
* is up to clients of this class to verify that a specific user has the correct permissions to extract text from the
* PDF document.
*
* The basic flow of this process is that we get a document and use a series of processXXX() functions that work on
* smaller and smaller chunks of the page. Eventually, we fully process each page and then print it.
*
* @author Ben Litchfield
*/
public class PDFTextStripper extends PDFTextStreamEngine
{
private static float defaultIndentThreshold = 2.0f;
private static float defaultDropThreshold = 2.5f;
private static final boolean useCustomQuickSort;
private static final Log LOG = LogFactory.getLog(PDFTextStripper.class);
// enable the ability to set the default indent/drop thresholds
// with -D system properties:
// pdftextstripper.indent
// pdftextstripper.drop
static
{
String strDrop = null, strIndent = null;
try
{
String className = PDFTextStripper.class.getSimpleName().toLowerCase();
String prop = className + ".indent";
strIndent = System.getProperty(prop);
prop = className + ".drop";
strDrop = System.getProperty(prop);
}
catch (SecurityException e)
{
// PDFBOX-1946 when run in an applet
// ignore and use default
}
if (strIndent != null && strIndent.length() > 0)
{
try
{
defaultIndentThreshold = Float.parseFloat(strIndent);
}
catch (NumberFormatException nfe)
{
// ignore and use default
}
}
if (strDrop != null && strDrop.length() > 0)
{
try
{
defaultDropThreshold = Float.parseFloat(strDrop);
}
catch (NumberFormatException nfe)
{
// ignore and use default
}
}
// check if we need to use the custom quicksort algorithm as a
// workaround to the transitivity issue of TextPositionComparator:
// https://issues.apache.org/jira/browse/PDFBOX-1512
boolean is16orLess = false;
try
{
String[] versionComponents = System.getProperty("java.version").split("\\.");
int javaMajorVersion = Integer.parseInt(versionComponents[0]);
int javaMinorVersion = Integer.parseInt(versionComponents[1]);
is16orLess = javaMajorVersion == 1 && javaMinorVersion <= 6;
}
catch (SecurityException x)
{
// when run in an applet ignore and use default
// assume 1.7 or higher so that quicksort is used
}
useCustomQuickSort = !is16orLess;
}
/**
* The platform's line separator.
*/
protected final String LINE_SEPARATOR = System.getProperty("line.separator");
private String lineSeparator = LINE_SEPARATOR;
private String wordSeparator = " ";
private String paragraphStart = "";
private String paragraphEnd = "";
private String pageStart = "";
private String pageEnd = LINE_SEPARATOR;
private String articleStart = "";
private String articleEnd = "";
private int currentPageNo = 0;
private int startPage = 1;
private int endPage = Integer.MAX_VALUE;
private PDOutlineItem startBookmark = null;
// 1-based bookmark pages
private int startBookmarkPageNumber = -1;
private int endBookmarkPageNumber = -1;
private PDOutlineItem endBookmark = null;
private boolean suppressDuplicateOverlappingText = true;
private boolean shouldSeparateByBeads = true;
private boolean sortByPosition = false;
private boolean addMoreFormatting = false;
private float indentThreshold = defaultIndentThreshold;
private float dropThreshold = defaultDropThreshold;
// we will need to estimate where to add spaces, these are used to help guess
private float spacingTolerance = .5f;
private float averageCharTolerance = .3f;
private List<PDThreadBead> pageArticles = null;
/**
* The charactersByArticle is used to extract text by article divisions. For example a PDF that has two columns like
* a newspaper, we want to extract the first column and then the second column. In this example the PDF would have 2
* beads(or articles), one for each column. The size of the charactersByArticle would be 5, because not all text on
* the screen will fall into one of the articles. The five divisions are shown below
*
* Text before first article first article text text between first article and second article second article text
* text after second article
*
* Most PDFs won't have any beads, so charactersByArticle will contain a single entry.
*/
protected Vector<List<TextPosition>> charactersByArticle = new Vector<List<TextPosition>>();
private Map<String, TreeMap<Float, TreeSet<Float>>> characterListMapping = new HashMap<String, TreeMap<Float, TreeSet<Float>>>();
protected PDDocument document;
protected Writer output;
/**
* True if we started a paragraph but haven't ended it yet.
*/
private boolean inParagraph;
/**
* Instantiate a new PDFTextStripper object.
*
* @throws IOException If there is an error loading the properties.
*/
public PDFTextStripper() throws IOException
{
}
/**
* This will return the text of a document. See writeText. <br />
* NOTE: The document must not be encrypted when coming into this method.
*
* @param doc The document to get the text from.
* @return The text of the PDF document.
* @throws IOException if the doc state is invalid or it is encrypted.
*/
public String getText(PDDocument doc) throws IOException
{
StringWriter outputStream = new StringWriter();
writeText(doc, outputStream);
return outputStream.toString();
}
private void resetEngine()
{
currentPageNo = 0;
document = null;
if (charactersByArticle != null)
{
charactersByArticle.clear();
}
if (characterListMapping != null)
{
characterListMapping.clear();
}
}
/**
* This will take a PDDocument and write the text of that document to the print writer.
*
* @param doc The document to get the data from.
* @param outputStream The location to put the text.
*
* @throws IOException If the doc is in an invalid state.
*/
public void writeText(PDDocument doc, Writer outputStream) throws IOException
{
resetEngine();
document = doc;
output = outputStream;
if (getAddMoreFormatting())
{
paragraphEnd = lineSeparator;
pageStart = lineSeparator;
articleStart = lineSeparator;
articleEnd = lineSeparator;
}
startDocument(document);
processPages(document.getPages());
endDocument(document);
}
/**
* This will process all of the pages and the text that is in them.
*
* @param pages The pages object in the document.
*
* @throws IOException If there is an error parsing the text.
*/
protected void processPages(PDPageTree pages) throws IOException
{
PDPageTree pagesTree = document.getPages();
PDPage startBookmarkPage = startBookmark == null ? null
: startBookmark.findDestinationPage(document);
if (startBookmarkPage != null)
{
startBookmarkPageNumber = pagesTree.indexOf(startBookmarkPage) + 1;
}
else
{
// -1 = undefined
startBookmarkPageNumber = -1;
}
PDPage endBookmarkPage = endBookmark == null ? null
: endBookmark.findDestinationPage(document);
if (endBookmarkPage != null)
{
endBookmarkPageNumber = pagesTree.indexOf(endBookmarkPage) + 1;
}
else
{
// -1 = undefined
endBookmarkPageNumber = -1;
}
if (startBookmarkPageNumber == -1 && startBookmark != null && endBookmarkPageNumber == -1
&& endBookmark != null
&& startBookmark.getCOSObject() == endBookmark.getCOSObject())
{
// this is a special case where both the start and end bookmark
// are the same but point to nothing. In this case
// we will not extract any text.
startBookmarkPageNumber = 0;
endBookmarkPageNumber = 0;
}
for (PDPage page : pages)
{
currentPageNo++;
if (page.hasContents())
{
processPage(page);
}
}
}
/**
* This method is available for subclasses of this class. It will be called before processing of the document start.
*
* @param document The PDF document that is being processed.
* @throws IOException If an IO error occurs.
*/
protected void startDocument(PDDocument document) throws IOException
{
// no default implementation, but available for subclasses
}
/**
* This method is available for subclasses of this class. It will be called after processing of the document
* finishes.
*
* @param document The PDF document that is being processed.
* @throws IOException If an IO error occurs.
*/
protected void endDocument(PDDocument document) throws IOException
{
// no default implementation, but available for subclasses
}
/**
* This will process the contents of a page.
*
* @param page The page to process.
*
* @throws IOException If there is an error processing the page.
*/
@Override
public void processPage(PDPage page) throws IOException
{
if (currentPageNo >= startPage && currentPageNo <= endPage
&& (startBookmarkPageNumber == -1 || currentPageNo >= startBookmarkPageNumber)
&& (endBookmarkPageNumber == -1 || currentPageNo <= endBookmarkPageNumber))
{
startPage(page);
pageArticles = page.getThreadBeads();
int numberOfArticleSections = 1 + pageArticles.size() * 2;
if (!shouldSeparateByBeads)
{
numberOfArticleSections = 1;
}
int originalSize = charactersByArticle.size();
charactersByArticle.setSize(numberOfArticleSections);
for (int i = 0; i < numberOfArticleSections; i++)
{
if (numberOfArticleSections < originalSize)
{
charactersByArticle.get(i).clear();
}
else
{
charactersByArticle.set(i, new ArrayList<TextPosition>());
}
}
characterListMapping.clear();
super.processPage(page);
writePage();
endPage(page);
}
}
/**
* Start a new article, which is typically defined as a column on a single page (also referred to as a bead). This
* assumes that the primary direction of text is left to right. Default implementation is to do nothing. Subclasses
* may provide additional information.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void startArticle() throws IOException
{
startArticle(true);
}
/**
* Start a new article, which is typically defined as a column on a single page (also referred to as a bead).
* Default implementation is to do nothing. Subclasses may provide additional information.
*
* @param isLTR true if primary direction of text is left to right.
* @throws IOException If there is any error writing to the stream.
*/
protected void startArticle(boolean isLTR) throws IOException
{
output.write(getArticleStart());
}
/**
* End an article. Default implementation is to do nothing. Subclasses may provide additional information.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void endArticle() throws IOException
{
output.write(getArticleEnd());
}
/**
* Start a new page. Default implementation is to do nothing. Subclasses may provide additional information.
*
* @param page The page we are about to process.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void startPage(PDPage page) throws IOException
{
// default is to do nothing
}
/**
* End a page. Default implementation is to do nothing. Subclasses may provide additional information.
*
* @param page The page we are about to process.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void endPage(PDPage page) throws IOException
{
// default is to do nothing
}
private static final float END_OF_LAST_TEXT_X_RESET_VALUE = -1;
private static final float MAX_Y_FOR_LINE_RESET_VALUE = -Float.MAX_VALUE;
private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE = -Float.MAX_VALUE;
private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE = -1;
private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE = Float.MAX_VALUE;
private static final float LAST_WORD_SPACING_RESET_VALUE = -1;
/**
* This will print the text of the processed page to "output". It will estimate, based on the coordinates of the
* text, where newlines and word spacings should be placed. The text will be sorted only if that feature was
* enabled.
*
* @throws IOException If there is an error writing the text.
*/
protected void writePage() throws IOException
{
float maxYForLine = MAX_Y_FOR_LINE_RESET_VALUE;
float minYTopForLine = MIN_Y_TOP_FOR_LINE_RESET_VALUE;
float endOfLastTextX = END_OF_LAST_TEXT_X_RESET_VALUE;
float lastWordSpacing = LAST_WORD_SPACING_RESET_VALUE;
float maxHeightForLine = MAX_HEIGHT_FOR_LINE_RESET_VALUE;
PositionWrapper lastPosition = null;
PositionWrapper lastLineStartPosition = null;
boolean startOfPage = true; // flag to indicate start of page
boolean startOfArticle;
if (charactersByArticle.size() > 0)
{
writePageStart();
}
for (List<TextPosition> textList : charactersByArticle)
{
if (getSortByPosition())
{
TextPositionComparator comparator = new TextPositionComparator();
// because the TextPositionComparator is not transitive, but
// JDK7+ enforces transitivity on comparators, we need to use
// a custom quicksort implementation (which is slower, unfortunately).
if (useCustomQuickSort)
{
QuickSort.sort(textList, comparator);
}
else
{
Collections.sort(textList, comparator);
}
}
Iterator<TextPosition> textIter = textList.iterator();
startArticle();
startOfArticle = true;
// Now cycle through to print the text.
// We queue up a line at a time before we print so that we can convert
// the line from presentation form to logical form (if needed).
List<LineItem> line = new ArrayList<LineItem>();
textIter = textList.iterator(); // start from the beginning again
// PDF files don't always store spaces. We will need to guess where we should add
// spaces based on the distances between TextPositions. Historically, this was done
// based on the size of the space character provided by the font. In general, this
// worked but there were cases where it did not work. Calculating the average character
// width and using that as a metric works better in some cases but fails in some cases
// where the spacing worked. So we use both. NOTE: Adobe reader also fails on some of
// these examples.
// Keeps track of the previous average character width
float previousAveCharWidth = -1;
while (textIter.hasNext())
{
TextPosition position = textIter.next();
PositionWrapper current = new PositionWrapper(position);
String characterValue = position.getUnicode();
// Resets the average character width when we see a change in font
// or a change in the font size
if (lastPosition != null && (position.getFont() != lastPosition.getTextPosition()
.getFont()
|| position.getFontSize() != lastPosition.getTextPosition().getFontSize()))
{
previousAveCharWidth = -1;
}
float positionX;
float positionY;
float positionWidth;
float positionHeight;
// If we are sorting, then we need to use the text direction
// adjusted coordinates, because they were used in the sorting.
if (getSortByPosition())
{
positionX = position.getXDirAdj();
positionY = position.getYDirAdj();
positionWidth = position.getWidthDirAdj();
positionHeight = position.getHeightDir();
}
else
{
positionX = position.getX();
positionY = position.getY();
positionWidth = position.getWidth();
positionHeight = position.getHeight();
}
// The current amount of characters in a word
int wordCharCount = position.getIndividualWidths().length;
// Estimate the expected width of the space based on the
// space character with some margin.
float wordSpacing = position.getWidthOfSpace();
float deltaSpace;
if (wordSpacing == 0 || Float.isNaN(wordSpacing))
{
deltaSpace = Float.MAX_VALUE;
}
else
{
if (lastWordSpacing < 0)
{
deltaSpace = wordSpacing * getSpacingTolerance();
}
else
{
deltaSpace = (wordSpacing + lastWordSpacing) / 2f * getSpacingTolerance();
}
}
// Estimate the expected width of the space based on the average character width
// with some margin. This calculation does not make a true average (average of
// averages) but we found that it gave the best results after numerous experiments.
// Based on experiments we also found that .3 worked well.
float averageCharWidth;
if (previousAveCharWidth < 0)
{
averageCharWidth = positionWidth / wordCharCount;
}
else
{
averageCharWidth = (previousAveCharWidth + positionWidth / wordCharCount) / 2f;
}
float deltaCharWidth = averageCharWidth * getAverageCharTolerance();
// Compares the values obtained by the average method and the wordSpacing method
// and picks the smaller number.
float expectedStartOfNextWordX = EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE;
if (endOfLastTextX != END_OF_LAST_TEXT_X_RESET_VALUE)
{
if (deltaCharWidth > deltaSpace)
{
expectedStartOfNextWordX = endOfLastTextX + deltaSpace;
}
else
{
expectedStartOfNextWordX = endOfLastTextX + deltaCharWidth;
}
}
if (lastPosition != null)
{
if (startOfArticle)
{
lastPosition.setArticleStart();
startOfArticle = false;
}
// RDD - Here we determine whether this text object is on the current
// line. We use the lastBaselineFontSize to handle the superscript
// case, and the size of the current font to handle the subscript case.
// Text must overlap with the last rendered baseline text by at least
// a small amount in order to be considered as being on the same line.
// XXX BC: In theory, this check should really check if the next char is in
// full range seen in this line. This is what I tried to do with minYTopForLine,
// but this caused a lot of regression test failures. So, I'm leaving it be for
// now
if (!overlap(positionY, positionHeight, maxYForLine, maxHeightForLine))
{
writeLine(normalize(line));
line.clear();
lastLineStartPosition = handleLineSeparation(current, lastPosition,
lastLineStartPosition, maxHeightForLine);
expectedStartOfNextWordX = EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE;
maxYForLine = MAX_Y_FOR_LINE_RESET_VALUE;
maxHeightForLine = MAX_HEIGHT_FOR_LINE_RESET_VALUE;
minYTopForLine = MIN_Y_TOP_FOR_LINE_RESET_VALUE;
}
// test if our TextPosition starts after a new word would be expected to start
if (expectedStartOfNextWordX != EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE
&& expectedStartOfNextWordX < positionX &&
// only bother adding a space if the last character was not a space
lastPosition.getTextPosition().getUnicode() != null
&& !lastPosition.getTextPosition().getUnicode().endsWith(" "))
{
line.add(LineItem.getWordSeparator());
}
}
if (positionY >= maxYForLine)
{
maxYForLine = positionY;
}
// RDD - endX is what PDF considers to be the x coordinate of the
// end position of the text. We use it in computing our metrics below.
endOfLastTextX = positionX + positionWidth;
// add it to the list
if (characterValue != null)
{
if (startOfPage && lastPosition == null)
{
writeParagraphStart();// not sure this is correct for RTL?
}
line.add(new LineItem(position));
}
maxHeightForLine = Math.max(maxHeightForLine, positionHeight);
minYTopForLine = Math.min(minYTopForLine, positionY - positionHeight);
lastPosition = current;
if (startOfPage)
{
lastPosition.setParagraphStart();
lastPosition.setLineStart();
lastLineStartPosition = lastPosition;
startOfPage = false;
}
lastWordSpacing = wordSpacing;
previousAveCharWidth = averageCharWidth;
}
// print the final line
if (line.size() > 0)
{
writeLine(normalize(line));
writeParagraphEnd();
}
endArticle();
}
writePageEnd();
}
private boolean overlap(float y1, float height1, float y2, float height2)
{
return within(y1, y2, .1f) || y2 <= y1 && y2 >= y1 - height1
|| y1 <= y2 && y1 >= y2 - height2;
}
/**
* Write the line separator value to the output stream.
*
* @throws IOException If there is a problem writing out the lineseparator to the document.
*/
protected void writeLineSeparator() throws IOException
{
output.write(getLineSeparator());
}
/**
* Write the word separator value to the output stream.
*
* @throws IOException If there is a problem writing out the wordseparator to the document.
*/
protected void writeWordSeparator() throws IOException
{
output.write(getWordSeparator());
}
/**
* Write the string in TextPosition to the output stream.
*
* @param text The text to write to the stream.
* @throws IOException If there is an error when writing the text.
*/
protected void writeCharacters(TextPosition text) throws IOException
{
output.write(text.getUnicode());
}
/**
* Write a Java string to the output stream. The default implementation will ignore the <code>textPositions</code>
* and just calls {@link #writeString(String)}.
*
* @param text The text to write to the stream.
* @param textPositions The TextPositions belonging to the text.
* @throws IOException If there is an error when writing the text.
*/
protected void writeString(String text, List<TextPosition> textPositions) throws IOException
{
writeString(text);
}
/**
* Write a Java string to the output stream.
*
* @param text The text to write to the stream.
* @throws IOException If there is an error when writing the text.
*/
protected void writeString(String text) throws IOException
{
output.write(text);
}
/**
* This will determine of two floating point numbers are within a specified variance.
*
* @param first The first number to compare to.
* @param second The second number to compare to.
* @param variance The allowed variance.
*/
private boolean within(float first, float second, float variance)
{
return second < first + variance && second > first - variance;
}
/**
* This will process a TextPosition object and add the text to the list of characters on a page. It takes care of
* overlapping text.
*
* @param text The text to process.
*/
@Override
protected void processTextPosition(TextPosition text)
{
boolean showCharacter = true;
if (suppressDuplicateOverlappingText)
{
showCharacter = false;
String textCharacter = text.getUnicode();
float textX = text.getX();
float textY = text.getY();
TreeMap<Float, TreeSet<Float>> sameTextCharacters = characterListMapping
.get(textCharacter);
if (sameTextCharacters == null)
{
sameTextCharacters = new TreeMap<Float, TreeSet<Float>>();
characterListMapping.put(textCharacter, sameTextCharacters);
}
// RDD - Here we compute the value that represents the end of the rendered
// text. This value is used to determine whether subsequent text rendered
// on the same line overwrites the current text.
//
// We subtract any positive padding to handle cases where extreme amounts
// of padding are applied, then backed off (not sure why this is done, but there
// are cases where the padding is on the order of 10x the character width, and
// the TJ just backs up to compensate after each character). Also, we subtract
// an amount to allow for kerning (a percentage of the width of the last
// character).
boolean suppressCharacter = false;
float tolerance = text.getWidth() / textCharacter.length() / 3.0f;
SortedMap<Float, TreeSet<Float>> xMatches = sameTextCharacters.subMap(textX - tolerance,
textX + tolerance);
for (TreeSet<Float> xMatch : xMatches.values())
{
SortedSet<Float> yMatches = xMatch.subSet(textY - tolerance, textY + tolerance);
if (!yMatches.isEmpty())
{
suppressCharacter = true;
break;
}
}
if (!suppressCharacter)
{
TreeSet<Float> ySet = sameTextCharacters.get(textX);
if (ySet == null)
{
ySet = new TreeSet<Float>();
sameTextCharacters.put(textX, ySet);
}
ySet.add(textY);
showCharacter = true;
}
}
if (showCharacter)
{
// if we are showing the character then we need to determine which article it belongs to
int foundArticleDivisionIndex = -1;
int notFoundButFirstLeftAndAboveArticleDivisionIndex = -1;
int notFoundButFirstLeftArticleDivisionIndex = -1;
int notFoundButFirstAboveArticleDivisionIndex = -1;
float x = text.getX();
float y = text.getY();
if (shouldSeparateByBeads)
{
for (int i = 0; i < pageArticles.size() && foundArticleDivisionIndex == -1; i++)
{
PDThreadBead bead = pageArticles.get(i);
if (bead != null)
{
PDRectangle rect = bead.getRectangle();
// bead rectangle is in PDF coordinates (y=0 is bottom),
// glyphs are in image coordinates (y=0 is top),
// so we must flip
PDPage pdPage = getCurrentPage();
PDRectangle mediaBox = pdPage.getMediaBox();
float upperRightY = mediaBox.getUpperRightY() - rect.getLowerLeftY();
float lowerLeftY = mediaBox.getUpperRightY() - rect.getUpperRightY();
rect.setLowerLeftY(lowerLeftY);
rect.setUpperRightY(upperRightY);
// adjust for cropbox
PDRectangle cropBox = pdPage.getCropBox();
if (cropBox.getLowerLeftX() != 0 || cropBox.getLowerLeftY() != 0)
{
rect.setLowerLeftX(rect.getLowerLeftX() - cropBox.getLowerLeftX());
rect.setLowerLeftY(rect.getLowerLeftY() - cropBox.getLowerLeftY());
rect.setUpperRightX(rect.getUpperRightX() - cropBox.getLowerLeftX());
rect.setUpperRightY(rect.getUpperRightY() - cropBox.getLowerLeftY());
}
if (rect.contains(x, y))
{
foundArticleDivisionIndex = i * 2 + 1;
}
else if ((x < rect.getLowerLeftX() || y < rect.getUpperRightY())
&& notFoundButFirstLeftAndAboveArticleDivisionIndex == -1)
{
notFoundButFirstLeftAndAboveArticleDivisionIndex = i * 2;
}
else if (x < rect.getLowerLeftX()
&& notFoundButFirstLeftArticleDivisionIndex == -1)
{
notFoundButFirstLeftArticleDivisionIndex = i * 2;
}
else if (y < rect.getUpperRightY()
&& notFoundButFirstAboveArticleDivisionIndex == -1)
{
notFoundButFirstAboveArticleDivisionIndex = i * 2;
}
}
else
{
foundArticleDivisionIndex = 0;
}
}
}
else
{
foundArticleDivisionIndex = 0;
}
int articleDivisionIndex;
if (foundArticleDivisionIndex != -1)
{
articleDivisionIndex = foundArticleDivisionIndex;
}
else if (notFoundButFirstLeftAndAboveArticleDivisionIndex != -1)
{
articleDivisionIndex = notFoundButFirstLeftAndAboveArticleDivisionIndex;
}
else if (notFoundButFirstLeftArticleDivisionIndex != -1)
{
articleDivisionIndex = notFoundButFirstLeftArticleDivisionIndex;
}
else if (notFoundButFirstAboveArticleDivisionIndex != -1)
{
articleDivisionIndex = notFoundButFirstAboveArticleDivisionIndex;
}
else
{
articleDivisionIndex = charactersByArticle.size() - 1;
}
List<TextPosition> textList = charactersByArticle.get(articleDivisionIndex);
// In the wild, some PDF encoded documents put diacritics (accents on
// top of characters) into a separate Tj element. When displaying them
// graphically, the two chunks get overlayed. With text output though,
// we need to do the overlay. This code recombines the diacritic with
// its associated character if the two are consecutive.
if (textList.isEmpty())
{
textList.add(text);
}
else
{
// test if we overlap the previous entry.
// Note that we are making an assumption that we need to only look back
// one TextPosition to find what we are overlapping.
// This may not always be true. */
TextPosition previousTextPosition = textList.get(textList.size() - 1);
if (text.isDiacritic() && previousTextPosition.contains(text))
{
previousTextPosition.mergeDiacritic(text);
}
// If the previous TextPosition was the diacritic, merge it into this
// one and remove it from the list.
else if (previousTextPosition.isDiacritic() && text.contains(previousTextPosition))
{
text.mergeDiacritic(previousTextPosition);
textList.remove(textList.size() - 1);
textList.add(text);
}
else
{
textList.add(text);
}
}
}
}
/**
* This is the page that the text extraction will start on. The pages start at page 1. For example in a 5 page PDF
* document, if the start page is 1 then all pages will be extracted. If the start page is 4 then pages 4 and 5 will
* be extracted. The default value is 1.
*
* @return Value of property startPage.
*/
public int getStartPage()
{
return startPage;
}
/**
* This will set the first page to be extracted by this class.
*
* @param startPageValue New value of 1-based startPage property.
*/
public void setStartPage(int startPageValue)
{
startPage = startPageValue;
}
/**
* This will get the last page that will be extracted. This is inclusive, for example if a 5 page PDF an endPage
* value of 5 would extract the entire document, an end page of 2 would extract pages 1 and 2. This defaults to
* Integer.MAX_VALUE such that all pages of the pdf will be extracted.
*
* @return Value of property endPage.
*/
public int getEndPage()
{
return endPage;
}
/**
* This will set the last page to be extracted by this class.
*
* @param endPageValue New value of 1-based endPage property.
*/
public void setEndPage(int endPageValue)
{
endPage = endPageValue;
}
/**
* Set the desired line separator for output text. The line.separator system property is used if the line separator
* preference is not set explicitly using this method.
*
* @param separator The desired line separator string.
*/
public void setLineSeparator(String separator)
{
lineSeparator = separator;
}
/**
* This will get the line separator.
*
* @return The desired line separator string.
*/
public String getLineSeparator()
{
return lineSeparator;
}
/**
* This will get the word separator.
*
* @return The desired word separator string.
*/
public String getWordSeparator()
{
return wordSeparator;
}
/**
* Set the desired word separator for output text. The PDFBox text extraction algorithm will output a space
* character if there is enough space between two words. By default a space character is used. If you need and
* accurate count of characters that are found in a PDF document then you might want to set the word separator to
* the empty string.
*
* @param separator The desired page separator string.
*/
public void setWordSeparator(String separator)
{
wordSeparator = separator;
}
/**
* @return Returns the suppressDuplicateOverlappingText.
*/
public boolean getSuppressDuplicateOverlappingText()
{
return suppressDuplicateOverlappingText;
}
/**
* Get the current page number that is being processed.
*
* @return A 1 based number representing the current page.
*/
protected int getCurrentPageNo()
{
return currentPageNo;
}
/**
* The output stream that is being written to.
*
* @return The stream that output is being written to.
*/
protected Writer getOutput()
{
return output;
}
/**
* Character strings are grouped by articles. It is quite common that there will only be a single article. This
* returns a List that contains List objects, the inner lists will contain TextPosition objects.
*
* @return A double List of TextPositions for all text strings on the page.
*/
protected List<List<TextPosition>> getCharactersByArticle()
{
return charactersByArticle;
}
/**
* By default the text stripper will attempt to remove text that overlapps each other. Word paints the same
* character several times in order to make it look bold. By setting this to false all text will be extracted, which
* means that certain sections will be duplicated, but better performance will be noticed.
*
* @param suppressDuplicateOverlappingTextValue The suppressDuplicateOverlappingText to set.
*/
public void setSuppressDuplicateOverlappingText(boolean suppressDuplicateOverlappingTextValue)
{
suppressDuplicateOverlappingText = suppressDuplicateOverlappingTextValue;
}
/**
* This will tell if the text stripper should separate by beads.
*
* @return If the text will be grouped by beads.
*/
public boolean getSeparateByBeads()
{
return shouldSeparateByBeads;
}
/**
* Set if the text stripper should group the text output by a list of beads. The default value is true!
*
* @param aShouldSeparateByBeads The new grouping of beads.
*/
public void setShouldSeparateByBeads(boolean aShouldSeparateByBeads)
{
shouldSeparateByBeads = aShouldSeparateByBeads;
}
/**
* Get the bookmark where text extraction should end, inclusive. Default is null.
*
* @return The ending bookmark.
*/
public PDOutlineItem getEndBookmark()
{
return endBookmark;
}
/**
* Set the bookmark where the text extraction should stop.
*
* @param aEndBookmark The ending bookmark.
*/
public void setEndBookmark(PDOutlineItem aEndBookmark)
{
endBookmark = aEndBookmark;
}
/**
* Get the bookmark where text extraction should start, inclusive. Default is null.
*
* @return The starting bookmark.
*/
public PDOutlineItem getStartBookmark()
{
return startBookmark;
}
/**
* Set the bookmark where text extraction should start, inclusive.
*
* @param aStartBookmark The starting bookmark.
*/
public void setStartBookmark(PDOutlineItem aStartBookmark)
{
startBookmark = aStartBookmark;
}
/**
* This will tell if the text stripper should add some more text formatting.
*
* @return true if some more text formatting will be added
*/
public boolean getAddMoreFormatting()
{
return addMoreFormatting;
}
/**
* There will some additional text formatting be added if addMoreFormatting is set to true. Default is false.
*
* @param newAddMoreFormatting Tell PDFBox to add some more text formatting
*/
public void setAddMoreFormatting(boolean newAddMoreFormatting)
{
addMoreFormatting = newAddMoreFormatting;
}
/**
* This will tell if the text stripper should sort the text tokens before writing to the stream.
*
* @return true If the text tokens will be sorted before being written.
*/
public boolean getSortByPosition()
{
return sortByPosition;
}
/**
* The order of the text tokens in a PDF file may not be in the same as they appear visually on the screen. For
* example, a PDF writer may write out all text by font, so all bold or larger text, then make a second pass and
* write out the normal text.<br/>
* The default is to <b>not</b> sort by position.<br/>
* <br/>
* A PDF writer could choose to write each character in a different order. By default PDFBox does <b>not</b> sort
* the text tokens before processing them due to performance reasons.
*
* @param newSortByPosition Tell PDFBox to sort the text positions.
*/
public void setSortByPosition(boolean newSortByPosition)
{
sortByPosition = newSortByPosition;
}
/**
* Get the current space width-based tolerance value that is being used to estimate where spaces in text should be
* added. Note that the default value for this has been determined from trial and error.
*
* @return The current tolerance / scaling factor
*/
public float getSpacingTolerance()
{
return spacingTolerance;
}
/**
* Set the space width-based tolerance value that is used to estimate where spaces in text should be added. Note
* that the default value for this has been determined from trial and error. Setting this value larger will reduce
* the number of spaces added.
*
* @param spacingToleranceValue tolerance / scaling factor to use
*/
public void setSpacingTolerance(float spacingToleranceValue)
{
spacingTolerance = spacingToleranceValue;
}
/**
* Get the current character width-based tolerance value that is being used to estimate where spaces in text should
* be added. Note that the default value for this has been determined from trial and error.
*
* @return The current tolerance / scaling factor
*/
public float getAverageCharTolerance()
{
return averageCharTolerance;
}
/**
* Set the character width-based tolerance value that is used to estimate where spaces in text should be added. Note
* that the default value for this has been determined from trial and error. Setting this value larger will reduce
* the number of spaces added.
*
* @param averageCharToleranceValue average tolerance / scaling factor to use
*/
public void setAverageCharTolerance(float averageCharToleranceValue)
{
averageCharTolerance = averageCharToleranceValue;
}
/**
* returns the multiple of whitespace character widths for the current text which the current line start can be
* indented from the previous line start beyond which the current line start is considered to be a paragraph start.
*
* @return the number of whitespace character widths to use when detecting paragraph indents.
*/
public float getIndentThreshold()
{
return indentThreshold;
}
/**
* sets the multiple of whitespace character widths for the current text which the current line start can be
* indented from the previous line start beyond which the current line start is considered to be a paragraph start.
* The default value is 2.0.
*
* @param indentThresholdValue the number of whitespace character widths to use when detecting paragraph indents.
*/
public void setIndentThreshold(float indentThresholdValue)
{
indentThreshold = indentThresholdValue;
}
/**
* the minimum whitespace, as a multiple of the max height of the current characters beyond which the current line
* start is considered to be a paragraph start.
*
* @return the character height multiple for max allowed whitespace between lines in the same paragraph.
*/
public float getDropThreshold()
{
return dropThreshold;
}
/**
* sets the minimum whitespace, as a multiple of the max height of the current characters beyond which the current
* line start is considered to be a paragraph start. The default value is 2.5.
*
* @param dropThresholdValue the character height multiple for max allowed whitespace between lines in the same
* paragraph.
*/
public void setDropThreshold(float dropThresholdValue)
{
dropThreshold = dropThresholdValue;
}
/**
* Returns the string which will be used at the beginning of a paragraph.
*
* @return the paragraph start string
*/
public String getParagraphStart()
{
return paragraphStart;
}
/**
* Sets the string which will be used at the beginning of a paragraph.
*
* @param s the paragraph start string
*/
public void setParagraphStart(String s)
{
paragraphStart = s;
}
/**
* Returns the string which will be used at the end of a paragraph.
*
* @return the paragraph end string
*/
public String getParagraphEnd()
{
return paragraphEnd;
}
/**
* Sets the string which will be used at the end of a paragraph.
*
* @param s the paragraph end string
*/
public void setParagraphEnd(String s)
{
paragraphEnd = s;
}
/**
* Returns the string which will be used at the beginning of a page.
*
* @return the page start string
*/
public String getPageStart()
{
return pageStart;
}
/**
* Sets the string which will be used at the beginning of a page.
*
* @param pageStartValue the page start string
*/
public void setPageStart(String pageStartValue)
{
pageStart = pageStartValue;
}
/**
* Returns the string which will be used at the end of a page.
*
* @return the page end string
*/
public String getPageEnd()
{
return pageEnd;
}
/**
* Sets the string which will be used at the end of a page.
*
* @param pageEndValue the page end string
*/
public void setPageEnd(String pageEndValue)
{
pageEnd = pageEndValue;
}
/**
* Returns the string which will be used at the beginning of an article.
*
* @return the article start string
*/
public String getArticleStart()
{
return articleStart;
}
/**
* Sets the string which will be used at the beginning of an article.
*
* @param articleStartValue the article start string
*/
public void setArticleStart(String articleStartValue)
{
articleStart = articleStartValue;
}
/**
* Returns the string which will be used at the end of an article.
*
* @return the article end string
*/
public String getArticleEnd()
{
return articleEnd;
}
/**
* Sets the string which will be used at the end of an article.
*
* @param articleEndValue the article end string
*/
public void setArticleEnd(String articleEndValue)
{
articleEnd = articleEndValue;
}
/**
* handles the line separator for a new line given the specified current and previous TextPositions.
*
* @param current the current text position
* @param lastPosition the previous text position
* @param lastLineStartPosition the last text position that followed a line separator.
* @param maxHeightForLine max height for positions since lastLineStartPosition
* @return start position of the last line
* @throws IOException if something went wrong
*/
private PositionWrapper handleLineSeparation(PositionWrapper current,
PositionWrapper lastPosition, PositionWrapper lastLineStartPosition,
float maxHeightForLine) throws IOException
{
current.setLineStart();
isParagraphSeparation(current, lastPosition, lastLineStartPosition, maxHeightForLine);
lastLineStartPosition = current;
if (current.isParagraphStart())
{
if (lastPosition.isArticleStart())
{
writeParagraphStart();
}
else
{
writeLineSeparator();
writeParagraphSeparator();
}
}
else
{
writeLineSeparator();
}
return lastLineStartPosition;
}
/**
* tests the relationship between the last text position, the current text position and the last text position that
* followed a line separator to decide if the gap represents a paragraph separation. This should <i>only</i> be
* called for consecutive text positions that first pass the line separation test.
* <p>
* This base implementation tests to see if the lastLineStartPosition is null OR if the current vertical position
* has dropped below the last text vertical position by at least 2.5 times the current text height OR if the current
* horizontal position is indented by at least 2 times the current width of a space character.
* </p>
* <p>
* This also attempts to identify text that is indented under a hanging indent.
* </p>
* <p>
* This method sets the isParagraphStart and isHangingIndent flags on the current position object.
* </p>
*
* @param position the current text position. This may have its isParagraphStart or isHangingIndent flags set upon
* return.
* @param lastPosition the previous text position (should not be null).
* @param lastLineStartPosition the last text position that followed a line separator, or null.
* @param maxHeightForLine max height for text positions since lasLineStartPosition.
*/
private void isParagraphSeparation(PositionWrapper position, PositionWrapper lastPosition,
PositionWrapper lastLineStartPosition, float maxHeightForLine)
{
boolean result = false;
if (lastLineStartPosition == null)
{
result = true;
}
else
{
float yGap = Math.abs(position.getTextPosition().getYDirAdj()
- lastPosition.getTextPosition().getYDirAdj());
float newYVal = multiplyFloat(getDropThreshold(), maxHeightForLine);
// do we need to flip this for rtl?
float xGap = position.getTextPosition().getXDirAdj()
- lastLineStartPosition.getTextPosition().getXDirAdj();
float newXVal = multiplyFloat(getIndentThreshold(),
position.getTextPosition().getWidthOfSpace());
float positionWidth = multiplyFloat(0.25f, position.getTextPosition().getWidth());
if (yGap > newYVal)
{
result = true;
}
else if (xGap > newXVal)
{
// text is indented, but try to screen for hanging indent
if (!lastLineStartPosition.isParagraphStart())
{
result = true;
}
else
{
position.setHangingIndent();
}
}
else if (xGap < -position.getTextPosition().getWidthOfSpace())
{
// text is left of previous line. Was it a hanging indent?
if (!lastLineStartPosition.isParagraphStart())
{
result = true;
}
}
else if (Math.abs(xGap) < positionWidth)
{
// current horizontal position is within 1/4 a char of the last
// linestart. We'll treat them as lined up.
if (lastLineStartPosition.isHangingIndent())
{
position.setHangingIndent();
}
else if (lastLineStartPosition.isParagraphStart())
{
// check to see if the previous line looks like
// any of a number of standard list item formats
Pattern liPattern = matchListItemPattern(lastLineStartPosition);
if (liPattern != null)
{
Pattern currentPattern = matchListItemPattern(position);
if (liPattern == currentPattern)
{
result = true;
}
}
}
}
}
if (result)
{
position.setParagraphStart();
}
}
private float multiplyFloat(float value1, float value2)
{
// multiply 2 floats and truncate the resulting value to 3 decimal places
// to avoid wrong results when comparing with another float
return Math.round(value1 * value2 * 1000) / 1000f;
}
/**
* writes the paragraph separator string to the output.
*
* @throws IOException if something went wrong
*/
protected void writeParagraphSeparator() throws IOException
{
writeParagraphEnd();
writeParagraphStart();
}
/**
* Write something (if defined) at the start of a paragraph.
*
* @throws IOException if something went wrong
*/
protected void writeParagraphStart() throws IOException
{
if (inParagraph)
{
writeParagraphEnd();
inParagraph = false;
}
output.write(getParagraphStart());
inParagraph = true;
}
/**
* Write something (if defined) at the end of a paragraph.
*
* @throws IOException if something went wrong
*/
protected void writeParagraphEnd() throws IOException
{
if (!inParagraph)
{
writeParagraphStart();
}
output.write(getParagraphEnd());
inParagraph = false;
}
/**
* Write something (if defined) at the start of a page.
*
* @throws IOException if something went wrong
*/
protected void writePageStart() throws IOException
{
output.write(getPageStart());
}
/**
* Write something (if defined) at the end of a page.
*
* @throws IOException if something went wrong
*/
protected void writePageEnd() throws IOException
{
output.write(getPageEnd());
}
/**
* returns the list item Pattern object that matches the text at the specified PositionWrapper or null if the text
* does not match such a pattern. The list of Patterns tested against is given by the {@link #getListItemPatterns()}
* method. To add to the list, simply override that method (if sub-classing) or explicitly supply your own list
* using {@link #setListItemPatterns(List)}.
*
* @param pw position
* @return the matching pattern
*/
private Pattern matchListItemPattern(PositionWrapper pw)
{
TextPosition tp = pw.getTextPosition();
String txt = tp.getUnicode();
return matchPattern(txt, getListItemPatterns());
}
/**
* a list of regular expressions that match commonly used list item formats, i.e. bullets, numbers, letters, Roman
* numerals, etc. Not meant to be comprehensive.
*/
private static final String[] LIST_ITEM_EXPRESSIONS = { "\\.", "\\d+\\.", "\\[\\d+\\]",
"\\d+\\)", "[A-Z]\\.", "[a-z]\\.", "[A-Z]\\)", "[a-z]\\)", "[IVXL]+\\.",
"[ivxl]+\\.", };
private List<Pattern> listOfPatterns = null;
/**
* use to supply a different set of regular expression patterns for matching list item starts.
*
* @param patterns list of patterns
*/
protected void setListItemPatterns(List<Pattern> patterns)
{
listOfPatterns = patterns;
}
/**
* returns a list of regular expression Patterns representing different common list item formats. For example
* numbered items of form:
* <ol>
* <li>some text</li>
* <li>more text</li>
* </ol>
* or
* <ul>
* <li>some text</li>
* <li>more text</li>
* </ul>
* etc., all begin with some character pattern. The pattern "\\d+\." (matches "1.", "2.", ...) or "\[\\d+\]"
* (matches "[1]", "[2]", ...).
* <p>
* This method returns a list of such regular expression Patterns.
*
* @return a list of Pattern objects.
*/
protected List<Pattern> getListItemPatterns()
{
if (listOfPatterns == null)
{
listOfPatterns = new ArrayList<Pattern>();
for (String expression : LIST_ITEM_EXPRESSIONS)
{
Pattern p = Pattern.compile(expression);
listOfPatterns.add(p);
}
}
return listOfPatterns;
}
/**
* iterates over the specified list of Patterns until it finds one that matches the specified string. Then returns
* the Pattern.
* <p>
* Order of the supplied list of patterns is important as most common patterns should come first. Patterns should be
* strict in general, and all will be used with case sensitivity on.
* </p>
*
* @param string the string to be searched
* @param patterns list of patterns
* @return matching pattern
*/
protected static Pattern matchPattern(String string, List<Pattern> patterns)
{
for (Pattern p : patterns)
{
if (p.matcher(string).matches())
{
return p;
}
}
return null;
}
/**
* Write a list of string containing a whole line of a document.
*
* @param line a list with the words of the given line
* @throws IOException if something went wrong
*/
private void writeLine(List<WordWithTextPositions> line)
throws IOException
{
int numberOfStrings = line.size();
for (int i = 0; i < numberOfStrings; i++)
{
WordWithTextPositions word = line.get(i);
writeString(word.getText(), word.getTextPositions());
if (i < numberOfStrings - 1)
{
writeWordSeparator();
}
}
}
/**
* Normalize the given list of TextPositions.
*
* @param line list of TextPositions
* @return a list of strings, one string for every word
*/
private List<WordWithTextPositions> normalize(List<LineItem> line)
{
List<WordWithTextPositions> normalized = new LinkedList<WordWithTextPositions>();
StringBuilder lineBuilder = new StringBuilder();
List<TextPosition> wordPositions = new ArrayList<TextPosition>();
for (LineItem item : line)
{
lineBuilder = normalizeAdd(normalized, lineBuilder, wordPositions, item);
}
if (lineBuilder.length() > 0)
{
normalized.add(createWord(lineBuilder.toString(), wordPositions));
}
return normalized;
}
/**
* Handles the LTR and RTL direction of the given words. The whole implementation stands and falls with the given
* word. If the word is a full line, the results will be the best. If the word contains of single words or
* characters, the order of the characters in a word or words in a line may wrong, due to RTL and LTR marks and
* characters!
*
* Based on http://www.nesterovsky-bros.com/weblog/2013/07/28/VisualToLogicalConversionInJava.aspx
*
* @param word The word that shall be processed
* @return new word with the correct direction of the containing characters
*/
private String handleDirection(String word)
{
Bidi bidi = new Bidi(word, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
// if there is pure LTR text no need to process further
if (!bidi.isMixed() && bidi.getBaseLevel() == Bidi.DIRECTION_LEFT_TO_RIGHT)
{
return word;
}
// collect individual bidi information
int runCount = bidi.getRunCount();
byte[] levels = new byte[runCount];
Integer[] runs = new Integer[runCount];
for (int i = 0; i < runCount; i++)
{
levels[i] = (byte)bidi.getRunLevel(i);
runs[i] = i;
}
// reorder individual parts based on their levels
Bidi.reorderVisually(levels, 0, runs, 0, runCount);
// collect the parts based on the direction within the run
StringBuilder result = new StringBuilder();
for (int i = 0; i < runCount; i++)
{
int index = runs[i];
int start = bidi.getRunStart(index);
int end = bidi.getRunLimit(index);
int level = levels[index];
if ((level & 1) != 0)
{
for (; --end >= start;)
{
if (Character.isMirrored(word.codePointAt(end)))
{
if (MIRRORING_CHAR_MAP.containsKey(word.charAt(end) + ""))
{
result.append(MIRRORING_CHAR_MAP.get(word.charAt(end) + "").charAt(0));
}
else
{
result.append(word.charAt(end));
}
}
else
{
result.append(word.charAt(end));
}
}
}
else
{
result.append(word, start, end);
}
}
return result.toString();
}
private static HashMap<String, String> MIRRORING_CHAR_MAP = new HashMap<String, String>();
static
{
String path = "org/apache/pdfbox/resources/text/BidiMirroring.txt";
InputStream input = PDFTextStripper.class.getClassLoader().getResourceAsStream(path);
try
{
parseBidiFile(input);
}
catch (IOException e)
{
LOG.warn("Could not parse BidiMirroring.txt, mirroring char map will be empty: "
+ e.getMessage());
}
};
/**
* This method parses the bidi file provided as inputstream.
*
* @param inputStream - The bidi file as inputstream
* @throws IOException if any line could not be read by the LineNumberReader
*/
private static void parseBidiFile(InputStream inputStream) throws IOException
{
LineNumberReader rd = new LineNumberReader(new InputStreamReader(inputStream));
do
{
String s = rd.readLine();
if (s == null)
{
break;
}
int comment = s.indexOf('#'); // ignore comments
if (comment != -1)
{
s = s.substring(0, comment);
}
if (s.length() < 2)
{
continue;
}
StringTokenizer st = new StringTokenizer(s, ";");
int nFields = st.countTokens();
String[] fields = new String[nFields];
for (int i = 0; i < nFields; i++)
{
fields[i] = "" + (char) Integer.parseInt(st.nextToken().trim(), 16); //
}
if (fields.length == 2)
{
// initialize the MIRRORING_CHAR_MAP
MIRRORING_CHAR_MAP.put(fields[0], fields[1]);
}
} while (true);
}
/**
* Used within {@link #normalize(List, boolean, boolean)} to create a single {@link WordWithTextPositions} entry.
*/
private WordWithTextPositions createWord(String word, List<TextPosition> wordPositions)
{
return new WordWithTextPositions(normalizeWord(word), wordPositions);
}
/**
* Normalize certain Unicode characters. For example, convert the single "fi" ligature to "f" and "i". Also
* normalises Arabic and Hebrew presentation forms.
*
* @param word Word to normalize
* @return Normalized word
*/
private String normalizeWord(String word)
{
StringBuilder builder = null;
int p = 0;
int q = 0;
int strLength = word.length();
for (; q < strLength; q++)
{
// We only normalize if the codepoint is in a given range.
// Otherwise, NFKC converts too many things that would cause
// confusion. For example, it converts the micro symbol in
// extended Latin to the value in the Greek script. We normalize
// the Unicode Alphabetic and Arabic A&B Presentation forms.
char c = word.charAt(q);
if (0xFB00 <= c && c <= 0xFDFF || 0xFE70 <= c && c <= 0xFEFF)
{
if (builder == null)
{
builder = new StringBuilder(strLength * 2);
}
builder.append(word.substring(p, q));
// Some fonts map U+FDF2 differently than the Unicode spec.
// They add an extra U+0627 character to compensate.
// This removes the extra character for those fonts.
if (c == 0xFDF2 && q > 0
&& (word.charAt(q - 1) == 0x0627 || word.charAt(q - 1) == 0xFE8D))
{
builder.append("\u0644\u0644\u0647");
}
else
{
// Trim because some decompositions have an extra space, such as U+FC5E
builder.append(Normalizer
.normalize(word.substring(q, q + 1), Normalizer.Form.NFKC).trim());
}
p = q + 1;
}
}
if (builder == null)
{
return handleDirection(word);
}
else
{
builder.append(word.substring(p, q));
return handleDirection(builder.toString());
}
}
/**
* Used within {@link #normalize(List, boolean, boolean)} to handle a {@link TextPosition}.
*
* @return The StringBuilder that must be used when calling this method.
*/
private StringBuilder normalizeAdd(List<WordWithTextPositions> normalized,
StringBuilder lineBuilder, List<TextPosition> wordPositions, LineItem item)
{
if (item.isWordSeparator())
{
normalized.add(
createWord(lineBuilder.toString(), new ArrayList<TextPosition>(wordPositions)));
lineBuilder = new StringBuilder();
wordPositions.clear();
}
else
{
TextPosition text = item.getTextPosition();
lineBuilder.append(text.getUnicode());
wordPositions.add(text);
}
return lineBuilder;
}
/**
* internal marker class. Used as a place holder in a line of TextPositions.
*/
private static final class LineItem
{
public static LineItem WORD_SEPARATOR = new LineItem();
public static LineItem getWordSeparator()
{
return WORD_SEPARATOR;
}
private final TextPosition textPosition;
private LineItem()
{
textPosition = null;
}
LineItem(TextPosition textPosition)
{
this.textPosition = textPosition;
}
public TextPosition getTextPosition()
{
return textPosition;
}
public boolean isWordSeparator()
{
return textPosition == null;
}
}
/**
* Internal class that maps strings to lists of {@link TextPosition} arrays. Note that the number of entries in that
* list may differ from the number of characters in the string due to normalization.
*
* @author Axel Dörfler
*/
private static final class WordWithTextPositions
{
String text;
List<TextPosition> textPositions;
WordWithTextPositions(String word, List<TextPosition> positions)
{
text = word;
textPositions = positions;
}
public String getText()
{
return text;
}
public List<TextPosition> getTextPositions()
{
return textPositions;
}
}
/**
* wrapper of TextPosition that adds flags to track status as linestart and paragraph start positions.
* <p>
* This is implemented as a wrapper since the TextPosition class doesn't provide complete access to its state fields
* to subclasses. Also, conceptually TextPosition is immutable while these flags need to be set post-creation so it
* makes sense to put these flags in this separate class.
* </p>
*
* @author [email protected]
*/
private static final class PositionWrapper
{
private boolean isLineStart = false;
private boolean isParagraphStart = false;
private boolean isPageBreak = false;
private boolean isHangingIndent = false;
private boolean isArticleStart = false;
private TextPosition position = null;
/**
* Constructs a PositionWrapper around the specified TextPosition object.
*
* @param position the text position.
*/
PositionWrapper(TextPosition position)
{
this.position = position;
}
/**
* Returns the underlying TextPosition object.
*
* @return the text position
*/
public TextPosition getTextPosition()
{
return position;
}
public boolean isLineStart()
{
return isLineStart;
}
/**
* Sets the isLineStart() flag to true.
*/
public void setLineStart()
{
this.isLineStart = true;
}
public boolean isParagraphStart()
{
return isParagraphStart;
}
/**
* sets the isParagraphStart() flag to true.
*/
public void setParagraphStart()
{
this.isParagraphStart = true;
}
public boolean isArticleStart()
{
return isArticleStart;
}
/**
* Sets the isArticleStart() flag to true.
*/
public void setArticleStart()
{
this.isArticleStart = true;
}
public boolean isPageBreak()
{
return isPageBreak;
}
/**
* Sets the isPageBreak() flag to true.
*/
public void setPageBreak()
{
this.isPageBreak = true;
}
public boolean isHangingIndent()
{
return isHangingIndent;
}
/**
* Sets the isHangingIndent() flag to true.
*/
public void setHangingIndent()
{
this.isHangingIndent = true;
}
}
}
| pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStripper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.text;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.StringWriter;
import java.io.Writer;
import java.text.Bidi;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.pagenavigation.PDThreadBead;
import org.apache.pdfbox.util.QuickSort;
/**
* This class will take a pdf document and strip out all of the text and ignore the formatting and such. Please note; it
* is up to clients of this class to verify that a specific user has the correct permissions to extract text from the
* PDF document.
*
* The basic flow of this process is that we get a document and use a series of processXXX() functions that work on
* smaller and smaller chunks of the page. Eventually, we fully process each page and then print it.
*
* @author Ben Litchfield
*/
public class PDFTextStripper extends PDFTextStreamEngine
{
private static float defaultIndentThreshold = 2.0f;
private static float defaultDropThreshold = 2.5f;
private static final boolean useCustomQuickSort;
private static final Log LOG = LogFactory.getLog(PDFTextStripper.class);
// enable the ability to set the default indent/drop thresholds
// with -D system properties:
// pdftextstripper.indent
// pdftextstripper.drop
static
{
String strDrop = null, strIndent = null;
try
{
String className = PDFTextStripper.class.getSimpleName().toLowerCase();
String prop = className + ".indent";
strIndent = System.getProperty(prop);
prop = className + ".drop";
strDrop = System.getProperty(prop);
}
catch (SecurityException e)
{
// PDFBOX-1946 when run in an applet
// ignore and use default
}
if (strIndent != null && strIndent.length() > 0)
{
try
{
defaultIndentThreshold = Float.parseFloat(strIndent);
}
catch (NumberFormatException nfe)
{
// ignore and use default
}
}
if (strDrop != null && strDrop.length() > 0)
{
try
{
defaultDropThreshold = Float.parseFloat(strDrop);
}
catch (NumberFormatException nfe)
{
// ignore and use default
}
}
// check if we need to use the custom quicksort algorithm as a
// workaround to the transitivity issue of TextPositionComparator:
// https://issues.apache.org/jira/browse/PDFBOX-1512
boolean is16orLess = false;
try
{
String[] versionComponents = System.getProperty("java.version").split("\\.");
int javaMajorVersion = Integer.parseInt(versionComponents[0]);
int javaMinorVersion = Integer.parseInt(versionComponents[1]);
is16orLess = javaMajorVersion == 1 && javaMinorVersion <= 6;
}
catch (SecurityException x)
{
// when run in an applet ignore and use default
// assume 1.7 or higher so that quicksort is used
}
useCustomQuickSort = !is16orLess;
}
/**
* The platform's line separator.
*/
protected final String LINE_SEPARATOR = System.getProperty("line.separator");
private String lineSeparator = LINE_SEPARATOR;
private String wordSeparator = " ";
private String paragraphStart = "";
private String paragraphEnd = "";
private String pageStart = "";
private String pageEnd = LINE_SEPARATOR;
private String articleStart = "";
private String articleEnd = "";
private int currentPageNo = 0;
private int startPage = 1;
private int endPage = Integer.MAX_VALUE;
private PDOutlineItem startBookmark = null;
// 1-based bookmark pages
private int startBookmarkPageNumber = -1;
private int endBookmarkPageNumber = -1;
private PDOutlineItem endBookmark = null;
private boolean suppressDuplicateOverlappingText = true;
private boolean shouldSeparateByBeads = true;
private boolean sortByPosition = false;
private boolean addMoreFormatting = false;
private float indentThreshold = defaultIndentThreshold;
private float dropThreshold = defaultDropThreshold;
// we will need to estimate where to add spaces, these are used to help guess
private float spacingTolerance = .5f;
private float averageCharTolerance = .3f;
private List<PDThreadBead> pageArticles = null;
/**
* The charactersByArticle is used to extract text by article divisions. For example a PDF that has two columns like
* a newspaper, we want to extract the first column and then the second column. In this example the PDF would have 2
* beads(or articles), one for each column. The size of the charactersByArticle would be 5, because not all text on
* the screen will fall into one of the articles. The five divisions are shown below
*
* Text before first article first article text text between first article and second article second article text
* text after second article
*
* Most PDFs won't have any beads, so charactersByArticle will contain a single entry.
*/
protected Vector<List<TextPosition>> charactersByArticle = new Vector<List<TextPosition>>();
private Map<String, TreeMap<Float, TreeSet<Float>>> characterListMapping = new HashMap<String, TreeMap<Float, TreeSet<Float>>>();
protected PDDocument document;
protected Writer output;
/**
* True if we started a paragraph but haven't ended it yet.
*/
private boolean inParagraph;
/**
* Instantiate a new PDFTextStripper object.
*
* @throws IOException If there is an error loading the properties.
*/
public PDFTextStripper() throws IOException
{
}
/**
* This will return the text of a document. See writeText. <br />
* NOTE: The document must not be encrypted when coming into this method.
*
* @param doc The document to get the text from.
* @return The text of the PDF document.
* @throws IOException if the doc state is invalid or it is encrypted.
*/
public String getText(PDDocument doc) throws IOException
{
StringWriter outputStream = new StringWriter();
writeText(doc, outputStream);
return outputStream.toString();
}
private void resetEngine()
{
currentPageNo = 0;
document = null;
if (charactersByArticle != null)
{
charactersByArticle.clear();
}
if (characterListMapping != null)
{
characterListMapping.clear();
}
}
/**
* This will take a PDDocument and write the text of that document to the print writer.
*
* @param doc The document to get the data from.
* @param outputStream The location to put the text.
*
* @throws IOException If the doc is in an invalid state.
*/
public void writeText(PDDocument doc, Writer outputStream) throws IOException
{
resetEngine();
document = doc;
output = outputStream;
if (getAddMoreFormatting())
{
paragraphEnd = lineSeparator;
pageStart = lineSeparator;
articleStart = lineSeparator;
articleEnd = lineSeparator;
}
startDocument(document);
processPages(document.getPages());
endDocument(document);
}
/**
* This will process all of the pages and the text that is in them.
*
* @param pages The pages object in the document.
*
* @throws IOException If there is an error parsing the text.
*/
protected void processPages(PDPageTree pages) throws IOException
{
PDPageTree pagesTree = document.getPages();
PDPage startBookmarkPage = startBookmark == null ? null
: startBookmark.findDestinationPage(document);
if (startBookmarkPage != null)
{
startBookmarkPageNumber = pagesTree.indexOf(startBookmarkPage) + 1;
}
else
{
// -1 = undefined
startBookmarkPageNumber = -1;
}
PDPage endBookmarkPage = endBookmark == null ? null
: endBookmark.findDestinationPage(document);
if (endBookmarkPage != null)
{
endBookmarkPageNumber = pagesTree.indexOf(endBookmarkPage) + 1;
}
else
{
// -1 = undefined
endBookmarkPageNumber = -1;
}
if (startBookmarkPageNumber == -1 && startBookmark != null && endBookmarkPageNumber == -1
&& endBookmark != null
&& startBookmark.getCOSObject() == endBookmark.getCOSObject())
{
// this is a special case where both the start and end bookmark
// are the same but point to nothing. In this case
// we will not extract any text.
startBookmarkPageNumber = 0;
endBookmarkPageNumber = 0;
}
for (PDPage page : pages)
{
currentPageNo++;
if (page.hasContents())
{
processPage(page);
}
}
}
/**
* This method is available for subclasses of this class. It will be called before processing of the document start.
*
* @param document The PDF document that is being processed.
* @throws IOException If an IO error occurs.
*/
protected void startDocument(PDDocument document) throws IOException
{
// no default implementation, but available for subclasses
}
/**
* This method is available for subclasses of this class. It will be called after processing of the document
* finishes.
*
* @param document The PDF document that is being processed.
* @throws IOException If an IO error occurs.
*/
protected void endDocument(PDDocument document) throws IOException
{
// no default implementation, but available for subclasses
}
/**
* This will process the contents of a page.
*
* @param page The page to process.
*
* @throws IOException If there is an error processing the page.
*/
@Override
public void processPage(PDPage page) throws IOException
{
if (currentPageNo >= startPage && currentPageNo <= endPage
&& (startBookmarkPageNumber == -1 || currentPageNo >= startBookmarkPageNumber)
&& (endBookmarkPageNumber == -1 || currentPageNo <= endBookmarkPageNumber))
{
startPage(page);
pageArticles = page.getThreadBeads();
int numberOfArticleSections = 1 + pageArticles.size() * 2;
if (!shouldSeparateByBeads)
{
numberOfArticleSections = 1;
}
int originalSize = charactersByArticle.size();
charactersByArticle.setSize(numberOfArticleSections);
for (int i = 0; i < numberOfArticleSections; i++)
{
if (numberOfArticleSections < originalSize)
{
charactersByArticle.get(i).clear();
}
else
{
charactersByArticle.set(i, new ArrayList<TextPosition>());
}
}
characterListMapping.clear();
super.processPage(page);
writePage();
endPage(page);
}
}
/**
* Start a new article, which is typically defined as a column on a single page (also referred to as a bead). This
* assumes that the primary direction of text is left to right. Default implementation is to do nothing. Subclasses
* may provide additional information.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void startArticle() throws IOException
{
startArticle(true);
}
/**
* Start a new article, which is typically defined as a column on a single page (also referred to as a bead).
* Default implementation is to do nothing. Subclasses may provide additional information.
*
* @param isLTR true if primary direction of text is left to right.
* @throws IOException If there is any error writing to the stream.
*/
protected void startArticle(boolean isLTR) throws IOException
{
output.write(getArticleStart());
}
/**
* End an article. Default implementation is to do nothing. Subclasses may provide additional information.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void endArticle() throws IOException
{
output.write(getArticleEnd());
}
/**
* Start a new page. Default implementation is to do nothing. Subclasses may provide additional information.
*
* @param page The page we are about to process.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void startPage(PDPage page) throws IOException
{
// default is to do nothing
}
/**
* End a page. Default implementation is to do nothing. Subclasses may provide additional information.
*
* @param page The page we are about to process.
*
* @throws IOException If there is any error writing to the stream.
*/
protected void endPage(PDPage page) throws IOException
{
// default is to do nothing
}
private static final float END_OF_LAST_TEXT_X_RESET_VALUE = -1;
private static final float MAX_Y_FOR_LINE_RESET_VALUE = -Float.MAX_VALUE;
private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE = -Float.MAX_VALUE;
private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE = -1;
private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE = Float.MAX_VALUE;
private static final float LAST_WORD_SPACING_RESET_VALUE = -1;
/**
* This will print the text of the processed page to "output". It will estimate, based on the coordinates of the
* text, where newlines and word spacings should be placed. The text will be sorted only if that feature was
* enabled.
*
* @throws IOException If there is an error writing the text.
*/
protected void writePage() throws IOException
{
float maxYForLine = MAX_Y_FOR_LINE_RESET_VALUE;
float minYTopForLine = MIN_Y_TOP_FOR_LINE_RESET_VALUE;
float endOfLastTextX = END_OF_LAST_TEXT_X_RESET_VALUE;
float lastWordSpacing = LAST_WORD_SPACING_RESET_VALUE;
float maxHeightForLine = MAX_HEIGHT_FOR_LINE_RESET_VALUE;
PositionWrapper lastPosition = null;
PositionWrapper lastLineStartPosition = null;
boolean startOfPage = true; // flag to indicate start of page
boolean startOfArticle;
if (charactersByArticle.size() > 0)
{
writePageStart();
}
for (List<TextPosition> textList : charactersByArticle)
{
if (getSortByPosition())
{
TextPositionComparator comparator = new TextPositionComparator();
// because the TextPositionComparator is not transitive, but
// JDK7+ enforces transitivity on comparators, we need to use
// a custom quicksort implementation (which is slower, unfortunately).
if (useCustomQuickSort)
{
QuickSort.sort(textList, comparator);
}
else
{
Collections.sort(textList, comparator);
}
}
Iterator<TextPosition> textIter = textList.iterator();
startArticle();
startOfArticle = true;
// Now cycle through to print the text.
// We queue up a line at a time before we print so that we can convert
// the line from presentation form to logical form (if needed).
List<LineItem> line = new ArrayList<LineItem>();
textIter = textList.iterator(); // start from the beginning again
// PDF files don't always store spaces. We will need to guess where we should add
// spaces based on the distances between TextPositions. Historically, this was done
// based on the size of the space character provided by the font. In general, this
// worked but there were cases where it did not work. Calculating the average character
// width and using that as a metric works better in some cases but fails in some cases
// where the spacing worked. So we use both. NOTE: Adobe reader also fails on some of
// these examples.
// Keeps track of the previous average character width
float previousAveCharWidth = -1;
while (textIter.hasNext())
{
TextPosition position = textIter.next();
PositionWrapper current = new PositionWrapper(position);
String characterValue = position.getUnicode();
// Resets the average character width when we see a change in font
// or a change in the font size
if (lastPosition != null && (position.getFont() != lastPosition.getTextPosition()
.getFont()
|| position.getFontSize() != lastPosition.getTextPosition().getFontSize()))
{
previousAveCharWidth = -1;
}
float positionX;
float positionY;
float positionWidth;
float positionHeight;
// If we are sorting, then we need to use the text direction
// adjusted coordinates, because they were used in the sorting.
if (getSortByPosition())
{
positionX = position.getXDirAdj();
positionY = position.getYDirAdj();
positionWidth = position.getWidthDirAdj();
positionHeight = position.getHeightDir();
}
else
{
positionX = position.getX();
positionY = position.getY();
positionWidth = position.getWidth();
positionHeight = position.getHeight();
}
// The current amount of characters in a word
int wordCharCount = position.getIndividualWidths().length;
// Estimate the expected width of the space based on the
// space character with some margin.
float wordSpacing = position.getWidthOfSpace();
float deltaSpace;
if (wordSpacing == 0 || Float.isNaN(wordSpacing))
{
deltaSpace = Float.MAX_VALUE;
}
else
{
if (lastWordSpacing < 0)
{
deltaSpace = wordSpacing * getSpacingTolerance();
}
else
{
deltaSpace = (wordSpacing + lastWordSpacing) / 2f * getSpacingTolerance();
}
}
// Estimate the expected width of the space based on the average character width
// with some margin. This calculation does not make a true average (average of
// averages) but we found that it gave the best results after numerous experiments.
// Based on experiments we also found that .3 worked well.
float averageCharWidth;
if (previousAveCharWidth < 0)
{
averageCharWidth = positionWidth / wordCharCount;
}
else
{
averageCharWidth = (previousAveCharWidth + positionWidth / wordCharCount) / 2f;
}
float deltaCharWidth = averageCharWidth * getAverageCharTolerance();
// Compares the values obtained by the average method and the wordSpacing method
// and picks the smaller number.
float expectedStartOfNextWordX = EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE;
if (endOfLastTextX != END_OF_LAST_TEXT_X_RESET_VALUE)
{
if (deltaCharWidth > deltaSpace)
{
expectedStartOfNextWordX = endOfLastTextX + deltaSpace;
}
else
{
expectedStartOfNextWordX = endOfLastTextX + deltaCharWidth;
}
}
if (lastPosition != null)
{
if (startOfArticle)
{
lastPosition.setArticleStart();
startOfArticle = false;
}
// RDD - Here we determine whether this text object is on the current
// line. We use the lastBaselineFontSize to handle the superscript
// case, and the size of the current font to handle the subscript case.
// Text must overlap with the last rendered baseline text by at least
// a small amount in order to be considered as being on the same line.
// XXX BC: In theory, this check should really check if the next char is in
// full range seen in this line. This is what I tried to do with minYTopForLine,
// but this caused a lot of regression test failures. So, I'm leaving it be for
// now
if (!overlap(positionY, positionHeight, maxYForLine, maxHeightForLine))
{
writeLine(normalize(line));
line.clear();
lastLineStartPosition = handleLineSeparation(current, lastPosition,
lastLineStartPosition, maxHeightForLine);
expectedStartOfNextWordX = EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE;
maxYForLine = MAX_Y_FOR_LINE_RESET_VALUE;
maxHeightForLine = MAX_HEIGHT_FOR_LINE_RESET_VALUE;
minYTopForLine = MIN_Y_TOP_FOR_LINE_RESET_VALUE;
}
// test if our TextPosition starts after a new word would be expected to start
if (expectedStartOfNextWordX != EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE
&& expectedStartOfNextWordX < positionX &&
// only bother adding a space if the last character was not a space
lastPosition.getTextPosition().getUnicode() != null
&& !lastPosition.getTextPosition().getUnicode().endsWith(" "))
{
line.add(LineItem.getWordSeparator());
}
}
if (positionY >= maxYForLine)
{
maxYForLine = positionY;
}
// RDD - endX is what PDF considers to be the x coordinate of the
// end position of the text. We use it in computing our metrics below.
endOfLastTextX = positionX + positionWidth;
// add it to the list
if (characterValue != null)
{
if (startOfPage && lastPosition == null)
{
writeParagraphStart();// not sure this is correct for RTL?
}
line.add(new LineItem(position));
}
maxHeightForLine = Math.max(maxHeightForLine, positionHeight);
minYTopForLine = Math.min(minYTopForLine, positionY - positionHeight);
lastPosition = current;
if (startOfPage)
{
lastPosition.setParagraphStart();
lastPosition.setLineStart();
lastLineStartPosition = lastPosition;
startOfPage = false;
}
lastWordSpacing = wordSpacing;
previousAveCharWidth = averageCharWidth;
}
// print the final line
if (line.size() > 0)
{
writeLine(normalize(line));
writeParagraphEnd();
}
endArticle();
}
writePageEnd();
}
private boolean overlap(float y1, float height1, float y2, float height2)
{
return within(y1, y2, .1f) || y2 <= y1 && y2 >= y1 - height1
|| y1 <= y2 && y1 >= y2 - height2;
}
/**
* Write the line separator value to the output stream.
*
* @throws IOException If there is a problem writing out the lineseparator to the document.
*/
protected void writeLineSeparator() throws IOException
{
output.write(getLineSeparator());
}
/**
* Write the word separator value to the output stream.
*
* @throws IOException If there is a problem writing out the wordseparator to the document.
*/
protected void writeWordSeparator() throws IOException
{
output.write(getWordSeparator());
}
/**
* Write the string in TextPosition to the output stream.
*
* @param text The text to write to the stream.
* @throws IOException If there is an error when writing the text.
*/
protected void writeCharacters(TextPosition text) throws IOException
{
output.write(text.getUnicode());
}
/**
* Write a Java string to the output stream. The default implementation will ignore the <code>textPositions</code>
* and just calls {@link #writeString(String)}.
*
* @param text The text to write to the stream.
* @param textPositions The TextPositions belonging to the text.
* @throws IOException If there is an error when writing the text.
*/
protected void writeString(String text, List<TextPosition> textPositions) throws IOException
{
writeString(text);
}
/**
* Write a Java string to the output stream.
*
* @param text The text to write to the stream.
* @throws IOException If there is an error when writing the text.
*/
protected void writeString(String text) throws IOException
{
output.write(text);
}
/**
* This will determine of two floating point numbers are within a specified variance.
*
* @param first The first number to compare to.
* @param second The second number to compare to.
* @param variance The allowed variance.
*/
private boolean within(float first, float second, float variance)
{
return second < first + variance && second > first - variance;
}
/**
* This will process a TextPosition object and add the text to the list of characters on a page. It takes care of
* overlapping text.
*
* @param text The text to process.
*/
@Override
protected void processTextPosition(TextPosition text)
{
boolean showCharacter = true;
if (suppressDuplicateOverlappingText)
{
showCharacter = false;
String textCharacter = text.getUnicode();
float textX = text.getX();
float textY = text.getY();
TreeMap<Float, TreeSet<Float>> sameTextCharacters = characterListMapping
.get(textCharacter);
if (sameTextCharacters == null)
{
sameTextCharacters = new TreeMap<Float, TreeSet<Float>>();
characterListMapping.put(textCharacter, sameTextCharacters);
}
// RDD - Here we compute the value that represents the end of the rendered
// text. This value is used to determine whether subsequent text rendered
// on the same line overwrites the current text.
//
// We subtract any positive padding to handle cases where extreme amounts
// of padding are applied, then backed off (not sure why this is done, but there
// are cases where the padding is on the order of 10x the character width, and
// the TJ just backs up to compensate after each character). Also, we subtract
// an amount to allow for kerning (a percentage of the width of the last
// character).
boolean suppressCharacter = false;
float tolerance = text.getWidth() / textCharacter.length() / 3.0f;
SortedMap<Float, TreeSet<Float>> xMatches = sameTextCharacters.subMap(textX - tolerance,
textX + tolerance);
for (TreeSet<Float> xMatch : xMatches.values())
{
SortedSet<Float> yMatches = xMatch.subSet(textY - tolerance, textY + tolerance);
if (!yMatches.isEmpty())
{
suppressCharacter = true;
break;
}
}
if (!suppressCharacter)
{
TreeSet<Float> ySet = sameTextCharacters.get(textX);
if (ySet == null)
{
ySet = new TreeSet<Float>();
sameTextCharacters.put(textX, ySet);
}
ySet.add(textY);
showCharacter = true;
}
}
if (showCharacter)
{
// if we are showing the character then we need to determine which article it belongs to
int foundArticleDivisionIndex = -1;
int notFoundButFirstLeftAndAboveArticleDivisionIndex = -1;
int notFoundButFirstLeftArticleDivisionIndex = -1;
int notFoundButFirstAboveArticleDivisionIndex = -1;
float x = text.getX();
float y = text.getY();
if (shouldSeparateByBeads)
{
for (int i = 0; i < pageArticles.size() && foundArticleDivisionIndex == -1; i++)
{
PDThreadBead bead = pageArticles.get(i);
if (bead != null)
{
PDRectangle rect = bead.getRectangle();
if (rect.contains(x, y))
{
foundArticleDivisionIndex = i * 2 + 1;
}
else if ((x < rect.getLowerLeftX() || y < rect.getUpperRightY())
&& notFoundButFirstLeftAndAboveArticleDivisionIndex == -1)
{
notFoundButFirstLeftAndAboveArticleDivisionIndex = i * 2;
}
else if (x < rect.getLowerLeftX()
&& notFoundButFirstLeftArticleDivisionIndex == -1)
{
notFoundButFirstLeftArticleDivisionIndex = i * 2;
}
else if (y < rect.getUpperRightY()
&& notFoundButFirstAboveArticleDivisionIndex == -1)
{
notFoundButFirstAboveArticleDivisionIndex = i * 2;
}
}
else
{
foundArticleDivisionIndex = 0;
}
}
}
else
{
foundArticleDivisionIndex = 0;
}
int articleDivisionIndex;
if (foundArticleDivisionIndex != -1)
{
articleDivisionIndex = foundArticleDivisionIndex;
}
else if (notFoundButFirstLeftAndAboveArticleDivisionIndex != -1)
{
articleDivisionIndex = notFoundButFirstLeftAndAboveArticleDivisionIndex;
}
else if (notFoundButFirstLeftArticleDivisionIndex != -1)
{
articleDivisionIndex = notFoundButFirstLeftArticleDivisionIndex;
}
else if (notFoundButFirstAboveArticleDivisionIndex != -1)
{
articleDivisionIndex = notFoundButFirstAboveArticleDivisionIndex;
}
else
{
articleDivisionIndex = charactersByArticle.size() - 1;
}
List<TextPosition> textList = charactersByArticle.get(articleDivisionIndex);
// In the wild, some PDF encoded documents put diacritics (accents on
// top of characters) into a separate Tj element. When displaying them
// graphically, the two chunks get overlayed. With text output though,
// we need to do the overlay. This code recombines the diacritic with
// its associated character if the two are consecutive.
if (textList.isEmpty())
{
textList.add(text);
}
else
{
// test if we overlap the previous entry.
// Note that we are making an assumption that we need to only look back
// one TextPosition to find what we are overlapping.
// This may not always be true. */
TextPosition previousTextPosition = textList.get(textList.size() - 1);
if (text.isDiacritic() && previousTextPosition.contains(text))
{
previousTextPosition.mergeDiacritic(text);
}
// If the previous TextPosition was the diacritic, merge it into this
// one and remove it from the list.
else if (previousTextPosition.isDiacritic() && text.contains(previousTextPosition))
{
text.mergeDiacritic(previousTextPosition);
textList.remove(textList.size() - 1);
textList.add(text);
}
else
{
textList.add(text);
}
}
}
}
/**
* This is the page that the text extraction will start on. The pages start at page 1. For example in a 5 page PDF
* document, if the start page is 1 then all pages will be extracted. If the start page is 4 then pages 4 and 5 will
* be extracted. The default value is 1.
*
* @return Value of property startPage.
*/
public int getStartPage()
{
return startPage;
}
/**
* This will set the first page to be extracted by this class.
*
* @param startPageValue New value of 1-based startPage property.
*/
public void setStartPage(int startPageValue)
{
startPage = startPageValue;
}
/**
* This will get the last page that will be extracted. This is inclusive, for example if a 5 page PDF an endPage
* value of 5 would extract the entire document, an end page of 2 would extract pages 1 and 2. This defaults to
* Integer.MAX_VALUE such that all pages of the pdf will be extracted.
*
* @return Value of property endPage.
*/
public int getEndPage()
{
return endPage;
}
/**
* This will set the last page to be extracted by this class.
*
* @param endPageValue New value of 1-based endPage property.
*/
public void setEndPage(int endPageValue)
{
endPage = endPageValue;
}
/**
* Set the desired line separator for output text. The line.separator system property is used if the line separator
* preference is not set explicitly using this method.
*
* @param separator The desired line separator string.
*/
public void setLineSeparator(String separator)
{
lineSeparator = separator;
}
/**
* This will get the line separator.
*
* @return The desired line separator string.
*/
public String getLineSeparator()
{
return lineSeparator;
}
/**
* This will get the word separator.
*
* @return The desired word separator string.
*/
public String getWordSeparator()
{
return wordSeparator;
}
/**
* Set the desired word separator for output text. The PDFBox text extraction algorithm will output a space
* character if there is enough space between two words. By default a space character is used. If you need and
* accurate count of characters that are found in a PDF document then you might want to set the word separator to
* the empty string.
*
* @param separator The desired page separator string.
*/
public void setWordSeparator(String separator)
{
wordSeparator = separator;
}
/**
* @return Returns the suppressDuplicateOverlappingText.
*/
public boolean getSuppressDuplicateOverlappingText()
{
return suppressDuplicateOverlappingText;
}
/**
* Get the current page number that is being processed.
*
* @return A 1 based number representing the current page.
*/
protected int getCurrentPageNo()
{
return currentPageNo;
}
/**
* The output stream that is being written to.
*
* @return The stream that output is being written to.
*/
protected Writer getOutput()
{
return output;
}
/**
* Character strings are grouped by articles. It is quite common that there will only be a single article. This
* returns a List that contains List objects, the inner lists will contain TextPosition objects.
*
* @return A double List of TextPositions for all text strings on the page.
*/
protected List<List<TextPosition>> getCharactersByArticle()
{
return charactersByArticle;
}
/**
* By default the text stripper will attempt to remove text that overlapps each other. Word paints the same
* character several times in order to make it look bold. By setting this to false all text will be extracted, which
* means that certain sections will be duplicated, but better performance will be noticed.
*
* @param suppressDuplicateOverlappingTextValue The suppressDuplicateOverlappingText to set.
*/
public void setSuppressDuplicateOverlappingText(boolean suppressDuplicateOverlappingTextValue)
{
suppressDuplicateOverlappingText = suppressDuplicateOverlappingTextValue;
}
/**
* This will tell if the text stripper should separate by beads.
*
* @return If the text will be grouped by beads.
*/
public boolean getSeparateByBeads()
{
return shouldSeparateByBeads;
}
/**
* Set if the text stripper should group the text output by a list of beads. The default value is true!
*
* @param aShouldSeparateByBeads The new grouping of beads.
*/
public void setShouldSeparateByBeads(boolean aShouldSeparateByBeads)
{
shouldSeparateByBeads = aShouldSeparateByBeads;
}
/**
* Get the bookmark where text extraction should end, inclusive. Default is null.
*
* @return The ending bookmark.
*/
public PDOutlineItem getEndBookmark()
{
return endBookmark;
}
/**
* Set the bookmark where the text extraction should stop.
*
* @param aEndBookmark The ending bookmark.
*/
public void setEndBookmark(PDOutlineItem aEndBookmark)
{
endBookmark = aEndBookmark;
}
/**
* Get the bookmark where text extraction should start, inclusive. Default is null.
*
* @return The starting bookmark.
*/
public PDOutlineItem getStartBookmark()
{
return startBookmark;
}
/**
* Set the bookmark where text extraction should start, inclusive.
*
* @param aStartBookmark The starting bookmark.
*/
public void setStartBookmark(PDOutlineItem aStartBookmark)
{
startBookmark = aStartBookmark;
}
/**
* This will tell if the text stripper should add some more text formatting.
*
* @return true if some more text formatting will be added
*/
public boolean getAddMoreFormatting()
{
return addMoreFormatting;
}
/**
* There will some additional text formatting be added if addMoreFormatting is set to true. Default is false.
*
* @param newAddMoreFormatting Tell PDFBox to add some more text formatting
*/
public void setAddMoreFormatting(boolean newAddMoreFormatting)
{
addMoreFormatting = newAddMoreFormatting;
}
/**
* This will tell if the text stripper should sort the text tokens before writing to the stream.
*
* @return true If the text tokens will be sorted before being written.
*/
public boolean getSortByPosition()
{
return sortByPosition;
}
/**
* The order of the text tokens in a PDF file may not be in the same as they appear visually on the screen. For
* example, a PDF writer may write out all text by font, so all bold or larger text, then make a second pass and
* write out the normal text.<br/>
* The default is to <b>not</b> sort by position.<br/>
* <br/>
* A PDF writer could choose to write each character in a different order. By default PDFBox does <b>not</b> sort
* the text tokens before processing them due to performance reasons.
*
* @param newSortByPosition Tell PDFBox to sort the text positions.
*/
public void setSortByPosition(boolean newSortByPosition)
{
sortByPosition = newSortByPosition;
}
/**
* Get the current space width-based tolerance value that is being used to estimate where spaces in text should be
* added. Note that the default value for this has been determined from trial and error.
*
* @return The current tolerance / scaling factor
*/
public float getSpacingTolerance()
{
return spacingTolerance;
}
/**
* Set the space width-based tolerance value that is used to estimate where spaces in text should be added. Note
* that the default value for this has been determined from trial and error. Setting this value larger will reduce
* the number of spaces added.
*
* @param spacingToleranceValue tolerance / scaling factor to use
*/
public void setSpacingTolerance(float spacingToleranceValue)
{
spacingTolerance = spacingToleranceValue;
}
/**
* Get the current character width-based tolerance value that is being used to estimate where spaces in text should
* be added. Note that the default value for this has been determined from trial and error.
*
* @return The current tolerance / scaling factor
*/
public float getAverageCharTolerance()
{
return averageCharTolerance;
}
/**
* Set the character width-based tolerance value that is used to estimate where spaces in text should be added. Note
* that the default value for this has been determined from trial and error. Setting this value larger will reduce
* the number of spaces added.
*
* @param averageCharToleranceValue average tolerance / scaling factor to use
*/
public void setAverageCharTolerance(float averageCharToleranceValue)
{
averageCharTolerance = averageCharToleranceValue;
}
/**
* returns the multiple of whitespace character widths for the current text which the current line start can be
* indented from the previous line start beyond which the current line start is considered to be a paragraph start.
*
* @return the number of whitespace character widths to use when detecting paragraph indents.
*/
public float getIndentThreshold()
{
return indentThreshold;
}
/**
* sets the multiple of whitespace character widths for the current text which the current line start can be
* indented from the previous line start beyond which the current line start is considered to be a paragraph start.
* The default value is 2.0.
*
* @param indentThresholdValue the number of whitespace character widths to use when detecting paragraph indents.
*/
public void setIndentThreshold(float indentThresholdValue)
{
indentThreshold = indentThresholdValue;
}
/**
* the minimum whitespace, as a multiple of the max height of the current characters beyond which the current line
* start is considered to be a paragraph start.
*
* @return the character height multiple for max allowed whitespace between lines in the same paragraph.
*/
public float getDropThreshold()
{
return dropThreshold;
}
/**
* sets the minimum whitespace, as a multiple of the max height of the current characters beyond which the current
* line start is considered to be a paragraph start. The default value is 2.5.
*
* @param dropThresholdValue the character height multiple for max allowed whitespace between lines in the same
* paragraph.
*/
public void setDropThreshold(float dropThresholdValue)
{
dropThreshold = dropThresholdValue;
}
/**
* Returns the string which will be used at the beginning of a paragraph.
*
* @return the paragraph start string
*/
public String getParagraphStart()
{
return paragraphStart;
}
/**
* Sets the string which will be used at the beginning of a paragraph.
*
* @param s the paragraph start string
*/
public void setParagraphStart(String s)
{
paragraphStart = s;
}
/**
* Returns the string which will be used at the end of a paragraph.
*
* @return the paragraph end string
*/
public String getParagraphEnd()
{
return paragraphEnd;
}
/**
* Sets the string which will be used at the end of a paragraph.
*
* @param s the paragraph end string
*/
public void setParagraphEnd(String s)
{
paragraphEnd = s;
}
/**
* Returns the string which will be used at the beginning of a page.
*
* @return the page start string
*/
public String getPageStart()
{
return pageStart;
}
/**
* Sets the string which will be used at the beginning of a page.
*
* @param pageStartValue the page start string
*/
public void setPageStart(String pageStartValue)
{
pageStart = pageStartValue;
}
/**
* Returns the string which will be used at the end of a page.
*
* @return the page end string
*/
public String getPageEnd()
{
return pageEnd;
}
/**
* Sets the string which will be used at the end of a page.
*
* @param pageEndValue the page end string
*/
public void setPageEnd(String pageEndValue)
{
pageEnd = pageEndValue;
}
/**
* Returns the string which will be used at the beginning of an article.
*
* @return the article start string
*/
public String getArticleStart()
{
return articleStart;
}
/**
* Sets the string which will be used at the beginning of an article.
*
* @param articleStartValue the article start string
*/
public void setArticleStart(String articleStartValue)
{
articleStart = articleStartValue;
}
/**
* Returns the string which will be used at the end of an article.
*
* @return the article end string
*/
public String getArticleEnd()
{
return articleEnd;
}
/**
* Sets the string which will be used at the end of an article.
*
* @param articleEndValue the article end string
*/
public void setArticleEnd(String articleEndValue)
{
articleEnd = articleEndValue;
}
/**
* handles the line separator for a new line given the specified current and previous TextPositions.
*
* @param current the current text position
* @param lastPosition the previous text position
* @param lastLineStartPosition the last text position that followed a line separator.
* @param maxHeightForLine max height for positions since lastLineStartPosition
* @return start position of the last line
* @throws IOException if something went wrong
*/
private PositionWrapper handleLineSeparation(PositionWrapper current,
PositionWrapper lastPosition, PositionWrapper lastLineStartPosition,
float maxHeightForLine) throws IOException
{
current.setLineStart();
isParagraphSeparation(current, lastPosition, lastLineStartPosition, maxHeightForLine);
lastLineStartPosition = current;
if (current.isParagraphStart())
{
if (lastPosition.isArticleStart())
{
writeParagraphStart();
}
else
{
writeLineSeparator();
writeParagraphSeparator();
}
}
else
{
writeLineSeparator();
}
return lastLineStartPosition;
}
/**
* tests the relationship between the last text position, the current text position and the last text position that
* followed a line separator to decide if the gap represents a paragraph separation. This should <i>only</i> be
* called for consecutive text positions that first pass the line separation test.
* <p>
* This base implementation tests to see if the lastLineStartPosition is null OR if the current vertical position
* has dropped below the last text vertical position by at least 2.5 times the current text height OR if the current
* horizontal position is indented by at least 2 times the current width of a space character.
* </p>
* <p>
* This also attempts to identify text that is indented under a hanging indent.
* </p>
* <p>
* This method sets the isParagraphStart and isHangingIndent flags on the current position object.
* </p>
*
* @param position the current text position. This may have its isParagraphStart or isHangingIndent flags set upon
* return.
* @param lastPosition the previous text position (should not be null).
* @param lastLineStartPosition the last text position that followed a line separator, or null.
* @param maxHeightForLine max height for text positions since lasLineStartPosition.
*/
private void isParagraphSeparation(PositionWrapper position, PositionWrapper lastPosition,
PositionWrapper lastLineStartPosition, float maxHeightForLine)
{
boolean result = false;
if (lastLineStartPosition == null)
{
result = true;
}
else
{
float yGap = Math.abs(position.getTextPosition().getYDirAdj()
- lastPosition.getTextPosition().getYDirAdj());
float newYVal = multiplyFloat(getDropThreshold(), maxHeightForLine);
// do we need to flip this for rtl?
float xGap = position.getTextPosition().getXDirAdj()
- lastLineStartPosition.getTextPosition().getXDirAdj();
float newXVal = multiplyFloat(getIndentThreshold(),
position.getTextPosition().getWidthOfSpace());
float positionWidth = multiplyFloat(0.25f, position.getTextPosition().getWidth());
if (yGap > newYVal)
{
result = true;
}
else if (xGap > newXVal)
{
// text is indented, but try to screen for hanging indent
if (!lastLineStartPosition.isParagraphStart())
{
result = true;
}
else
{
position.setHangingIndent();
}
}
else if (xGap < -position.getTextPosition().getWidthOfSpace())
{
// text is left of previous line. Was it a hanging indent?
if (!lastLineStartPosition.isParagraphStart())
{
result = true;
}
}
else if (Math.abs(xGap) < positionWidth)
{
// current horizontal position is within 1/4 a char of the last
// linestart. We'll treat them as lined up.
if (lastLineStartPosition.isHangingIndent())
{
position.setHangingIndent();
}
else if (lastLineStartPosition.isParagraphStart())
{
// check to see if the previous line looks like
// any of a number of standard list item formats
Pattern liPattern = matchListItemPattern(lastLineStartPosition);
if (liPattern != null)
{
Pattern currentPattern = matchListItemPattern(position);
if (liPattern == currentPattern)
{
result = true;
}
}
}
}
}
if (result)
{
position.setParagraphStart();
}
}
private float multiplyFloat(float value1, float value2)
{
// multiply 2 floats and truncate the resulting value to 3 decimal places
// to avoid wrong results when comparing with another float
return Math.round(value1 * value2 * 1000) / 1000f;
}
/**
* writes the paragraph separator string to the output.
*
* @throws IOException if something went wrong
*/
protected void writeParagraphSeparator() throws IOException
{
writeParagraphEnd();
writeParagraphStart();
}
/**
* Write something (if defined) at the start of a paragraph.
*
* @throws IOException if something went wrong
*/
protected void writeParagraphStart() throws IOException
{
if (inParagraph)
{
writeParagraphEnd();
inParagraph = false;
}
output.write(getParagraphStart());
inParagraph = true;
}
/**
* Write something (if defined) at the end of a paragraph.
*
* @throws IOException if something went wrong
*/
protected void writeParagraphEnd() throws IOException
{
if (!inParagraph)
{
writeParagraphStart();
}
output.write(getParagraphEnd());
inParagraph = false;
}
/**
* Write something (if defined) at the start of a page.
*
* @throws IOException if something went wrong
*/
protected void writePageStart() throws IOException
{
output.write(getPageStart());
}
/**
* Write something (if defined) at the end of a page.
*
* @throws IOException if something went wrong
*/
protected void writePageEnd() throws IOException
{
output.write(getPageEnd());
}
/**
* returns the list item Pattern object that matches the text at the specified PositionWrapper or null if the text
* does not match such a pattern. The list of Patterns tested against is given by the {@link #getListItemPatterns()}
* method. To add to the list, simply override that method (if sub-classing) or explicitly supply your own list
* using {@link #setListItemPatterns(List)}.
*
* @param pw position
* @return the matching pattern
*/
private Pattern matchListItemPattern(PositionWrapper pw)
{
TextPosition tp = pw.getTextPosition();
String txt = tp.getUnicode();
return matchPattern(txt, getListItemPatterns());
}
/**
* a list of regular expressions that match commonly used list item formats, i.e. bullets, numbers, letters, Roman
* numerals, etc. Not meant to be comprehensive.
*/
private static final String[] LIST_ITEM_EXPRESSIONS = { "\\.", "\\d+\\.", "\\[\\d+\\]",
"\\d+\\)", "[A-Z]\\.", "[a-z]\\.", "[A-Z]\\)", "[a-z]\\)", "[IVXL]+\\.",
"[ivxl]+\\.", };
private List<Pattern> listOfPatterns = null;
/**
* use to supply a different set of regular expression patterns for matching list item starts.
*
* @param patterns list of patterns
*/
protected void setListItemPatterns(List<Pattern> patterns)
{
listOfPatterns = patterns;
}
/**
* returns a list of regular expression Patterns representing different common list item formats. For example
* numbered items of form:
* <ol>
* <li>some text</li>
* <li>more text</li>
* </ol>
* or
* <ul>
* <li>some text</li>
* <li>more text</li>
* </ul>
* etc., all begin with some character pattern. The pattern "\\d+\." (matches "1.", "2.", ...) or "\[\\d+\]"
* (matches "[1]", "[2]", ...).
* <p>
* This method returns a list of such regular expression Patterns.
*
* @return a list of Pattern objects.
*/
protected List<Pattern> getListItemPatterns()
{
if (listOfPatterns == null)
{
listOfPatterns = new ArrayList<Pattern>();
for (String expression : LIST_ITEM_EXPRESSIONS)
{
Pattern p = Pattern.compile(expression);
listOfPatterns.add(p);
}
}
return listOfPatterns;
}
/**
* iterates over the specified list of Patterns until it finds one that matches the specified string. Then returns
* the Pattern.
* <p>
* Order of the supplied list of patterns is important as most common patterns should come first. Patterns should be
* strict in general, and all will be used with case sensitivity on.
* </p>
*
* @param string the string to be searched
* @param patterns list of patterns
* @return matching pattern
*/
protected static Pattern matchPattern(String string, List<Pattern> patterns)
{
for (Pattern p : patterns)
{
if (p.matcher(string).matches())
{
return p;
}
}
return null;
}
/**
* Write a list of string containing a whole line of a document.
*
* @param line a list with the words of the given line
* @throws IOException if something went wrong
*/
private void writeLine(List<WordWithTextPositions> line)
throws IOException
{
int numberOfStrings = line.size();
for (int i = 0; i < numberOfStrings; i++)
{
WordWithTextPositions word = line.get(i);
writeString(word.getText(), word.getTextPositions());
if (i < numberOfStrings - 1)
{
writeWordSeparator();
}
}
}
/**
* Normalize the given list of TextPositions.
*
* @param line list of TextPositions
* @return a list of strings, one string for every word
*/
private List<WordWithTextPositions> normalize(List<LineItem> line)
{
List<WordWithTextPositions> normalized = new LinkedList<WordWithTextPositions>();
StringBuilder lineBuilder = new StringBuilder();
List<TextPosition> wordPositions = new ArrayList<TextPosition>();
for (LineItem item : line)
{
lineBuilder = normalizeAdd(normalized, lineBuilder, wordPositions, item);
}
if (lineBuilder.length() > 0)
{
normalized.add(createWord(lineBuilder.toString(), wordPositions));
}
return normalized;
}
/**
* Handles the LTR and RTL direction of the given words. The whole implementation stands and falls with the given
* word. If the word is a full line, the results will be the best. If the word contains of single words or
* characters, the order of the characters in a word or words in a line may wrong, due to RTL and LTR marks and
* characters!
*
* Based on http://www.nesterovsky-bros.com/weblog/2013/07/28/VisualToLogicalConversionInJava.aspx
*
* @param word The word that shall be processed
* @return new word with the correct direction of the containing characters
*/
private String handleDirection(String word)
{
Bidi bidi = new Bidi(word, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
// if there is pure LTR text no need to process further
if (!bidi.isMixed() && bidi.getBaseLevel() == Bidi.DIRECTION_LEFT_TO_RIGHT)
{
return word;
}
// collect individual bidi information
int runCount = bidi.getRunCount();
byte[] levels = new byte[runCount];
Integer[] runs = new Integer[runCount];
for (int i = 0; i < runCount; i++)
{
levels[i] = (byte)bidi.getRunLevel(i);
runs[i] = i;
}
// reorder individual parts based on their levels
Bidi.reorderVisually(levels, 0, runs, 0, runCount);
// collect the parts based on the direction within the run
StringBuilder result = new StringBuilder();
for (int i = 0; i < runCount; i++)
{
int index = runs[i];
int start = bidi.getRunStart(index);
int end = bidi.getRunLimit(index);
int level = levels[index];
if ((level & 1) != 0)
{
for (; --end >= start;)
{
if (Character.isMirrored(word.codePointAt(end)))
{
if (MIRRORING_CHAR_MAP.containsKey(word.charAt(end) + ""))
{
result.append(MIRRORING_CHAR_MAP.get(word.charAt(end) + "").charAt(0));
}
else
{
result.append(word.charAt(end));
}
}
else
{
result.append(word.charAt(end));
}
}
}
else
{
result.append(word, start, end);
}
}
return result.toString();
}
private static HashMap<String, String> MIRRORING_CHAR_MAP = new HashMap<String, String>();
static
{
String path = "org/apache/pdfbox/resources/text/BidiMirroring.txt";
InputStream input = PDFTextStripper.class.getClassLoader().getResourceAsStream(path);
try
{
parseBidiFile(input);
}
catch (IOException e)
{
LOG.warn("Could not parse BidiMirroring.txt, mirroring char map will be empty: "
+ e.getMessage());
}
};
/**
* This method parses the bidi file provided as inputstream.
*
* @param inputStream - The bidi file as inputstream
* @throws IOException if any line could not be read by the LineNumberReader
*/
private static void parseBidiFile(InputStream inputStream) throws IOException
{
LineNumberReader rd = new LineNumberReader(new InputStreamReader(inputStream));
do
{
String s = rd.readLine();
if (s == null)
{
break;
}
int comment = s.indexOf('#'); // ignore comments
if (comment != -1)
{
s = s.substring(0, comment);
}
if (s.length() < 2)
{
continue;
}
StringTokenizer st = new StringTokenizer(s, ";");
int nFields = st.countTokens();
String[] fields = new String[nFields];
for (int i = 0; i < nFields; i++)
{
fields[i] = "" + (char) Integer.parseInt(st.nextToken().trim(), 16); //
}
if (fields.length == 2)
{
// initialize the MIRRORING_CHAR_MAP
MIRRORING_CHAR_MAP.put(fields[0], fields[1]);
}
} while (true);
}
/**
* Used within {@link #normalize(List, boolean, boolean)} to create a single {@link WordWithTextPositions} entry.
*/
private WordWithTextPositions createWord(String word, List<TextPosition> wordPositions)
{
return new WordWithTextPositions(normalizeWord(word), wordPositions);
}
/**
* Normalize certain Unicode characters. For example, convert the single "fi" ligature to "f" and "i". Also
* normalises Arabic and Hebrew presentation forms.
*
* @param word Word to normalize
* @return Normalized word
*/
private String normalizeWord(String word)
{
StringBuilder builder = null;
int p = 0;
int q = 0;
int strLength = word.length();
for (; q < strLength; q++)
{
// We only normalize if the codepoint is in a given range.
// Otherwise, NFKC converts too many things that would cause
// confusion. For example, it converts the micro symbol in
// extended Latin to the value in the Greek script. We normalize
// the Unicode Alphabetic and Arabic A&B Presentation forms.
char c = word.charAt(q);
if (0xFB00 <= c && c <= 0xFDFF || 0xFE70 <= c && c <= 0xFEFF)
{
if (builder == null)
{
builder = new StringBuilder(strLength * 2);
}
builder.append(word.substring(p, q));
// Some fonts map U+FDF2 differently than the Unicode spec.
// They add an extra U+0627 character to compensate.
// This removes the extra character for those fonts.
if (c == 0xFDF2 && q > 0
&& (word.charAt(q - 1) == 0x0627 || word.charAt(q - 1) == 0xFE8D))
{
builder.append("\u0644\u0644\u0647");
}
else
{
// Trim because some decompositions have an extra space, such as U+FC5E
builder.append(Normalizer
.normalize(word.substring(q, q + 1), Normalizer.Form.NFKC).trim());
}
p = q + 1;
}
}
if (builder == null)
{
return handleDirection(word);
}
else
{
builder.append(word.substring(p, q));
return handleDirection(builder.toString());
}
}
/**
* Used within {@link #normalize(List, boolean, boolean)} to handle a {@link TextPosition}.
*
* @return The StringBuilder that must be used when calling this method.
*/
private StringBuilder normalizeAdd(List<WordWithTextPositions> normalized,
StringBuilder lineBuilder, List<TextPosition> wordPositions, LineItem item)
{
if (item.isWordSeparator())
{
normalized.add(
createWord(lineBuilder.toString(), new ArrayList<TextPosition>(wordPositions)));
lineBuilder = new StringBuilder();
wordPositions.clear();
}
else
{
TextPosition text = item.getTextPosition();
lineBuilder.append(text.getUnicode());
wordPositions.add(text);
}
return lineBuilder;
}
/**
* internal marker class. Used as a place holder in a line of TextPositions.
*/
private static final class LineItem
{
public static LineItem WORD_SEPARATOR = new LineItem();
public static LineItem getWordSeparator()
{
return WORD_SEPARATOR;
}
private final TextPosition textPosition;
private LineItem()
{
textPosition = null;
}
LineItem(TextPosition textPosition)
{
this.textPosition = textPosition;
}
public TextPosition getTextPosition()
{
return textPosition;
}
public boolean isWordSeparator()
{
return textPosition == null;
}
}
/**
* Internal class that maps strings to lists of {@link TextPosition} arrays. Note that the number of entries in that
* list may differ from the number of characters in the string due to normalization.
*
* @author Axel Dörfler
*/
private static final class WordWithTextPositions
{
String text;
List<TextPosition> textPositions;
WordWithTextPositions(String word, List<TextPosition> positions)
{
text = word;
textPositions = positions;
}
public String getText()
{
return text;
}
public List<TextPosition> getTextPositions()
{
return textPositions;
}
}
/**
* wrapper of TextPosition that adds flags to track status as linestart and paragraph start positions.
* <p>
* This is implemented as a wrapper since the TextPosition class doesn't provide complete access to its state fields
* to subclasses. Also, conceptually TextPosition is immutable while these flags need to be set post-creation so it
* makes sense to put these flags in this separate class.
* </p>
*
* @author [email protected]
*/
private static final class PositionWrapper
{
private boolean isLineStart = false;
private boolean isParagraphStart = false;
private boolean isPageBreak = false;
private boolean isHangingIndent = false;
private boolean isArticleStart = false;
private TextPosition position = null;
/**
* Constructs a PositionWrapper around the specified TextPosition object.
*
* @param position the text position.
*/
PositionWrapper(TextPosition position)
{
this.position = position;
}
/**
* Returns the underlying TextPosition object.
*
* @return the text position
*/
public TextPosition getTextPosition()
{
return position;
}
public boolean isLineStart()
{
return isLineStart;
}
/**
* Sets the isLineStart() flag to true.
*/
public void setLineStart()
{
this.isLineStart = true;
}
public boolean isParagraphStart()
{
return isParagraphStart;
}
/**
* sets the isParagraphStart() flag to true.
*/
public void setParagraphStart()
{
this.isParagraphStart = true;
}
public boolean isArticleStart()
{
return isArticleStart;
}
/**
* Sets the isArticleStart() flag to true.
*/
public void setArticleStart()
{
this.isArticleStart = true;
}
public boolean isPageBreak()
{
return isPageBreak;
}
/**
* Sets the isPageBreak() flag to true.
*/
public void setPageBreak()
{
this.isPageBreak = true;
}
public boolean isHangingIndent()
{
return isHangingIndent;
}
/**
* Sets the isHangingIndent() flag to true.
*/
public void setHangingIndent()
{
this.isHangingIndent = true;
}
}
}
| PDFBOX-3110: adjust bead rectangles for flip and cropbox
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1714590 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStripper.java | PDFBOX-3110: adjust bead rectangles for flip and cropbox | <ide><path>dfbox/src/main/java/org/apache/pdfbox/text/PDFTextStripper.java
<ide> if (bead != null)
<ide> {
<ide> PDRectangle rect = bead.getRectangle();
<add>
<add> // bead rectangle is in PDF coordinates (y=0 is bottom),
<add> // glyphs are in image coordinates (y=0 is top),
<add> // so we must flip
<add> PDPage pdPage = getCurrentPage();
<add> PDRectangle mediaBox = pdPage.getMediaBox();
<add> float upperRightY = mediaBox.getUpperRightY() - rect.getLowerLeftY();
<add> float lowerLeftY = mediaBox.getUpperRightY() - rect.getUpperRightY();
<add> rect.setLowerLeftY(lowerLeftY);
<add> rect.setUpperRightY(upperRightY);
<add>
<add> // adjust for cropbox
<add> PDRectangle cropBox = pdPage.getCropBox();
<add> if (cropBox.getLowerLeftX() != 0 || cropBox.getLowerLeftY() != 0)
<add> {
<add> rect.setLowerLeftX(rect.getLowerLeftX() - cropBox.getLowerLeftX());
<add> rect.setLowerLeftY(rect.getLowerLeftY() - cropBox.getLowerLeftY());
<add> rect.setUpperRightX(rect.getUpperRightX() - cropBox.getLowerLeftX());
<add> rect.setUpperRightY(rect.getUpperRightY() - cropBox.getLowerLeftY());
<add> }
<add>
<ide> if (rect.contains(x, y))
<ide> {
<ide> foundArticleDivisionIndex = i * 2 + 1; |
|
Java | apache-2.0 | 57a8756a9eacb390d79e820aae5319270c65558f | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.index.memory;
/**
* 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.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.analysis.StopAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util._TestUtil;
/**
* Verifies that Lucene MemoryIndex and RAMDirectory have the same behaviour,
* returning the same results for queries on some randomish indexes.
*/
public class MemoryIndexTest extends BaseTokenStreamTestCase {
private Set<String> queries = new HashSet<String>();
private Random random;
public static final int ITERATIONS = 100*_TestUtil.getRandomMultiplier();
@Override
public void setUp() throws Exception {
super.setUp();
queries.addAll(readQueries("testqueries.txt"));
queries.addAll(readQueries("testqueries2.txt"));
random = newRandom();
}
/**
* read a set of queries from a resource file
*/
private Set<String> readQueries(String resource) throws IOException {
Set<String> queries = new HashSet<String>();
InputStream stream = getClass().getResourceAsStream(resource);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0 && !line.startsWith("#") && !line.startsWith("//")) {
queries.add(line);
}
}
return queries;
}
/**
* runs random tests, up to ITERATIONS times.
*/
public void testRandomQueries() throws Exception {
for (int i = 0; i < ITERATIONS; i++)
assertAgainstRAMDirectory();
}
/**
* Build a randomish document for both RAMDirectory and MemoryIndex,
* and run all the queries against it.
*/
public void assertAgainstRAMDirectory() throws Exception {
StringBuilder fooField = new StringBuilder();
StringBuilder termField = new StringBuilder();
// add up to 250 terms to field "foo"
final int numFooTerms = random.nextInt(250*_TestUtil.getRandomMultiplier());
for (int i = 0; i < numFooTerms; i++) {
fooField.append(" ");
fooField.append(randomTerm());
}
// add up to 250 terms to field "term"
final int numTermTerms = random.nextInt(250*_TestUtil.getRandomMultiplier());
for (int i = 0; i < numTermTerms; i++) {
termField.append(" ");
termField.append(randomTerm());
}
RAMDirectory ramdir = new RAMDirectory();
Analyzer analyzer = randomAnalyzer();
IndexWriter writer = new IndexWriter(ramdir, analyzer,
IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document();
Field field1 = new Field("foo", fooField.toString(), Field.Store.NO, Field.Index.ANALYZED);
Field field2 = new Field("term", termField.toString(), Field.Store.NO, Field.Index.ANALYZED);
doc.add(field1);
doc.add(field2);
writer.addDocument(doc);
writer.close();
MemoryIndex memory = new MemoryIndex();
memory.addField("foo", fooField.toString(), analyzer);
memory.addField("term", termField.toString(), analyzer);
assertAllQueries(memory, ramdir, analyzer);
}
/**
* Run all queries against both the RAMDirectory and MemoryIndex, ensuring they are the same.
*/
public void assertAllQueries(MemoryIndex memory, RAMDirectory ramdir, Analyzer analyzer) throws Exception {
IndexSearcher ram = new IndexSearcher(ramdir);
IndexSearcher mem = memory.createSearcher();
QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer);
for (String query : queries) {
TopDocs ramDocs = ram.search(qp.parse(query), 1);
TopDocs memDocs = mem.search(qp.parse(query), 1);
assertEquals(ramDocs.totalHits, memDocs.totalHits);
}
}
/**
* Return a random analyzer (Simple, Stop, Standard) to analyze the terms.
*/
private Analyzer randomAnalyzer() {
switch(random.nextInt(3)) {
case 0: return new SimpleAnalyzer(TEST_VERSION_CURRENT);
case 1: return new StopAnalyzer(TEST_VERSION_CURRENT);
default: return new StandardAnalyzer(TEST_VERSION_CURRENT);
}
}
/**
* Some terms to be indexed, in addition to random words.
* These terms are commonly used in the queries.
*/
private static final String[] TEST_TERMS = {"term", "Term", "tErm", "TERM",
"telm", "stop", "drop", "roll", "phrase", "a", "c", "bar", "blar",
"gack", "weltbank", "worlbank", "hello", "on", "the", "apache", "Apache",
"copyright", "Copyright"};
/**
* half of the time, returns a random term from TEST_TERMS.
* the other half of the time, returns a random unicode string.
*/
private String randomTerm() {
if (random.nextBoolean()) {
// return a random TEST_TERM
return TEST_TERMS[random.nextInt(TEST_TERMS.length)];
} else {
// return a random unicode term
return _TestUtil.randomUnicodeString(random);
}
}
}
| lucene/contrib/memory/src/test/org/apache/lucene/index/memory/MemoryIndexTest.java | package org.apache.lucene.index.memory;
/**
* 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.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.analysis.StopAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util._TestUtil;
/**
* Verifies that Lucene MemoryIndex and RAMDirectory have the same behaviour,
* returning the same results for queries on some randomish indexes.
*/
public class MemoryIndexTest extends BaseTokenStreamTestCase {
private Set<String> queries = new HashSet<String>();
private Random random;
public static final int ITERATIONS = 100;
@Override
public void setUp() throws Exception {
super.setUp();
queries.addAll(readQueries("testqueries.txt"));
queries.addAll(readQueries("testqueries2.txt"));
random = newRandom();
}
/**
* read a set of queries from a resource file
*/
private Set<String> readQueries(String resource) throws IOException {
Set<String> queries = new HashSet<String>();
InputStream stream = getClass().getResourceAsStream(resource);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0 && !line.startsWith("#") && !line.startsWith("//")) {
queries.add(line);
}
}
return queries;
}
/**
* runs random tests, up to ITERATIONS times.
*/
public void testRandomQueries() throws Exception {
for (int i = 0; i < ITERATIONS; i++)
assertAgainstRAMDirectory();
}
/**
* Build a randomish document for both RAMDirectory and MemoryIndex,
* and run all the queries against it.
*/
public void assertAgainstRAMDirectory() throws Exception {
StringBuilder fooField = new StringBuilder();
StringBuilder termField = new StringBuilder();
// add up to 250 terms to field "foo"
for (int i = 0; i < random.nextInt(250); i++) {
fooField.append(" ");
fooField.append(randomTerm());
}
// add up to 250 terms to field "term"
for (int i = 0; i < random.nextInt(250); i++) {
termField.append(" ");
termField.append(randomTerm());
}
RAMDirectory ramdir = new RAMDirectory();
Analyzer analyzer = randomAnalyzer();
IndexWriter writer = new IndexWriter(ramdir, analyzer,
IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document();
Field field1 = new Field("foo", fooField.toString(), Field.Store.NO, Field.Index.ANALYZED);
Field field2 = new Field("term", termField.toString(), Field.Store.NO, Field.Index.ANALYZED);
doc.add(field1);
doc.add(field2);
writer.addDocument(doc);
writer.close();
MemoryIndex memory = new MemoryIndex();
memory.addField("foo", fooField.toString(), analyzer);
memory.addField("term", termField.toString(), analyzer);
assertAllQueries(memory, ramdir, analyzer);
}
/**
* Run all queries against both the RAMDirectory and MemoryIndex, ensuring they are the same.
*/
public void assertAllQueries(MemoryIndex memory, RAMDirectory ramdir, Analyzer analyzer) throws Exception {
IndexSearcher ram = new IndexSearcher(ramdir);
IndexSearcher mem = memory.createSearcher();
QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer);
for (String query : queries) {
TopDocs ramDocs = ram.search(qp.parse(query), 1);
TopDocs memDocs = mem.search(qp.parse(query), 1);
assertEquals(ramDocs.totalHits, memDocs.totalHits);
}
}
/**
* Return a random analyzer (Simple, Stop, Standard) to analyze the terms.
*/
private Analyzer randomAnalyzer() {
switch(random.nextInt(3)) {
case 0: return new SimpleAnalyzer(TEST_VERSION_CURRENT);
case 1: return new StopAnalyzer(TEST_VERSION_CURRENT);
default: return new StandardAnalyzer(TEST_VERSION_CURRENT);
}
}
/**
* Some terms to be indexed, in addition to random words.
* These terms are commonly used in the queries.
*/
private static final String[] TEST_TERMS = {"term", "Term", "tErm", "TERM",
"telm", "stop", "drop", "roll", "phrase", "a", "c", "bar", "blar",
"gack", "weltbank", "worlbank", "hello", "on", "the", "apache", "Apache",
"copyright", "Copyright"};
/**
* half of the time, returns a random term from TEST_TERMS.
* the other half of the time, returns a random unicode string.
*/
private String randomTerm() {
if (random.nextBoolean()) {
// return a random TEST_TERM
return TEST_TERMS[random.nextInt(TEST_TERMS.length)];
} else {
// return a random unicode term
return _TestUtil.randomUnicodeString(random);
}
}
}
| support cranking up the memory index test randomness
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@942719 13f79535-47bb-0310-9956-ffa450edef68
| lucene/contrib/memory/src/test/org/apache/lucene/index/memory/MemoryIndexTest.java | support cranking up the memory index test randomness | <ide><path>ucene/contrib/memory/src/test/org/apache/lucene/index/memory/MemoryIndexTest.java
<ide> private Set<String> queries = new HashSet<String>();
<ide> private Random random;
<ide>
<del> public static final int ITERATIONS = 100;
<add> public static final int ITERATIONS = 100*_TestUtil.getRandomMultiplier();
<ide>
<ide> @Override
<ide> public void setUp() throws Exception {
<ide> StringBuilder termField = new StringBuilder();
<ide>
<ide> // add up to 250 terms to field "foo"
<del> for (int i = 0; i < random.nextInt(250); i++) {
<add> final int numFooTerms = random.nextInt(250*_TestUtil.getRandomMultiplier());
<add> for (int i = 0; i < numFooTerms; i++) {
<ide> fooField.append(" ");
<ide> fooField.append(randomTerm());
<ide> }
<ide>
<ide> // add up to 250 terms to field "term"
<del> for (int i = 0; i < random.nextInt(250); i++) {
<add> final int numTermTerms = random.nextInt(250*_TestUtil.getRandomMultiplier());
<add> for (int i = 0; i < numTermTerms; i++) {
<ide> termField.append(" ");
<ide> termField.append(randomTerm());
<ide> } |
|
JavaScript | mit | 6b768ae3a21664d18b9533fa88d602b793b23371 | 0 | kfbow/CouponApp,kfbow/CouponApp,kfbow/CouponApp | /** @flow */
'use strict';
import React from 'react';
import {
Alert,
Clipboard,
View,
Text,
Image,
Linking,
ScrollView,
StatusBar,
TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
import { stringDiscounted, stringOriginal } from './RandomStrings';
export const dimensions = Dimensions.get('window');
const styles = {
categoryContainer: {
borderRadius: 20,
borderWidth: 1,
borderStyle: 'solid',
borderColor: '#CEEAE7',
backgroundColor: '#CEEAE7',
paddingTop: 4,
paddingBottom: 4,
paddingLeft: 8,
paddingRight: 8,
},
container: {
padding: 10,
},
description: {
marginTop: 15,
},
expire: {
alignSelf: 'center',
color: '#ccc'
},
image: {
width: dimensions.width * (9/10),
height: dimensions.width * (9/10),
resizeMode: 'contain',
alignSelf: 'center'
},
name: {
fontSize: 30,
marginTop: 20,
},
greyOut: {
color: '#ccc',
},
priceAmazon: {
flexDirection: 'row',
marginTop: 20,
justifyContent: 'space-around'
},
promoContainer: {
position: 'absolute',
backgroundColor: '#fff',
bottom: 0,
paddingBottom: 10,
paddingTop: 10
},
promoPrice: {
fontSize: 20,
},
promoReveal: {
padding: dimensions.height * (.2/10),
textAlign: 'center',
backgroundColor: '#159588',
color: '#fff',
width: dimensions.width * .9,
marginRight: dimensions.width * .05,
marginLeft: dimensions.width * .05,
},
seeAmazon: {
padding: 15,
backgroundColor: '#558EFC',
color: '#fff'
},
separator: {
height: 1,
backgroundColor: '#d3d3d3',
marginTop: 5,
}
}
/*
// Open an alert giving the user the option to go to Amazon or Cancel while
// setting the promo code to their clipboard
*/
const onButtonPress = (data) => {
Alert.alert(
`Copied code ${data.promoCode}`,
'Promo code copied to your clipboard',
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
{text: 'Go To Amazon',
onPress: () => openAmazon(data)
},
]
);
Clipboard.setString(data.promoCode);
}
// Open the Amazon app or webpage in Safari if app is not installed
const openAmazon = (data) => {
return Linking
.openURL(data.externalUrl)
.catch(err => {
console.log('An error occurred', err);
})
}
const onClose = (setStateObject, data) => {
setStateObject('showModal', false, data);
}
const Detail = (props) => {
const { showModal, setStateObject, data } = props;
return (
<View style={{ flex: 1 }}>
<StatusBar
hidden={ true } />
<ScrollView
style={ styles.container }
contentInset={{ bottom: dimensions.height * .1 }}>
<Text
style={{ padding: 20 }}
onPress={ () => onClose(setStateObject, data) }>
Close
</Text>
<Image
source={{uri: `https:${data.imageUrl}`}}
style={ styles.image }/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={ styles.categoryContainer }>
<Text style={ styles.category }>
{ data.categoryName }
</Text>
</View>
<Text style={ styles.expire }>
{ data.expiresAt }
</Text>
</View>
<View style={ styles.separator } />
<View>
<Text style={ styles.name }>
{ data.name }
</Text>
<Text style={ styles.description }>
{ data.description }
</Text>
<View style={ styles.priceAmazon }>
<View>
<Text style={ styles.greyOut }>
{`${stringOriginal()} `}
<Text style={{textDecorationLine: 'line-through'}}>
${ data.price }
</Text>
</Text>
<Text style={ styles.promoPrice }>
{stringDiscounted()} ${data.promoPrice}
</Text>
</View>
<Text
style={ styles.seeAmazon }
onPress={ () => openAmazon(data) }>
See on Amazon
</Text>
</View>
</View>
</ScrollView>
<View style={ styles.promoContainer }>
<TouchableOpacity
onPress={ () => onButtonPress(data) }>
<Text style={ styles.promoReveal }>
Reveal Promo Code
</Text>
</TouchableOpacity>
</View>
</View>
)
}
export default Detail;
| src/Detail.js | /** @flow */
'use strict';
import React from 'react';
import {
Alert,
Clipboard,
View,
Text,
Image,
Linking,
ScrollView,
StatusBar,
TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
import { stringDiscounted, stringOriginal } from './RandomStrings';
export const dimensions = Dimensions.get('window');
const styles = {
categoryContainer: {
borderRadius: 20,
borderWidth: 1,
borderStyle: 'solid',
borderColor: '#CEEAE7',
backgroundColor: '#CEEAE7',
paddingTop: 4,
paddingBottom: 4,
paddingLeft: 8,
paddingRight: 8,
},
container: {
padding: 10,
},
description: {
marginTop: 15,
},
expire: {
alignSelf: 'center',
color: '#ccc'
},
image: {
width: dimensions.width * (9/10),
height: dimensions.width * (9/10),
resizeMode: 'contain',
alignSelf: 'center'
},
name: {
fontSize: 30,
marginTop: 20,
},
greyOut: {
color: '#ccc',
},
priceAmazon: {
flexDirection: 'row',
marginTop: 20,
justifyContent: 'space-around'
},
promoContainer: {
position: 'absolute',
backgroundColor: '#fff',
bottom: 0,
paddingBottom: 10,
paddingTop: 10
},
promoPrice: {
fontSize: 20,
},
promoReveal: {
padding: dimensions.height * (.2/10),
textAlign: 'center',
backgroundColor: '#159588',
color: '#fff',
width: dimensions.width * .9,
marginRight: dimensions.width * .05,
marginLeft: dimensions.width * .05,
},
seeAmazon: {
padding: 15,
backgroundColor: '#558EFC',
color: '#fff'
},
separator: {
height: 1,
backgroundColor: '#d3d3d3',
marginTop: 5,
}
}
/*
// Open an alert giving the user the option to go to Amazon or Cancel while
// setting the promo code to their clipboard
*/
const onButtonPress = (data) => {
Alert.alert(
`Copied code ${data.promoCode}`,
'Promo code copied to your clipboard',
[
{text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
{text: 'Go To Amazon',
onPress: () => openAmazon(data)
},
]
);
Clipboard.setString(data.promoCode);
}
// Open the Amazon app or webpage in Safari if app is not installed
const openAmazon = (data) => {
return Linking
.openURL(data.externalUrl)
.catch(err => {
console.log('An error occurred', err);
})
}
const onClose = (setStateObject, data) => {
setStateObject('showModal', false, data);
}
const Detail = (props) => {
const { showModal, setStateObject, data } = props;
return (
<View style={{ flex: 1 }}>
<StatusBar
hidden={ true } />
<ScrollView
style={ styles.container }
contentInset={{ bottom: dimensions.height * .1 }}>
<Text
style={{ padding: 20 }}
onPress={ () => onClose(setStateObject, data) }>
Close
</Text>
<Image
source={{uri: `https:${data.imageUrl}`}}
style={ styles.image }/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={ styles.categoryContainer }>
<Text style={ styles.category }>
{ data.categoryName }
</Text>
</View>
<Text style={ styles.expire }>
{ data.expiresAt }
</Text>
</View>
<View style={ styles.separator } />
<View>
<Text style={ styles.name }>
{ data.name }
</Text>
<Text style={ styles.description }>
{ data.description }
</Text>
<View style={ styles.priceAmazon }>
<View>
<Text style={ styles.greyOut }>
{`${stringOriginal()} `}
<Text style={{textDecorationLine: 'line-through'}}>
${ data.price }
</Text>
</Text>
<Text style={ styles.promoPrice }>
{stringDiscounted()} ${data.promoPrice}
</Text>
</View>
<Text
style={ styles.seeAmazon }
onPress={ () => openAmazon(data) }>
See on Amazon
</Text>
</View>
</View>
</ScrollView>
<TouchableOpacity
onPress={ () => onButtonPress(data) }>
<View style={ styles.promoContainer }>
<Text style={ styles.promoReveal }>
Reveal Promo Code
</Text>
</View>
</TouchableOpacity>
</View>
)
}
export default Detail;
| Fix button bug
| src/Detail.js | Fix button bug | <ide><path>rc/Detail.js
<ide> </View>
<ide> </ScrollView>
<ide>
<del> <TouchableOpacity
<del> onPress={ () => onButtonPress(data) }>
<del> <View style={ styles.promoContainer }>
<add> <View style={ styles.promoContainer }>
<add> <TouchableOpacity
<add> onPress={ () => onButtonPress(data) }>
<ide> <Text style={ styles.promoReveal }>
<ide> Reveal Promo Code
<ide> </Text>
<del> </View>
<del> </TouchableOpacity>
<add> </TouchableOpacity>
<add> </View>
<ide>
<ide> </View>
<ide> ) |
|
Java | apache-2.0 | 99358c62075b6fdd833466e3985edc10e2d0232e | 0 | kelemen/JTrim,kelemen/JTrim | package org.jtrim.concurrent;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.jtrim.cancel.*;
import org.jtrim.event.*;
import org.jtrim.utils.ExceptionHelper;
import org.junit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
*
* @author Kelemen Attila
*/
public class AbstractTaskExecutorServiceTest {
public AbstractTaskExecutorServiceTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testExecuteNoCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
executor.execute(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
executeCount.incrementAndGet();
}
}, null);
executor.executeSubmittedTasks();
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
}
@Test
public void testExecuteWithCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final AtomicInteger cleanupCount = new AtomicInteger(0);
executor.execute(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
assertEquals("Task was executed after cleanup", 0, cleanupCount.intValue());
executeCount.incrementAndGet();
}
},
new CleanupTask() {
@Override
public void cleanup(boolean canceled, Throwable error) throws Exception {
assertFalse(canceled);
assertNull(error);
assertEquals("Cleanup was executed before task", 1, executeCount.intValue());
cleanupCount.incrementAndGet();
}
});
executor.executeSubmittedTasks();
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
assertEquals("Unexpected number of cleanup", 1, cleanupCount.intValue());
}
@Test
public void testSubmitNoCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
executeCount.incrementAndGet();
}
}, null);
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertNull(future.tryGetResult());
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitWithCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final AtomicInteger cleanupCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
assertEquals("Task was executed after cleanup", 0, cleanupCount.intValue());
executeCount.incrementAndGet();
}
},
new CleanupTask() {
@Override
public void cleanup(boolean canceled, Throwable error) throws Exception {
assertFalse(canceled);
assertNull(error);
assertEquals("Cleanup was executed before task", 1, executeCount.intValue());
cleanupCount.incrementAndGet();
}
});
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertNull(future.tryGetResult());
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
assertEquals("Unexpected number of cleanup", 1, cleanupCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitFunctionNoCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final Object taskResult = "TASK-RESULT";
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableFunction<Object>() {
@Override
public Object execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
executeCount.incrementAndGet();
return taskResult;
}
}, null);
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertSame(taskResult, future.tryGetResult());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitFunctionWithCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final AtomicInteger cleanupCount = new AtomicInteger(0);
final Object taskResult = "TASK-RESULT";
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableFunction<Object>() {
@Override
public Object execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
assertEquals("Task was executed after cleanup", 0, cleanupCount.intValue());
executeCount.incrementAndGet();
return taskResult;
}
},
new CleanupTask() {
@Override
public void cleanup(boolean canceled, Throwable error) throws Exception {
assertFalse(canceled);
assertNull(error);
assertEquals("Cleanup was executed before task", 1, executeCount.intValue());
cleanupCount.incrementAndGet();
}
});
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertSame(taskResult, future.tryGetResult());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
assertEquals("Unexpected number of cleanup", 1, cleanupCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testCanceledSubmit() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.CANCELED_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
executeCount.incrementAndGet();
}
}, null);
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Unexpected number of execution", 0, executeCount.intValue());
}
@Test(expected = OperationCanceledException.class)
public void testCanceledSubmitFuture() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.CANCELED_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
executeCount.incrementAndGet();
}
}, null);
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
future.tryGetResult();
}
@Test
public void testPostSubmitCanceledSubmit() {
ManualExecutor executor = new ManualExecutor();
CancellationSource cancelSource = Cancellation.createCancellationSource();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(cancelSource.getToken(),
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
executeCount.incrementAndGet();
}
}, null);
cancelSource.getController().cancel();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Unexpected number of execution", 0, executeCount.intValue());
}
@Test(expected = TaskExecutionException.class)
public void testSubmitError() {
ManualExecutor executor = new ManualExecutor();
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
throw new UnsupportedOperationException();
}
}, null);
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_ERROR, future.getTaskState());
try {
future.tryGetResult();
} catch (TaskExecutionException ex) {
assertEquals(UnsupportedOperationException.class, ex.getCause().getClass());
throw ex;
}
}
@Test
public void testUnregisterListener() {
ManualExecutor executor = new ManualExecutor();
RegCounterCancelToken cancelToken = new RegCounterCancelToken();
TaskFuture<?> future = executor.submit(cancelToken,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
}
}, null);
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertEquals("Remaining registered listener.",
0, cancelToken.getRegistrationCount());
}
@Test
public void testUnregisterListenerPreCancel() {
ManualExecutor executor = new ManualExecutor();
RegCounterCancelToken cancelToken = new RegCounterCancelToken(
Cancellation.CANCELED_TOKEN);
TaskFuture<?> future = executor.submit(cancelToken,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
}
}, null);
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Remaining registered listener.",
0, cancelToken.getRegistrationCount());
}
@Test
public void testUnregisterListenerPostCancel() {
ManualExecutor executor = new ManualExecutor();
CancellationSource cancelSource = Cancellation.createCancellationSource();
RegCounterCancelToken cancelToken = new RegCounterCancelToken(
cancelSource.getToken());
TaskFuture<?> future = executor.submit(cancelToken,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
}
}, null);
cancelSource.getController().cancel();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Remaining registered listener.",
0, cancelToken.getRegistrationCount());
}
@Test
public void testAwaitTerminate() {
ManualExecutor executor = new ManualExecutor();
executor.shutdown();
executor.awaitTermination(Cancellation.CANCELED_TOKEN);
executor.awaitTermination(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitAfterShutdownWithCleanup() throws Exception {
CancelableTask task = mock(CancelableTask.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
executor.shutdown();
executor.execute(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
executor.executeSubmittedTasks();
verifyZeroInteractions(task);
verify(cleanupTask).cleanup(anyBoolean(), any(Throwable.class));
verifyNoMoreInteractions(cleanupTask);
}
@Test
public void testSubmitAfterShutdownWithCleanupGetState() throws Exception {
CancelableTask task = mock(CancelableTask.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
executor.shutdown();
TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
assertEquals(TaskState.DONE_CANCELED, taskState.getTaskState());
executor.executeSubmittedTasks();
verifyZeroInteractions(task);
verify(cleanupTask).cleanup(anyBoolean(), any(Throwable.class));
verifyNoMoreInteractions(cleanupTask);
}
@Test(timeout = 5000)
public void testTryGetResultOfNotExecutedTask() throws Exception {
CancelableFunction<?> task = mock(CancelableFunction.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
Object expectedResult = "RESULT-OF-CancelableFunction";
stub(task.execute(any(CancellationToken.class))).toReturn(expectedResult);
ManualExecutor executor = new ManualExecutor();
TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
assertNull(taskState.tryGetResult());
}
// testSimpleGetResult is added only to ensure, that waitAndGet does not
// throw an OperationCanceledException when the submitted task has not been
// canceled. This is needed because the subsequent tests check if waitAndGet
// throws OperationCanceledException when the task is canceled.
@Test(timeout = 5000)
public void testSimpleGetResult() throws Exception {
CancelableFunction<?> task = mock(CancelableFunction.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
Object expectedResult = "RESULT-OF-CancelableFunction";
stub(task.execute(any(CancellationToken.class))).toReturn(expectedResult);
ManualExecutor executor = new ManualExecutor();
TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
executor.executeSubmittedTasks();
Object result1 = taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
assertEquals(expectedResult, result1);
Object result2 = taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN, Long.MAX_VALUE, TimeUnit.DAYS);
assertEquals(expectedResult, result2);
}
@Test(expected = OperationCanceledException.class, timeout = 5000)
public void testTimeoutWaitResult() throws Exception {
CancelableFunction<?> task = mock(CancelableFunction.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN, 1, TimeUnit.NANOSECONDS);
}
@Test(expected = OperationCanceledException.class)
public void testResultOfCanceledTask() throws Exception {
CancelableFunction<?> task = mock(CancelableFunction.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
CancellationSource cancelSource = Cancellation.createCancellationSource();
TaskFuture<?> taskState = executor.submit(cancelSource.getToken(), task, cleanupTask);
cancelSource.getController().cancel();
executor.executeSubmittedTasks();
taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test(expected = OperationCanceledException.class)
public void testResultOfCanceledTaskWithTimeout() throws Exception {
CancelableFunction<?> task = mock(CancelableFunction.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
CancellationSource cancelSource = Cancellation.createCancellationSource();
TaskFuture<?> taskState = executor.submit(cancelSource.getToken(), task, cleanupTask);
cancelSource.getController().cancel();
executor.executeSubmittedTasks();
taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN, Long.MAX_VALUE, TimeUnit.DAYS);
}
@Test
public void testExecuteCanceledTask() throws Exception {
CancelableTask task = mock(CancelableTask.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
doThrow(OperationCanceledException.class)
.when(task).execute(any(CancellationToken.class));
ManualExecutor executor = new ManualExecutor();
TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
assertEquals(TaskState.NOT_STARTED, taskState.getTaskState());
executor.executeSubmittedTasks();
assertEquals(TaskState.DONE_CANCELED, taskState.getTaskState());
verify(task).execute(any(CancellationToken.class));
verify(cleanupTask).cleanup(anyBoolean(), any(Throwable.class));
verifyNoMoreInteractions(task, cleanupTask);
}
@Test
public void testExecuteAfterFailedCleanup() throws Exception {
CancelableTask task1 = mock(CancelableTask.class);
CleanupTask cleanupTask1 = mock(CleanupTask.class);
doThrow(RuntimeException.class)
.when(cleanupTask1)
.cleanup(anyBoolean(), any(Throwable.class));
CancelableTask task2 = mock(CancelableTask.class);
CleanupTask cleanupTask2 = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
executor.execute(Cancellation.UNCANCELABLE_TOKEN, task1, cleanupTask1);
executor.execute(Cancellation.UNCANCELABLE_TOKEN, task2, cleanupTask2);
executor.executeSubmittedTasks();
verify(task1).execute(any(CancellationToken.class));
verify(cleanupTask1).cleanup(anyBoolean(), any(Throwable.class));
verifyNoMoreInteractions(task1, cleanupTask1);
verify(task2).execute(any(CancellationToken.class));
verify(cleanupTask2).cleanup(anyBoolean(), any(Throwable.class));
verifyNoMoreInteractions(task2, cleanupTask2);
}
@Test(expected = IllegalStateException.class)
public void testMisuseMultipleExecute() throws Exception {
CancelableTask task = mock(CancelableTask.class);
CleanupTask cleanupTask = mock(CleanupTask.class);
ManualExecutor executor = new ManualExecutor();
executor.execute(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
executor.executeSubmittedTasksWithoutRemoving();
executor.executeSubmittedTasksWithoutRemoving();
}
private static class RegCounterCancelToken implements CancellationToken {
private final AtomicLong regCounter;
private final CancellationToken wrappedToken;
public RegCounterCancelToken() {
this(Cancellation.UNCANCELABLE_TOKEN);
}
public RegCounterCancelToken(CancellationToken wrappedToken) {
this.regCounter = new AtomicLong(0);
this.wrappedToken = wrappedToken;
}
@Override
public ListenerRef addCancellationListener(Runnable listener) {
final ListenerRef result
= wrappedToken.addCancellationListener(listener);
regCounter.incrementAndGet();
return new ListenerRef() {
private final AtomicBoolean registered
= new AtomicBoolean(true);
@Override
public boolean isRegistered() {
return result.isRegistered();
}
@Override
public void unregister() {
if (registered.getAndSet(false)) {
result.unregister();
regCounter.decrementAndGet();
}
}
};
}
@Override
public boolean isCanceled() {
return wrappedToken.isCanceled();
}
@Override
public void checkCanceled() {
wrappedToken.checkCanceled();
}
public long getRegistrationCount() {
return regCounter.get();
}
}
private static class SubmittedTask {
public final CancellationToken cancelToken;
public final CancellationController cancelController;
public final CancelableTask task;
public final Runnable cleanupTask;
public final boolean hasUserDefinedCleanup;
public SubmittedTask(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask,
boolean hasUserDefinedCleanup) {
this.cancelToken = cancelToken;
this.cancelController = cancelController;
this.task = task;
this.cleanupTask = cleanupTask;
this.hasUserDefinedCleanup = hasUserDefinedCleanup;
}
}
private class ManualExecutor extends AbstractTaskExecutorService {
private ListenerManager<Runnable, Void> listeners = new CopyOnTriggerListenerManager<>();
private boolean shuttedDown = false;
private final List<SubmittedTask> submittedTasks = new LinkedList<>();
public void executeSubmittedTasksWithoutRemoving() {
try {
for (SubmittedTask task: submittedTasks) {
task.task.execute(task.cancelToken);
task.cleanupTask.run();
}
} catch (Exception ex) {
ExceptionHelper.rethrow(ex);
}
}
public void executeSubmittedTasks() {
try {
executeSubmittedTasksMayFail();
} catch (Exception ex) {
ExceptionHelper.rethrow(ex);
}
}
private void executeSubmittedTasksMayFail() throws Exception {
if (shuttedDown) {
while (!submittedTasks.isEmpty()) {
SubmittedTask task = submittedTasks.remove(0);
task.cleanupTask.run();
}
}
else {
while (!submittedTasks.isEmpty()) {
SubmittedTask task = submittedTasks.remove(0);
task.task.execute(task.cancelToken);
task.cleanupTask.run();
}
}
}
@Override
protected void submitTask(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask,
boolean hasUserDefinedCleanup) {
ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken");
ExceptionHelper.checkNotNullArgument(cancelController, "cancelController");
ExceptionHelper.checkNotNullArgument(task, "task");
ExceptionHelper.checkNotNullArgument(cleanupTask, "cleanupTask");
submittedTasks.add(new SubmittedTask(cancelToken, cancelController,
task, cleanupTask, hasUserDefinedCleanup));
}
@Override
public void shutdown() {
shuttedDown = true;
ListenerManager<Runnable, Void> currentListeners = listeners;
if (currentListeners != null) {
listeners = null;
currentListeners.onEvent(new EventDispatcher<Runnable, Void>() {
@Override
public void onEvent(Runnable eventListener, Void arg) {
eventListener.run();
}
}, null);
}
}
@Override
public void shutdownAndCancel() {
shutdown();
}
@Override
public boolean isShutdown() {
return shuttedDown;
}
@Override
public boolean isTerminated() {
return shuttedDown;
}
@Override
public ListenerRef addTerminateListener(Runnable listener) {
if (listeners == null) {
listener.run();
return UnregisteredListenerRef.INSTANCE;
}
else {
return listeners.registerListener(listener);
}
}
@Override
public boolean awaitTermination(CancellationToken cancelToken, long timeout, TimeUnit unit) {
return shuttedDown;
}
}
}
| jtrim-core/src/test/java/org/jtrim/concurrent/AbstractTaskExecutorServiceTest.java | package org.jtrim.concurrent;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.jtrim.cancel.*;
import org.jtrim.event.*;
import org.jtrim.utils.ExceptionHelper;
import org.junit.*;
import static org.junit.Assert.*;
/**
*
* @author Kelemen Attila
*/
public class AbstractTaskExecutorServiceTest {
public AbstractTaskExecutorServiceTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testExecuteNoCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
executor.execute(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
executeCount.incrementAndGet();
}
}, null);
executor.executeSubmittedTasks();
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
}
@Test
public void testExecuteWithCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final AtomicInteger cleanupCount = new AtomicInteger(0);
executor.execute(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
assertEquals("Task was executed after cleanup", 0, cleanupCount.intValue());
executeCount.incrementAndGet();
}
},
new CleanupTask() {
@Override
public void cleanup(boolean canceled, Throwable error) throws Exception {
assertFalse(canceled);
assertNull(error);
assertEquals("Cleanup was executed before task", 1, executeCount.intValue());
cleanupCount.incrementAndGet();
}
});
executor.executeSubmittedTasks();
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
assertEquals("Unexpected number of cleanup", 1, cleanupCount.intValue());
}
@Test
public void testSubmitNoCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
executeCount.incrementAndGet();
}
}, null);
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertNull(future.tryGetResult());
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitWithCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final AtomicInteger cleanupCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
assertEquals("Task was executed after cleanup", 0, cleanupCount.intValue());
executeCount.incrementAndGet();
}
},
new CleanupTask() {
@Override
public void cleanup(boolean canceled, Throwable error) throws Exception {
assertFalse(canceled);
assertNull(error);
assertEquals("Cleanup was executed before task", 1, executeCount.intValue());
cleanupCount.incrementAndGet();
}
});
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertNull(future.tryGetResult());
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
assertEquals("Unexpected number of cleanup", 1, cleanupCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitFunctionNoCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final Object taskResult = "TASK-RESULT";
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableFunction<Object>() {
@Override
public Object execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
executeCount.incrementAndGet();
return taskResult;
}
}, null);
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertSame(taskResult, future.tryGetResult());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testSubmitFunctionWithCleanup() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
final AtomicInteger cleanupCount = new AtomicInteger(0);
final Object taskResult = "TASK-RESULT";
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableFunction<Object>() {
@Override
public Object execute(CancellationToken cancelToken) {
assertFalse(cancelToken.isCanceled());
assertEquals("Task was executed after cleanup", 0, cleanupCount.intValue());
executeCount.incrementAndGet();
return taskResult;
}
},
new CleanupTask() {
@Override
public void cleanup(boolean canceled, Throwable error) throws Exception {
assertFalse(canceled);
assertNull(error);
assertEquals("Cleanup was executed before task", 1, executeCount.intValue());
cleanupCount.incrementAndGet();
}
});
assertNull(future.tryGetResult());
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertSame(taskResult, future.tryGetResult());
assertEquals("Unexpected number of execution", 1, executeCount.intValue());
assertEquals("Unexpected number of cleanup", 1, cleanupCount.intValue());
future.waitAndGet(Cancellation.CANCELED_TOKEN);
future.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
}
@Test
public void testCanceledSubmit() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.CANCELED_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
executeCount.incrementAndGet();
}
}, null);
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Unexpected number of execution", 0, executeCount.intValue());
}
@Test(expected = OperationCanceledException.class)
public void testCanceledSubmitFuture() {
ManualExecutor executor = new ManualExecutor();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(Cancellation.CANCELED_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
executeCount.incrementAndGet();
}
}, null);
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
future.tryGetResult();
}
@Test
public void testPostSubmitCanceledSubmit() {
ManualExecutor executor = new ManualExecutor();
CancellationSource cancelSource = Cancellation.createCancellationSource();
final AtomicInteger executeCount = new AtomicInteger(0);
TaskFuture<?> future = executor.submit(cancelSource.getToken(),
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
executeCount.incrementAndGet();
}
}, null);
cancelSource.getController().cancel();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Unexpected number of execution", 0, executeCount.intValue());
}
@Test(expected = TaskExecutionException.class)
public void testSubmitError() {
ManualExecutor executor = new ManualExecutor();
TaskFuture<?> future = executor.submit(Cancellation.UNCANCELABLE_TOKEN,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
throw new UnsupportedOperationException();
}
}, null);
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_ERROR, future.getTaskState());
try {
future.tryGetResult();
} catch (TaskExecutionException ex) {
assertEquals(UnsupportedOperationException.class, ex.getCause().getClass());
throw ex;
}
}
@Test
public void testUnregisterListener() {
ManualExecutor executor = new ManualExecutor();
RegCounterCancelToken cancelToken = new RegCounterCancelToken();
TaskFuture<?> future = executor.submit(cancelToken,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
}
}, null);
assertSame(TaskState.NOT_STARTED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_COMPLETED, future.getTaskState());
assertEquals("Remaining registered listener.",
0, cancelToken.getRegistrationCount());
}
@Test
public void testUnregisterListenerPreCancel() {
ManualExecutor executor = new ManualExecutor();
RegCounterCancelToken cancelToken = new RegCounterCancelToken(
Cancellation.CANCELED_TOKEN);
TaskFuture<?> future = executor.submit(cancelToken,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
}
}, null);
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Remaining registered listener.",
0, cancelToken.getRegistrationCount());
}
@Test
public void testUnregisterListenerPostCancel() {
ManualExecutor executor = new ManualExecutor();
CancellationSource cancelSource = Cancellation.createCancellationSource();
RegCounterCancelToken cancelToken = new RegCounterCancelToken(
cancelSource.getToken());
TaskFuture<?> future = executor.submit(cancelToken,
new CancelableTask() {
@Override
public void execute(CancellationToken cancelToken) {
}
}, null);
cancelSource.getController().cancel();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
executor.executeSubmittedTasks();
assertSame(TaskState.DONE_CANCELED, future.getTaskState());
assertEquals("Remaining registered listener.",
0, cancelToken.getRegistrationCount());
}
@Test
public void testAwaitTerminate() {
ManualExecutor executor = new ManualExecutor();
executor.shutdown();
executor.awaitTermination(Cancellation.CANCELED_TOKEN);
executor.awaitTermination(Cancellation.UNCANCELABLE_TOKEN);
}
private static class RegCounterCancelToken implements CancellationToken {
private final AtomicLong regCounter;
private final CancellationToken wrappedToken;
public RegCounterCancelToken() {
this(Cancellation.UNCANCELABLE_TOKEN);
}
public RegCounterCancelToken(CancellationToken wrappedToken) {
this.regCounter = new AtomicLong(0);
this.wrappedToken = wrappedToken;
}
@Override
public ListenerRef addCancellationListener(Runnable listener) {
final ListenerRef result
= wrappedToken.addCancellationListener(listener);
regCounter.incrementAndGet();
return new ListenerRef() {
private final AtomicBoolean registered
= new AtomicBoolean(true);
@Override
public boolean isRegistered() {
return result.isRegistered();
}
@Override
public void unregister() {
if (registered.getAndSet(false)) {
result.unregister();
regCounter.decrementAndGet();
}
}
};
}
@Override
public boolean isCanceled() {
return wrappedToken.isCanceled();
}
@Override
public void checkCanceled() {
wrappedToken.checkCanceled();
}
public long getRegistrationCount() {
return regCounter.get();
}
}
private static class SubmittedTask {
public final CancellationToken cancelToken;
public final CancellationController cancelController;
public final CancelableTask task;
public final Runnable cleanupTask;
public final boolean hasUserDefinedCleanup;
public SubmittedTask(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask,
boolean hasUserDefinedCleanup) {
this.cancelToken = cancelToken;
this.cancelController = cancelController;
this.task = task;
this.cleanupTask = cleanupTask;
this.hasUserDefinedCleanup = hasUserDefinedCleanup;
}
}
private class ManualExecutor extends AbstractTaskExecutorService {
private ListenerManager<Runnable, Void> listeners = new CopyOnTriggerListenerManager<>();
private boolean shuttedDown = false;
private final List<SubmittedTask> submittedTasks = new LinkedList<>();
public void executeSubmittedTasks() {
try {
executeSubmittedTasksMayFail();
} catch (Exception ex) {
ExceptionHelper.rethrow(ex);
}
}
private void executeSubmittedTasksMayFail() throws Exception {
if (shuttedDown) {
while (!submittedTasks.isEmpty()) {
SubmittedTask task = submittedTasks.remove(0);
task.cleanupTask.run();
}
}
else {
while (!submittedTasks.isEmpty()) {
SubmittedTask task = submittedTasks.remove(0);
task.task.execute(task.cancelToken);
task.cleanupTask.run();
}
}
}
@Override
protected void submitTask(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask,
boolean hasUserDefinedCleanup) {
ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken");
ExceptionHelper.checkNotNullArgument(cancelController, "cancelController");
ExceptionHelper.checkNotNullArgument(task, "task");
ExceptionHelper.checkNotNullArgument(cleanupTask, "cleanupTask");
submittedTasks.add(new SubmittedTask(cancelToken, cancelController,
task, cleanupTask, hasUserDefinedCleanup));
}
@Override
public void shutdown() {
shuttedDown = true;
ListenerManager<Runnable, Void> currentListeners = listeners;
if (currentListeners != null) {
listeners = null;
currentListeners.onEvent(new EventDispatcher<Runnable, Void>() {
@Override
public void onEvent(Runnable eventListener, Void arg) {
eventListener.run();
}
}, null);
}
}
@Override
public void shutdownAndCancel() {
shutdown();
}
@Override
public boolean isShutdown() {
return shuttedDown;
}
@Override
public boolean isTerminated() {
return shuttedDown;
}
@Override
public ListenerRef addTerminateListener(Runnable listener) {
if (listeners == null) {
listener.run();
return UnregisteredListenerRef.INSTANCE;
}
else {
return listeners.registerListener(listener);
}
}
@Override
public boolean awaitTermination(CancellationToken cancelToken, long timeout, TimeUnit unit) {
return shuttedDown;
}
}
}
| Added more tests for AbstractTaskExecutorService | jtrim-core/src/test/java/org/jtrim/concurrent/AbstractTaskExecutorServiceTest.java | Added more tests for AbstractTaskExecutorService | <ide><path>trim-core/src/test/java/org/jtrim/concurrent/AbstractTaskExecutorServiceTest.java
<ide> import org.junit.*;
<ide>
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide> *
<ide> executor.shutdown();
<ide> executor.awaitTermination(Cancellation.CANCELED_TOKEN);
<ide> executor.awaitTermination(Cancellation.UNCANCELABLE_TOKEN);
<add> }
<add>
<add> @Test
<add> public void testSubmitAfterShutdownWithCleanup() throws Exception {
<add> CancelableTask task = mock(CancelableTask.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> executor.shutdown();
<add>
<add> executor.execute(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add> executor.executeSubmittedTasks();
<add>
<add> verifyZeroInteractions(task);
<add> verify(cleanupTask).cleanup(anyBoolean(), any(Throwable.class));
<add> verifyNoMoreInteractions(cleanupTask);
<add> }
<add>
<add> @Test
<add> public void testSubmitAfterShutdownWithCleanupGetState() throws Exception {
<add> CancelableTask task = mock(CancelableTask.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> executor.shutdown();
<add>
<add> TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add> assertEquals(TaskState.DONE_CANCELED, taskState.getTaskState());
<add> executor.executeSubmittedTasks();
<add>
<add> verifyZeroInteractions(task);
<add> verify(cleanupTask).cleanup(anyBoolean(), any(Throwable.class));
<add> verifyNoMoreInteractions(cleanupTask);
<add> }
<add>
<add> @Test(timeout = 5000)
<add> public void testTryGetResultOfNotExecutedTask() throws Exception {
<add> CancelableFunction<?> task = mock(CancelableFunction.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> Object expectedResult = "RESULT-OF-CancelableFunction";
<add> stub(task.execute(any(CancellationToken.class))).toReturn(expectedResult);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add> assertNull(taskState.tryGetResult());
<add> }
<add>
<add> // testSimpleGetResult is added only to ensure, that waitAndGet does not
<add> // throw an OperationCanceledException when the submitted task has not been
<add> // canceled. This is needed because the subsequent tests check if waitAndGet
<add> // throws OperationCanceledException when the task is canceled.
<add>
<add> @Test(timeout = 5000)
<add> public void testSimpleGetResult() throws Exception {
<add> CancelableFunction<?> task = mock(CancelableFunction.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> Object expectedResult = "RESULT-OF-CancelableFunction";
<add> stub(task.execute(any(CancellationToken.class))).toReturn(expectedResult);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add> executor.executeSubmittedTasks();
<add>
<add> Object result1 = taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
<add> assertEquals(expectedResult, result1);
<add>
<add> Object result2 = taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN, Long.MAX_VALUE, TimeUnit.DAYS);
<add> assertEquals(expectedResult, result2);
<add> }
<add>
<add> @Test(expected = OperationCanceledException.class, timeout = 5000)
<add> public void testTimeoutWaitResult() throws Exception {
<add> CancelableFunction<?> task = mock(CancelableFunction.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add> taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN, 1, TimeUnit.NANOSECONDS);
<add> }
<add>
<add> @Test(expected = OperationCanceledException.class)
<add> public void testResultOfCanceledTask() throws Exception {
<add> CancelableFunction<?> task = mock(CancelableFunction.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> CancellationSource cancelSource = Cancellation.createCancellationSource();
<add> TaskFuture<?> taskState = executor.submit(cancelSource.getToken(), task, cleanupTask);
<add> cancelSource.getController().cancel();
<add> executor.executeSubmittedTasks();
<add> taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN);
<add> }
<add>
<add> @Test(expected = OperationCanceledException.class)
<add> public void testResultOfCanceledTaskWithTimeout() throws Exception {
<add> CancelableFunction<?> task = mock(CancelableFunction.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> CancellationSource cancelSource = Cancellation.createCancellationSource();
<add> TaskFuture<?> taskState = executor.submit(cancelSource.getToken(), task, cleanupTask);
<add> cancelSource.getController().cancel();
<add> executor.executeSubmittedTasks();
<add> taskState.waitAndGet(Cancellation.UNCANCELABLE_TOKEN, Long.MAX_VALUE, TimeUnit.DAYS);
<add> }
<add>
<add> @Test
<add> public void testExecuteCanceledTask() throws Exception {
<add> CancelableTask task = mock(CancelableTask.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> doThrow(OperationCanceledException.class)
<add> .when(task).execute(any(CancellationToken.class));
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> TaskFuture<?> taskState = executor.submit(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add> assertEquals(TaskState.NOT_STARTED, taskState.getTaskState());
<add>
<add> executor.executeSubmittedTasks();
<add> assertEquals(TaskState.DONE_CANCELED, taskState.getTaskState());
<add>
<add> verify(task).execute(any(CancellationToken.class));
<add> verify(cleanupTask).cleanup(anyBoolean(), any(Throwable.class));
<add> verifyNoMoreInteractions(task, cleanupTask);
<add> }
<add>
<add> @Test
<add> public void testExecuteAfterFailedCleanup() throws Exception {
<add> CancelableTask task1 = mock(CancelableTask.class);
<add> CleanupTask cleanupTask1 = mock(CleanupTask.class);
<add>
<add> doThrow(RuntimeException.class)
<add> .when(cleanupTask1)
<add> .cleanup(anyBoolean(), any(Throwable.class));
<add>
<add> CancelableTask task2 = mock(CancelableTask.class);
<add> CleanupTask cleanupTask2 = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> executor.execute(Cancellation.UNCANCELABLE_TOKEN, task1, cleanupTask1);
<add> executor.execute(Cancellation.UNCANCELABLE_TOKEN, task2, cleanupTask2);
<add>
<add> executor.executeSubmittedTasks();
<add>
<add> verify(task1).execute(any(CancellationToken.class));
<add> verify(cleanupTask1).cleanup(anyBoolean(), any(Throwable.class));
<add> verifyNoMoreInteractions(task1, cleanupTask1);
<add>
<add> verify(task2).execute(any(CancellationToken.class));
<add> verify(cleanupTask2).cleanup(anyBoolean(), any(Throwable.class));
<add> verifyNoMoreInteractions(task2, cleanupTask2);
<add> }
<add>
<add> @Test(expected = IllegalStateException.class)
<add> public void testMisuseMultipleExecute() throws Exception {
<add> CancelableTask task = mock(CancelableTask.class);
<add> CleanupTask cleanupTask = mock(CleanupTask.class);
<add>
<add> ManualExecutor executor = new ManualExecutor();
<add> executor.execute(Cancellation.UNCANCELABLE_TOKEN, task, cleanupTask);
<add>
<add> executor.executeSubmittedTasksWithoutRemoving();
<add> executor.executeSubmittedTasksWithoutRemoving();
<ide> }
<ide>
<ide> private static class RegCounterCancelToken implements CancellationToken {
<ide> private boolean shuttedDown = false;
<ide>
<ide> private final List<SubmittedTask> submittedTasks = new LinkedList<>();
<add>
<add> public void executeSubmittedTasksWithoutRemoving() {
<add> try {
<add> for (SubmittedTask task: submittedTasks) {
<add> task.task.execute(task.cancelToken);
<add> task.cleanupTask.run();
<add> }
<add> } catch (Exception ex) {
<add> ExceptionHelper.rethrow(ex);
<add> }
<add> }
<ide>
<ide> public void executeSubmittedTasks() {
<ide> try { |
|
Java | apache-2.0 | 9df45dc1240e9b2154c8d7454b7b6e05e53a36a6 | 0 | kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe | /*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.kythe.extractors.java.standalone;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.flogger.FluentLogger;
import com.google.common.hash.Hashing;
import com.google.devtools.kythe.extractors.java.JavaCompilationUnitExtractor;
import com.google.devtools.kythe.extractors.shared.CompilationDescription;
import com.google.devtools.kythe.extractors.shared.FileVNames;
import com.google.devtools.kythe.extractors.shared.IndexInfoUtils;
import com.google.devtools.kythe.proto.Analysis.CompilationUnit;
import com.google.devtools.kythe.proto.Analysis.FileData;
import com.google.devtools.kythe.util.JsonUtil;
import com.sun.tools.javac.main.CommandLine;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* General logic for a javac-based {@link CompilationUnit} extractor.
*
* <p>Environment Variables Used (note that these can also be set as JVM system properties):
*
* <p>KYTHE_VNAMES: optional path to a JSON configuration file for {@link FileVNames} to populate
* the {@link CompilationUnit}'s required input {@link VName}s
*
* <p>KYTHE_CORPUS: if KYTHE_VNAMES is not given, all {@link VName}s will be populated with this
* corpus (default {@link DEFAULT_CORPUS})
*
* <p>KYTHE_ROOT_DIRECTORY: required root path for file inputs; the {@link FileData} paths stored in
* the {@link CompilationUnit} will be made to be relative to this directory
*
* <p>KYTHE_OUTPUT_FILE: if set to a non-empty value, write the resulting .kzip file to this path
* instead of using KYTHE_OUTPUT_DIRECTORY
*
* <p>KYTHE_OUTPUT_DIRECTORY: directory path to store the resulting .kzip file, if KYTHE_OUTPUT_FILE
* is not set
*/
public abstract class AbstractJavacWrapper {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String DEFAULT_CORPUS = "kythe";
protected abstract Collection<CompilationDescription> processCompilation(
String[] arguments, JavaCompilationUnitExtractor javaCompilationUnitExtractor)
throws Exception;
protected abstract void passThrough(String[] args) throws Exception;
/**
* Given the command-line arguments to javac, construct a {@link CompilationUnit} and write it to
* a .kindex file. Parameters to the extraction logic are passed by environment variables (see
* class comment).
*/
public void process(String[] args) {
JsonUtil.usingTypeRegistry(JsonUtil.JSON_TYPE_REGISTRY);
try {
if (!passThroughIfAnalysisOnly(args)) {
String vnamesConfig = System.getenv("KYTHE_VNAMES");
JavaCompilationUnitExtractor extractor;
if (Strings.isNullOrEmpty(vnamesConfig)) {
String corpus = readEnvironmentVariable("KYTHE_CORPUS", DEFAULT_CORPUS);
extractor =
new JavaCompilationUnitExtractor(
corpus, readEnvironmentVariable("KYTHE_ROOT_DIRECTORY"));
} else {
extractor =
new JavaCompilationUnitExtractor(
FileVNames.fromFile(vnamesConfig),
readEnvironmentVariable("KYTHE_ROOT_DIRECTORY"));
}
Collection<CompilationDescription> indexInfos =
processCompilation(getCleanedUpArguments(args), extractor);
outputIndexInfo(indexInfos);
if (indexInfos.stream().anyMatch(cd -> cd.getCompilationUnit().getHasCompileErrors())) {
System.err.println("Errors encountered during compilation");
System.exit(1);
}
}
} catch (IOException e) {
System.err.printf(
"Unexpected IO error (probably while writing to index file): %s%n", e.toString());
System.err.println(Throwables.getStackTraceAsString(e));
System.exit(2);
} catch (Exception e) {
System.err.printf(
"Unexpected error compiling and indexing java compilation: %s%n", e.toString());
System.err.println(Throwables.getStackTraceAsString(e));
System.exit(2);
}
}
private static void outputIndexInfo(Collection<CompilationDescription> indexInfos)
throws IOException {
String outputFile = System.getenv("KYTHE_OUTPUT_FILE");
if (!Strings.isNullOrEmpty(outputFile)) {
if (outputFile.endsWith(IndexInfoUtils.KZIP_FILE_EXT)) {
IndexInfoUtils.writeKzipToFile(indexInfos, outputFile);
} else {
System.err.printf("Unsupported output file: %s%n", outputFile);
System.exit(2);
}
return;
}
String outputDir = readEnvironmentVariable("KYTHE_OUTPUT_DIRECTORY");
// Just rely on the underlying compilation unit's signature to get the filename, if we're not
// writing to a single kzip file.
for (CompilationDescription indexInfo : indexInfos) {
String name =
indexInfo
.getCompilationUnit()
.getVName()
.getSignature()
.trim()
.replaceAll("^/+|/+$", "")
.replace('/', '_');
String path = IndexInfoUtils.getKzipPath(outputDir, name).toString();
IndexInfoUtils.writeKzipToFile(indexInfo, path);
}
}
private static String[] getCleanedUpArguments(String[] args) throws IOException {
// Expand all @file arguments
List<String> expandedArgs = Lists.newArrayList(CommandLine.parse(args));
// We skip some arguments that would normally be passed to javac:
// -J, these are flags to the java environment running javac.
// -XD, these are internal flags used for special debug information
// when compiling javac itself.
// -Werror, we do not want to treat any warnings as errors.
// -target, we do not care about the compiler outputs
boolean skipArg = false;
List<String> cleanedUpArgs = new ArrayList<>();
for (String arg : expandedArgs) {
if (arg.equals("-target")) {
skipArg = true;
continue;
} else if (!(skipArg
|| arg.startsWith("-J")
|| arg.startsWith("-XD")
|| arg.startsWith("-Werror")
// The errorprone plugin complicates the build due to certain other
// flags it requires (such as -XDcompilePolicy=byfile) and is not
// necessary for extraction.
|| arg.startsWith("-Xplugin:ErrorProne"))) {
cleanedUpArgs.add(arg);
}
skipArg = false;
}
String[] cleanedUpArgsArray = new String[cleanedUpArgs.size()];
return cleanedUpArgs.toArray(cleanedUpArgsArray);
}
private boolean passThroughIfAnalysisOnly(String[] args) throws Exception {
// If '-proc:only' is passed as an argument, this is not a source file compilation, but an
// analysis. We will let the real java compiler do its work.
boolean hasProcOnly = false;
for (String arg : args) {
if (arg.equals("-proc:only")) {
hasProcOnly = true;
break;
}
}
if (hasProcOnly) {
passThrough(args);
return true;
}
return false;
}
protected static String createTargetFromSourceFiles(List<String> sourceFiles) {
List<String> sortedSourceFiles = Ordering.natural().sortedCopy(sourceFiles);
String joinedSourceFiles = Joiner.on(":").join(sortedSourceFiles);
return "#" + Hashing.sha256().hashUnencodedChars(joinedSourceFiles);
}
protected static List<String> splitPaths(String path) {
return path == null ? Collections.<String>emptyList() : Splitter.on(':').splitToList(path);
}
protected static List<String> splitCSV(String lst) {
return lst == null ? Collections.<String>emptyList() : Splitter.on(',').splitToList(lst);
}
static String readEnvironmentVariable(String variableName) {
return readEnvironmentVariable(variableName, null);
}
static String readEnvironmentVariable(String variableName, String defaultValue) {
return tryReadEnvironmentVariable(variableName)
.orElseGet(
() -> {
if (Strings.isNullOrEmpty(defaultValue)) {
System.err.printf("Missing environment variable: %s%n", variableName);
System.exit(1);
}
return defaultValue;
});
}
static Optional<String> tryReadEnvironmentVariable(String variableName) {
// First see if we have a system property.
String result = System.getProperty(variableName);
if (Strings.isNullOrEmpty(result)) {
// Fall back to the environment variable.
result = System.getenv(variableName);
}
if (Strings.isNullOrEmpty(result)) {
return Optional.empty();
}
return Optional.of(result);
}
static Optional<Integer> readSourcesBatchSize() {
return tryReadEnvironmentVariable("KYTHE_JAVA_SOURCE_BATCH_SIZE")
.map(
s -> {
try {
return Integer.parseInt(s);
} catch (NumberFormatException err) {
logger.atWarning().withCause(err).log("Invalid KYTHE_JAVA_SOURCE_BATCH_SIZE");
return null;
}
});
}
protected static List<String> getSourceList(Collection<File> files) {
List<String> sources = new ArrayList<>();
for (File file : files) {
sources.add(file.getPath());
}
return sources;
}
}
| kythe/java/com/google/devtools/kythe/extractors/java/standalone/AbstractJavacWrapper.java | /*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.kythe.extractors.java.standalone;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.flogger.FluentLogger;
import com.google.common.hash.Hashing;
import com.google.devtools.kythe.extractors.java.JavaCompilationUnitExtractor;
import com.google.devtools.kythe.extractors.shared.CompilationDescription;
import com.google.devtools.kythe.extractors.shared.FileVNames;
import com.google.devtools.kythe.extractors.shared.IndexInfoUtils;
import com.google.devtools.kythe.proto.Analysis.CompilationUnit;
import com.google.devtools.kythe.proto.Analysis.FileData;
import com.google.devtools.kythe.util.JsonUtil;
import com.sun.tools.javac.main.CommandLine;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* General logic for a javac-based {@link CompilationUnit} extractor.
*
* <p>Environment Variables Used (note that these can also be set as JVM system properties):
*
* <p>KYTHE_VNAMES: optional path to a JSON configuration file for {@link FileVNames} to populate
* the {@link CompilationUnit}'s required input {@link VName}s
*
* <p>KYTHE_CORPUS: if KYTHE_VNAMES is not given, all {@link VName}s will be populated with this
* corpus (default {@link DEFAULT_CORPUS})
*
* <p>KYTHE_ROOT_DIRECTORY: required root path for file inputs; the {@link FileData} paths stored in
* the {@link CompilationUnit} will be made to be relative to this directory
*
* <p>KYTHE_OUTPUT_FILE: if set to a non-empty value, write the resulting .kzip file to this path
* instead of using KYTHE_OUTPUT_DIRECTORY
*
* <p>KYTHE_OUTPUT_DIRECTORY: directory path to store the resulting .kzip file, if KYTHE_OUTPUT_FILE
* is not set
*/
public abstract class AbstractJavacWrapper {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String DEFAULT_CORPUS = "kythe";
protected abstract Collection<CompilationDescription> processCompilation(
String[] arguments, JavaCompilationUnitExtractor javaCompilationUnitExtractor)
throws Exception;
protected abstract void passThrough(String[] args) throws Exception;
/**
* Given the command-line arguments to javac, construct a {@link CompilationUnit} and write it to
* a .kindex file. Parameters to the extraction logic are passed by environment variables (see
* class comment).
*/
public void process(String[] args) {
JsonUtil.usingTypeRegistry(JsonUtil.JSON_TYPE_REGISTRY);
try {
if (!passThroughIfAnalysisOnly(args)) {
String vnamesConfig = System.getenv("KYTHE_VNAMES");
JavaCompilationUnitExtractor extractor;
if (Strings.isNullOrEmpty(vnamesConfig)) {
String corpus = readEnvironmentVariable("KYTHE_CORPUS", DEFAULT_CORPUS);
extractor =
new JavaCompilationUnitExtractor(
corpus, readEnvironmentVariable("KYTHE_ROOT_DIRECTORY"));
} else {
extractor =
new JavaCompilationUnitExtractor(
FileVNames.fromFile(vnamesConfig),
readEnvironmentVariable("KYTHE_ROOT_DIRECTORY"));
}
Collection<CompilationDescription> indexInfos =
processCompilation(getCleanedUpArguments(args), extractor);
outputIndexInfo(indexInfos);
if (indexInfos.stream().anyMatch(cd -> cd.getCompilationUnit().getHasCompileErrors())) {
System.err.println("Errors encountered during compilation");
System.exit(1);
}
}
} catch (IOException e) {
System.err.printf(
"Unexpected IO error (probably while writing to index file): %s%n", e.toString());
System.err.println(Throwables.getStackTraceAsString(e));
System.exit(2);
} catch (Exception e) {
System.err.printf(
"Unexpected error compiling and indexing java compilation: %s%n", e.toString());
System.err.println(Throwables.getStackTraceAsString(e));
System.exit(2);
}
}
private static void outputIndexInfo(Collection<CompilationDescription> indexInfos)
throws IOException {
String outputFile = System.getenv("KYTHE_OUTPUT_FILE");
if (!Strings.isNullOrEmpty(outputFile)) {
if (outputFile.endsWith(IndexInfoUtils.KZIP_FILE_EXT)) {
IndexInfoUtils.writeKzipToFile(indexInfos, outputFile);
} else {
System.err.printf("Unsupported output file: %s%n", outputFile);
System.exit(2);
}
return;
}
String outputDir = readEnvironmentVariable("KYTHE_OUTPUT_DIRECTORY");
// Just rely on the underlying compilation unit's signature to get the filename, if we're not
// writing to a single kzip file.
for (CompilationDescription indexInfo : indexInfos) {
String name =
indexInfo
.getCompilationUnit()
.getVName()
.getSignature()
.trim()
.replaceAll("^/+|/+$", "")
.replace('/', '_');
String path = IndexInfoUtils.getKzipPath(outputDir, name).toString();
IndexInfoUtils.writeKzipToFile(indexInfo, path);
}
}
private static String[] getCleanedUpArguments(String[] args) throws IOException {
// Expand all @file arguments
List<String> expandedArgs = Lists.newArrayList(CommandLine.parse(args));
// We skip some arguments that would normally be passed to javac:
// -J, these are flags to the java environment running javac.
// -XD, these are internal flags used for special debug information
// when compiling javac itself.
// -Werror, we do not want to treat any warnings as errors.
// -target, we do not care about the compiler outputs
boolean skipArg = false;
List<String> cleanedUpArgs = new ArrayList<>();
for (String arg : expandedArgs) {
if (arg.equals("-target")) {
skipArg = true;
continue;
} else if (!(skipArg
|| arg.startsWith("-J")
|| arg.startsWith("-XD")
|| arg.startsWith("-Werror")
// The errorprone plugin complicates the build due to certain other
// flags it requires (such as -XDcompilePolicy=byfile) and is not
// necessary for extraction.
|| arg.startsWith("-Xplugin:ErrorProne"))) {
cleanedUpArgs.add(arg);
}
skipArg = false;
}
String[] cleanedUpArgsArray = new String[cleanedUpArgs.size()];
return cleanedUpArgs.toArray(cleanedUpArgsArray);
}
private boolean passThroughIfAnalysisOnly(String[] args) throws Exception {
// If '-proc:only' is passed as an argument, this is not a source file compilation, but an
// analysis. We will let the real java compiler do its work.
boolean hasProcOnly = false;
for (String arg : args) {
if (arg.equals("-proc:only")) {
hasProcOnly = true;
break;
}
}
if (hasProcOnly) {
passThrough(args);
return true;
}
return false;
}
protected static String createTargetFromSourceFiles(List<String> sourceFiles) {
List<String> sortedSourceFiles = Ordering.natural().sortedCopy(sourceFiles);
String joinedSourceFiles = Joiner.on(":").join(sortedSourceFiles);
return "#" + Hashing.sha256().hashUnencodedChars(joinedSourceFiles);
}
protected static List<String> splitPaths(String path) {
return path == null ? Collections.<String>emptyList() : Splitter.on(':').splitToList(path);
}
protected static List<String> splitCSV(String lst) {
return lst == null ? Collections.<String>emptyList() : Splitter.on(',').splitToList(lst);
}
static String readEnvironmentVariable(String variableName) {
return readEnvironmentVariable(variableName, null);
}
static String readEnvironmentVariable(String variableName, String defaultValue) {
return tryReadEnvironmentVariable(variableName)
.orElseGet(
() -> {
if (Strings.isNullOrEmpty(defaultValue)) {
System.err.printf("Missing environment variable: %s%n", variableName);
System.exit(1);
}
return defaultValue;
});
}
static Optional<String> tryReadEnvironmentVariable(String variableName) {
// First see if we have a system property.
String result = System.getProperty(variableName);
if (Strings.isNullOrEmpty(result)) {
// Fall back to the environment variable.
result = System.getenv(variableName);
}
if (Strings.isNullOrEmpty(result)) {
return Optional.empty();
}
return Optional.of(result);
}
static Optional<Integer> readSourcesBatchSize() {
return tryReadEnvironmentVariable("KYTHE_JAVA_SOURCE_BATCH_SIZE")
.map(
s -> {
try {
return Integer.parseInt(s);
} catch (NumberFormatException err) {
logger.atWarning().log("Invalid KYTHE_JAVA_SOURCE_BATCH_SIZE: %s", err);
return null;
}
});
}
protected static List<String> getSourceList(Collection<File> files) {
List<String> sources = new ArrayList<>();
for (File file : files) {
sources.add(file.getPath());
}
return sources;
}
}
| chore: use withCause for logging (#4826)
| kythe/java/com/google/devtools/kythe/extractors/java/standalone/AbstractJavacWrapper.java | chore: use withCause for logging (#4826) | <ide><path>ythe/java/com/google/devtools/kythe/extractors/java/standalone/AbstractJavacWrapper.java
<ide> try {
<ide> return Integer.parseInt(s);
<ide> } catch (NumberFormatException err) {
<del> logger.atWarning().log("Invalid KYTHE_JAVA_SOURCE_BATCH_SIZE: %s", err);
<add> logger.atWarning().withCause(err).log("Invalid KYTHE_JAVA_SOURCE_BATCH_SIZE");
<ide> return null;
<ide> }
<ide> }); |
|
JavaScript | agpl-3.0 | 45db396c38fa058f8d6650502bf675157932a857 | 0 | Daksh/turtleblocksjs,tchx84/turtleblocksjs,hemantkasat/turtleblocksjs,hemantkasat/turtleblocksjs,garyservin/turtleblocksjs,walterbender/turtleblocksjs,garyservin/turtleblocksjs,i5o/turtleblocksjs,hemantkasat/turtleblocksjs,i5o/turtleblocksjs,Daksh/turtleblocksjs,garyservin/turtleblocksjs,tchx84/turtleblocksjs,i5o/turtleblocksjs,walterbender/turtleblocksjs,Daksh/turtleblocksjs,rodibot/turtleblocksjs,tradzik/turtleblocksjs,walterbender/turtleblocksjs,tradzik/turtleblocksjs,tchx84/turtleblocksjs,rodibot/turtleblocksjs,tradzik/turtleblocksjs,rodibot/turtleblocksjs | // Copyright (c) 2014,2015 Walter Bender
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// You should have received a copy of the GNU General Public License
// along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
// All things related to blocks
// A place in the DOM to put modifiable labels (textareas).
var labelElem = docById('labelDiv');
var blockBlocks = null;
// Minimum distance (squared) between to docks required before
// connecting them.
var MINIMUMDOCKDISTANCE = 400;
// Special value flags to uniquely identify these media blocks.
var CAMERAVALUE = '##__CAMERA__##';
var VIDEOVALUE = '##__VIDEO__##';
// Length of a long touch
var LONGPRESSTIME = 2000;
// There are three "classes" defined in this file: ProtoBlocks,
// Blocks, and Block. Protoblocks are the prototypes from which Blocks
// are created; Blocks is the list of all blocks; and Block is a block
// instance.
// Protoblock contain generic information about blocks and some
// methods common to all blocks.
function ProtoBlock(name) {
// Name is used run-dictionary index, and palette label.
this.name = name;
// The palette to which this block is assigned.
this.palette = null;
// The graphic style used by the block.
this.style = null;
// Does the block expand (or collapse) when other blocks are
// attached? e.g., start, repeat...
this.expandable = false;
// Is this block a parameter? Parameters have their labels
// overwritten with their current value.
this.parameter = false;
// How many "non-flow" arguments does a block have? (flow is
// vertical down a stack; args are horizontal. The pendown block
// has 0 args; the forward block has 1 arg; the setxy block has 2
// args.
this.args = 0;
// Default values for block parameters, e.g., forward 100 or right 90.
this.defaults = [];
// What is the size of the block prior to any expansion?
this.size = 1;
// Static labels are generated as part of the inline SVG.
this.staticLabels = [];
// Default fontsize used for static labels.
this.fontsize = null;
// Extra block width for long labels
this.extraWidth = 0;
// Block scale
this.scale = 2;
// The SVG template used to generate the block graphic.
this.artwork = null;
// Docks define where blocks connect and which connections are
// valid.
this.docks = [];
// The filepath of the image.
this.image = null;
// Hidden: don't show on any palette
this.hidden = false;
// We need a copy of the dock, since it is modified by individual
// blocks as they are expanded or contracted.
this.copyDock = function(dockStyle) {
this.docks = [];
for (var i = 0; i < dockStyle.length; i++) {
var dock = [dockStyle[i][0], dockStyle[i][1], dockStyle[i][2]];
this.docks.push(dock);
}
}
// What follows are the initializations for different block
// styles.
// E.g., penup, pendown
this.zeroArgBlock = function() {
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('in');
this.copyDock(svg.docks);
}
// E.g., break
this.basicBlockNoFlow = function() {
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(true);
svg.setTail(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., collapsed
this.basicBlockCollapsed = function() {
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setCap(true);
svg.setTail(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('unavailable');
svg.docks[1].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., forward, right
this.oneArgBlock = function() {
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setInnies([true]);
svg.setSlot(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('numberin');
svg.docks[2].push('in');
this.copyDock(svg.docks);
}
// E.g., wait for
this.oneBooleanArgBlock = function() {
this.args = 1;
this.size = 3;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setBoolean(true);
svg.setClampCount(0);
svg.setExpand(0, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('in');
svg.docks[1].push('booleanin');
svg.docks[2].push('out');
this.copyDock(svg.docks);
}
// E.g., setxy. These are expandable.
this.twoArgBlock = function(expandY) {
this.expandable = true;
this.style = 'twoarg';
this.size = 2;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setInnies([true, true]);
svg.setSlot(true);
if (expandY) {
svg.setExpand(30 + this.extraWidth, (expandY - 1) * STANDARDBLOCKHEIGHT / 2, 0, 0);
} else if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('numberin');
svg.docks[2].push('numberin');
svg.docks[3].push('in');
this.copyDock(svg.docks);
}
// E.g., sqrt
this.oneArgMathBlock = function() {
this.style = 'arg';
this.size = 1;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(false);
svg.setInnies([true]);
svg.setOutie(true);
svg.setTab(false);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('numberout');
svg.docks[1].push('numberin');
this.copyDock(svg.docks);
}
// E.g., box
this.oneArgMathWithLabelBlock = function() {
this.style = 'arg';
this.size = 1;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(false);
svg.setInnies([true]);
svg.setOutie(true);
svg.setTab(false);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('numberout');
svg.docks[0].push('numberin');
this.copyDock(svg.docks);
}
// E.g., plus, minus, multiply, divide. These are also expandable.
this.twoArgMathBlock = function(expandY) {
this.expandable = true;
this.style = 'arg';
this.size = 2;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(false);
svg.setInnies([true, true]);
svg.setOutie(true);
svg.setTab(false);
if (expandY) {
svg.setExpand(30 + this.extraWidth, (expandY - 1) * STANDARDBLOCKHEIGHT / 2, 0, 0);
} else if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('numberout');
svg.docks[1].push('numberin');
svg.docks[2].push('numberin');
this.copyDock(svg.docks);
}
// E.g., number, string. Value blocks get DOM textareas associated
// with them so their values can be edited by the user.
this.valueBlock = function() {
this.style = 'value';
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(60 + this.extraWidth, 0, 0, 0);
svg.setOutie(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBox();
svg.docks[0].push('numberout');
this.copyDock(svg.docks);
}
// E.g., media. Media blocks invoke a chooser and a thumbnail
// image is overlayed to represent the data associated with the
// block.
this.mediaBlock = function() {
this.style = 'value';
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(60 + this.extraWidth, 23, 0, 0);
svg.setOutie(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBox();
svg.docks[0].push('mediaout');
this.copyDock(svg.docks);
}
// E.g., start. A "child" flow is docked in an expandable clamp.
// There are no additional arguments and no flow above or below.
this.stackClampZeroArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setCap(true);
svg.setTail(true);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('unavailable');
svg.docks[1].push('in');
svg.docks[2].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., repeat. Unlike action, there is a flow above and below.
this.flowClampOneArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setInnies([true]);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('numberin');
svg.docks[2].push('in');
svg.docks[3].push('in');
this.copyDock(svg.docks);
}
// E.g., if. A "child" flow is docked in an expandable clamp. The
// additional argument is a boolean. There is flow above and below.
this.flowClampBooleanArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 3;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setBoolean(true);
svg.setSlot(true);
svg.setExpand(this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('booleanin');
svg.docks[2].push('in');
svg.docks[3].push('in');
this.copyDock(svg.docks);
}
// E.g., if then else. Two "child" flows are docked in expandable
// clamps. The additional argument is a boolean. There is flow
// above and below.
this.doubleFlowClampBooleanArgBlock = function(bottomSlots, topSlots) {
this.style = 'doubleclamp';
this.expandable = true;
this.size = 4;
this.args = 3;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setBoolean(true);
svg.setClampCount(this.scale);
if (topSlots) {
svg.setClampSlots(0, topSlots);
} else {
svg.setClampSlots(0, 1);
}
if (bottomSlots) {
svg.setClampSlots(1, bottomSlots);
} else {
svg.setClampSlots(1, 1);
}
svg.setExpand(this.extraWidth, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('booleanin');
svg.docks[2].push('in');
svg.docks[3].push('in');
svg.docks[4].push('in');
this.copyDock(svg.docks);
}
// E.g., forever. Unlike start, there is flow above and below.
this.flowClampZeroArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setExpand(10 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('in');
svg.docks[2].push('in');
this.copyDock(svg.docks);
}
// E.g., action. A "child" flow is docked in an expandable clamp.
// The additional argument is a name. Again, no flow above or below.
this.stackClampOneArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setCap(true);
svg.setTail(true);
svg.setInnies([true]);
svg.setExpand(10 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('unavailable');
svg.docks[1].push('anyin');
svg.docks[2].push('in');
svg.docks[3].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., mouse button.
this.booleanZeroArgBlock = function() {
this.style = 'arg';
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(60 + this.extraWidth, 0, 0, 4);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanNot(true);
svg.docks[0].push('booleanout');
this.copyDock(svg.docks);
}
// E.g., not
this.booleanOneBooleanArgBlock = function() {
this.style = 'arg';
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanNot(false);
svg.docks[0].push('booleanout');
svg.docks[1].push('booleanin');
this.copyDock(svg.docks);
}
// E.g., and
this.booleanTwoBooleanArgBlock = function() {
this.style = 'arg';
this.size = 3;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanAndOr();
svg.docks[0].push('booleanout');
svg.docks[1].push('booleanin');
svg.docks[2].push('booleanin');
this.copyDock(svg.docks);
}
// E.g., greater, less, equal
this.booleanTwoArgBlock = function(expandY) {
this.style = 'arg';
this.size = 2;
this.args = 2;
this.expandable = true;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
if (expandY) {
svg.setExpand(10 + this.extraWidth, (expandY - 1) * STANDARDBLOCKHEIGHT / 2, 0, 0);
} else {
svg.setExpand(10 + this.extraWidth, 0, 0, 0);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanCompare();
svg.docks[0].push('booleanout');
svg.docks[1].push('numberin');
svg.docks[2].push('numberin');
this.copyDock(svg.docks);
}
// E.g., color, shade, pensize, ...
this.parameterBlock = function() {
this.style = 'arg';
this.parameter = true;
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(70 + this.extraWidth, 0, 0, 0);
svg.setOutie(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBox();
svg.docks[0].push('numberout');
this.copyDock(svg.docks);
}
}
// Blocks holds the list of blocks and most of the block-associated
// methods, since most block manipulations are inter-block.
function Blocks(canvas, stage, refreshCanvas, trashcan) {
// Things we need from outside include access to the canvas, the
// stage, and the trashcan.
this.canvas = canvas;
this.stage = stage;
this.refreshCanvas = refreshCanvas;
this.trashcan = trashcan;
// We keep a dictionary for the proto blocks,
this.protoBlockDict = {}
// and a list of the blocks we create.
this.blockList = [];
// Track the time with mouse down.
this.time = 0;
this.timeOut = null;
// "Copy stack" selects a stack for pasting. Are we selecting?
this.selectingStack = false;
// and what did we select?
this.selectedStack = null;
// If we somehow have a malformed block database (for example,
// from importing a corrupted datafile, we need to avoid infinite
// loops while crawling the block list.
this.loopCounter = 0;
this.sizeCounter = 0;
this.searchCounter = 0;
// We need a reference to the palettes.
this.palettes = null;
// Which block, if any, is highlighted?
this.highlightedBlock = null;
// Which block, if any, is active?
this.activeBlock = null;
// Are the blocks visible?
this.visible = true;
// The group of blocks being dragged or moved together
this.dragGroup = [];
// The blocks at the tops of stacks
this.stackList = [];
// The blocks that need expanding
this.expandablesList = [];
// Number of blocks to load
this.loadCounter = 0;
// Stacks of blocks that need adjusting as blocks are repositioned
// due to expanding and contracting or insertion into the flow.
this.adjustTheseDocks = [];
// We need to keep track of certain classes of blocks that exhibit
// different types of behavior.
// Blocks with parts that expand, e.g.,
this.expandableBlocks = [];
// Blocks that contain child flows of blocks
this.clampBlocks = [];
this.doubleExpandable = [];
// Blocks that are used as arguments to other blocks
this.argBlocks = [];
// Blocks that return values
this.valueBlocks = [];
// Two-arg blocks with two arguments (expandable).
this.twoArgBlocks = [];
// Blocks that don't run when clicked.
this.noRunBlocks = ['action'];
// We need to know if we are processing a copy or save stack command.
this.inLongPress = false;
// We need access to the msg block...
this.setMsgText = function(msgText) {
this.msgText = msgText;
}
// and the Error msg function.
this.setErrorMsg = function(errorMsg) {
this.errorMsg = errorMsg;
}
// We need access to the macro dictionary because we add to it.
this.setMacroDictionary = function(obj) {
this.macroDict = obj;
}
// We need access to the turtles list because we associate a
// turtle with each start block.
this.setTurtles = function(turtles) {
this.turtles = turtles;
}
// We need to access the "pseudo-Logo interpreter" when we click
// on blocks.
this.setLogo = function(logo) {
this.logo = logo;
}
// The scale of the graphics is determined by screen size.
this.setScale = function(scale) {
this.scale = scale;
}
// Toggle state of collapsible blocks.
this.toggleCollapsibles = function() {
for (var blk in this.blockList) {
var myBlock = this.blockList[blk];
if (['start', 'action'].indexOf(myBlock.name) != -1) {
collapseToggle(this, myBlock);
}
}
}
// set up copy/paste, dismiss, and copy-stack buttons
this.makeCopyPasteButtons = function(makeButton, updatePasteButton) {
var blocks = this;
this.updatePasteButton = updatePasteButton;
this.copyButton = makeButton('copy-button', 0, 0, 55);
this.copyButton.visible = false;
this.dismissButton = makeButton('cancel-button', 0, 0, 55);
this.dismissButton.visible = false;
this.saveStackButton = makeButton('save-blocks-button', 0, 0, 55);
this.saveStackButton.visible = false;
this.copyButton.on('click', function(event) {
var topBlock = blocks.findTopBlock(blocks.activeBlock);
blocks.selectedStack = topBlock;
blocks.copyButton.visible = false;
blocks.saveStackButton.visible = false;
blocks.dismissButton.visible = false;
blocks.inLongPress = false;
blocks.updatePasteButton();
blocks.refreshCanvas();
});
this.dismissButton.on('click', function(event) {
blocks.copyButton.visible = false;
blocks.saveStackButton.visible = false;
blocks.dismissButton.visible = false;
blocks.inLongPress = false;
blocks.refreshCanvas();
});
this.saveStackButton.on('click', function(event) {
// Only invoked from action blocks.
var topBlock = blocks.findTopBlock(blocks.activeBlock);
blocks.inLongPress = false;
blocks.selectedStack = topBlock;
blocks.copyButton.visible = false;
blocks.saveStackButton.visible = false;
blocks.dismissButton.visible = false;
blocks.saveStack();
blocks.refreshCanvas();
});
}
// Walk through all of the proto blocks in order to make lists of
// any blocks that need special treatment.
this.findBlockTypes = function() {
for (var proto in this.protoBlockDict) {
if (this.protoBlockDict[proto].expandable) {
this.expandableBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'clamp') {
this.clampBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'twoarg') {
this.twoArgBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'arg') {
this.argBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'value') {
this.argBlocks.push(this.protoBlockDict[proto].name);
this.valueBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'doubleclamp') {
this.doubleExpandable.push(this.protoBlockDict[proto].name);
}
}
}
// Adjust the docking postions of all blocks in the current drag
// group.
this.adjustBlockPositions = function() {
if (this.dragGroup.length < 2) {
return;
}
// Just in case the block list is corrupted, count iterations.
this.loopCounter = 0;
this.adjustDocks(this.dragGroup[0])
}
// Adjust the size of the clamp in an expandable block when blocks
// are inserted into (or removed from) the child flow. This is a
// common operation for start and action blocks, but also for
// repeat, forever, if, etc.
this.adjustExpandableClampBlock = function(blocksToCheck) {
if (blocksToCheck.length == 0) {
// Should not happen
return;
}
var blk = blocksToCheck.pop();
var myBlock = this.blockList[blk];
// Make sure it is the proper type of expandable block.
if (myBlock.isArgBlock() || myBlock.isTwoArgBlock()) {
return;
}
function clampAdjuster(me, blk, myBlock, clamp, blocksToCheck) {
// First we need to count up the number of (and size of) the
// blocks inside the clamp; The child flow is usually the
// second-to-last argument.
if (clamp == 0) {
var c = myBlock.connections.length - 2;
} else { // e.g., Bottom clamp in if-then-else
var c = myBlock.connections.length - 3;
}
me.sizeCounter = 0;
var childFlowSize = 1;
if (c > 0 && myBlock.connections[c] != null) {
childFlowSize = Math.max(me.getStackSize(myBlock.connections[c]), 1);
}
// Adjust the clamp size to match the size of the child
// flow.
var plusMinus = childFlowSize - myBlock.clampCount[clamp];
if (plusMinus != 0) {
if (!(childFlowSize == 0 && myBlock.clampCount[clamp] == 1)) {
myBlock.updateSlots(clamp, plusMinus, blocksToCheck);
}
}
}
if (myBlock.isDoubleClampBlock()) {
clampAdjuster(this, blk, myBlock, 1, blocksToCheck);
}
clampAdjuster(this, blk, myBlock, 0, blocksToCheck);
}
// Returns the block size. (TODO recurse on first argument in
// twoarg blocks.)
this.getBlockSize = function(blk) {
return this.blockList[blk].size;
}
// We also adjust the size of twoarg blocks. It is similar to how
// we adjust clamps, but enough different that it is in its own
// function.
this.adjustExpandableTwoArgBlock = function(blocksToCheck) {
if (blocksToCheck.length == 0) {
// Should not happen
return;
}
var blk = blocksToCheck.pop();
var myBlock = this.blockList[blk];
// Determine the size of the first argument.
var c = myBlock.connections[1];
var firstArgumentSize = 1; // Minimum size
if (c != null) {
firstArgumentSize = Math.max(this.getBlockSize(c), 1);
}
var plusMinus = firstArgumentSize - myBlock.clampCount[0];
if (plusMinus != 0) {
if (!(firstArgumentSize == 0 && myBlock.clampCount[0] == 1)) {
myBlock.updateSlots(0, plusMinus, blocksToCheck);
}
}
}
this.addRemoveVspaceBlock = function(blk) {
var myBlock = blockBlocks.blockList[blk];
var c = myBlock.connections[myBlock.connections.length - 2];
var secondArgumentSize = 1;
if (c != null) {
var secondArgumentSize = Math.max(this.getBlockSize(c), 1);
}
var vSpaceCount = howManyVSpaceBlocksBelow(blk);
if (secondArgumentSize < vSpaceCount + 1) {
// Remove a vspace block
var n = Math.abs(secondArgumentSize - vSpaceCount - 1);
for (var i = 0; i < n; i++) {
var lastConnection = myBlock.connections.length - 1;
var vspaceBlock = this.blockList[myBlock.connections[lastConnection]];
var nextBlockIndex = vspaceBlock.connections[1];
myBlock.connections[lastConnection] = nextBlockIndex;
if (nextBlockIndex != null) {
this.blockList[nextBlockIndex].connections[0] = blk;
}
vspaceBlock.connections = [null, null];
vspaceBlock.hide();
}
} else if (secondArgumentSize > vSpaceCount + 1) {
// Add a vspace block
var n = secondArgumentSize - vSpaceCount - 1;
for (var nextBlock, newPos, i = 0; i < n; i++) {
nextBlock = last(myBlock.connections);
newPos = blockBlocks.blockList.length;
blockBlocks.makeNewBlockWithConnections('vspace', newPos, [null, null], function(args) {
var vspace = args[1];
var nextBlock = args[0];
var vspaceBlock = blockBlocks.blockList[vspace];
vspaceBlock.connections[0] = blk;
vspaceBlock.connections[1] = nextBlock;
myBlock.connections[myBlock.connections.length - 1] = vspace;
if (nextBlock) {
blockBlocks.blockList[nextBlock].connections[0] = vspace;
}
}, [nextBlock, newPos]);
}
}
function howManyVSpaceBlocksBelow(blk) {
// Need to know how many vspace blocks are below the block
// we're checking against.
var nextBlock = last(blockBlocks.blockList[blk].connections);
if (nextBlock && blockBlocks.blockList[nextBlock].name == 'vspace') {
return 1 + howManyVSpaceBlocksBelow(nextBlock);
// Recurse until it isn't a vspace
}
return 0;
}
}
this.getStackSize = function(blk) {
// How many block units in this stack?
var size = 0;
this.sizeCounter += 1;
if (this.sizeCounter > this.blockList.length * 2) {
console.log('Infinite loop encountered detecting size of expandable block? ' + blk);
return size;
}
if (blk == null) {
return size;
}
var myBlock = this.blockList[blk];
if (myBlock == null) {
console.log('Something very broken in getStackSize.');
}
if (myBlock.isClampBlock()) {
var c = myBlock.connections.length - 2;
var csize = 0;
if (c > 0) {
var cblk = myBlock.connections[c];
if (cblk != null) {
csize = this.getStackSize(cblk);
}
if (csize == 0) {
size = 1; // minimum of 1 slot in clamp
} else {
size = csize;
}
}
if (myBlock.isDoubleClampBlock()) {
var c = myBlock.connections.length - 3;
var csize = 0;
if (c > 0) {
var cblk = myBlock.connections[c];
if (cblk != null) {
var csize = this.getStackSize(cblk);
}
if (csize == 0) {
size += 1; // minimum of 1 slot in clamp
} else {
size += csize;
}
}
}
// add top and bottom of clamp
size += myBlock.size;
} else {
size = myBlock.size;
}
// check on any connected block
if (!myBlock.isValueBlock()) {
var cblk = last(myBlock.connections);
if (cblk != null) {
size += this.getStackSize(cblk);
}
}
return size;
}
this.adjustDocks = function(blk, resetLoopCounter) {
// Give a block, adjust the dock positions
// of all of the blocks connected to it
// For when we come in from makeBlock
if (resetLoopCounter != null) {
this.loopCounter = 0;
}
// These checks are to test for malformed data. All blocks
// should have connections.
if (this.blockList[blk] == null) {
console.log('Saw a null block: ' + blk);
return;
}
if (this.blockList[blk].connections == null) {
console.log('Saw a block with null connections: ' + blk);
return;
}
if (this.blockList[blk].connections.length == 0) {
console.log('Saw a block with [] connections: ' + blk);
return;
}
// Value blocks only have one dock.
if (this.blockList[blk].docks.length == 1) {
return;
}
this.loopCounter += 1;
if (this.loopCounter > this.blockList.length * 2) {
console.log('Infinite loop encountered while adjusting docks: ' + blk + ' ' + this.blockList);
return;
}
// Walk through each connection except the parent block.
for (var c = 1; c < this.blockList[blk].connections.length; c++) {
// Get the dock position for this connection.
var bdock = this.blockList[blk].docks[c];
// Find the connecting block.
var cblk = this.blockList[blk].connections[c];
// Nothing connected here so continue to the next connection.
if (cblk == null) {
continue;
}
// Another database integrety check.
if (this.blockList[cblk] == null) {
console.log('This is not good: we encountered a null block: ' + cblk);
continue;
}
// Find the dock position in the connected block.
var foundMatch = false;
for (var b = 0; b < this.blockList[cblk].connections.length; b++) {
if (this.blockList[cblk].connections[b] == blk) {
foundMatch = true;
break
}
}
// Yet another database integrety check.
if (!foundMatch) {
console.log('Did not find match for ' + this.blockList[blk].name + ' and ' + this.blockList[cblk].name);
break;
}
var cdock = this.blockList[cblk].docks[b];
// Move the connected block.
var dx = bdock[0] - cdock[0];
var dy = bdock[1] - cdock[1];
if (this.blockList[blk].bitmap == null) {
var nx = this.blockList[blk].x + dx;
var ny = this.blockList[blk].y + dy;
} else {
var nx = this.blockList[blk].container.x + dx;
var ny = this.blockList[blk].container.y + dy;
}
this.moveBlock(cblk, nx, ny);
// Recurse on connected blocks.
this.adjustDocks(cblk);
}
}
this.blockMoved = function(thisBlock) {
// When a block is moved, we have lots of things to check:
// (0) Is it inside of a expandable block?
// (1) Is it an arg block connected to a two-arg block?
// (2) Disconnect its connection[0];
// (3) Look for a new connection;
// (4) Is it an arg block connected to a 2-arg block?
// (5) Recheck if it inside of a expandable block.
// Find any containing expandable blocks.
var checkExpandableBlocks = [];
var blk = this.insideExpandableBlock(thisBlock);
var expandableLoopCounter = 0;
while (blk != null) {
expandableLoopCounter += 1;
if (expandableLoopCounter > 2 * this.blockList.length) {
console.log('Inifinite loop encountered checking for expandables?');
break;
}
checkExpandableBlocks.push(blk);
blk = this.insideExpandableBlock(blk);
}
var checkTwoArgBlocks = [];
var checkArgBlocks = [];
var myBlock = this.blockList[thisBlock];
var c = myBlock.connections[0];
if (c != null) {
var cBlock = this.blockList[c];
}
// If it is an arg block, where is it coming from?
if (myBlock.isArgBlock() && c != null) {
// We care about twoarg (2arg) blocks with
// connections to the first arg;
if (this.blockList[c].isTwoArgBlock()) {
if (cBlock.connections[1] == thisBlock) {
checkTwoArgBlocks.push(c);
}
} else if (this.blockList[c].isArgBlock() && this.blockList[c].isExpandableBlock()) {
if (cBlock.connections[1] == thisBlock) {
checkTwoArgBlocks.push(c);
}
}
}
// Disconnect from connection[0] (both sides of the connection).
if (c != null) {
// disconnect both ends of the connection
for (var i = 1; i < cBlock.connections.length; i++) {
if (cBlock.connections[i] == thisBlock) {
cBlock.connections[i] = null;
break;
}
}
myBlock.connections[0] = null;
}
// Look for a new connection.
var x1 = myBlock.container.x + myBlock.docks[0][0];
var y1 = myBlock.container.y + myBlock.docks[0][1];
// Find the nearest dock; if it is close
// enough, connect;
var newBlock = null;
var newConnection = null;
// TODO: Make minimum distance relative to scale.
var min = MINIMUMDOCKDISTANCE;
var blkType = myBlock.docks[0][2]
for (var b = 0; b < this.blockList.length; b++) {
// Don't connect to yourself.
if (b == thisBlock) {
continue;
}
for (var i = 1; i < this.blockList[b].connections.length; i++) {
// When converting from Python to JS, sometimes extra
// null connections are added. We need to ignore them.
if (i == this.blockList[b].docks.length) {
break;
}
// Look for available connections.
if (this.testConnectionType(
blkType,
this.blockList[b].docks[i][2])) {
x2 = this.blockList[b].container.x + this.blockList[b].docks[i][0];
y2 = this.blockList[b].container.y + this.blockList[b].docks[i][1];
dist = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if (dist < min) {
newBlock = b;
newConnection = i;
min = dist;
}
} else {
// TODO: bounce away from illegal connection?
// only if the distance was small
// console.log('cannot not connect these two block types');
}
}
}
if (newBlock != null) {
// We found a match.
myBlock.connections[0] = newBlock;
var connection = this.blockList[newBlock].connections[newConnection];
if (connection != null) {
if (myBlock.isArgBlock()) {
this.blockList[connection].connections[0] = null;
// Fixme: could be more than one block.
this.moveBlockRelative(connection, 40, 40);
} else {
var bottom = this.findBottomBlock(thisBlock);
this.blockList[connection].connections[0] = bottom;
this.blockList[bottom].connections[this.blockList[bottom].connections.length - 1] = connection;
}
}
this.blockList[newBlock].connections[newConnection] = thisBlock;
this.loopCounter = 0;
this.adjustDocks(newBlock);
// TODO: some graphical feedback re new connection?
}
// If it is an arg block, where is it coming from?
if (myBlock.isArgBlock() && newBlock != null) {
// We care about twoarg blocks with connections to the
// first arg;
if (this.blockList[newBlock].isTwoArgBlock()) {
if (this.blockList[newBlock].connections[1] == thisBlock) {
if (checkTwoArgBlocks.indexOf(newBlock) == -1) {
checkTwoArgBlocks.push(newBlock);
}
}
} else if (this.blockList[newBlock].isArgBlock() && this.blockList[newBlock].isExpandableBlock()) {
if (this.blockList[newBlock].connections[1] == thisBlock) {
if (checkTwoArgBlocks.indexOf(newBlock) == -1) {
checkTwoArgBlocks.push(newBlock);
}
}
}
// We also care about the second-to-last connection to an arg block.
var n = this.blockList[newBlock].connections.length;
if (this.blockList[newBlock].connections[n - 2] == thisBlock) {
// Only flow blocks.
if (this.blockList[newBlock].docks[n - 1][2] == 'in') {
checkArgBlocks.push(newBlock);
}
}
}
// If we changed the contents of a arg block, we may need a vspace.
if (checkArgBlocks.length > 0) {
for (var i = 0; i < checkArgBlocks.length; i++) {
this.addRemoveVspaceBlock(checkArgBlocks[i]);
}
}
// If we changed the contents of a two-arg block, we need to
// adjust it.
if (checkTwoArgBlocks.length > 0) {
this.adjustExpandableTwoArgBlock(checkTwoArgBlocks);
}
var blocks = this;
// FIXME: Make these callbacks so there is no race condition.
setTimeout(function() {
// First, adjust the docks for any blocks that may have
// had a vspace added.
for (var i = 0; i < checkArgBlocks.length; i++) {
blocks.adjustDocks(checkArgBlocks[i]);
}
// Next, recheck if the connection is inside of a
// expandable block.
var blk = blocks.insideExpandableBlock(thisBlock);
var expandableLoopCounter = 0;
while (blk != null) {
// Extra check for malformed data.
expandableLoopCounter += 1;
if (expandableLoopCounter > 2 * blocks.blockList.length) {
console.log('Infinite loop checking for expandables?');
console.log(blocks.blockList);
break;
}
if (checkExpandableBlocks.indexOf(blk) == -1) {
checkExpandableBlocks.push(blk);
}
blk = blocks.insideExpandableBlock(blk);
}
blocks.refreshCanvas();
}, 500);
setTimeout(function() {
// If we changed the contents of an expandable block, we need
// to adjust its clamp.
blocks.adjustExpandableClampBlock(checkExpandableBlocks);
}, 1000);
}
this.testConnectionType = function(type1, type2) {
// Can these two blocks dock?
if (type1 == 'in' && type2 == 'out') {
return true;
}
if (type1 == 'out' && type2 == 'in') {
return true;
}
if (type1 == 'numberin' && ['numberout', 'anyout'].indexOf(type2) != -1) {
return true;
}
if (['numberout', 'anyout'].indexOf(type1) != -1 && type2 == 'numberin') {
return true;
}
if (type1 == 'textin' && ['textout', 'anyout'].indexOf(type2) != -1) {
return true;
}
if (['textout', 'anyout'].indexOf(type1) != -1 && type2 == 'textin') {
return true;
}
if (type1 == 'booleanout' && type2 == 'booleanin') {
return true;
}
if (type1 == 'booleanin' && type2 == 'booleanout') {
return true;
}
if (type1 == 'mediain' && type2 == 'mediaout') {
return true;
}
if (type1 == 'mediaout' && type2 == 'mediain') {
return true;
}
if (type1 == 'mediain' && type2 == 'textout') {
return true;
}
if (type2 == 'mediain' && type1 == 'textout') {
return true;
}
if (type1 == 'filein' && type2 == 'fileout') {
return true;
}
if (type1 == 'fileout' && type2 == 'filein') {
return true;
}
if (type1 == 'anyin' && ['textout', 'mediaout', 'numberout', 'anyout', 'fileout'].indexOf(type2) != -1) {
return true;
}
if (type2 == 'anyin' && ['textout', 'mediaout', 'numberout', 'anyout', 'fileout'].indexOf(type1) != -1) {
return true;
}
return false;
}
this.updateBlockPositions = function() {
// Create the block image if it doesn't yet exist.
for (var blk = 0; blk < this.blockList.length; blk++) {
this.moveBlock(blk, this.blockList[blk].x, this.blockList[blk].y);
}
}
this.bringToTop = function() {
// Move all the blocks to the top layer of the stage
for (var blk in this.blockList) {
var myBlock = this.blockList[blk];
this.stage.removeChild(myBlock.container);
this.stage.addChild(myBlock.container);
if (myBlock.collapseContainer != null) {
this.stage.removeChild(myBlock.collapseContainer);
this.stage.addChild(myBlock.collapseContainer);
}
}
this.refreshCanvas();
}
this.moveBlock = function(blk, x, y) {
// Move a block (and its label) to x, y.
var myBlock = this.blockList[blk];
if (myBlock.container != null) {
myBlock.container.x = x;
myBlock.container.y = y;
myBlock.x = x
myBlock.y = y
if (myBlock.collapseContainer != null) {
myBlock.collapseContainer.x = x + COLLAPSEBUTTONXOFF;
myBlock.collapseContainer.y = y + COLLAPSEBUTTONYOFF;
}
} else {
console.log('no container yet');
myBlock.x = x
myBlock.y = y
}
}
this.moveBlockRelative = function(blk, dx, dy) {
// Move a block (and its label) by dx, dy.
var myBlock = this.blockList[blk];
if (myBlock.container != null) {
myBlock.container.x += dx;
myBlock.container.y += dy;
myBlock.x = myBlock.container.x;
myBlock.y = myBlock.container.y;
if (myBlock.collapseContainer != null) {
myBlock.collapseContainer.x += dx;
myBlock.collapseContainer.y += dy;
}
} else {
console.log('no container yet');
myBlock.x += dx
myBlock.y += dy
}
}
this.updateBlockText = function(blk) {
// When we create new blocks, we may not have assigned the
// value yet.
var myBlock = this.blockList[blk];
var maxLength = 8;
if (myBlock.text == null) {
return;
}
if (myBlock.name == 'loadFile') {
try {
var label = myBlock.value[0].toString();
} catch (e) {
var label = _('open file');
}
maxLength = 10;
} else {
var label = myBlock.value.toString();
}
if (label.length > maxLength) {
label = label.substr(0, maxLength - 1) + '...';
}
myBlock.text.text = label;
// Make sure text is on top.
z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.text, z);
if (myBlock.loadComplete) {
myBlock.container.updateCache();
} else {
console.log('load not yet complete for ' + blk);
}
}
this.findTopBlock = function(blk) {
// Find the top block in a stack.
if (blk == null) {
return null;
}
var myBlock = this.blockList[blk];
if (myBlock.connections == null) {
return blk;
}
if (myBlock.connections.length == 0) {
return blk;
}
var topBlockLoop = 0;
while (myBlock.connections[0] != null) {
topBlockLoop += 1;
if (topBlockLoop > 2 * this.blockList.length) {
// Could happen if the block data is malformed.
console.log('infinite loop finding topBlock?');
console.log(myBlock.name);
break;
}
blk = myBlock.connections[0];
myBlock = this.blockList[blk];
}
return blk;
}
this.findBottomBlock = function(blk) {
// Find the bottom block in a stack.
if (blk == null) {
return null;
}
var myBlock = this.blockList[blk];
if (myBlock.connections == null) {
return blk;
}
if (myBlock.connections.length == 0) {
return blk;
}
var bottomBlockLoop = 0;
while (last(myBlock.connections) != null) {
bottomBlockLoop += 1;
if (bottomBlockLoop > 2 * this.blockList.length) {
// Could happen if the block data is malformed.
console.log('infinite loop finding bottomBlock?');
break;
}
blk = last(myBlock.connections);
myBlock = this.blockList[blk];
}
return blk;
}
this.findStacks = function() {
// Find any blocks with null in the first connection.
this.stackList = [];
for (i = 0; i < this.blockList.length; i++) {
if (this.blockList[i].connections[0] == null) {
this.stackList.push(i)
}
}
}
this.findClamps = function() {
// Find any clamp blocks.
this.expandablesList = [];
this.findStacks(); // We start by finding the stacks
for (var i = 0; i < this.stackList.length; i++) {
this.searchCounter = 0;
this.searchForExpandables(this.stackList[i]);
}
}
this.findTwoArgs = function() {
// Find any expandable arg blocks.
this.expandablesList = [];
for (var i = 0; i < this.blockList.length; i++) {
if (this.blockList[i].isArgBlock() && this.blockList[i].isExpandableBlock()) {
this.expandablesList.push(i);
} else if (this.blockList[i].isTwoArgBlock()) {
this.expandablesList.push(i);
}
}
}
this.searchForExpandables = function(blk) {
// Find the expandable blocks below blk in a stack.
while (blk != null && this.blockList[blk] != null && !this.blockList[blk].isValueBlock()) {
// More checks for malformed or corrupted block data.
this.searchCounter += 1;
if (this.searchCounter > 2 * this.blockList.length) {
console.log('infinite loop searching for Expandables? ' + this.searchCounter);
console.log(blk + ' ' + this.blockList[blk].name);
break;
}
if (this.blockList[blk].isClampBlock()) {
this.expandablesList.push(blk);
var c = this.blockList[blk].connections.length - 2;
this.searchForExpandables(this.blockList[blk].connections[c]);
}
blk = last(this.blockList[blk].connections);
}
}
this.expandTwoArgs = function() {
// Expand expandable 2-arg blocks as needed.
this.findTwoArgs();
this.adjustExpandableTwoArgBlock(this.expandablesList);
this.refreshCanvas();
}
this.expandClamps = function() {
// Expand expandable clamp blocks as needed.
this.findClamps();
this.adjustExpandableClampBlock(this.expandablesList);
this.refreshCanvas();
}
this.unhighlightAll = function() {
for (blk in this.blockList) {
this.unhighlight(blk);
}
}
this.unhighlight = function(blk) {
if (!this.visible) {
return;
}
if (blk != null) {
var thisBlock = blk;
} else {
var thisBlock = this.highlightedBlock;
}
if (thisBlock != null) {
this.blockList[thisBlock].unhighlight();
}
if (this.highlightedBlock = thisBlock) {
this.highlightedBlock = null;
}
}
this.highlight = function(blk, unhighlight) {
if (!this.visible) {
return;
}
if (blk != null) {
if (unhighlight) {
this.unhighlight(null);
}
this.blockList[blk].highlight();
this.highlightedBlock = blk;
}
}
this.hide = function() {
for (var blk in this.blockList) {
this.blockList[blk].hide();
}
this.visible = false;
}
this.show = function() {
for (var blk in this.blockList) {
this.blockList[blk].show();
}
this.visible = true;
}
this.makeNewBlockWithConnections = function(name, blockOffset, connections, postProcess, postProcessArg, collapsed) {
if (typeof(collapsed) === 'undefined') {
collapsed = false
}
myBlock = this.makeNewBlock(name, postProcess, postProcessArg);
if (myBlock == null) {
console.log('could not make block ' + name);
return;
}
myBlock.collapsed = !collapsed;
for (var c = 0; c < connections.length; c++) {
if (c == myBlock.docks.length) {
break;
}
if (connections[c] == null) {
myBlock.connections.push(null);
} else {
myBlock.connections.push(connections[c] + blockOffset);
}
}
}
this.makeNewBlock = function(name, postProcess, postProcessArg) {
// Create a new block
if (!name in this.protoBlockDict) {
// Should never happen: nop blocks should be substituted
console.log('makeNewBlock: no prototype for ' + name);
return null;
}
if (this.protoBlockDict[name] == null) {
// Should never happen
console.log('makeNewBlock: no prototype for ' + name);
return null;
}
this.blockList.push(new Block(this.protoBlockDict[name], this));
if (last(this.blockList) == null) {
// Should never happen
console.log('failed to make protoblock for ' + name);
return null;
}
// We copy the dock because expandable blocks modify it.
var myBlock = last(this.blockList);
myBlock.copyDocks();
myBlock.copySize();
// We may need to do some postProcessing to the block
myBlock.postProcess = postProcess;
myBlock.postProcessArg = postProcessArg;
// We need a container for the block graphics.
myBlock.container = new createjs.Container();
this.stage.addChild(myBlock.container);
myBlock.container.snapToPixelEnabled = true;
myBlock.container.x = myBlock.x;
myBlock.container.y = myBlock.y;
// and we need to load the images into the container.
myBlock.imageLoad();
return myBlock;
}
this.makeBlock = function(name, arg) {
// Make a new block from a proto block.
// Called from palettes.
var postProcess = null;
var postProcessArg = null;
var me = this;
var thisBlock = this.blockList.length;
if (name == 'start') {
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = me.turtles.turtleList.length;
me.turtles.add(me.blockList[thisBlock]);
}
postProcessArg = thisBlock;
} else if (name == 'text') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value;
me.blockList[thisBlock].container.updateCache();
}
postProcessArg = [thisBlock, _('text')];
} else if (name == 'number') {
postProcess = function(args) {
var thisBlock = args[0];
var value = Number(args[1]);
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value.toString();
me.blockList[thisBlock].container.updateCache();
}
postProcessArg = [thisBlock, 100];
} else if (name == 'media') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
if (value == null) {
me.blockList[thisBlock].image = 'images/load-media.svg';
} else {
me.blockList[thisBlock].image = null;
}
}
postProcessArg = [thisBlock, null];
} else if (name == 'camera') {
postProcess = function(args) {
console.log('post process camera ' + args[1]);
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = CAMERAVALUE;
if (value == null) {
me.blockList[thisBlock].image = 'images/camera.svg';
} else {
me.blockList[thisBlock].image = null;
}
}
postProcessArg = [thisBlock, null];
} else if (name == 'video') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = VIDEOVALUE;
if (value == null) {
me.blockList[thisBlock].image = 'images/video.svg';
} else {
me.blockList[thisBlock].image = null;
}
}
postProcessArg = [thisBlock, null];
} else if (name == 'loadFile') {
postProcess = function(args) {
me.updateBlockText(args[0]);
}
postProcessArg = [thisBlock, null];
}
for (var proto in this.protoBlockDict) {
if (this.protoBlockDict[proto].name == name) {
if (arg == '__NOARG__') {
console.log('creating ' + name + ' block with no args');
this.makeNewBlock(proto, postProcess, postProcessArg);
break;
} else {
if (this.protoBlockDict[proto].defaults[0] == arg) {
console.log('creating ' + name + ' block with default arg ' + arg);
this.makeNewBlock(proto, postProcess, postProcessArg);
break;
}
}
}
}
var blk = this.blockList.length - 1;
var myBlock = this.blockList[blk];
for (var i = 0; i < myBlock.docks.length; i++) {
myBlock.connections.push(null);
}
// Attach default args if any
var cblk = blk + 1;
for (var i = 0; i < myBlock.protoblock.defaults.length; i++) {
var value = myBlock.protoblock.defaults[i];
var me = this;
var thisBlock = this.blockList.length;
if (myBlock.docks[i + 1][2] == 'anyin') {
if (value == null) {
console.log('cannot set default value');
} else if (typeof(value) == 'string') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
var label = value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
me.blockList[thisBlock].text.text = label;
me.blockList[thisBlock].container.updateCache();
}
this.makeNewBlock('text', postProcess, [thisBlock, value]);
} else {
postProcess = function(args) {
var thisBlock = args[0];
var value = Number(args[1]);
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value.toString();
}
this.makeNewBlock('number', postProcess, [thisBlock, value]);
}
} else if (myBlock.docks[i + 1][2] == 'textin') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
var label = value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
me.blockList[thisBlock].text.text = label;
}
this.makeNewBlock('text', postProcess, [thisBlock, value]);
} else if (myBlock.docks[i + 1][2] == 'mediain') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
if (value != null) {
// loadThumbnail(me, thisBlock, null);
}
}
this.makeNewBlock('media', postProcess, [thisBlock, value]);
} else if (myBlock.docks[i + 1][2] == 'filein') {
postProcess = function(blk) {
me.updateBlockText(blk);
}
this.makeNewBlock('loadFile', postProcess, thisBlock);
} else {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value.toString();
}
this.makeNewBlock('number', postProcess, [thisBlock, value]);
}
var myConnectionBlock = this.blockList[cblk + i];
myConnectionBlock.connections = [blk];
if (myBlock.name == 'action') {
// Make sure we don't make two actions with the same name.
console.log('calling findUniqueActionName');
value = this.findUniqueActionName(_('action'));
console.log('renaming action block to ' + value);
if (value != _('action')) {
// There is a race condition with creation of new
// text block, hence the timeout.
setTimeout(function() {
myConnectionBlock.text.text = value;
myConnectionBlock.value = value;
myConnectionBlock.container.updateCache();
}, 1000);
console.log('calling newDoBlock with value ' + value);
this.newDoBlock(value);
this.palettes.updatePalettes();
}
}
myConnectionBlock.value = value;
myBlock.connections[i + 1] = cblk + i;
}
// Generate and position the block bitmaps and labels
this.updateBlockPositions();
this.adjustDocks(blk, true);
this.refreshCanvas();
return blk;
}
this.findDragGroup = function(blk) {
// Generate a drag group from blocks connected to blk
this.dragGroup = [];
this.calculateDragGroup(blk);
}
this.calculateDragGroup = function(blk) {
// Give a block, find all the blocks connected to it
if (blk == null) {
return;
}
var myBlock = this.blockList[blk];
// If this happens, something is really broken.
if (myBlock == null) {
console.log('null block encountered... this is bad. ' + blk);
return;
}
// As before, does these ever happen?
if (myBlock.connections == null) {
return;
}
if (myBlock.connections.length == 0) {
return;
}
this.dragGroup.push(blk);
for (var c = 1; c < myBlock.connections.length; c++) {
var cblk = myBlock.connections[c];
if (cblk != null) {
// Recurse
this.calculateDragGroup(cblk);
}
}
}
this.findUniqueActionName = function(name) {
// Make sure we don't make two actions with the same name.
var actionNames = [];
for (var blk = 0; blk < this.blockList.length; blk++) {
if (this.blockList[blk].name == 'text') {
var c = this.blockList[blk].connections[0];
if (c != null && this.blockList[c].name == 'action') {
actionNames.push(this.blockList[blk].value);
}
}
}
if (actionNames.length == 1) {
return name;
}
var i = 1;
var value = name;
while (actionNames.indexOf(value) != -1) {
value = name + i.toString();
i += 1;
}
return value;
}
this.renameBoxes = function(oldName, newName) {
for (var blk = 0; blk < this.blockList.length; blk++) {
if (this.blockList[blk].name == 'text') {
var c = this.blockList[blk].connections[0];
if (c != null && this.blockList[c].name == 'box') {
if (this.blockList[blk].value == oldName) {
this.blockList[blk].value = newName;
this.blockList[blk].text.text = newName;
try {
this.blockList[blk].container.updateCache();
} catch (e) {
console.log(e);
}
}
}
}
}
}
this.renameDos = function(oldName, newName) {
var blockPalette = this.palettes.dict['blocks'];
var nameChanged = false;
// Update the blocks, do->oldName should be do->newName
for (var blk = 0; blk < this.blockList.length; blk++) {
var myBlk = this.blockList[blk];
var blkParent = this.blockList[myBlk.connections[0]];
if (blkParent == null) {
continue;
}
if (['do', 'action'].indexOf(blkParent.name) == -1) {
continue;
}
var blockValue = myBlk.value;
if (blockValue == oldName) {
myBlk.value = newName;
myBlk.text.text = newName;
myBlk.container.updateCache();
}
}
// Update the palette
for (var blockId = 0; blockId < blockPalette.protoList.length; blockId++) {
var block = blockPalette.protoList[blockId];
if (block.name == 'do' && block.defaults[0] != _('action') && block.defaults[0] == oldName) {
blockPalette.protoList.splice(blockPalette.protoList.indexOf(block), 1);
delete this.protoBlockDict['myDo_' + oldName];
blockPalette.y = 0;
nameChanged = true;
}
}
// Force an update if the name has changed.
if (nameChanged) {
regeneratePalette(blockPalette);
}
}
this.newStoreinBlock = function(name) {
var myStoreinBlock = new ProtoBlock('storein');
this.protoBlockDict['myStorein_' + name] = myStoreinBlock;
myStoreinBlock.palette = this.palettes.dict['blocks'];
myStoreinBlock.twoArgBlock();
myStoreinBlock.defaults.push(name);
myStoreinBlock.defaults.push(100);
myStoreinBlock.staticLabels.push(_('store in'));
myStoreinBlock.staticLabels.push(_('name'));
myStoreinBlock.staticLabels.push(_('value'));
if (name == 'box') {
return;
}
myStoreinBlock.palette.add(myStoreinBlock);
}
this.newBoxBlock = function(name) {
var myBoxBlock = new ProtoBlock('box');
this.protoBlockDict['myBox_' + name] = myBoxBlock;
myBoxBlock.oneArgMathWithLabelBlock();
myBoxBlock.palette = this.palettes.dict['blocks'];
myBoxBlock.defaults.push(name);
myBoxBlock.staticLabels.push(_('box'));
myBoxBlock.style = 'arg';
if (name == 'box') {
return;
}
myBoxBlock.palette.add(myBoxBlock);
}
this.newDoBlock = function(name) {
var myDoBlock = new ProtoBlock('do');
this.protoBlockDict['myDo_' + name] = myDoBlock;
myDoBlock.oneArgBlock();
myDoBlock.palette = this.palettes.dict['blocks'];
myDoBlock.docks[1][2] = 'anyin';
myDoBlock.defaults.push(name);
myDoBlock.staticLabels.push(_('do'));
if (name == 'action') {
return;
}
myDoBlock.palette.add(myDoBlock);
}
this.newActionBlock = function(name) {
var myActionBlock = new ProtoBlock('action');
this.protoBlockDict['myAction_' + name] = myActionBlock;
myActionBlock.stackClampOneArgBlock();
myActionBlock.palette = this.palettes.dict['blocks'];
myActionBlock.artworkOffset = [0, 0, 86];
myActionBlock.defaults.push(name);
myActionBlock.staticLabels.push(_('action'));
myActionBlock.expandable = true;
myActionBlock.style = 'clamp';
if (name == 'action') {
return;
}
myActionBlock.palette.add(myActionBlock);
}
this.insideExpandableBlock = function(blk) {
// Returns a containing expandable block or null
if (this.blockList[blk].connections[0] == null) {
return null;
} else {
var cblk = this.blockList[blk].connections[0];
if (this.blockList[cblk].isExpandableBlock()) {
// If it is the last connection, keep searching.
if (blk == last(this.blockList[cblk].connections)) {
return this.insideExpandableBlock(cblk);
} else {
return cblk;
}
} else {
return this.insideExpandableBlock(cblk);
}
}
}
this.triggerLongPress = function(myBlock) {
this.timeOut == null;
this.inLongPress = true;
this.copyButton.visible = true;
this.copyButton.x = myBlock.container.x - 27;
this.copyButton.y = myBlock.container.y - 27;
this.dismissButton.visible = true;
this.dismissButton.x = myBlock.container.x + 27;
this.dismissButton.y = myBlock.container.y - 27;
if (myBlock.name == 'action') {
this.saveStackButton.visible = true;
this.saveStackButton.x = myBlock.container.x + 82;
this.saveStackButton.y = myBlock.container.y - 27;
}
this.refreshCanvas();
}
this.pasteStack = function() {
// Copy a stack of blocks by creating a blockObjs and passing
// it to this.load.
if (this.selectedStack == null) {
return;
}
var blockObjs = this.copyBlocksToObj();
this.loadNewBlocks(blockObjs);
}
this.saveStack = function() {
// Save a stack of blocks to local storage and the my-stack
// palette by creating a blockObjs and ...
if (this.selectedStack == null) {
return;
}
var blockObjs = this.copyBlocksToObj();
var nameBlk = blockObjs[0][4][1];
if (nameBlk == null) {
console.log('action not named... skipping');
} else {
console.log(blockObjs[nameBlk][1][1]);
var name = blockObjs[nameBlk][1][1];
localStorage.setItem('macros', prepareMacroExports(name, blockObjs, this.macroDict));
this.addToMyPalette(name, blockObjs);
this.palettes.makeMenu();
}
}
this.copyBlocksToObj = function() {
var blockObjs = [];
var blockMap = {};
this.findDragGroup(this.selectedStack);
for (var b = 0; b < this.dragGroup.length; b++) {
myBlock = this.blockList[this.dragGroup[b]];
if (b == 0) {
x = 25;
y = 25;
} else {
x = 0;
y = 0;
}
if (myBlock.isValueBlock()) {
switch (myBlock.name) {
case 'media':
blockItem = [b, [myBlock.name, null], x, y, []];
break;
default:
blockItem = [b, [myBlock.name, myBlock.value], x, y, []];
break;
}
} else {
blockItem = [b, myBlock.name, x, y, []];
}
blockMap[this.dragGroup[b]] = b;
blockObjs.push(blockItem);
}
for (var b = 0; b < this.dragGroup.length; b++) {
myBlock = this.blockList[this.dragGroup[b]];
for (var c = 0; c < myBlock.connections.length; c++) {
if (myBlock.connections[c] == null) {
blockObjs[b][4].push(null);
} else {
blockObjs[b][4].push(blockMap[myBlock.connections[c]]);
}
}
}
return blockObjs;
}
this.addToMyPalette = function(name, obj) {
// On the palette we store the macro as a basic block.
var myBlock = new ProtoBlock('macro_' + name);
this.protoBlockDict['macro_' + name] = myBlock;
myBlock.palette = this.palettes.dict['myblocks'];
myBlock.zeroArgBlock();
myBlock.staticLabels.push(_(name));
}
this.loadNewBlocks = function(blockObjs) {
// Check for blocks connected to themselves,
// and for action blocks not connected to text blocks.
for (var b = 0; b < blockObjs.length; b++) {
var blkData = blockObjs[b];
for (var c in blkData[4]) {
if (blkData[4][c] == blkData[0]) {
console.log('Circular connection in block data: ' + blkData);
console.log('Punting loading of new blocks!');
console.log(blockObjs);
return;
}
}
}
// We'll need a list of existing storein and action names.
var currentActionNames = [];
var currentStoreinNames = [];
for (var b = 0; b < this.blockList.length; b++) {
if (this.blockList[b].name == 'action') {
if (this.blockList[b].connections[1] != null) {
currentActionNames.push(this.blockList[this.blockList[b].connections[1]].value);
}
} else if (this.blockList[b].name == 'storein') {
if (this.blockList[b].connections[1] != null) {
currentStoreinNames.push(this.blockList[this.blockList[b].connections[1]].value);
}
}
}
// Don't make duplicate action names.
// Add a palette entry for any new storein blocks.
var stringNames = [];
var stringValues = {}; // label: [blocks with that label]
var actionNames = {}; // action block: label block
var storeinNames = {}; // storein block: label block
var doNames = {}; // do block: label block
// Scan for any new action and storein blocks to identify
// duplicates.
for (var b = 0; b < blockObjs.length; b++) {
var blkData = blockObjs[b];
// blkData[1] could be a string or an object.
if (typeof(blkData[1]) == 'string') {
var name = blkData[1];
} else {
var name = blkData[1][0];
}
switch (name) {
case 'text':
var key = blkData[1][1];
if (stringValues[key] == undefined) {
stringValues[key] = [];
}
stringValues[key].push(b);
break;
case 'action':
if (blkData[4][1] != null) {
actionNames[b] = blkData[4][1];
}
case 'hat':
if (blkData[4][1] != null) {
actionNames[b] = blkData[4][1];
}
break;
case 'storein':
if (blkData[4][1] != null) {
storeinNames[b] = blkData[4][1];
}
break;
case 'do':
case 'stack':
if (blkData[4][1] != null) {
doNames[b] = blkData[4][1];
}
break;
default:
break;
}
}
var updatePalettes = false;
// Make sure new storein names have palette entries.
for (var b in storeinNames) {
var blkData = blockObjs[storeinNames[b]];
if (currentStoreinNames.indexOf(blkData[1][1]) == -1) {
console.log('adding new palette entries for ' + blkData[1][1]);
if (typeof(blkData[1][1]) == 'string') {
var name = blkData[1][1];
} else {
var name = blkData[1][1]['value'];
}
console.log(name);
this.newStoreinBlock(name);
this.newBoxBlock(name);
updatePalettes = true;
}
}
console.log(actionNames);
// Make sure action names are unique.
for (var b in actionNames) {
// Is there a proto do block with this name? If so, find a
// new name.
// Name = the value of the connected label.
var blkData = blockObjs[actionNames[b]];
if (typeof(blkData[1][1]) == 'string') {
var name = blkData[1][1];
} else {
var name = blkData[1][1]['value'];
}
var oldName = name;
var i = 0;
while (currentActionNames.indexOf(name) != -1) {
name = blkData[1][1] + i.toString();
i += 1;
// Should never happen... but just in case.
if (i > this.blockList.length) {
console.log('could not generate unique action name');
break;
}
}
// Change the name of the action...
console.log('action ' + oldName + ' is being renamed ' + name);
blkData[1][1] = {
'value': name
};
// add a new do block to the palette...
this.newDoBlock(name);
updatePalettes = true;
// and any do blocks
for (var d in doNames) {
var doBlkData = blockObjs[doNames[d]];
if (typeof(doBlkData[1][1]) == 'string') {
if (doBlkData[1][1] == oldName) {
doBlkData[1][1] = name;
}
} else {
if (doBlkData[1][1]['value'] == oldName) {
doBlkData[1][1] = {
'value': name
};
}
}
}
}
if (updatePalettes) {
this.palettes.updatePalettes();
}
// Append to the current set of blocks.
this.adjustTheseDocks = [];
this.loadCounter = blockObjs.length;
console.log(this.loadCounter + ' blocks to load');
var blockOffset = this.blockList.length;
for (var b = 0; b < this.loadCounter; b++) {
var thisBlock = blockOffset + b;
var blkData = blockObjs[b];
if (typeof(blkData[1]) == 'object') {
if (typeof(blkData[1][1]) == 'number' | typeof(blkData[1][1]) == 'string') {
blkInfo = [blkData[1][0], {
'value': blkData[1][1]
}];
if (['start', 'action', 'hat'].indexOf != -1) {
blkInfo[1]['collapsed'] = false;
}
} else {
blkInfo = blkData[1];
}
} else {
blkInfo = [blkData[1], {
'value': null
}];
if (['start', 'action', 'hat'].indexOf != -1) {
blkInfo[1]['collapsed'] = false;
}
}
var name = blkInfo[0];
var collapsed = false;
if (['start', 'action', 'hat'].indexOf(name) != -1) {
collapsed = blkInfo[1]['collapsed'];
}
var value = blkInfo[1]['value'];
if (name in NAMEDICT) {
name = NAMEDICT[name];
}
var me = this;
// A few special cases.
switch (name) {
// Only add 'collapsed' arg to start, action blocks.
case 'start':
blkData[4][0] = null;
blkData[4][2] = null;
postProcess = function(args) {
var thisBlock = args[0];
var blkInfo = args[1];
me.blockList[thisBlock].value = me.turtles.turtleList.length;
me.turtles.add(me.blockList[thisBlock], blkInfo);
}
this.makeNewBlockWithConnections('start', blockOffset, blkData[4], postProcess, [thisBlock, blkInfo[1]], collapsed);
break;
case 'action':
case 'hat':
blkData[4][0] = null;
blkData[4][3] = null;
this.makeNewBlockWithConnections('action', blockOffset, blkData[4], null, null, collapsed);
break;
// Value blocks need a default value set.
case 'number':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = Number(value);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'text':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'media':
// Load a thumbnail into a media blocks.
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
if (value != null) {
// Load artwork onto media block.
loadThumbnail(me, thisBlock, null);
}
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'camera':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = CAMERAVALUE;
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'video':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = VIDEOVALUE;
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
// Define some constants for legacy blocks for
// backward compatibility with Python projects.
case 'red':
case 'white':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 0;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'orange':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 10;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'yellow':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 20;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'green':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 40;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'blue':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 70;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'leftpos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = -(canvas.width / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'rightpos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = (canvas.width / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'toppos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = (canvas.height / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'botpos':
case 'bottompos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = -(canvas.height / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'width':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = canvas.width;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'height':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = canvas.height;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'loadFile':
postProcess = function(args) {
me.blockList[args[0]].value = args[1];
me.updateBlockText(args[0]);
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
default:
// Check that name is in the proto list
if (!name in this.protoBlockDict || this.protoBlockDict[name] == null) {
// Lots of assumptions here.
// TODO: figure out if it is a flow or an arg block.
// Substitute a NOP block for an unknown block.
n = blkData[4].length;
console.log(n + ': substituting nop block for ' + name);
switch (n) {
case 1:
name = 'nopValueBlock';
break;
case 2:
name = 'nopZeroArgBlock';
break;
case 3:
name = 'nopOneArgBlock';
break;
default:
name = 'nopTwoArgBlock';
break;
}
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], null);
break;
}
if (thisBlock == this.blockList.length - 1) {
if (this.blockList[thisBlock].connections[0] == null) {
this.blockList[thisBlock].x = blkData[2];
this.blockList[thisBlock].y = blkData[3];
this.adjustTheseDocks.push(thisBlock);
}
}
}
}
this.cleanupAfterLoad = function() {
// If all the blocks are loaded, we can make the final adjustments.
this.loadCounter -= 1;
if (this.loadCounter > 0) {
return;
}
this.updateBlockPositions();
for (var blk = 0; blk < this.adjustTheseDocks.length; blk++) {
this.loopCounter = 0;
this.adjustDocks(this.adjustTheseDocks[blk]);
}
this.refreshCanvas();
// FIXME: Make these callbacks so there is no race condition.
// We need to wait for the blocks to load before expanding them.
setTimeout(function() {
blockBlocks.expandTwoArgs();
}, 1000);
setTimeout(function() {
blockBlocks.expandClamps();
}, 2000);
}
blockBlocks = this;
return this;
}
// Define block instance objects and any methods that are intra-block.
function Block(protoblock, blocks) {
if (protoblock == null) {
console.log('null protoblock sent to Block');
return;
}
this.protoblock = protoblock;
this.name = protoblock.name;
this.blocks = blocks;
this.x = 0;
this.y = 0;
this.collapsed = false; // Is this block in a collapsed stack?
this.trash = false; // Is this block in the trash?
this.loadComplete = false; // Has the block finished loading?
this.label = null; // Editable textview in DOM.
this.text = null; // A dynamically generated text label on block itself.
this.value = null; // Value for number, text, and media blocks.
this.image = protoblock.image; // The file path of the image.
// All blocks have at a container and least one bitmap.
this.container = null;
this.bounds = null;
this.bitmap = null;
this.highlightBitmap = null;
// Start and Action blocks has a collapse button (in a separate
// container).
this.collapseContainer = null;
this.collapseBitmap = null;
this.expandBitmap = null;
this.collapseBlockBitmap = null;
this.highlightCollapseBlockBitmap = null;
this.collapseText = null;
this.size = 1; // Proto size is copied here.
this.docks = []; // Proto dock is copied here.
// We save a copy of the dock types because we need to restore
// them after docks change when blocks resize.
this.dockTypes = [];
this.connections = []; // Blocks that cannot be run on their own.
// Keep track of clamp count for blocks with clamps
this.clampCount = [1, 1];
// Some blocks have some post process after they are first loaded.
this.postProcess = null;
this.postProcessArg = null;
this.copySize = function() {
this.size = this.protoblock.size;
}
this.copyDocks = function() {
for (var i in this.protoblock.docks) {
var dock = [this.protoblock.docks[i][0], this.protoblock.docks[i][1], this.protoblock.docks[i][2]];
this.docks.push(dock);
}
}
this.getInfo = function() {
return this.name + ' block';
}
this.highlight = function() {
if (this.collapsed && ['start', 'action'].indexOf(this.name) != -1) {
this.highlightCollapseBlockBitmap.visible = true;
this.collapseBlockBitmap.visible = false;
this.collapseText.visible = true;
} else {
this.bitmap.visible = false;
this.highlightBitmap.visible = true;
if (['start', 'action'].indexOf(this.name) != -1) {
// There could be a race condition when making a
// new action block.
if (this.collapseText != null) {
this.collapseText.visible = false;
}
if (this.collapseBlockBitmap.visible != null) {
this.collapseBlockBitmap.visible = false;
}
if (this.highlightCollapseBlockBitmap.visible != null) {
this.highlightCollapseBlockBitmap.visible = false;
}
}
}
this.container.updateCache();
this.blocks.refreshCanvas();
}
this.unhighlight = function() {
if (this.collapsed && ['start', 'action'].indexOf(this.name) != -1) {
this.highlightCollapseBlockBitmap.visible = false;
this.collapseBlockBitmap.visible = true;
this.collapseText.visible = true;
} else {
this.bitmap.visible = true;
this.highlightBitmap.visible = false;
if (['start', 'action'].indexOf(this.name) != -1) {
this.highlightCollapseBlockBitmap.visible = false;
this.collapseBlockBitmap.visible = false;
this.collapseText.visible = false;
}
}
this.container.updateCache();
this.blocks.refreshCanvas();
}
this.updateSlots = function(clamp, plusMinus, blocksToCheck) {
// Resize an expandable block.
var thisBlock = this.blocks.blockList.indexOf(this);
// First, remove the old artwork.
var targets = ['bmp_highlight_' + thisBlock, 'bmp_' + thisBlock];
var deleteQueue = [];
for (var child = 0; child < this.container.getNumChildren(); child++) {
if (targets.indexOf(this.container.children[child].name) != -1) {
deleteQueue.push(this.container.children[child]);
}
}
for (var child in deleteQueue) {
this.container.removeChild(deleteQueue[child]);
}
// Save the dock types so we can restore them...
this.dockTypes = [];
for (i = 0; i < this.docks.length; i++) {
this.dockTypes.push(this.docks[i][2]);
}
// before clearing the docks (they will be regenerated).
this.docks = [];
this.clampCount[clamp] += plusMinus;
switch (this.name) {
case 'start':
this.protoblock.stackClampZeroArgBlock(this.clampCount[clamp]);
break;
case 'action':
this.protoblock.stackClampOneArgBlock(this.clampCount[clamp]);
break;
case 'repeat':
this.protoblock.flowClampOneArgBlock(this.clampCount[clamp]);
break;
case 'forever':
this.protoblock.flowClampZeroArgBlock(this.clampCount[clamp]);
break;
case 'if':
case 'while':
case 'until':
this.protoblock.flowClampBooleanArgBlock(this.clampCount[clamp]);
break;
case 'ifthenelse':
this.protoblock.doubleFlowClampBooleanArgBlock(this.clampCount[0], this.clampCount[1]);
break;
case 'less':
case 'greater':
case 'equal':
this.protoblock.booleanTwoArgBlock(this.clampCount[0]);
break;
default:
if (this.isArgBlock()) {
this.protoblock.twoArgMathBlock(this.clampCount[0]);
} else if (this.isTwoArgBlock()) {
this.protoblock.twoArgBlock(this.clampCount[0]);
}
break;
}
this.generateArtwork(false, blocksToCheck);
}
this.resetProtoArtwork = function() {
// We may have modified the protoblock artwork. We need to
// reset it.
switch (this.name) {
case 'start':
this.protoblock.stackClampZeroArgBlock();
break;
case 'action':
this.protoblock.stackClampOneArgBlock();
break;
case 'repeat':
this.protoblock.flowClampOneArgBlock();
break;
case 'forever':
this.protoblock.flowClampZeroArgBlock();
break;
case 'if':
case 'while':
case 'until':
this.protoblock.flowClampBooleanArgBlock();
break;
case 'ifthenelse':
this.protoblock.doubleFlowClampBooleanArgBlock();
break;
case 'less':
case 'greater':
case 'equal':
this.protoblock.booleanTwoArgBlock();
break;
default:
if (this.isArgBlock()) {
this.protoblock.twoArgMathBlock();
} else if (this.isTwoArgBlock()) {
this.protoblock.twoArgBlock();
}
break;
}
}
this.imageLoad = function() {
// Load any artwork associated with the block and create any
// extra parts. Image components are loaded asynchronously so
// most the work happens in callbacks.
// We need a label for most blocks.
// TODO: use Text exclusively for all block labels.
this.text = new createjs.Text('', '20px Sans', '#000000');
var doubleExpandable = this.blocks.doubleExpandable;
this.generateArtwork(true, []);
}
this.addImage = function() {
var image = new Image();
var me = this;
image.onload = function() {
var bitmap = new createjs.Bitmap(image);
bitmap.name = 'media';
if (image.width > image.height) {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[2] / image.width;
} else {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[3] / image.height;
}
me.container.addChild(bitmap);
bitmap.x = MEDIASAFEAREA[0] - 10;
bitmap.y = MEDIASAFEAREA[1];
me.container.updateCache();
me.blocks.refreshCanvas();
}
image.src = this.image;
}
this.generateArtwork = function(firstTime, blocksToCheck) {
// Get the block labels from the protoblock
var thisBlock = this.blocks.blockList.indexOf(this);
var block_label = '';
if (this.protoblock.staticLabels.length > 0 && !this.protoblock.image) {
block_label = _(this.protoblock.staticLabels[0]);
}
while (this.protoblock.staticLabels.length < this.protoblock.args + 1) {
this.protoblock.staticLabels.push('');
}
// Create the bitmap for the block.
function processBitmap(name, bitmap, me) {
me.bitmap = bitmap;
me.container.addChild(me.bitmap);
me.bitmap.x = 0;
me.bitmap.y = 0;
me.bitmap.name = 'bmp_' + thisBlock;
me.bitmap.cursor = 'pointer';
me.blocks.refreshCanvas();
// Create the highlight bitmap for the block.
function processHighlightBitmap(name, bitmap, me) {
me.highlightBitmap = bitmap;
me.container.addChild(me.highlightBitmap);
me.highlightBitmap.x = 0;
me.highlightBitmap.y = 0;
me.highlightBitmap.name = 'bmp_highlight_' + thisBlock;
me.highlightBitmap.cursor = 'pointer';
// Hide it to start
me.highlightBitmap.visible = false;
if (me.text != null) {
// Make sure text is on top.
z = me.container.getNumChildren() - 1;
me.container.setChildIndex(me.text, z);
}
// At me point, it should be safe to calculate the
// bounds of the container and cache its contents.
if (!firstTime) {
me.container.uncache();
}
me.bounds = me.container.getBounds();
me.container.cache(me.bounds.x, me.bounds.y, me.bounds.width, me.bounds.height);
me.blocks.refreshCanvas();
if (firstTime) {
loadEventHandlers(blocks, me);
if (me.image != null) {
me.addImage();
}
me.finishImageLoad();
} else {
if (me.name == 'start') {
// Find the turtle decoration and move it to the top.
for (var child = 0; child < me.container.getNumChildren(); child++) {
if (me.container.children[child].name == 'decoration') {
me.container.setChildIndex(me.container.children[child], me.container.getNumChildren() - 1);
break;
}
}
}
me.copyDocks();
// Restore the dock types.
for (i = 0; i < me.docks.length; i++) {
me.docks[i][2] = me.dockTypes[i];
}
// Restore protoblock artwork to its original state.
me.resetProtoArtwork();
// Adjust the docks.
me.blocks.loopCounter = 0;
me.blocks.adjustDocks(thisBlock);
if (blocksToCheck.length > 0) {
if (me.isArgBlock() || me.isTwoArgBlock()) {
me.blocks.adjustExpandableTwoArgBlock(blocksToCheck);
} else {
me.blocks.adjustExpandableClampBlock(blocksToCheck);
}
}
}
}
var artwork = me.protoblock.artwork.replace(/fill_color/g, PALETTEHIGHLIGHTCOLORS[me.protoblock.palette.name]).replace(/stroke_color/g, HIGHLIGHTSTROKECOLORS[me.protoblock.palette.name]).replace('block_label', block_label);
for (var i = 1; i < me.protoblock.staticLabels.length; i++) {
artwork = artwork.replace('arg_label_' + i, _(me.protoblock.staticLabels[i]));
}
makeBitmap(artwork, me.name, processHighlightBitmap, me);
}
var artwork = this.protoblock.artwork.replace(/fill_color/g, PALETTEFILLCOLORS[this.protoblock.palette.name]).replace(/stroke_color/g, PALETTESTROKECOLORS[this.protoblock.palette.name]).replace('block_label', block_label);
if (this.protoblock.staticLabels.length > 1 && !this.protoblock.image) {
top_label = _(this.protoblock.staticLabels[1]);
}
for (var i = 1; i < this.protoblock.staticLabels.length; i++) {
artwork = artwork.replace('arg_label_' + i, _(this.protoblock.staticLabels[i]));
}
makeBitmap(artwork, this.name, processBitmap, this);
}
this.finishImageLoad = function() {
var thisBlock = this.blocks.blockList.indexOf(this);
// Value blocks get a modifiable text label
if (this.name == 'text' || this.name == 'number') {
if (this.value == null) {
if (this.name == 'text') {
this.value = '---';
} else {
this.value = 100;
}
}
var label = this.value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
this.text.text = label;
this.text.textAlign = 'center';
this.text.textBaseline = 'alphabetic';
this.container.addChild(this.text);
this.text.x = VALUETEXTX;
this.text.y = VALUETEXTY;
// Make sure text is on top.
z = this.container.getNumChildren() - 1;
this.container.setChildIndex(this.text, z);
this.container.updateCache();
}
if (this.protoblock.parameter) {
// Parameter blocks get a text label to show their current value
this.text.textAlign = 'right';
this.text.textBaseline = 'alphabetic';
this.container.addChild(this.text);
if (this.name == 'box') {
this.text.x = BOXTEXTX;
} else {
this.text.x = PARAMETERTEXTX;
}
this.text.y = VALUETEXTY;
z = this.container.getNumChildren() - 1;
this.container.setChildIndex(this.text, z);
this.container.updateCache();
}
this.loadComplete = true;
if (this.postProcess != null) {
this.postProcess(this.postProcessArg);
}
this.blocks.refreshCanvas();
this.blocks.cleanupAfterLoad();
// Start blocks and Action blocks can collapse, so add an
// event handler
if (['start', 'action'].indexOf(this.name) != -1) {
block_label = ''; // We use a Text element for the label
function processCollapseBitmap(name, bitmap, me) {
me.collapseBlockBitmap = bitmap;
me.collapseBlockBitmap.name = 'collapse_' + thisBlock;
me.container.addChild(me.collapseBlockBitmap);
me.collapseBlockBitmap.visible = false;
me.blocks.refreshCanvas();
}
var proto = new ProtoBlock('collapse');
proto.basicBlockCollapsed();
var artwork = proto.artwork;
makeBitmap(artwork.replace(/fill_color/g, PALETTEFILLCOLORS[this.protoblock.palette.name]).replace(/stroke_color/g, PALETTESTROKECOLORS[this.protoblock.palette.name]).replace('block_label', _(block_label)), '', processCollapseBitmap, this);
function processHighlightCollapseBitmap(name, bitmap, me) {
me.highlightCollapseBlockBitmap = bitmap;
me.highlightCollapseBlockBitmap.name = 'highlight_collapse_' + thisBlock;
me.container.addChild(me.highlightCollapseBlockBitmap);
me.highlightCollapseBlockBitmap.visible = false;
me.blocks.refreshCanvas();
if (me.name == 'action') {
me.collapseText = new createjs.Text('action', '20px Sans', '#000000');
me.collapseText.x = ACTIONTEXTX;
me.collapseText.y = ACTIONTEXTY;
me.collapseText.textAlign = 'right';
} else {
me.collapseText = new createjs.Text('start', '20px Sans', '#000000');
me.collapseText.x = STARTTEXTX;
me.collapseText.y = ACTIONTEXTY;
me.collapseText.textAlign = 'left';
}
me.collapseText.textBaseline = 'alphabetic';
me.container.addChild(me.collapseText);
me.collapseText.visible = false;
me.collapseContainer = new createjs.Container();
me.collapseContainer.snapToPixelEnabled = true;
var image = new Image();
image.onload = function() {
me.collapseBitmap = new createjs.Bitmap(image);
me.collapseContainer.addChild(me.collapseBitmap);
finishCollapseButton(me);
}
image.src = 'images/collapse.svg';
finishCollapseButton = function(me) {
var image = new Image();
image.onload = function() {
me.expandBitmap = new createjs.Bitmap(image);
me.collapseContainer.addChild(me.expandBitmap);
me.expandBitmap.visible = false;
var bounds = me.collapseContainer.getBounds();
me.collapseContainer.cache(bounds.x, bounds.y, bounds.width, bounds.height);
me.blocks.stage.addChild(me.collapseContainer);
me.collapseContainer.x = me.container.x + COLLAPSEBUTTONXOFF;
me.collapseContainer.y = me.container.y + COLLAPSEBUTTONYOFF;
loadCollapsibleEventHandlers(me.blocks, me);
}
image.src = 'images/expand.svg';
}
}
var artwork = proto.artwork;
makeBitmap(artwork.replace(/fill_color/g, PALETTEHIGHLIGHTCOLORS[this.protoblock.palette.name]).replace(/stroke_color/g, HIGHLIGHTSTROKECOLORS[this.protoblock.palette.name]).replace('block_label', block_label), '', processHighlightCollapseBitmap, this);
}
}
this.hide = function() {
this.container.visible = false;
if (this.collapseContainer != null) {
this.collapseContainer.visible = false;
this.collapseText.visible = false;
}
}
this.show = function() {
if (!this.trash) {
// If it is an action block or it is not collapsed then show it.
if (!(['action', 'start'].indexOf(this.name) == -1 && this.collapsed)) {
this.container.visible = true;
if (this.collapseContainer != null) {
this.collapseContainer.visible = true;
this.collapseText.visible = true;
}
}
}
}
// Utility functions
this.isValueBlock = function() {
return this.protoblock.style == 'value';
}
this.isArgBlock = function() {
return this.protoblock.style == 'value' || this.protoblock.style == 'arg';
}
this.isTwoArgBlock = function() {
return this.protoblock.style == 'twoarg';
}
this.isClampBlock = function() {
return this.protoblock.style == 'clamp' || this.isDoubleClampBlock();
}
this.isDoubleClampBlock = function() {
return this.protoblock.style == 'doubleclamp';
}
this.isNoRunBlock = function() {
return this.name == 'action';
}
this.isExpandableBlock = function() {
return this.protoblock.expandable;
}
// Based on the block index into the blockList.
this.getBlockId = function() {
var number = blockBlocks.blockList.indexOf(this);
return '_' + number.toString();
}
}
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = docById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
// Update the block values as they change in the DOM label
function labelChanged(myBlock) {
// For some reason, arg passing from the DOM is not working
// properly, so we need to find the label that changed.
if (myBlock == null) {
return;
}
var oldValue = myBlock.value;
var newValue = myBlock.label.value;
// Update the block value and block text.
if (myBlock.name == 'number') {
try {
myBlock.value = Number(newValue);
console.log('assigned ' + myBlock.value + ' to number block (' + typeof(myBlock.value) + ')');
} catch (e) {
console.log(e);
// FIXME: Expose errorMsg to blocks
// errorMsg('Not a number.');
}
} else {
myBlock.value = newValue;
}
var label = myBlock.value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
myBlock.text.text = label;
// and hide the DOM textview...
myBlock.label.style.display = 'none';
// Make sure text is on top.
var z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.text, z);
try {
myBlock.container.updateCache();
} catch (e) {
console.log(e);
}
myBlock.blocks.refreshCanvas();
// TODO: Don't allow duplicate action names
var c = myBlock.connections[0];
if (myBlock.name == 'text' && c != null) {
var cblock = myBlock.blocks.blockList[c];
console.log('label changed' + ' ' + myBlock.name);
switch (cblock.name) {
case 'action':
// If the label was the name of an action, update the
// associated run myBlock.blocks and the palette buttons
if (myBlock.value != _('action')) {
myBlock.blocks.newDoBlock(myBlock.value);
}
console.log('rename action: ' + myBlock.value);
myBlock.blocks.renameDos(oldValue, newValue);
myBlock.blocks.palettes.updatePalettes();
break;
case 'storein':
// If the label was the name of a storein, update the
//associated box myBlock.blocks and the palette buttons
if (myBlock.value != 'box') {
myBlock.blocks.newStoreinBlock(myBlock.value);
myBlock.blocks.newBoxBlock(myBlock.value);
}
myBlock.blocks.renameBoxes(oldValue, newValue);
myBlock.blocks.palettes.updatePalettes();
break;
}
}
}
function removeChildBitmap(myBlock, name) {
for (var child = 0; child < myBlock.container.getNumChildren(); child++) {
if (myBlock.container.children[child].name == name) {
myBlock.container.removeChild(myBlock.container.children[child]);
break;
}
}
}
// Load an image thumbnail onto block.
function loadThumbnail(blocks, thisBlock, imagePath) {
if (blocks.blockList[thisBlock].value == null && imagePath == null) {
console.log('loadThumbnail: no image to load?');
return;
}
var image = new Image();
image.onload = function() {
var myBlock = blocks.blockList[thisBlock];
// Before adding new artwork, remove any old artwork.
removeChildBitmap(myBlock, 'media');
var bitmap = new createjs.Bitmap(image);
bitmap.name = 'media';
if (image.width > image.height) {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[2] / image.width;
} else {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[3] / image.height;
}
myBlock.container.addChild(bitmap);
bitmap.x = MEDIASAFEAREA[0] - 10;
bitmap.y = MEDIASAFEAREA[1];
myBlock.container.updateCache();
blocks.refreshCanvas();
}
if (imagePath == null) {
image.src = blocks.blockList[thisBlock].value;
} else {
image.src = imagePath;
}
}
// Open a file from the DOM.
function doOpenMedia(blocks, thisBlock) {
var fileChooser = docById('myMedia');
fileChooser.addEventListener('change', function(event) {
var reader = new FileReader();
reader.onloadend = (function() {
if (reader.result) {
var dataURL = reader.result;
blocks.blockList[thisBlock].value = reader.result
if (blocks.blockList[thisBlock].container.children.length > 2) {
blocks.blockList[thisBlock].container.removeChild(last(blocks.blockList[thisBlock].container.children));
}
thisBlock.image = null;
blocks.refreshCanvas();
loadThumbnail(blocks, thisBlock, null);
}
});
reader.readAsDataURL(fileChooser.files[0]);
}, false);
fileChooser.focus();
fileChooser.click();
}
function doOpenFile(blocks, thisBlock) {
var fileChooser = docById('myOpenAll');
var block = blocks.blockList[thisBlock];
fileChooser.addEventListener('change', function(event) {
var reader = new FileReader();
reader.onloadend = (function() {
if (reader.result) {
block.value = [fileChooser.files[0].name, reader.result];
blocks.updateBlockText(thisBlock);
}
});
reader.readAsText(fileChooser.files[0]);
}, false);
fileChooser.focus();
fileChooser.click();
}
// TODO: Consolidate into loadEventHandlers
// These are the event handlers for collapsible blocks.
function loadCollapsibleEventHandlers(blocks, myBlock) {
var thisBlock = blocks.blockList.indexOf(myBlock);
var bounds = myBlock.collapseContainer.getBounds();
var hitArea = new createjs.Shape();
var w2 = bounds.width;
var h2 = bounds.height;
hitArea.graphics.beginFill('#FFF').drawEllipse(-w2 / 2, -h2 / 2, w2, h2);
hitArea.x = w2 / 2;
hitArea.y = h2 / 2;
myBlock.collapseContainer.hitArea = hitArea;
myBlock.collapseContainer.on('mouseover', function(event) {
blocks.highlight(thisBlock, true);
blocks.activeBlock = thisBlock;
blocks.refreshCanvas();
});
var moved = false;
var locked = false;
myBlock.collapseContainer.on('click', function(event) {
if (locked) {
return;
}
locked = true;
setTimeout(function() {
locked = false;
}, 500);
hideDOMLabel();
if (!moved) {
collapseToggle(blocks, myBlock);
}
});
myBlock.collapseContainer.on('mousedown', function(event) {
hideDOMLabel();
// Always show the trash when there is a block selected.
trashcan.show();
moved = false;
var offset = {
x: myBlock.collapseContainer.x - Math.round(event.stageX / blocks.scale),
y: myBlock.collapseContainer.y - Math.round(event.stageY / blocks.scale)
};
myBlock.collapseContainer.on('pressup', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
myBlock.collapseContainer.on('mouseout', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
myBlock.collapseContainer.on('pressmove', function(event) {
moved = true;
var oldX = myBlock.collapseContainer.x;
var oldY = myBlock.collapseContainer.y;
myBlock.collapseContainer.x = Math.round(event.stageX / blocks.scale + offset.x);
myBlock.collapseContainer.y = Math.round(event.stageY / blocks.scale + offset.y);
var dx = myBlock.collapseContainer.x - oldX;
var dy = myBlock.collapseContainer.y - oldY;
myBlock.container.x += dx;
myBlock.container.y += dy;
myBlock.x = myBlock.container.x;
myBlock.y = myBlock.container.y;
// If we are over the trash, warn the user.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
trashcan.highlight();
} else {
trashcan.unhighlight();
}
blocks.findDragGroup(thisBlock)
if (blocks.dragGroup.length > 0) {
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
if (b != 0) {
blocks.moveBlockRelative(blk, dx, dy);
}
}
}
blocks.refreshCanvas();
});
});
myBlock.collapseContainer.on('pressup', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
myBlock.collapseContainer.on('mouseout', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
}
function collapseToggle(blocks, myBlock) {
if (['start', 'action'].indexOf(myBlock.name) == -1) {
// Should not happen, but just in case.
return;
}
// Find the blocks to collapse/expand
var thisBlock = blocks.blockList.indexOf(myBlock);
blocks.findDragGroup(thisBlock)
function toggle(collapse) {
if (myBlock.collapseBitmap == null) {
console.log('collapse bitmap not ready');
return;
}
myBlock.collapsed = !collapse;
myBlock.collapseBitmap.visible = collapse;
myBlock.expandBitmap.visible = !collapse;
myBlock.collapseBlockBitmap.visible = !collapse;
myBlock.highlightCollapseBlockBitmap.visible = false;
myBlock.collapseText.visible = !collapse;
if (myBlock.bitmap != null) {
myBlock.bitmap.visible = false;
}
if (myBlock.highlightBitmap != null) {
myBlock.highlightBitmap.visible = collapse;
}
if (myBlock.name != 'start') {
// Label the collapsed block with the action label
if (myBlock.connections[1] != null) {
myBlock.collapseText.text = blocks.blockList[myBlock.connections[1]].value;
} else {
myBlock.collapseText.text = '';
}
}
var z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.collapseText, z);
if (blocks.dragGroup.length > 0) {
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
if (b != 0) {
blocks.blockList[blk].collapsed = !collapse;
blocks.blockList[blk].container.visible = collapse;
}
}
}
}
toggle(myBlock.collapsed);
myBlock.collapseContainer.updateCache();
myBlock.container.updateCache();
blocks.refreshCanvas();
return;
}
function collapseOut(blocks, myBlock, thisBlock, moved, event) {
// Always hide the trash when there is no block selected.
trashcan.hide();
blocks.unhighlight(thisBlock);
if (moved) {
// Check if block is in the trash.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
sendStackToTrash(blocks, myBlock);
} else {
// Otherwise, process move.
blocks.blockMoved(thisBlock);
}
}
if (blocks.activeBlock != myBlock) {
return;
}
blocks.unhighlight(null);
blocks.activeBlock = null;
blocks.refreshCanvas();
}
// These are the event handlers for block containers.
function loadEventHandlers(blocks, myBlock) {
var thisBlock = blocks.blockList.indexOf(myBlock);
var hitArea = new createjs.Shape();
var bounds = myBlock.container.getBounds()
// Only detect hits on top section of block.
if (myBlock.isClampBlock()) {
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, bounds.width, STANDARDBLOCKHEIGHT);
} else {
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, bounds.width, bounds.height);
}
myBlock.container.hitArea = hitArea;
myBlock.container.on('mouseover', function(event) {
blocks.highlight(thisBlock, true);
blocks.activeBlock = thisBlock;
blocks.refreshCanvas();
});
var moved = false;
var locked = false;
myBlock.container.on('click', function(event) {
if (locked) {
return;
}
locked = true;
setTimeout(function() {
locked = false;
}, 500);
hideDOMLabel();
if (!moved) {
if (blocks.selectingStack) {
var topBlock = blocks.findTopBlock(thisBlock);
blocks.selectedStack = topBlock;
blocks.selectingStack = false;
} else if (myBlock.name == 'media') {
doOpenMedia(blocks, thisBlock);
} else if (myBlock.name == 'loadFile') {
doOpenFile(blocks, thisBlock);
} else if (myBlock.name == 'text' || myBlock.name == 'number') {
var x = myBlock.container.x
var y = myBlock.container.y
var canvasLeft = blocks.canvas.offsetLeft + 28;
var canvasTop = blocks.canvas.offsetTop + 6;
if (myBlock.name == 'text') {
labelElem.innerHTML = '<textarea id="' + 'textLabel' +
'" style="position: absolute; ' +
'-webkit-user-select: text;-moz-user-select: text;-ms-user-select: text;" ' +
'class="text", ' +
'onkeypress="if(event.keyCode==13){return false;}"' +
'cols="8", rows="1", maxlength="256">' +
myBlock.value + '</textarea>';
myBlock.label = docById('textLabel');
myBlock.label.addEventListener(
'change',
function() {
labelChanged(myBlock);
});
myBlock.label.style.left = Math.round((x + blocks.stage.x) * blocks.scale + canvasLeft) + 'px';
myBlock.label.style.top = Math.round((y + blocks.stage.y) * blocks.scale + canvasTop) + 'px';
myBlock.label.style.display = '';
myBlock.label.focus();
} else {
labelElem.innerHTML = '<textarea id="' + 'numberLabel' +
'" style="position: absolute; ' +
'-webkit-user-select: text;-moz-user-select: text;-ms-user-select: text;" ' +
'class="number", ' +
'onkeypress="if(event.keyCode==13){return false;}"' +
'cols="8", rows="1", maxlength="8">' +
myBlock.value + '</textarea>';
myBlock.label = docById('numberLabel');
myBlock.label.addEventListener(
'change',
function() {
labelChanged(myBlock);
});
myBlock.label.style.left = Math.round((x + blocks.stage.x) * blocks.scale + canvasLeft) + 'px';
myBlock.label.style.top = Math.round((y + blocks.stage.y) * blocks.scale + canvasTop) + 'px';
myBlock.label.style.display = '';
myBlock.label.focus();
}
} else {
if (!blocks.inLongPress) {
var topBlock = blocks.findTopBlock(thisBlock);
console.log('running from ' + blocks.blockList[topBlock].name);
blocks.logo.runLogoCommands(topBlock);
}
}
}
});
myBlock.container.on('mousedown', function(event) {
hideDOMLabel();
// Track time for detecting long pause...
// but only for top block in stack
if (myBlock.connections[0] == null) {
var d = new Date();
blocks.time = d.getTime();
blocks.timeOut = setTimeout(function() {
blocks.triggerLongPress(myBlock);
}, LONGPRESSTIME);
}
// Always show the trash when there is a block selected.
trashcan.show();
// Bump the bitmap in front of its siblings.
blocks.stage.setChildIndex(myBlock.container, blocks.stage.getNumChildren() - 1);
if (myBlock.collapseContainer != null) {
blocks.stage.setChildIndex(myBlock.collapseContainer, blocks.stage.getNumChildren() - 1);
}
moved = false;
var offset = {
x: myBlock.container.x - Math.round(event.stageX / blocks.scale),
y: myBlock.container.y - Math.round(event.stageY / blocks.scale)
};
myBlock.container.on('mouseout', function(event) {
if (!blocks.inLongPress) {
mouseoutCallback(blocks, myBlock, event, moved);
}
moved = false;
});
myBlock.container.on('pressup', function(event) {
if (!blocks.inLongPress) {
mouseoutCallback(blocks, myBlock, event, moved);
}
moved = false;
});
myBlock.container.on('pressmove', function(event) {
// FIXME: More voodoo
event.nativeEvent.preventDefault();
// FIXME: need to remove timer
if (blocks.timeOut != null) {
clearTimeout(blocks.timeOut);
blocks.timeOut = null;
}
if (!moved && myBlock.label != null) {
myBlock.label.style.display = 'none';
}
moved = true;
var oldX = myBlock.container.x;
var oldY = myBlock.container.y;
myBlock.container.x = Math.round(event.stageX / blocks.scale) + offset.x;
myBlock.container.y = Math.round(event.stageY / blocks.scale) + offset.y;
myBlock.x = myBlock.container.x;
myBlock.y = myBlock.container.y;
var dx = Math.round(myBlock.container.x - oldX);
var dy = Math.round(myBlock.container.y - oldY);
// If we are over the trash, warn the user.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
trashcan.highlight();
} else {
trashcan.unhighlight();
}
if (myBlock.isValueBlock() && myBlock.name != 'media') {
// Ensure text is on top
var z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.text, z);
} else if (myBlock.collapseContainer != null) {
myBlock.collapseContainer.x = myBlock.container.x + COLLAPSEBUTTONXOFF;
myBlock.collapseContainer.y = myBlock.container.y + COLLAPSEBUTTONYOFF;
}
// Move any connected blocks.
blocks.findDragGroup(thisBlock)
if (blocks.dragGroup.length > 0) {
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
if (b != 0) {
blocks.moveBlockRelative(blk, dx, dy);
}
}
}
blocks.refreshCanvas();
});
});
myBlock.container.on('mouseout', function(event) {
if (!blocks.inLongPress) {
mouseoutCallback(blocks, myBlock, event, moved);
}
});
}
function hideDOMLabel() {
var textLabel = docById('textLabel');
if (textLabel != null) {
textLabel.style.display = 'none';
}
var numberLabel = docById('numberLabel');
if (numberLabel != null) {
numberLabel.style.display = 'none';
}
}
function displayMsg(blocks, text) {
return;
var msgContainer = blocks.msgText.parent;
msgContainer.visible = true;
blocks.msgText.text = text;
msgContainer.updateCache();
blocks.stage.setChildIndex(msgContainer, blocks.stage.getNumChildren() - 1);
}
function mouseoutCallback(blocks, myBlock, event, moved) {
var thisBlock = blocks.blockList.indexOf(myBlock);
// Always hide the trash when there is no block selected.
// FIXME: need to remove timer
if (blocks.timeOut != null) {
clearTimeout(blocks.timeOut);
blocks.timeOut = null;
}
trashcan.hide();
if (moved) {
// Check if block is in the trash.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
sendStackToTrash(blocks, myBlock);
} else {
// Otherwise, process move.
blocks.blockMoved(thisBlock);
}
}
if (blocks.activeBlock != myBlock) {
return;
}
blocks.unhighlight(null);
blocks.activeBlock = null;
blocks.refreshCanvas();
}
function sendStackToTrash(blocks, myBlock) {
var thisBlock = blocks.blockList.indexOf(myBlock);
// disconnect block
var b = myBlock.connections[0];
if (b != null) {
for (var c in blocks.blockList[b].connections) {
if (blocks.blockList[b].connections[c] == thisBlock) {
blocks.blockList[b].connections[c] = null;
break;
}
}
myBlock.connections[0] = null;
}
if (myBlock.name == 'start') {
turtle = myBlock.value;
if (turtle != null) {
console.log('putting turtle ' + turtle + ' in the trash');
blocks.turtles.turtleList[turtle].trash = true;
blocks.turtles.turtleList[turtle].container.visible = false;
} else {
console.log('null turtle');
}
}
if (myBlock.name == 'action') {
var actionArg = blocks.blockList[myBlock.connections[1]];
var actionName = actionArg.value;
for (var blockId = 0; blockId < blocks.blockList.length; blockId++) {
var myBlk = blocks.blockList[blockId];
var blkParent = blocks.blockList[myBlk.connections[0]];
if (blkParent == null) {
continue;
}
if (['do', 'action'].indexOf(blkParent.name) != -1) {
continue;
}
var blockValue = myBlk.value;
if (blockValue == _('action')) {
continue;
}
if (blockValue == actionName) {
blkParent.hide();
myBlk.hide();
myBlk.trash = true;
blkParent.trash = true;
}
}
var blockPalette = blocks.palettes.dict['blocks'];
var blockRemoved = false;
for (var blockId = 0; blockId < blockPalette.protoList.length; blockId++) {
var block = blockPalette.protoList[blockId];
if (block.name == 'do' && block.defaults[0] != _('action') && block.defaults[0] == actionName) {
blockPalette.protoList.splice(blockPalette.protoList.indexOf(block), 1);
delete blocks.protoBlockDict['myDo_' + actionName];
blockPalette.y = 0;
blockRemoved = true;
}
}
// Force an update if a block was removed.
if (blockRemoved) {
regeneratePalette(blockPalette);
}
}
// put drag group in trash
blocks.findDragGroup(thisBlock);
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
console.log('putting ' + blocks.blockList[blk].name + ' in the trash');
blocks.blockList[blk].trash = true;
blocks.blockList[blk].hide();
blocks.refreshCanvas();
}
}
function makeBitmap(data, name, callback, args) {
// Async creation of bitmap from SVG data
// Works with Chrome, Safari, Firefox (untested on IE)
var img = new Image();
img.onload = function() {
bitmap = new createjs.Bitmap(img);
callback(name, bitmap, args);
}
img.src = 'data:image/svg+xml;base64,' + window.btoa(
unescape(encodeURIComponent(data)));
}
function regeneratePalette(palette) {
palette.visible = false;
palette.hideMenuItems();
palette.protoContainers = {};
palette.protoBackgrounds = {};
palette.palettes.updatePalettes();
}
| js/blocks.js | // Copyright (c) 2014,2015 Walter Bender
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// You should have received a copy of the GNU General Public License
// along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
// All things related to blocks
// A place in the DOM to put modifiable labels (textareas).
var labelElem = docById('labelDiv');
var blockBlocks = null;
// Minimum distance (squared) between to docks required before
// connecting them.
var MINIMUMDOCKDISTANCE = 400;
// Special value flags to uniquely identify these media blocks.
var CAMERAVALUE = '##__CAMERA__##';
var VIDEOVALUE = '##__VIDEO__##';
// Length of a long touch
var LONGPRESSTIME = 2000;
// There are three "classes" defined in this file: ProtoBlocks,
// Blocks, and Block. Protoblocks are the prototypes from which Blocks
// are created; Blocks is the list of all blocks; and Block is a block
// instance.
// Protoblock contain generic information about blocks and some
// methods common to all blocks.
function ProtoBlock(name) {
// Name is used run-dictionary index, and palette label.
this.name = name;
// The palette to which this block is assigned.
this.palette = null;
// The graphic style used by the block.
this.style = null;
// Does the block expand (or collapse) when other blocks are
// attached? e.g., start, repeat...
this.expandable = false;
// Is this block a parameter? Parameters have their labels
// overwritten with their current value.
this.parameter = false;
// How many "non-flow" arguments does a block have? (flow is
// vertical down a stack; args are horizontal. The pendown block
// has 0 args; the forward block has 1 arg; the setxy block has 2
// args.
this.args = 0;
// Default values for block parameters, e.g., forward 100 or right 90.
this.defaults = [];
// What is the size of the block prior to any expansion?
this.size = 1;
// Static labels are generated as part of the inline SVG.
this.staticLabels = [];
// Default fontsize used for static labels.
this.fontsize = null;
// Extra block width for long labels
this.extraWidth = 0;
// Block scale
this.scale = 2;
// The SVG template used to generate the block graphic.
this.artwork = null;
// Docks define where blocks connect and which connections are
// valid.
this.docks = [];
// The filepath of the image.
this.image = null;
// Hidden: don't show on any palette
this.hidden = false;
// We need a copy of the dock, since it is modified by individual
// blocks as they are expanded or contracted.
this.copyDock = function(dockStyle) {
this.docks = [];
for (var i = 0; i < dockStyle.length; i++) {
var dock = [dockStyle[i][0], dockStyle[i][1], dockStyle[i][2]];
this.docks.push(dock);
}
}
// What follows are the initializations for different block
// styles.
// E.g., penup, pendown
this.zeroArgBlock = function() {
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('in');
this.copyDock(svg.docks);
}
// E.g., break
this.basicBlockNoFlow = function() {
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(true);
svg.setTail(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., collapsed
this.basicBlockCollapsed = function() {
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setCap(true);
svg.setTail(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('unavailable');
svg.docks[1].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., forward, right
this.oneArgBlock = function() {
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setInnies([true]);
svg.setSlot(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('numberin');
svg.docks[2].push('in');
this.copyDock(svg.docks);
}
// E.g., wait for
this.oneBooleanArgBlock = function() {
this.args = 1;
this.size = 3;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setBoolean(true);
svg.setClampCount(0);
svg.setExpand(0, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('in');
svg.docks[1].push('booleanin');
svg.docks[2].push('out');
this.copyDock(svg.docks);
}
// E.g., setxy. These are expandable.
this.twoArgBlock = function(expandY) {
this.expandable = true;
this.style = 'twoarg';
this.size = 2;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setInnies([true, true]);
svg.setSlot(true);
if (expandY) {
svg.setExpand(30 + this.extraWidth, (expandY - 1) * STANDARDBLOCKHEIGHT / 2, 0, 0);
} else if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('out');
svg.docks[1].push('numberin');
svg.docks[2].push('numberin');
svg.docks[3].push('in');
this.copyDock(svg.docks);
}
// E.g., sqrt
this.oneArgMathBlock = function() {
this.style = 'arg';
this.size = 1;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(false);
svg.setInnies([true]);
svg.setOutie(true);
svg.setTab(false);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('numberout');
svg.docks[1].push('numberin');
this.copyDock(svg.docks);
}
// E.g., box
this.oneArgMathWithLabelBlock = function() {
this.style = 'arg';
this.size = 1;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(false);
svg.setInnies([true]);
svg.setOutie(true);
svg.setTab(false);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('numberout');
svg.docks[0].push('numberin');
this.copyDock(svg.docks);
}
// E.g., plus, minus, multiply, divide. These are also expandable.
this.twoArgMathBlock = function(expandY) {
this.expandable = true;
this.style = 'arg';
this.size = 2;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setSlot(false);
svg.setInnies([true, true]);
svg.setOutie(true);
svg.setTab(false);
if (expandY) {
svg.setExpand(30 + this.extraWidth, (expandY - 1) * STANDARDBLOCKHEIGHT / 2, 0, 0);
} else if (this.extraWidth != 0) {
svg.setExpand(30 + this.extraWidth, 0, 0, 0);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBlock();
svg.docks[0].push('numberout');
svg.docks[1].push('numberin');
svg.docks[2].push('numberin');
this.copyDock(svg.docks);
}
// E.g., number, string. Value blocks get DOM textareas associated
// with them so their values can be edited by the user.
this.valueBlock = function() {
this.style = 'value';
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(60 + this.extraWidth, 0, 0, 0);
svg.setOutie(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBox();
svg.docks[0].push('numberout');
this.copyDock(svg.docks);
}
// E.g., media. Media blocks invoke a chooser and a thumbnail
// image is overlayed to represent the data associated with the
// block.
this.mediaBlock = function() {
this.style = 'value';
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(60 + this.extraWidth, 23, 0, 0);
svg.setOutie(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBox();
svg.docks[0].push('mediaout');
this.copyDock(svg.docks);
}
// E.g., start. A "child" flow is docked in an expandable clamp.
// There are no additional arguments and no flow above or below.
this.stackClampZeroArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setCap(true);
svg.setTail(true);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('unavailable');
svg.docks[1].push('in');
svg.docks[2].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., repeat. Unlike action, there is a flow above and below.
this.flowClampOneArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setInnies([true]);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('numberin');
svg.docks[2].push('in');
svg.docks[3].push('in');
this.copyDock(svg.docks);
}
// E.g., if. A "child" flow is docked in an expandable clamp. The
// additional argument is a boolean. There is flow above and below.
this.flowClampBooleanArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 3;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setBoolean(true);
svg.setSlot(true);
svg.setExpand(this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('booleanin');
svg.docks[2].push('in');
svg.docks[3].push('in');
this.copyDock(svg.docks);
}
// E.g., if then else. Two "child" flows are docked in expandable
// clamps. The additional argument is a boolean. There is flow
// above and below.
this.doubleFlowClampBooleanArgBlock = function(bottomSlots, topSlots) {
this.style = 'doubleclamp';
this.expandable = true;
this.size = 4;
this.args = 3;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setBoolean(true);
svg.setClampCount(this.scale);
if (topSlots) {
svg.setClampSlots(0, topSlots);
} else {
svg.setClampSlots(0, 1);
}
if (bottomSlots) {
svg.setClampSlots(1, bottomSlots);
} else {
svg.setClampSlots(1, 1);
}
svg.setExpand(this.extraWidth, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('booleanin');
svg.docks[2].push('in');
svg.docks[3].push('in');
svg.docks[4].push('in');
this.copyDock(svg.docks);
}
// E.g., forever. Unlike start, there is flow above and below.
this.flowClampZeroArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setTab(true);
svg.setSlot(true);
svg.setExpand(10 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('out');
svg.docks[1].push('in');
svg.docks[2].push('in');
this.copyDock(svg.docks);
}
// E.g., action. A "child" flow is docked in an expandable clamp.
// The additional argument is a name. Again, no flow above or below.
this.stackClampOneArgBlock = function(slots) {
this.style = 'clamp';
this.expandable = true;
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setCap(true);
svg.setTail(true);
svg.setInnies([true]);
svg.setExpand(10 + this.extraWidth, 0, 0, 0);
if (slots) {
svg.setClampSlots(0, slots);
} else {
svg.setClampSlots(0, 1);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicClamp();
svg.docks[0].push('unavailable');
svg.docks[1].push('anyin');
svg.docks[2].push('in');
svg.docks[3].push('unavailable');
this.copyDock(svg.docks);
}
// E.g., mouse button.
this.booleanZeroArgBlock = function() {
this.style = 'arg';
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(60 + this.extraWidth, 0, 0, 4);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanNot(true);
svg.docks[0].push('booleanout');
this.copyDock(svg.docks);
}
// E.g., not
this.booleanOneBooleanArgBlock = function() {
this.style = 'arg';
this.size = 2;
this.args = 1;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanNot(false);
svg.docks[0].push('booleanout');
svg.docks[1].push('booleanin');
this.copyDock(svg.docks);
}
// E.g., and
this.booleanTwoBooleanArgBlock = function() {
this.style = 'arg';
this.size = 3;
this.args = 2;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(20 + this.extraWidth, 0, 0, 0);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanAndOr();
svg.docks[0].push('booleanout');
svg.docks[1].push('booleanin');
svg.docks[2].push('booleanin');
this.copyDock(svg.docks);
}
// E.g., greater, less, equal
this.booleanTwoArgBlock = function(expandY) {
this.style = 'arg';
this.size = 2;
this.args = 2;
this.expandable = true;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
if (expandY) {
svg.setExpand(10 + this.extraWidth, (expandY - 1) * STANDARDBLOCKHEIGHT / 2, 0, 0);
} else {
svg.setExpand(10 + this.extraWidth, 0, 0, 0);
}
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.booleanCompare();
svg.docks[0].push('booleanout');
svg.docks[1].push('numberin');
svg.docks[2].push('numberin');
this.copyDock(svg.docks);
}
// E.g., color, shade, pensize, ...
this.parameterBlock = function() {
this.style = 'arg';
this.parameter = true;
this.size = 1;
this.args = 0;
var svg = new SVG();
svg.init();
svg.setScale(this.scale);
svg.setExpand(70 + this.extraWidth, 0, 0, 0);
svg.setOutie(true);
if (this.fontsize) {
svg.setFontSize(this.fontsize);
}
this.artwork = svg.basicBox();
svg.docks[0].push('numberout');
this.copyDock(svg.docks);
}
}
// Blocks holds the list of blocks and most of the block-associated
// methods, since most block manipulations are inter-block.
function Blocks(canvas, stage, refreshCanvas, trashcan) {
// Things we need from outside include access to the canvas, the
// stage, and the trashcan.
this.canvas = canvas;
this.stage = stage;
this.refreshCanvas = refreshCanvas;
this.trashcan = trashcan;
// We keep a dictionary for the proto blocks,
this.protoBlockDict = {}
// and a list of the blocks we create.
this.blockList = [];
// Track the time with mouse down.
this.time = 0;
this.timeOut = null;
// "Copy stack" selects a stack for pasting. Are we selecting?
this.selectingStack = false;
// and what did we select?
this.selectedStack = null;
// If we somehow have a malformed block database (for example,
// from importing a corrupted datafile, we need to avoid infinite
// loops while crawling the block list.
this.loopCounter = 0;
this.sizeCounter = 0;
this.searchCounter = 0;
// We need a reference to the palettes.
this.palettes = null;
// Which block, if any, is highlighted?
this.highlightedBlock = null;
// Which block, if any, is active?
this.activeBlock = null;
// Are the blocks visible?
this.visible = true;
// The group of blocks being dragged or moved together
this.dragGroup = [];
// The blocks at the tops of stacks
this.stackList = [];
// The blocks that need expanding
this.expandablesList = [];
// Number of blocks to load
this.loadCounter = 0;
// Stacks of blocks that need adjusting as blocks are repositioned
// due to expanding and contracting or insertion into the flow.
this.adjustTheseDocks = [];
// We need to keep track of certain classes of blocks that exhibit
// different types of behavior.
// Blocks with parts that expand, e.g.,
this.expandableBlocks = [];
// Blocks that contain child flows of blocks
this.clampBlocks = [];
this.doubleExpandable = [];
// Blocks that are used as arguments to other blocks
this.argBlocks = [];
// Blocks that return values
this.valueBlocks = [];
// Two-arg blocks with two arguments (expandable).
this.twoArgBlocks = [];
// Blocks that don't run when clicked.
this.noRunBlocks = ['action'];
// We need to know if we are processing a copy or save stack command.
this.inLongPress = false;
// We need access to the msg block...
this.setMsgText = function(msgText) {
this.msgText = msgText;
}
// and the Error msg function.
this.setErrorMsg = function(errorMsg) {
this.errorMsg = errorMsg;
}
// We need access to the macro dictionary because we add to it.
this.setMacroDictionary = function(obj) {
this.macroDict = obj;
}
// We need access to the turtles list because we associate a
// turtle with each start block.
this.setTurtles = function(turtles) {
this.turtles = turtles;
}
// We need to access the "pseudo-Logo interpreter" when we click
// on blocks.
this.setLogo = function(logo) {
this.logo = logo;
}
// The scale of the graphics is determined by screen size.
this.setScale = function(scale) {
this.scale = scale;
}
// Toggle state of collapsible blocks.
this.toggleCollapsibles = function() {
for (var blk in this.blockList) {
var myBlock = this.blockList[blk];
if (['start', 'action'].indexOf(myBlock.name) != -1) {
collapseToggle(this, myBlock);
}
}
}
// set up copy/paste, dismiss, and copy-stack buttons
this.makeCopyPasteButtons = function(makeButton, updatePasteButton) {
var blocks = this;
this.updatePasteButton = updatePasteButton;
this.copyButton = makeButton('copy-button', 0, 0, 55);
this.copyButton.visible = false;
this.dismissButton = makeButton('cancel-button', 0, 0, 55);
this.dismissButton.visible = false;
this.saveStackButton = makeButton('save-blocks-button', 0, 0, 55);
this.saveStackButton.visible = false;
this.copyButton.on('click', function(event) {
var topBlock = blocks.findTopBlock(blocks.activeBlock);
blocks.selectedStack = topBlock;
blocks.copyButton.visible = false;
blocks.saveStackButton.visible = false;
blocks.dismissButton.visible = false;
blocks.inLongPress = false;
blocks.updatePasteButton();
blocks.refreshCanvas();
});
this.dismissButton.on('click', function(event) {
blocks.copyButton.visible = false;
blocks.saveStackButton.visible = false;
blocks.dismissButton.visible = false;
blocks.inLongPress = false;
blocks.refreshCanvas();
});
this.saveStackButton.on('click', function(event) {
// Only invoked from action blocks.
var topBlock = blocks.findTopBlock(blocks.activeBlock);
blocks.inLongPress = false;
blocks.selectedStack = topBlock;
blocks.copyButton.visible = false;
blocks.saveStackButton.visible = false;
blocks.dismissButton.visible = false;
blocks.saveStack();
blocks.refreshCanvas();
});
}
// Walk through all of the proto blocks in order to make lists of
// any blocks that need special treatment.
this.findBlockTypes = function() {
for (var proto in this.protoBlockDict) {
if (this.protoBlockDict[proto].expandable) {
this.expandableBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'clamp') {
this.clampBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'twoarg') {
this.twoArgBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'arg') {
this.argBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'value') {
this.argBlocks.push(this.protoBlockDict[proto].name);
this.valueBlocks.push(this.protoBlockDict[proto].name);
}
if (this.protoBlockDict[proto].style == 'doubleclamp') {
this.doubleExpandable.push(this.protoBlockDict[proto].name);
}
}
}
// Adjust the docking postions of all blocks in the current drag
// group.
this.adjustBlockPositions = function() {
if (this.dragGroup.length < 2) {
return;
}
// Just in case the block list is corrupted, count iterations.
this.loopCounter = 0;
this.adjustDocks(this.dragGroup[0])
}
// Adjust the size of the clamp in an expandable block when blocks
// are inserted into (or removed from) the child flow. This is a
// common operation for start and action blocks, but also for
// repeat, forever, if, etc.
this.adjustExpandableClampBlock = function(blocksToCheck) {
if (blocksToCheck.length == 0) {
// Should not happen
return;
}
var blk = blocksToCheck.pop();
var myBlock = this.blockList[blk];
// Make sure it is the proper type of expandable block.
if (myBlock.isArgBlock() || myBlock.isTwoArgBlock()) {
return;
}
function clampAdjuster(me, blk, myBlock, clamp, blocksToCheck) {
// First we need to count up the number of (and size of) the
// blocks inside the clamp; The child flow is usually the
// second-to-last argument.
if (clamp == 0) {
var c = myBlock.connections.length - 2;
} else { // e.g., Bottom clamp in if-then-else
var c = myBlock.connections.length - 3;
}
me.sizeCounter = 0;
var childFlowSize = 1;
if (c > 0 && myBlock.connections[c] != null) {
childFlowSize = Math.max(me.getStackSize(myBlock.connections[c]), 1);
}
// Adjust the clamp size to match the size of the child
// flow.
var plusMinus = childFlowSize - myBlock.clampCount[clamp];
if (plusMinus != 0) {
if (!(childFlowSize == 0 && myBlock.clampCount[clamp] == 1)) {
myBlock.updateSlots(clamp, plusMinus, blocksToCheck);
}
}
}
if (myBlock.isDoubleClampBlock()) {
clampAdjuster(this, blk, myBlock, 1, blocksToCheck);
}
clampAdjuster(this, blk, myBlock, 0, blocksToCheck);
}
// Returns the block size. (TODO recurse on first argument in
// twoarg blocks.)
this.getBlockSize = function(blk) {
return this.blockList[blk].size;
}
// We also adjust the size of twoarg blocks. It is similar to how
// we adjust clamps, but enough different that it is in its own
// function.
this.adjustExpandableTwoArgBlock = function(blocksToCheck) {
if (blocksToCheck.length == 0) {
// Should not happen
return;
}
var blk = blocksToCheck.pop();
var myBlock = this.blockList[blk];
// Determine the size of the first argument.
var c = myBlock.connections[1];
var firstArgumentSize = 1; // Minimum size
if (c != null) {
firstArgumentSize = Math.max(this.getBlockSize(c), 1);
}
var plusMinus = firstArgumentSize - myBlock.clampCount[0];
if (plusMinus != 0) {
if (!(firstArgumentSize == 0 && myBlock.clampCount[0] == 1)) {
myBlock.updateSlots(0, plusMinus, blocksToCheck);
}
}
}
this.addRemoveVspaceBlock = function(blk) {
var myBlock = blockBlocks.blockList[blk];
var c = myBlock.connections[myBlock.connections.length - 2];
var secondArgumentSize = 1;
if (c != null) {
var secondArgumentSize = Math.max(this.getBlockSize(c), 1);
}
var vSpaceCount = howManyVSpaceBlocksBelow(blk);
if (secondArgumentSize < vSpaceCount + 1) {
// Remove a vspace block
var n = Math.abs(secondArgumentSize - vSpaceCount - 1);
for (var i = 0; i < n; i++) {
var lastConnection = myBlock.connections.length - 1;
var vspaceBlock = this.blockList[myBlock.connections[lastConnection]];
var nextBlockIndex = vspaceBlock.connections[1];
myBlock.connections[lastConnection] = nextBlockIndex;
if (nextBlockIndex != null) {
this.blockList[nextBlockIndex].connections[0] = blk;
}
vspaceBlock.connections = [null, null];
vspaceBlock.hide();
}
} else if (secondArgumentSize > vSpaceCount + 1) {
// Add a vspace block
var n = secondArgumentSize - vSpaceCount - 1;
for (var nextBlock, newPos, i = 0; i < n; i++) {
nextBlock = last(myBlock.connections);
newPos = blockBlocks.blockList.length;
blockBlocks.makeNewBlockWithConnections('vspace', newPos, [null, null], function(args) {
var vspace = args[1];
var nextBlock = args[0];
var vspaceBlock = blockBlocks.blockList[vspace];
vspaceBlock.connections[0] = blk;
vspaceBlock.connections[1] = nextBlock;
myBlock.connections[myBlock.connections.length - 1] = vspace;
if (nextBlock) {
blockBlocks.blockList[nextBlock].connections[0] = vspace;
}
}, [nextBlock, newPos]);
}
}
function howManyVSpaceBlocksBelow(blk) {
// Need to know how many vspace blocks are below the block
// we're checking against.
var nextBlock = last(blockBlocks.blockList[blk].connections);
if (nextBlock && blockBlocks.blockList[nextBlock].name == 'vspace') {
return 1 + howManyVSpaceBlocksBelow(nextBlock);
// Recurse until it isn't a vspace
}
return 0;
}
}
this.getStackSize = function(blk) {
// How many block units in this stack?
var size = 0;
this.sizeCounter += 1;
if (this.sizeCounter > this.blockList.length * 2) {
console.log('Infinite loop encountered detecting size of expandable block? ' + blk);
return size;
}
if (blk == null) {
return size;
}
var myBlock = this.blockList[blk];
if (myBlock == null) {
console.log('Something very broken in getStackSize.');
}
if (myBlock.isClampBlock()) {
var c = myBlock.connections.length - 2;
var csize = 0;
if (c > 0) {
var cblk = myBlock.connections[c];
if (cblk != null) {
csize = this.getStackSize(cblk);
}
if (csize == 0) {
size = 1; // minimum of 1 slot in clamp
} else {
size = csize;
}
}
if (myBlock.isDoubleClampBlock()) {
var c = myBlock.connections.length - 3;
var csize = 0;
if (c > 0) {
var cblk = myBlock.connections[c];
if (cblk != null) {
var csize = this.getStackSize(cblk);
}
if (csize == 0) {
size += 1; // minimum of 1 slot in clamp
} else {
size += csize;
}
}
}
// add top and bottom of clamp
size += myBlock.size;
} else {
size = myBlock.size;
}
// check on any connected block
if (!myBlock.isValueBlock()) {
var cblk = last(myBlock.connections);
if (cblk != null) {
size += this.getStackSize(cblk);
}
}
return size;
}
this.adjustDocks = function(blk, resetLoopCounter) {
// Give a block, adjust the dock positions
// of all of the blocks connected to it
// For when we come in from makeBlock
if (resetLoopCounter != null) {
this.loopCounter = 0;
}
// These checks are to test for malformed data. All blocks
// should have connections.
if (this.blockList[blk] == null) {
console.log('Saw a null block: ' + blk);
return;
}
if (this.blockList[blk].connections == null) {
console.log('Saw a block with null connections: ' + blk);
return;
}
if (this.blockList[blk].connections.length == 0) {
console.log('Saw a block with [] connections: ' + blk);
return;
}
// Value blocks only have one dock.
if (this.blockList[blk].docks.length == 1) {
return;
}
this.loopCounter += 1;
if (this.loopCounter > this.blockList.length * 2) {
console.log('Infinite loop encountered while adjusting docks: ' + blk + ' ' + this.blockList);
return;
}
// Walk through each connection except the parent block.
for (var c = 1; c < this.blockList[blk].connections.length; c++) {
// Get the dock position for this connection.
var bdock = this.blockList[blk].docks[c];
// Find the connecting block.
var cblk = this.blockList[blk].connections[c];
// Nothing connected here so continue to the next connection.
if (cblk == null) {
continue;
}
// Another database integrety check.
if (this.blockList[cblk] == null) {
console.log('This is not good: we encountered a null block: ' + cblk);
continue;
}
// Find the dock position in the connected block.
var foundMatch = false;
for (var b = 0; b < this.blockList[cblk].connections.length; b++) {
if (this.blockList[cblk].connections[b] == blk) {
foundMatch = true;
break
}
}
// Yet another database integrety check.
if (!foundMatch) {
console.log('Did not find match for ' + this.blockList[blk].name + ' and ' + this.blockList[cblk].name);
break;
}
var cdock = this.blockList[cblk].docks[b];
// Move the connected block.
var dx = bdock[0] - cdock[0];
var dy = bdock[1] - cdock[1];
if (this.blockList[blk].bitmap == null) {
var nx = this.blockList[blk].x + dx;
var ny = this.blockList[blk].y + dy;
} else {
var nx = this.blockList[blk].container.x + dx;
var ny = this.blockList[blk].container.y + dy;
}
this.moveBlock(cblk, nx, ny);
// Recurse on connected blocks.
this.adjustDocks(cblk);
}
}
this.blockMoved = function(thisBlock) {
// When a block is moved, we have lots of things to check:
// (0) Is it inside of a expandable block?
// (1) Is it an arg block connected to a two-arg block?
// (2) Disconnect its connection[0];
// (3) Look for a new connection;
// (4) Is it an arg block connected to a 2-arg block?
// (5) Recheck if it inside of a expandable block.
// Find any containing expandable blocks.
var checkExpandableBlocks = [];
var blk = this.insideExpandableBlock(thisBlock);
var expandableLoopCounter = 0;
while (blk != null) {
expandableLoopCounter += 1;
if (expandableLoopCounter > 2 * this.blockList.length) {
console.log('Inifinite loop encountered checking for expandables?');
break;
}
checkExpandableBlocks.push(blk);
blk = this.insideExpandableBlock(blk);
}
var checkTwoArgBlocks = [];
var checkArgBlocks = [];
var myBlock = this.blockList[thisBlock];
var c = myBlock.connections[0];
if (c != null) {
var cBlock = this.blockList[c];
}
// If it is an arg block, where is it coming from?
if (myBlock.isArgBlock() && c != null) {
// We care about twoarg (2arg) blocks with
// connections to the first arg;
if (this.blockList[c].isTwoArgBlock()) {
if (cBlock.connections[1] == thisBlock) {
checkTwoArgBlocks.push(c);
}
} else if (this.blockList[c].isArgBlock() && this.blockList[c].isExpandableBlock()) {
if (cBlock.connections[1] == thisBlock) {
checkTwoArgBlocks.push(c);
}
}
}
// Disconnect from connection[0] (both sides of the connection).
if (c != null) {
// disconnect both ends of the connection
for (var i = 1; i < cBlock.connections.length; i++) {
if (cBlock.connections[i] == thisBlock) {
cBlock.connections[i] = null;
break;
}
}
myBlock.connections[0] = null;
}
// Look for a new connection.
var x1 = myBlock.container.x + myBlock.docks[0][0];
var y1 = myBlock.container.y + myBlock.docks[0][1];
// Find the nearest dock; if it is close
// enough, connect;
var newBlock = null;
var newConnection = null;
// TODO: Make minimum distance relative to scale.
var min = MINIMUMDOCKDISTANCE;
var blkType = myBlock.docks[0][2]
for (var b = 0; b < this.blockList.length; b++) {
// Don't connect to yourself.
if (b == thisBlock) {
continue;
}
for (var i = 1; i < this.blockList[b].connections.length; i++) {
// When converting from Python to JS, sometimes extra
// null connections are added. We need to ignore them.
if (i == this.blockList[b].docks.length) {
break;
}
// Look for available connections.
if (this.testConnectionType(
blkType,
this.blockList[b].docks[i][2])) {
x2 = this.blockList[b].container.x + this.blockList[b].docks[i][0];
y2 = this.blockList[b].container.y + this.blockList[b].docks[i][1];
dist = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if (dist < min) {
newBlock = b;
newConnection = i;
min = dist;
}
} else {
// TODO: bounce away from illegal connection?
// only if the distance was small
// console.log('cannot not connect these two block types');
}
}
}
if (newBlock != null) {
// We found a match.
myBlock.connections[0] = newBlock;
var connection = this.blockList[newBlock].connections[newConnection];
if (connection != null) {
if (myBlock.isArgBlock()) {
this.blockList[connection].connections[0] = null;
// Fixme: could be more than one block.
this.moveBlockRelative(connection, 40, 40);
} else {
var bottom = this.findBottomBlock(thisBlock);
this.blockList[connection].connections[0] = bottom;
this.blockList[bottom].connections[this.blockList[bottom].connections.length - 1] = connection;
}
}
this.blockList[newBlock].connections[newConnection] = thisBlock;
this.loopCounter = 0;
this.adjustDocks(newBlock);
// TODO: some graphical feedback re new connection?
}
// If it is an arg block, where is it coming from?
if (myBlock.isArgBlock() && newBlock != null) {
// We care about twoarg blocks with connections to the
// first arg;
if (this.blockList[newBlock].isTwoArgBlock()) {
if (this.blockList[newBlock].connections[1] == thisBlock) {
if (checkTwoArgBlocks.indexOf(newBlock) == -1) {
checkTwoArgBlocks.push(newBlock);
}
}
} else if (this.blockList[newBlock].isArgBlock() && this.blockList[newBlock].isExpandableBlock()) {
if (this.blockList[newBlock].connections[1] == thisBlock) {
if (checkTwoArgBlocks.indexOf(newBlock) == -1) {
checkTwoArgBlocks.push(newBlock);
}
}
}
// We also care about the second-to-last connection to an arg block.
var n = this.blockList[newBlock].connections.length;
if (this.blockList[newBlock].connections[n - 2] == thisBlock) {
// Only flow blocks.
if (this.blockList[newBlock].docks[n - 1][2] == 'in') {
checkArgBlocks.push(newBlock);
}
}
}
// If we changed the contents of a arg block, we may need a vspace.
if (checkArgBlocks.length > 0) {
for (var i = 0; i < checkArgBlocks.length; i++) {
this.addRemoveVspaceBlock(checkArgBlocks[i]);
}
}
// If we changed the contents of a two-arg block, we need to
// adjust it.
if (checkTwoArgBlocks.length > 0) {
this.adjustExpandableTwoArgBlock(checkTwoArgBlocks);
}
var blocks = this;
// FIXME: Make these callbacks so there is no race condition.
setTimeout(function() {
// First, adjust the docks for any blocks that may have
// had a vspace added.
for (var i = 0; i < checkArgBlocks.length; i++) {
blocks.adjustDocks(checkArgBlocks[i]);
}
// Next, recheck if the connection is inside of a
// expandable block.
var blk = blocks.insideExpandableBlock(thisBlock);
var expandableLoopCounter = 0;
while (blk != null) {
// Extra check for malformed data.
expandableLoopCounter += 1;
if (expandableLoopCounter > 2 * blocks.blockList.length) {
console.log('Infinite loop checking for expandables?');
console.log(blocks.blockList);
break;
}
if (checkExpandableBlocks.indexOf(blk) == -1) {
checkExpandableBlocks.push(blk);
}
blk = blocks.insideExpandableBlock(blk);
}
blocks.refreshCanvas();
}, 500);
setTimeout(function() {
// If we changed the contents of an expandable block, we need
// to adjust its clamp.
blocks.adjustExpandableClampBlock(checkExpandableBlocks);
}, 1000);
}
this.testConnectionType = function(type1, type2) {
// Can these two blocks dock?
if (type1 == 'in' && type2 == 'out') {
return true;
}
if (type1 == 'out' && type2 == 'in') {
return true;
}
if (type1 == 'numberin' && ['numberout', 'anyout'].indexOf(type2) != -1) {
return true;
}
if (['numberout', 'anyout'].indexOf(type1) != -1 && type2 == 'numberin') {
return true;
}
if (type1 == 'textin' && ['textout', 'anyout'].indexOf(type2) != -1) {
return true;
}
if (['textout', 'anyout'].indexOf(type1) != -1 && type2 == 'textin') {
return true;
}
if (type1 == 'booleanout' && type2 == 'booleanin') {
return true;
}
if (type1 == 'booleanin' && type2 == 'booleanout') {
return true;
}
if (type1 == 'mediain' && type2 == 'mediaout') {
return true;
}
if (type1 == 'mediaout' && type2 == 'mediain') {
return true;
}
if (type1 == 'mediain' && type2 == 'textout') {
return true;
}
if (type2 == 'mediain' && type1 == 'textout') {
return true;
}
if (type1 == 'filein' && type2 == 'fileout') {
return true;
}
if (type1 == 'fileout' && type2 == 'filein') {
return true;
}
if (type1 == 'anyin' && ['textout', 'mediaout', 'numberout', 'anyout', 'fileout'].indexOf(type2) != -1) {
return true;
}
if (type2 == 'anyin' && ['textout', 'mediaout', 'numberout', 'anyout', 'fileout'].indexOf(type1) != -1) {
return true;
}
return false;
}
this.updateBlockPositions = function() {
// Create the block image if it doesn't yet exist.
for (var blk = 0; blk < this.blockList.length; blk++) {
this.moveBlock(blk, this.blockList[blk].x, this.blockList[blk].y);
}
}
this.bringToTop = function() {
// Move all the blocks to the top layer of the stage
for (var blk in this.blockList) {
var myBlock = this.blockList[blk];
this.stage.removeChild(myBlock.container);
this.stage.addChild(myBlock.container);
if (myBlock.collapseContainer != null) {
this.stage.removeChild(myBlock.collapseContainer);
this.stage.addChild(myBlock.collapseContainer);
}
}
this.refreshCanvas();
}
this.moveBlock = function(blk, x, y) {
// Move a block (and its label) to x, y.
var myBlock = this.blockList[blk];
if (myBlock.container != null) {
myBlock.container.x = x;
myBlock.container.y = y;
myBlock.x = x
myBlock.y = y
if (myBlock.collapseContainer != null) {
myBlock.collapseContainer.x = x + COLLAPSEBUTTONXOFF;
myBlock.collapseContainer.y = y + COLLAPSEBUTTONYOFF;
}
} else {
console.log('no container yet');
myBlock.x = x
myBlock.y = y
}
}
this.moveBlockRelative = function(blk, dx, dy) {
// Move a block (and its label) by dx, dy.
var myBlock = this.blockList[blk];
if (myBlock.container != null) {
myBlock.container.x += dx;
myBlock.container.y += dy;
myBlock.x = myBlock.container.x;
myBlock.y = myBlock.container.y;
if (myBlock.collapseContainer != null) {
myBlock.collapseContainer.x += dx;
myBlock.collapseContainer.y += dy;
}
} else {
console.log('no container yet');
myBlock.x += dx
myBlock.y += dy
}
}
this.updateBlockText = function(blk) {
// When we create new blocks, we may not have assigned the
// value yet.
var myBlock = this.blockList[blk];
var maxLength = 8;
if (myBlock.text == null) {
return;
}
if (myBlock.name == 'loadFile') {
try {
var label = myBlock.value[0].toString();
} catch (e) {
var label = _('open file');
}
maxLength = 10;
} else {
var label = myBlock.value.toString();
}
if (label.length > maxLength) {
label = label.substr(0, maxLength - 1) + '...';
}
myBlock.text.text = label;
// Make sure text is on top.
z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.text, z);
if (myBlock.loadComplete) {
myBlock.container.updateCache();
} else {
console.log('load not yet complete for ' + blk);
}
}
this.findTopBlock = function(blk) {
// Find the top block in a stack.
if (blk == null) {
return null;
}
var myBlock = this.blockList[blk];
if (myBlock.connections == null) {
return blk;
}
if (myBlock.connections.length == 0) {
return blk;
}
var topBlockLoop = 0;
while (myBlock.connections[0] != null) {
topBlockLoop += 1;
if (topBlockLoop > 2 * this.blockList.length) {
// Could happen if the block data is malformed.
console.log('infinite loop finding topBlock?');
console.log(myBlock.name);
break;
}
blk = myBlock.connections[0];
myBlock = this.blockList[blk];
}
return blk;
}
this.findBottomBlock = function(blk) {
// Find the bottom block in a stack.
if (blk == null) {
return null;
}
var myBlock = this.blockList[blk];
if (myBlock.connections == null) {
return blk;
}
if (myBlock.connections.length == 0) {
return blk;
}
var bottomBlockLoop = 0;
while (last(myBlock.connections) != null) {
bottomBlockLoop += 1;
if (bottomBlockLoop > 2 * this.blockList.length) {
// Could happen if the block data is malformed.
console.log('infinite loop finding bottomBlock?');
break;
}
blk = last(myBlock.connections);
myBlock = this.blockList[blk];
}
return blk;
}
this.findStacks = function() {
// Find any blocks with null in the first connection.
this.stackList = [];
for (i = 0; i < this.blockList.length; i++) {
if (this.blockList[i].connections[0] == null) {
this.stackList.push(i)
}
}
}
this.findClamps = function() {
// Find any clamp blocks.
this.expandablesList = [];
this.findStacks(); // We start by finding the stacks
for (var i = 0; i < this.stackList.length; i++) {
this.searchCounter = 0;
this.searchForExpandables(this.stackList[i]);
}
}
this.findTwoArgs = function() {
// Find any expandable arg blocks.
this.expandablesList = [];
for (var i = 0; i < this.blockList.length; i++) {
if (this.blockList[i].isArgBlock() && this.blockList[i].isExpandableBlock()) {
this.expandablesList.push(i);
} else if (this.blockList[i].isTwoArgBlock()) {
this.expandablesList.push(i);
}
}
}
this.searchForExpandables = function(blk) {
// Find the expandable blocks below blk in a stack.
while (blk != null && this.blockList[blk] != null && !this.blockList[blk].isValueBlock()) {
// More checks for malformed or corrupted block data.
this.searchCounter += 1;
if (this.searchCounter > 2 * this.blockList.length) {
console.log('infinite loop searching for Expandables? ' + this.searchCounter);
console.log(blk + ' ' + this.blockList[blk].name);
break;
}
if (this.blockList[blk].isClampBlock()) {
this.expandablesList.push(blk);
var c = this.blockList[blk].connections.length - 2;
this.searchForExpandables(this.blockList[blk].connections[c]);
}
blk = last(this.blockList[blk].connections);
}
}
this.expandTwoArgs = function() {
// Expand expandable 2-arg blocks as needed.
this.findTwoArgs();
this.adjustExpandableTwoArgBlock(this.expandablesList);
this.refreshCanvas();
}
this.expandClamps = function() {
// Expand expandable clamp blocks as needed.
this.findClamps();
this.adjustExpandableClampBlock(this.expandablesList);
this.refreshCanvas();
}
this.unhighlightAll = function() {
for (blk in this.blockList) {
this.unhighlight(blk);
}
}
this.unhighlight = function(blk) {
if (!this.visible) {
return;
}
if (blk != null) {
var thisBlock = blk;
} else {
var thisBlock = this.highlightedBlock;
}
if (thisBlock != null) {
this.blockList[thisBlock].unhighlight();
}
if (this.highlightedBlock = thisBlock) {
this.highlightedBlock = null;
}
}
this.highlight = function(blk, unhighlight) {
if (!this.visible) {
return;
}
if (blk != null) {
if (unhighlight) {
this.unhighlight(null);
}
this.blockList[blk].highlight();
this.highlightedBlock = blk;
}
}
this.hide = function() {
for (var blk in this.blockList) {
this.blockList[blk].hide();
}
this.visible = false;
}
this.show = function() {
for (var blk in this.blockList) {
this.blockList[blk].show();
}
this.visible = true;
}
this.makeNewBlockWithConnections = function(name, blockOffset, connections, postProcess, postProcessArg, collapsed) {
if (typeof(collapsed) === 'undefined') {
collapsed = false
}
myBlock = this.makeNewBlock(name, postProcess, postProcessArg);
if (myBlock == null) {
console.log('could not make block ' + name);
return;
}
myBlock.collapsed = !collapsed;
for (var c = 0; c < connections.length; c++) {
if (c == myBlock.docks.length) {
break;
}
if (connections[c] == null) {
myBlock.connections.push(null);
} else {
myBlock.connections.push(connections[c] + blockOffset);
}
}
}
this.makeNewBlock = function(name, postProcess, postProcessArg) {
// Create a new block
if (!name in this.protoBlockDict) {
// Should never happen: nop blocks should be substituted
console.log('makeNewBlock: no prototype for ' + name);
return null;
}
if (this.protoBlockDict[name] == null) {
// Should never happen
console.log('makeNewBlock: no prototype for ' + name);
return null;
}
this.blockList.push(new Block(this.protoBlockDict[name], this));
if (last(this.blockList) == null) {
// Should never happen
console.log('failed to make protoblock for ' + name);
return null;
}
// We copy the dock because expandable blocks modify it.
var myBlock = last(this.blockList);
myBlock.copyDocks();
myBlock.copySize();
// We may need to do some postProcessing to the block
myBlock.postProcess = postProcess;
myBlock.postProcessArg = postProcessArg;
// We need a container for the block graphics.
myBlock.container = new createjs.Container();
this.stage.addChild(myBlock.container);
myBlock.container.snapToPixelEnabled = true;
myBlock.container.x = myBlock.x;
myBlock.container.y = myBlock.y;
// and we need to load the images into the container.
myBlock.imageLoad();
return myBlock;
}
this.makeBlock = function(name, arg) {
// Make a new block from a proto block.
// Called from palettes.
var postProcess = null;
var postProcessArg = null;
var me = this;
var thisBlock = this.blockList.length;
if (name == 'start') {
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = me.turtles.turtleList.length;
me.turtles.add(me.blockList[thisBlock]);
}
postProcessArg = thisBlock;
} else if (name == 'text') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value;
me.blockList[thisBlock].container.updateCache();
}
postProcessArg = [thisBlock, _('text')];
} else if (name == 'number') {
postProcess = function(args) {
var thisBlock = args[0];
var value = Number(args[1]);
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value.toString();
me.blockList[thisBlock].container.updateCache();
}
postProcessArg = [thisBlock, 100];
} else if (name == 'media') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
if (value == null) {
me.blockList[thisBlock].image = 'images/load-media.svg';
} else {
me.blockList[thisBlock].image = null;
}
}
postProcessArg = [thisBlock, null];
} else if (name == 'camera') {
postProcess = function(args) {
console.log('post process camera ' + args[1]);
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = CAMERAVALUE;
if (value == null) {
me.blockList[thisBlock].image = 'images/camera.svg';
} else {
me.blockList[thisBlock].image = null;
}
}
postProcessArg = [thisBlock, null];
} else if (name == 'video') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = VIDEOVALUE;
if (value == null) {
me.blockList[thisBlock].image = 'images/video.svg';
} else {
me.blockList[thisBlock].image = null;
}
}
postProcessArg = [thisBlock, null];
} else if (name == 'loadFile') {
postProcess = function(args) {
me.updateBlockText(args[0]);
}
postProcessArg = [thisBlock, null];
}
for (var proto in this.protoBlockDict) {
if (this.protoBlockDict[proto].name == name) {
if (arg == '__NOARG__') {
console.log('creating ' + name + ' block with no args');
this.makeNewBlock(proto, postProcess, postProcessArg);
break;
} else {
if (this.protoBlockDict[proto].defaults[0] == arg) {
console.log('creating ' + name + ' block with default arg ' + arg);
this.makeNewBlock(proto, postProcess, postProcessArg);
break;
}
}
}
}
var blk = this.blockList.length - 1;
var myBlock = this.blockList[blk];
for (var i = 0; i < myBlock.docks.length; i++) {
myBlock.connections.push(null);
}
// Attach default args if any
var cblk = blk + 1;
for (var i = 0; i < myBlock.protoblock.defaults.length; i++) {
var value = myBlock.protoblock.defaults[i];
var me = this;
var thisBlock = this.blockList.length;
if (myBlock.docks[i + 1][2] == 'anyin') {
if (value == null) {
console.log('cannot set default value');
} else if (typeof(value) == 'string') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
var label = value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
me.blockList[thisBlock].text.text = label;
me.blockList[thisBlock].container.updateCache();
}
this.makeNewBlock('text', postProcess, [thisBlock, value]);
} else {
postProcess = function(args) {
var thisBlock = args[0];
var value = Number(args[1]);
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value.toString();
}
this.makeNewBlock('number', postProcess, [thisBlock, value]);
}
} else if (myBlock.docks[i + 1][2] == 'textin') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
var label = value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
me.blockList[thisBlock].text.text = label;
}
this.makeNewBlock('text', postProcess, [thisBlock, value]);
} else if (myBlock.docks[i + 1][2] == 'mediain') {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
if (value != null) {
// loadThumbnail(me, thisBlock, null);
}
}
this.makeNewBlock('media', postProcess, [thisBlock, value]);
} else if (myBlock.docks[i + 1][2] == 'filein') {
postProcess = function(blk) {
me.updateBlockText(blk);
}
this.makeNewBlock('loadFile', postProcess, thisBlock);
} else {
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
me.blockList[thisBlock].text.text = value.toString();
}
this.makeNewBlock('number', postProcess, [thisBlock, value]);
}
var myConnectionBlock = this.blockList[cblk + i];
myConnectionBlock.connections = [blk];
if (myBlock.name == 'action') {
// Make sure we don't make two actions with the same name.
console.log('calling findUniqueActionName');
value = this.findUniqueActionName(_('action'));
console.log('renaming action block to ' + value);
if (value != _('action')) {
// There is a race condition with creation of new
// text block, hence the timeout.
setTimeout(function() {
myConnectionBlock.text.text = value;
myConnectionBlock.value = value;
myConnectionBlock.container.updateCache();
}, 1000);
console.log('calling newDoBlock with value ' + value);
this.newDoBlock(value);
this.palettes.updatePalettes();
}
}
myConnectionBlock.value = value;
myBlock.connections[i + 1] = cblk + i;
}
// Generate and position the block bitmaps and labels
this.updateBlockPositions();
this.adjustDocks(blk, true);
this.refreshCanvas();
return blk;
}
this.findDragGroup = function(blk) {
// Generate a drag group from blocks connected to blk
this.dragGroup = [];
this.calculateDragGroup(blk);
}
this.calculateDragGroup = function(blk) {
// Give a block, find all the blocks connected to it
if (blk == null) {
return;
}
var myBlock = this.blockList[blk];
// If this happens, something is really broken.
if (myBlock == null) {
console.log('null block encountered... this is bad. ' + blk);
return;
}
// As before, does these ever happen?
if (myBlock.connections == null) {
return;
}
if (myBlock.connections.length == 0) {
return;
}
this.dragGroup.push(blk);
for (var c = 1; c < myBlock.connections.length; c++) {
var cblk = myBlock.connections[c];
if (cblk != null) {
// Recurse
this.calculateDragGroup(cblk);
}
}
}
this.findUniqueActionName = function(name) {
// Make sure we don't make two actions with the same name.
var actionNames = [];
for (var blk = 0; blk < this.blockList.length; blk++) {
if (this.blockList[blk].name == 'text') {
var c = this.blockList[blk].connections[0];
if (c != null && this.blockList[c].name == 'action') {
actionNames.push(this.blockList[blk].value);
}
}
}
if (actionNames.length == 1) {
return name;
}
var i = 1;
var value = name;
while (actionNames.indexOf(value) != -1) {
value = name + i.toString();
i += 1;
}
return value;
}
this.renameBoxes = function(oldName, newName) {
for (var blk = 0; blk < this.blockList.length; blk++) {
if (this.blockList[blk].name == 'text') {
var c = this.blockList[blk].connections[0];
if (c != null && this.blockList[c].name == 'box') {
if (this.blockList[blk].value == oldName) {
this.blockList[blk].value = newName;
this.blockList[blk].text.text = newName;
try {
this.blockList[blk].container.updateCache();
} catch (e) {
console.log(e);
}
}
}
}
}
}
this.renameDos = function(oldName, newName) {
var blockPalette = this.palettes.dict['blocks'];
var nameChanged = false;
// Update the blocks, do->oldName should be do->newName
for (var blk = 0; blk < this.blockList.length; blk++) {
var myBlk = this.blockList[blk];
var blkParent = this.blockList[myBlk.connections[0]];
if (blkParent == null) {
continue;
}
if (['do', 'action'].indexOf(blkParent.name) == -1) {
continue;
}
var blockValue = myBlk.value;
if (blockValue == oldName) {
myBlk.value = newName;
myBlk.text.text = newName;
myBlk.container.updateCache();
}
}
// Update the palette
for (var blockId = 0; blockId < blockPalette.protoList.length; blockId++) {
var block = blockPalette.protoList[blockId];
if (block.name == 'do' && block.defaults[0] != _('action') && block.defaults[0] == oldName) {
blockPalette.protoList.splice(blockPalette.protoList.indexOf(block), 1);
delete this.protoBlockDict['myDo_' + oldName];
blockPalette.y = 0;
nameChanged = true;
}
}
// Force an update if the name has changed.
if (nameChanged) {
regeneratePalette(blockPalette);
}
}
this.newStoreinBlock = function(name) {
var myStoreinBlock = new ProtoBlock('storein');
this.protoBlockDict['myStorein_' + name] = myStoreinBlock;
myStoreinBlock.palette = this.palettes.dict['blocks'];
myStoreinBlock.twoArgBlock();
myStoreinBlock.defaults.push(name);
myStoreinBlock.defaults.push(100);
myStoreinBlock.staticLabels.push(_('store in'));
myStoreinBlock.staticLabels.push(_('name'));
myStoreinBlock.staticLabels.push(_('value'));
if (name == 'box') {
return;
}
myStoreinBlock.palette.add(myStoreinBlock);
}
this.newBoxBlock = function(name) {
var myBoxBlock = new ProtoBlock('box');
this.protoBlockDict['myBox_' + name] = myBoxBlock;
myBoxBlock.oneArgMathWithLabelBlock();
myBoxBlock.palette = this.palettes.dict['blocks'];
myBoxBlock.defaults.push(name);
myBoxBlock.staticLabels.push(_('box'));
myBoxBlock.style = 'arg';
if (name == 'box') {
return;
}
myBoxBlock.palette.add(myBoxBlock);
}
this.newDoBlock = function(name) {
var myDoBlock = new ProtoBlock('do');
this.protoBlockDict['myDo_' + name] = myDoBlock;
myDoBlock.oneArgBlock();
myDoBlock.palette = this.palettes.dict['blocks'];
myDoBlock.docks[1][2] = 'anyin';
myDoBlock.defaults.push(name);
myDoBlock.staticLabels.push(_('do'));
if (name == 'action') {
return;
}
myDoBlock.palette.add(myDoBlock);
}
this.newActionBlock = function(name) {
var myActionBlock = new ProtoBlock('action');
this.protoBlockDict['myAction_' + name] = myActionBlock;
myActionBlock.stackClampOneArgBlock();
myActionBlock.palette = this.palettes.dict['blocks'];
myActionBlock.artworkOffset = [0, 0, 86];
myActionBlock.defaults.push(name);
myActionBlock.staticLabels.push(_('action'));
myActionBlock.expandable = true;
myActionBlock.style = 'clamp';
if (name == 'action') {
return;
}
myActionBlock.palette.add(myActionBlock);
}
this.insideExpandableBlock = function(blk) {
// Returns a containing expandable block or null
if (this.blockList[blk].connections[0] == null) {
return null;
} else {
var cblk = this.blockList[blk].connections[0];
if (this.blockList[cblk].isExpandableBlock()) {
// If it is the last connection, keep searching.
if (blk == last(this.blockList[cblk].connections)) {
return this.insideExpandableBlock(cblk);
} else {
return cblk;
}
} else {
return this.insideExpandableBlock(cblk);
}
}
}
this.triggerLongPress = function(myBlock) {
this.timeOut == null;
this.inLongPress = true;
this.copyButton.visible = true;
this.copyButton.x = myBlock.container.x - 27;
this.copyButton.y = myBlock.container.y - 27;
this.dismissButton.visible = true;
this.dismissButton.x = myBlock.container.x + 27;
this.dismissButton.y = myBlock.container.y - 27;
if (myBlock.name == 'action') {
this.saveStackButton.visible = true;
this.saveStackButton.x = myBlock.container.x + 82;
this.saveStackButton.y = myBlock.container.y - 27;
}
this.refreshCanvas();
}
this.pasteStack = function() {
// Copy a stack of blocks by creating a blockObjs and passing
// it to this.load.
if (this.selectedStack == null) {
return;
}
var blockObjs = this.copyBlocksToObj();
this.loadNewBlocks(blockObjs);
}
this.saveStack = function() {
// Save a stack of blocks to local storage and the my-stack
// palette by creating a blockObjs and ...
if (this.selectedStack == null) {
return;
}
var blockObjs = this.copyBlocksToObj();
var nameBlk = blockObjs[0][4][1];
if (nameBlk == null) {
console.log('action not named... skipping');
} else {
console.log(blockObjs[nameBlk][1][1]);
var name = blockObjs[nameBlk][1][1];
localStorage.setItem('macros', prepareMacroExports(name, blockObjs, this.macroDict));
this.addToMyPalette(name, blockObjs);
this.palettes.makeMenu();
}
}
this.copyBlocksToObj = function() {
var blockObjs = [];
var blockMap = {};
this.findDragGroup(this.selectedStack);
for (var b = 0; b < this.dragGroup.length; b++) {
myBlock = this.blockList[this.dragGroup[b]];
if (b == 0) {
x = 25;
y = 25;
} else {
x = 0;
y = 0;
}
if (myBlock.isValueBlock()) {
switch (myBlock.name) {
case 'media':
blockItem = [b, [myBlock.name, null], x, y, []];
break;
default:
blockItem = [b, [myBlock.name, myBlock.value], x, y, []];
break;
}
} else {
blockItem = [b, myBlock.name, x, y, []];
}
blockMap[this.dragGroup[b]] = b;
blockObjs.push(blockItem);
}
for (var b = 0; b < this.dragGroup.length; b++) {
myBlock = this.blockList[this.dragGroup[b]];
for (var c = 0; c < myBlock.connections.length; c++) {
if (myBlock.connections[c] == null) {
blockObjs[b][4].push(null);
} else {
blockObjs[b][4].push(blockMap[myBlock.connections[c]]);
}
}
}
return blockObjs;
}
this.addToMyPalette = function(name, obj) {
// On the palette we store the macro as a basic block.
var myBlock = new ProtoBlock('macro_' + name);
this.protoBlockDict['macro_' + name] = myBlock;
myBlock.palette = this.palettes.dict['myblocks'];
myBlock.zeroArgBlock();
myBlock.staticLabels.push(_(name));
}
this.loadNewBlocks = function(blockObjs) {
// Check for blocks connected to themselves,
// and for action blocks not connected to text blocks.
for (var b = 0; b < blockObjs.length; b++) {
var blkData = blockObjs[b];
for (var c in blkData[4]) {
if (blkData[4][c] == blkData[0]) {
console.log('Circular connection in block data: ' + blkData);
console.log('Punting loading of new blocks!');
console.log(blockObjs);
return;
}
}
}
// We'll need a list of existing storein and action names.
var currentActionNames = [];
var currentStoreinNames = [];
for (var b = 0; b < this.blockList.length; b++) {
if (this.blockList[b].name == 'action') {
if (this.blockList[b].connections[1] != null) {
currentActionNames.push(this.blockList[this.blockList[b].connections[1]].value);
}
} else if (this.blockList[b].name == 'storein') {
if (this.blockList[b].connections[1] != null) {
currentStoreinNames.push(this.blockList[this.blockList[b].connections[1]].value);
}
}
}
// Don't make duplicate action names.
// Add a palette entry for any new storein blocks.
var stringNames = [];
var stringValues = {}; // label: [blocks with that label]
var actionNames = {}; // action block: label block
var storeinNames = {}; // storein block: label block
var doNames = {}; // do block: label block
// Scan for any new action and storein blocks to identify
// duplicates.
for (var b = 0; b < blockObjs.length; b++) {
var blkData = blockObjs[b];
// blkData[1] could be a string or an object.
if (typeof(blkData[1]) == 'string') {
var name = blkData[1];
} else {
var name = blkData[1][0];
}
switch (name) {
case 'text':
var key = blkData[1][1];
if (stringValues[key] == undefined) {
stringValues[key] = [];
}
stringValues[key].push(b);
break;
case 'action':
if (blkData[4][1] != null) {
actionNames[b] = blkData[4][1];
}
case 'hat':
if (blkData[4][1] != null) {
actionNames[b] = blkData[4][1];
}
break;
case 'storein':
if (blkData[4][1] != null) {
storeinNames[b] = blkData[4][1];
}
break;
case 'do':
case 'stack':
if (blkData[4][1] != null) {
doNames[b] = blkData[4][1];
}
break;
default:
break;
}
}
var updatePalettes = false;
// Make sure new storein names have palette entries.
for (var b in storeinNames) {
var blkData = blockObjs[storeinNames[b]];
if (currentStoreinNames.indexOf(blkData[1][1]) == -1) {
console.log('adding new palette entries for ' + blkData[1][1]);
if (typeof(blkData[1][1]) == 'string') {
var name = blkData[1][1];
} else {
var name = blkData[1][1]['value'];
}
console.log(name);
this.newStoreinBlock(name);
this.newBoxBlock(name);
updatePalettes = true;
}
}
console.log(actionNames);
// Make sure action names are unique.
for (var b in actionNames) {
// Is there a proto do block with this name? If so, find a
// new name.
// Name = the value of the connected label.
var blkData = blockObjs[actionNames[b]];
if (typeof(blkData[1][1]) == 'string') {
var name = blkData[1][1];
} else {
var name = blkData[1][1]['value'];
}
var oldName = name;
var i = 0;
while (currentActionNames.indexOf(name) != -1) {
name = blkData[1][1] + i.toString();
i += 1;
// Should never happen... but just in case.
if (i > this.blockList.length) {
console.log('could not generate unique action name');
break;
}
}
// Change the name of the action...
console.log('action ' + oldName + ' is being renamed ' + name);
blkData[1][1] = {
'value': name
};
// add a new do block to the palette...
this.newDoBlock(name);
updatePalettes = true;
// and any do blocks
for (var d in doNames) {
var doBlkData = blockObjs[doNames[d]];
if (typeof(doBlkData[1][1]) == 'string') {
if (doBlkData[1][1] == oldName) {
doBlkData[1][1] = name;
}
} else {
if (doBlkData[1][1]['value'] == oldName) {
doBlkData[1][1] = {
'value': name
};
}
}
}
}
if (updatePalettes) {
this.palettes.updatePalettes();
}
// Append to the current set of blocks.
this.adjustTheseDocks = [];
this.loadCounter = blockObjs.length;
console.log(this.loadCounter + ' blocks to load');
var blockOffset = this.blockList.length;
for (var b = 0; b < this.loadCounter; b++) {
var thisBlock = blockOffset + b;
var blkData = blockObjs[b];
if (typeof(blkData[1]) == 'object') {
if (typeof(blkData[1][1]) == 'number' | typeof(blkData[1][1]) == 'string') {
blkInfo = [blkData[1][0], {
'value': blkData[1][1]
}];
if (['start', 'action', 'hat'].indexOf != -1) {
blkInfo[1]['collapsed'] = false;
}
} else {
blkInfo = blkData[1];
}
} else {
blkInfo = [blkData[1], {
'value': null
}];
if (['start', 'action', 'hat'].indexOf != -1) {
blkInfo[1]['collapsed'] = false;
}
}
var name = blkInfo[0];
var collapsed = false;
if (['start', 'action', 'hat'].indexOf(name) != -1) {
collapsed = blkInfo[1]['collapsed'];
}
var value = blkInfo[1]['value'];
if (name in NAMEDICT) {
name = NAMEDICT[name];
}
var me = this;
// A few special cases.
switch (name) {
// Only add 'collapsed' arg to start, action blocks.
case 'start':
blkData[4][0] = null;
blkData[4][2] = null;
postProcess = function(args) {
var thisBlock = args[0];
var blkInfo = args[1];
me.blockList[thisBlock].value = me.turtles.turtleList.length;
me.turtles.add(me.blockList[thisBlock], blkInfo);
}
this.makeNewBlockWithConnections('start', blockOffset, blkData[4], postProcess, [thisBlock, blkInfo[1]], collapsed);
break;
case 'action':
case 'hat':
blkData[4][0] = null;
blkData[4][3] = null;
this.makeNewBlockWithConnections('action', blockOffset, blkData[4], null, null, collapsed);
break;
// Value blocks need a default value set.
case 'number':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = Number(value);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'text':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'media':
// Load a thumbnail into a media blocks.
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = value;
if (value != null) {
// Load artwork onto media block.
loadThumbnail(me, thisBlock, null);
}
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'camera':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = CAMERAVALUE;
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
case 'video':
postProcess = function(args) {
var thisBlock = args[0];
var value = args[1];
me.blockList[thisBlock].value = VIDEOVALUE;
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
// Define some constants for legacy blocks for
// backward compatibility with Python projects.
case 'red':
case 'white':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 0;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'orange':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 10;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'yellow':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 20;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'green':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 40;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'blue':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = 70;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'leftpos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = -(canvas.width / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'rightpos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = (canvas.width / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'toppos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = (canvas.height / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'botpos':
case 'bottompos':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = -(canvas.height / 2);
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'width':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = canvas.width;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'height':
postProcess = function(thisBlock) {
me.blockList[thisBlock].value = canvas.height;
me.updateBlockText(thisBlock);
}
this.makeNewBlockWithConnections('number', blockOffset, blkData[4], postProcess, thisBlock);
break;
case 'loadFile':
postProcess = function(args) {
me.blockList[args[0]].value = args[1];
me.updateBlockText(args[0]);
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], postProcess, [thisBlock, value]);
break;
default:
// Check that name is in the proto list
if (!name in this.protoBlockDict || this.protoBlockDict[name] == null) {
// Lots of assumptions here.
// TODO: figure out if it is a flow or an arg block.
// Substitute a NOP block for an unknown block.
n = blkData[4].length;
console.log(n + ': substituting nop block for ' + name);
switch (n) {
case 1:
name = 'nopValueBlock';
break;
case 2:
name = 'nopZeroArgBlock';
break;
case 3:
name = 'nopOneArgBlock';
break;
default:
name = 'nopTwoArgBlock';
break;
}
}
this.makeNewBlockWithConnections(name, blockOffset, blkData[4], null);
break;
}
if (thisBlock == this.blockList.length - 1) {
if (this.blockList[thisBlock].connections[0] == null) {
this.blockList[thisBlock].x = blkData[2];
this.blockList[thisBlock].y = blkData[3];
this.adjustTheseDocks.push(thisBlock);
}
}
}
}
this.cleanupAfterLoad = function() {
// If all the blocks are loaded, we can make the final adjustments.
this.loadCounter -= 1;
if (this.loadCounter > 0) {
return;
}
this.updateBlockPositions();
for (var blk = 0; blk < this.adjustTheseDocks.length; blk++) {
this.loopCounter = 0;
this.adjustDocks(this.adjustTheseDocks[blk]);
}
this.refreshCanvas();
// FIXME: Make these callbacks so there is no race condition.
// We need to wait for the blocks to load before expanding them.
setTimeout(function() {
blockBlocks.expandTwoArgs();
}, 1000);
setTimeout(function() {
blockBlocks.expandClamps();
}, 2000);
}
blockBlocks = this;
return this;
}
// Define block instance objects and any methods that are intra-block.
function Block(protoblock, blocks) {
if (protoblock == null) {
console.log('null protoblock sent to Block');
return;
}
this.protoblock = protoblock;
this.name = protoblock.name;
this.blocks = blocks;
this.x = 0;
this.y = 0;
this.collapsed = false; // Is this block in a collapsed stack?
this.trash = false; // Is this block in the trash?
this.loadComplete = false; // Has the block finished loading?
this.label = null; // Editable textview in DOM.
this.text = null; // A dynamically generated text label on block itself.
this.value = null; // Value for number, text, and media blocks.
this.image = protoblock.image; // The file path of the image.
// All blocks have at a container and least one bitmap.
this.container = null;
this.bounds = null;
this.bitmap = null;
this.highlightBitmap = null;
// Start and Action blocks has a collapse button (in a separate
// container).
this.collapseContainer = null;
this.collapseBitmap = null;
this.expandBitmap = null;
this.collapseBlockBitmap = null;
this.highlightCollapseBlockBitmap = null;
this.collapseText = null;
this.size = 1; // Proto size is copied here.
this.docks = []; // Proto dock is copied here.
// We save a copy of the dock types because we need to restore
// them after docks change when blocks resize.
this.dockTypes = [];
this.connections = []; // Blocks that cannot be run on their own.
// Keep track of clamp count for blocks with clamps
this.clampCount = [1, 1];
// Some blocks have some post process after they are first loaded.
this.postProcess = null;
this.postProcessArg = null;
this.copySize = function() {
this.size = this.protoblock.size;
}
this.copyDocks = function() {
for (var i in this.protoblock.docks) {
var dock = [this.protoblock.docks[i][0], this.protoblock.docks[i][1], this.protoblock.docks[i][2]];
this.docks.push(dock);
}
}
this.getInfo = function() {
return this.name + ' block';
}
this.highlight = function() {
if (this.collapsed && ['start', 'action'].indexOf(this.name) != -1) {
this.highlightCollapseBlockBitmap.visible = true;
this.collapseBlockBitmap.visible = false;
this.collapseText.visible = true;
} else {
this.bitmap.visible = false;
this.highlightBitmap.visible = true;
if (['start', 'action'].indexOf(this.name) != -1) {
// There could be a race condition when making a
// new action block.
if (this.collapseText != null) {
this.collapseText.visible = false;
}
if (this.collapseBlockBitmap.visible != null) {
this.collapseBlockBitmap.visible = false;
}
if (this.highlightCollapseBlockBitmap.visible != null) {
this.highlightCollapseBlockBitmap.visible = false;
}
}
}
this.container.updateCache();
this.blocks.refreshCanvas();
}
this.unhighlight = function() {
if (this.collapsed && ['start', 'action'].indexOf(this.name) != -1) {
this.highlightCollapseBlockBitmap.visible = false;
this.collapseBlockBitmap.visible = true;
this.collapseText.visible = true;
} else {
this.bitmap.visible = true;
this.highlightBitmap.visible = false;
if (['start', 'action'].indexOf(this.name) != -1) {
this.highlightCollapseBlockBitmap.visible = false;
this.collapseBlockBitmap.visible = false;
this.collapseText.visible = false;
}
}
this.container.updateCache();
this.blocks.refreshCanvas();
}
this.updateSlots = function(clamp, plusMinus, blocksToCheck) {
// Resize an expandable block.
var thisBlock = this.blocks.blockList.indexOf(this);
// First, remove the old artwork.
var targets = ['bmp_highlight_' + thisBlock, 'bmp_' + thisBlock];
var deleteQueue = [];
for (var child = 0; child < this.container.getNumChildren(); child++) {
if (targets.indexOf(this.container.children[child].name) != -1) {
deleteQueue.push(this.container.children[child]);
}
}
for (var child in deleteQueue) {
this.container.removeChild(deleteQueue[child]);
}
// Save the dock types so we can restore them...
this.dockTypes = [];
for (i = 0; i < this.docks.length; i++) {
this.dockTypes.push(this.docks[i][2]);
}
// before clearing the docks (they will be regenerated).
this.docks = [];
this.clampCount[clamp] += plusMinus;
switch (this.name) {
case 'start':
this.protoblock.stackClampZeroArgBlock(this.clampCount[clamp]);
break;
case 'action':
this.protoblock.stackClampOneArgBlock(this.clampCount[clamp]);
break;
case 'repeat':
this.protoblock.flowClampOneArgBlock(this.clampCount[clamp]);
break;
case 'forever':
this.protoblock.flowClampZeroArgBlock(this.clampCount[clamp]);
break;
case 'if':
case 'while':
case 'until':
this.protoblock.flowClampBooleanArgBlock(this.clampCount[clamp]);
break;
case 'ifthenelse':
this.protoblock.doubleFlowClampBooleanArgBlock(this.clampCount[0], this.clampCount[1]);
break;
case 'less':
case 'greater':
case 'equal':
this.protoblock.booleanTwoArgBlock(this.clampCount[0]);
break;
default:
if (this.isArgBlock()) {
this.protoblock.twoArgMathBlock(this.clampCount[0]);
} else if (this.isTwoArgBlock()) {
this.protoblock.twoArgBlock(this.clampCount[0]);
}
break;
}
this.generateArtwork(false, blocksToCheck);
}
this.resetProtoArtwork = function() {
// We may have modified the protoblock artwork. We need to
// reset it.
switch (this.name) {
case 'start':
this.protoblock.stackClampZeroArgBlock();
break;
case 'action':
this.protoblock.stackClampOneArgBlock();
break;
case 'repeat':
this.protoblock.flowClampOneArgBlock();
break;
case 'forever':
this.protoblock.flowClampZeroArgBlock();
break;
case 'if':
case 'while':
case 'until':
this.protoblock.flowClampBooleanArgBlock();
break;
case 'ifthenelse':
this.protoblock.doubleFlowClampBooleanArgBlock();
break;
case 'less':
case 'greater':
case 'equal':
this.protoblock.booleanTwoArgBlock();
break;
default:
if (this.isArgBlock()) {
this.protoblock.twoArgMathBlock();
} else if (this.isTwoArgBlock()) {
this.protoblock.twoArgBlock();
}
break;
}
}
this.imageLoad = function() {
// Load any artwork associated with the block and create any
// extra parts. Image components are loaded asynchronously so
// most the work happens in callbacks.
// We need a label for most blocks.
// TODO: use Text exclusively for all block labels.
this.text = new createjs.Text('', '20px Sans', '#000000');
var doubleExpandable = this.blocks.doubleExpandable;
this.generateArtwork(true, []);
}
this.addImage = function() {
var image = new Image();
var me = this;
image.onload = function() {
var bitmap = new createjs.Bitmap(image);
bitmap.name = 'media';
if (image.width > image.height) {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[2] / image.width;
} else {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[3] / image.height;
}
me.container.addChild(bitmap);
bitmap.x = MEDIASAFEAREA[0];
bitmap.y = MEDIASAFEAREA[1];
me.container.updateCache();
me.blocks.refreshCanvas();
}
image.src = this.image;
}
this.generateArtwork = function(firstTime, blocksToCheck) {
// Get the block labels from the protoblock
var thisBlock = this.blocks.blockList.indexOf(this);
var block_label = '';
if (this.protoblock.staticLabels.length > 0 && !this.protoblock.image) {
block_label = _(this.protoblock.staticLabels[0]);
}
while (this.protoblock.staticLabels.length < this.protoblock.args + 1) {
this.protoblock.staticLabels.push('');
}
// Create the bitmap for the block.
function processBitmap(name, bitmap, me) {
me.bitmap = bitmap;
me.container.addChild(me.bitmap);
me.bitmap.x = 0;
me.bitmap.y = 0;
me.bitmap.name = 'bmp_' + thisBlock;
me.bitmap.cursor = 'pointer';
me.blocks.refreshCanvas();
// Create the highlight bitmap for the block.
function processHighlightBitmap(name, bitmap, me) {
me.highlightBitmap = bitmap;
me.container.addChild(me.highlightBitmap);
me.highlightBitmap.x = 0;
me.highlightBitmap.y = 0;
me.highlightBitmap.name = 'bmp_highlight_' + thisBlock;
me.highlightBitmap.cursor = 'pointer';
// Hide it to start
me.highlightBitmap.visible = false;
if (me.text != null) {
// Make sure text is on top.
z = me.container.getNumChildren() - 1;
me.container.setChildIndex(me.text, z);
}
// At me point, it should be safe to calculate the
// bounds of the container and cache its contents.
if (!firstTime) {
me.container.uncache();
}
me.bounds = me.container.getBounds();
me.container.cache(me.bounds.x, me.bounds.y, me.bounds.width, me.bounds.height);
me.blocks.refreshCanvas();
if (firstTime) {
loadEventHandlers(blocks, me);
if (me.image != null) {
me.addImage();
}
me.finishImageLoad();
} else {
if (me.name == 'start') {
// Find the turtle decoration and move it to the top.
for (var child = 0; child < me.container.getNumChildren(); child++) {
if (me.container.children[child].name == 'decoration') {
me.container.setChildIndex(me.container.children[child], me.container.getNumChildren() - 1);
break;
}
}
}
me.copyDocks();
// Restore the dock types.
for (i = 0; i < me.docks.length; i++) {
me.docks[i][2] = me.dockTypes[i];
}
// Restore protoblock artwork to its original state.
me.resetProtoArtwork();
// Adjust the docks.
me.blocks.loopCounter = 0;
me.blocks.adjustDocks(thisBlock);
if (blocksToCheck.length > 0) {
if (me.isArgBlock() || me.isTwoArgBlock()) {
me.blocks.adjustExpandableTwoArgBlock(blocksToCheck);
} else {
me.blocks.adjustExpandableClampBlock(blocksToCheck);
}
}
}
}
var artwork = me.protoblock.artwork.replace(/fill_color/g, PALETTEHIGHLIGHTCOLORS[me.protoblock.palette.name]).replace(/stroke_color/g, HIGHLIGHTSTROKECOLORS[me.protoblock.palette.name]).replace('block_label', block_label);
for (var i = 1; i < me.protoblock.staticLabels.length; i++) {
artwork = artwork.replace('arg_label_' + i, _(me.protoblock.staticLabels[i]));
}
makeBitmap(artwork, me.name, processHighlightBitmap, me);
}
var artwork = this.protoblock.artwork.replace(/fill_color/g, PALETTEFILLCOLORS[this.protoblock.palette.name]).replace(/stroke_color/g, PALETTESTROKECOLORS[this.protoblock.palette.name]).replace('block_label', block_label);
if (this.protoblock.staticLabels.length > 1 && !this.protoblock.image) {
top_label = _(this.protoblock.staticLabels[1]);
}
for (var i = 1; i < this.protoblock.staticLabels.length; i++) {
artwork = artwork.replace('arg_label_' + i, _(this.protoblock.staticLabels[i]));
}
makeBitmap(artwork, this.name, processBitmap, this);
}
this.finishImageLoad = function() {
var thisBlock = this.blocks.blockList.indexOf(this);
// Value blocks get a modifiable text label
if (this.name == 'text' || this.name == 'number') {
if (this.value == null) {
if (this.name == 'text') {
this.value = '---';
} else {
this.value = 100;
}
}
var label = this.value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
this.text.text = label;
this.text.textAlign = 'center';
this.text.textBaseline = 'alphabetic';
this.container.addChild(this.text);
this.text.x = VALUETEXTX;
this.text.y = VALUETEXTY;
// Make sure text is on top.
z = this.container.getNumChildren() - 1;
this.container.setChildIndex(this.text, z);
this.container.updateCache();
}
if (this.protoblock.parameter) {
// Parameter blocks get a text label to show their current value
this.text.textAlign = 'right';
this.text.textBaseline = 'alphabetic';
this.container.addChild(this.text);
if (this.name == 'box') {
this.text.x = BOXTEXTX;
} else {
this.text.x = PARAMETERTEXTX;
}
this.text.y = VALUETEXTY;
z = this.container.getNumChildren() - 1;
this.container.setChildIndex(this.text, z);
this.container.updateCache();
}
this.loadComplete = true;
if (this.postProcess != null) {
this.postProcess(this.postProcessArg);
}
this.blocks.refreshCanvas();
this.blocks.cleanupAfterLoad();
// Start blocks and Action blocks can collapse, so add an
// event handler
if (['start', 'action'].indexOf(this.name) != -1) {
block_label = ''; // We use a Text element for the label
function processCollapseBitmap(name, bitmap, me) {
me.collapseBlockBitmap = bitmap;
me.collapseBlockBitmap.name = 'collapse_' + thisBlock;
me.container.addChild(me.collapseBlockBitmap);
me.collapseBlockBitmap.visible = false;
me.blocks.refreshCanvas();
}
var proto = new ProtoBlock('collapse');
proto.basicBlockCollapsed();
var artwork = proto.artwork;
makeBitmap(artwork.replace(/fill_color/g, PALETTEFILLCOLORS[this.protoblock.palette.name]).replace(/stroke_color/g, PALETTESTROKECOLORS[this.protoblock.palette.name]).replace('block_label', _(block_label)), '', processCollapseBitmap, this);
function processHighlightCollapseBitmap(name, bitmap, me) {
me.highlightCollapseBlockBitmap = bitmap;
me.highlightCollapseBlockBitmap.name = 'highlight_collapse_' + thisBlock;
me.container.addChild(me.highlightCollapseBlockBitmap);
me.highlightCollapseBlockBitmap.visible = false;
me.blocks.refreshCanvas();
if (me.name == 'action') {
me.collapseText = new createjs.Text('action', '20px Sans', '#000000');
me.collapseText.x = ACTIONTEXTX;
me.collapseText.y = ACTIONTEXTY;
me.collapseText.textAlign = 'right';
} else {
me.collapseText = new createjs.Text('start', '20px Sans', '#000000');
me.collapseText.x = STARTTEXTX;
me.collapseText.y = ACTIONTEXTY;
me.collapseText.textAlign = 'left';
}
me.collapseText.textBaseline = 'alphabetic';
me.container.addChild(me.collapseText);
me.collapseText.visible = false;
me.collapseContainer = new createjs.Container();
me.collapseContainer.snapToPixelEnabled = true;
var image = new Image();
image.onload = function() {
me.collapseBitmap = new createjs.Bitmap(image);
me.collapseContainer.addChild(me.collapseBitmap);
finishCollapseButton(me);
}
image.src = 'images/collapse.svg';
finishCollapseButton = function(me) {
var image = new Image();
image.onload = function() {
me.expandBitmap = new createjs.Bitmap(image);
me.collapseContainer.addChild(me.expandBitmap);
me.expandBitmap.visible = false;
var bounds = me.collapseContainer.getBounds();
me.collapseContainer.cache(bounds.x, bounds.y, bounds.width, bounds.height);
me.blocks.stage.addChild(me.collapseContainer);
me.collapseContainer.x = me.container.x + COLLAPSEBUTTONXOFF;
me.collapseContainer.y = me.container.y + COLLAPSEBUTTONYOFF;
loadCollapsibleEventHandlers(me.blocks, me);
}
image.src = 'images/expand.svg';
}
}
var artwork = proto.artwork;
makeBitmap(artwork.replace(/fill_color/g, PALETTEHIGHLIGHTCOLORS[this.protoblock.palette.name]).replace(/stroke_color/g, HIGHLIGHTSTROKECOLORS[this.protoblock.palette.name]).replace('block_label', block_label), '', processHighlightCollapseBitmap, this);
}
}
this.hide = function() {
this.container.visible = false;
if (this.collapseContainer != null) {
this.collapseContainer.visible = false;
this.collapseText.visible = false;
}
}
this.show = function() {
if (!this.trash) {
// If it is an action block or it is not collapsed then show it.
if (!(['action', 'start'].indexOf(this.name) == -1 && this.collapsed)) {
this.container.visible = true;
if (this.collapseContainer != null) {
this.collapseContainer.visible = true;
this.collapseText.visible = true;
}
}
}
}
// Utility functions
this.isValueBlock = function() {
return this.protoblock.style == 'value';
}
this.isArgBlock = function() {
return this.protoblock.style == 'value' || this.protoblock.style == 'arg';
}
this.isTwoArgBlock = function() {
return this.protoblock.style == 'twoarg';
}
this.isClampBlock = function() {
return this.protoblock.style == 'clamp' || this.isDoubleClampBlock();
}
this.isDoubleClampBlock = function() {
return this.protoblock.style == 'doubleclamp';
}
this.isNoRunBlock = function() {
return this.name == 'action';
}
this.isExpandableBlock = function() {
return this.protoblock.expandable;
}
// Based on the block index into the blockList.
this.getBlockId = function() {
var number = blockBlocks.blockList.indexOf(this);
return '_' + number.toString();
}
}
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = docById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
// Update the block values as they change in the DOM label
function labelChanged(myBlock) {
// For some reason, arg passing from the DOM is not working
// properly, so we need to find the label that changed.
if (myBlock == null) {
return;
}
var oldValue = myBlock.value;
var newValue = myBlock.label.value;
// Update the block value and block text.
if (myBlock.name == 'number') {
try {
myBlock.value = Number(newValue);
console.log('assigned ' + myBlock.value + ' to number block (' + typeof(myBlock.value) + ')');
} catch (e) {
console.log(e);
// FIXME: Expose errorMsg to blocks
// errorMsg('Not a number.');
}
} else {
myBlock.value = newValue;
}
var label = myBlock.value.toString();
if (label.length > 8) {
label = label.substr(0, 7) + '...';
}
myBlock.text.text = label;
// and hide the DOM textview...
myBlock.label.style.display = 'none';
// Make sure text is on top.
var z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.text, z);
try {
myBlock.container.updateCache();
} catch (e) {
console.log(e);
}
myBlock.blocks.refreshCanvas();
// TODO: Don't allow duplicate action names
var c = myBlock.connections[0];
if (myBlock.name == 'text' && c != null) {
var cblock = myBlock.blocks.blockList[c];
console.log('label changed' + ' ' + myBlock.name);
switch (cblock.name) {
case 'action':
// If the label was the name of an action, update the
// associated run myBlock.blocks and the palette buttons
if (myBlock.value != _('action')) {
myBlock.blocks.newDoBlock(myBlock.value);
}
console.log('rename action: ' + myBlock.value);
myBlock.blocks.renameDos(oldValue, newValue);
myBlock.blocks.palettes.updatePalettes();
break;
case 'storein':
// If the label was the name of a storein, update the
//associated box myBlock.blocks and the palette buttons
if (myBlock.value != 'box') {
myBlock.blocks.newStoreinBlock(myBlock.value);
myBlock.blocks.newBoxBlock(myBlock.value);
}
myBlock.blocks.renameBoxes(oldValue, newValue);
myBlock.blocks.palettes.updatePalettes();
break;
}
}
}
function removeChildBitmap(myBlock, name) {
for (var child = 0; child < myBlock.container.getNumChildren(); child++) {
if (myBlock.container.children[child].name == name) {
myBlock.container.removeChild(myBlock.container.children[child]);
break;
}
}
}
// Load an image thumbnail onto block.
function loadThumbnail(blocks, thisBlock, imagePath) {
if (blocks.blockList[thisBlock].value == null && imagePath == null) {
console.log('loadThumbnail: no image to load?');
return;
}
var image = new Image();
image.onload = function() {
var myBlock = blocks.blockList[thisBlock];
// Before adding new artwork, remove any old artwork.
removeChildBitmap(myBlock, 'media');
var bitmap = new createjs.Bitmap(image);
bitmap.name = 'media';
if (image.width > image.height) {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[2] / image.width;
} else {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[3] / image.height;
}
myBlock.container.addChild(bitmap);
bitmap.x = MEDIASAFEAREA[0];
bitmap.y = MEDIASAFEAREA[1];
myBlock.container.updateCache();
blocks.refreshCanvas();
}
if (imagePath == null) {
image.src = blocks.blockList[thisBlock].value;
} else {
image.src = imagePath;
}
}
// Open a file from the DOM.
function doOpenMedia(blocks, thisBlock) {
var fileChooser = docById('myMedia');
fileChooser.addEventListener('change', function(event) {
var reader = new FileReader();
reader.onloadend = (function() {
if (reader.result) {
var dataURL = reader.result;
blocks.blockList[thisBlock].value = reader.result
if (blocks.blockList[thisBlock].container.children.length > 2) {
blocks.blockList[thisBlock].container.removeChild(last(blocks.blockList[thisBlock].container.children));
}
thisBlock.image = null;
blocks.refreshCanvas();
loadThumbnail(blocks, thisBlock, null);
}
});
reader.readAsDataURL(fileChooser.files[0]);
}, false);
fileChooser.focus();
fileChooser.click();
}
function doOpenFile(blocks, thisBlock) {
var fileChooser = docById('myOpenAll');
var block = blocks.blockList[thisBlock];
fileChooser.addEventListener('change', function(event) {
var reader = new FileReader();
reader.onloadend = (function() {
if (reader.result) {
block.value = [fileChooser.files[0].name, reader.result];
blocks.updateBlockText(thisBlock);
}
});
reader.readAsText(fileChooser.files[0]);
}, false);
fileChooser.focus();
fileChooser.click();
}
// TODO: Consolidate into loadEventHandlers
// These are the event handlers for collapsible blocks.
function loadCollapsibleEventHandlers(blocks, myBlock) {
var thisBlock = blocks.blockList.indexOf(myBlock);
var bounds = myBlock.collapseContainer.getBounds();
var hitArea = new createjs.Shape();
var w2 = bounds.width;
var h2 = bounds.height;
hitArea.graphics.beginFill('#FFF').drawEllipse(-w2 / 2, -h2 / 2, w2, h2);
hitArea.x = w2 / 2;
hitArea.y = h2 / 2;
myBlock.collapseContainer.hitArea = hitArea;
myBlock.collapseContainer.on('mouseover', function(event) {
blocks.highlight(thisBlock, true);
blocks.activeBlock = thisBlock;
blocks.refreshCanvas();
});
var moved = false;
var locked = false;
myBlock.collapseContainer.on('click', function(event) {
if (locked) {
return;
}
locked = true;
setTimeout(function() {
locked = false;
}, 500);
hideDOMLabel();
if (!moved) {
collapseToggle(blocks, myBlock);
}
});
myBlock.collapseContainer.on('mousedown', function(event) {
hideDOMLabel();
// Always show the trash when there is a block selected.
trashcan.show();
moved = false;
var offset = {
x: myBlock.collapseContainer.x - Math.round(event.stageX / blocks.scale),
y: myBlock.collapseContainer.y - Math.round(event.stageY / blocks.scale)
};
myBlock.collapseContainer.on('pressup', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
myBlock.collapseContainer.on('mouseout', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
myBlock.collapseContainer.on('pressmove', function(event) {
moved = true;
var oldX = myBlock.collapseContainer.x;
var oldY = myBlock.collapseContainer.y;
myBlock.collapseContainer.x = Math.round(event.stageX / blocks.scale + offset.x);
myBlock.collapseContainer.y = Math.round(event.stageY / blocks.scale + offset.y);
var dx = myBlock.collapseContainer.x - oldX;
var dy = myBlock.collapseContainer.y - oldY;
myBlock.container.x += dx;
myBlock.container.y += dy;
myBlock.x = myBlock.container.x;
myBlock.y = myBlock.container.y;
// If we are over the trash, warn the user.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
trashcan.highlight();
} else {
trashcan.unhighlight();
}
blocks.findDragGroup(thisBlock)
if (blocks.dragGroup.length > 0) {
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
if (b != 0) {
blocks.moveBlockRelative(blk, dx, dy);
}
}
}
blocks.refreshCanvas();
});
});
myBlock.collapseContainer.on('pressup', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
myBlock.collapseContainer.on('mouseout', function(event) {
collapseOut(blocks, myBlock, thisBlock, moved, event);
moved = false;
});
}
function collapseToggle(blocks, myBlock) {
if (['start', 'action'].indexOf(myBlock.name) == -1) {
// Should not happen, but just in case.
return;
}
// Find the blocks to collapse/expand
var thisBlock = blocks.blockList.indexOf(myBlock);
blocks.findDragGroup(thisBlock)
function toggle(collapse) {
if (myBlock.collapseBitmap == null) {
console.log('collapse bitmap not ready');
return;
}
myBlock.collapsed = !collapse;
myBlock.collapseBitmap.visible = collapse;
myBlock.expandBitmap.visible = !collapse;
myBlock.collapseBlockBitmap.visible = !collapse;
myBlock.highlightCollapseBlockBitmap.visible = false;
myBlock.collapseText.visible = !collapse;
if (myBlock.bitmap != null) {
myBlock.bitmap.visible = false;
}
if (myBlock.highlightBitmap != null) {
myBlock.highlightBitmap.visible = collapse;
}
if (myBlock.name != 'start') {
// Label the collapsed block with the action label
if (myBlock.connections[1] != null) {
myBlock.collapseText.text = blocks.blockList[myBlock.connections[1]].value;
} else {
myBlock.collapseText.text = '';
}
}
var z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.collapseText, z);
if (blocks.dragGroup.length > 0) {
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
if (b != 0) {
blocks.blockList[blk].collapsed = !collapse;
blocks.blockList[blk].container.visible = collapse;
}
}
}
}
toggle(myBlock.collapsed);
myBlock.collapseContainer.updateCache();
myBlock.container.updateCache();
blocks.refreshCanvas();
return;
}
function collapseOut(blocks, myBlock, thisBlock, moved, event) {
// Always hide the trash when there is no block selected.
trashcan.hide();
blocks.unhighlight(thisBlock);
if (moved) {
// Check if block is in the trash.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
sendStackToTrash(blocks, myBlock);
} else {
// Otherwise, process move.
blocks.blockMoved(thisBlock);
}
}
if (blocks.activeBlock != myBlock) {
return;
}
blocks.unhighlight(null);
blocks.activeBlock = null;
blocks.refreshCanvas();
}
// These are the event handlers for block containers.
function loadEventHandlers(blocks, myBlock) {
var thisBlock = blocks.blockList.indexOf(myBlock);
var hitArea = new createjs.Shape();
var bounds = myBlock.container.getBounds()
// Only detect hits on top section of block.
if (myBlock.isClampBlock()) {
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, bounds.width, STANDARDBLOCKHEIGHT);
} else {
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, bounds.width, bounds.height);
}
myBlock.container.hitArea = hitArea;
myBlock.container.on('mouseover', function(event) {
blocks.highlight(thisBlock, true);
blocks.activeBlock = thisBlock;
blocks.refreshCanvas();
});
var moved = false;
var locked = false;
myBlock.container.on('click', function(event) {
if (locked) {
return;
}
locked = true;
setTimeout(function() {
locked = false;
}, 500);
hideDOMLabel();
if (!moved) {
if (blocks.selectingStack) {
var topBlock = blocks.findTopBlock(thisBlock);
blocks.selectedStack = topBlock;
blocks.selectingStack = false;
} else if (myBlock.name == 'media') {
doOpenMedia(blocks, thisBlock);
} else if (myBlock.name == 'loadFile') {
doOpenFile(blocks, thisBlock);
} else if (myBlock.name == 'text' || myBlock.name == 'number') {
var x = myBlock.container.x
var y = myBlock.container.y
var canvasLeft = blocks.canvas.offsetLeft + 28;
var canvasTop = blocks.canvas.offsetTop + 6;
if (myBlock.name == 'text') {
labelElem.innerHTML = '<textarea id="' + 'textLabel' +
'" style="position: absolute; ' +
'-webkit-user-select: text;-moz-user-select: text;-ms-user-select: text;" ' +
'class="text", ' +
'onkeypress="if(event.keyCode==13){return false;}"' +
'cols="8", rows="1", maxlength="256">' +
myBlock.value + '</textarea>';
myBlock.label = docById('textLabel');
myBlock.label.addEventListener(
'change',
function() {
labelChanged(myBlock);
});
myBlock.label.style.left = Math.round((x + blocks.stage.x) * blocks.scale + canvasLeft) + 'px';
myBlock.label.style.top = Math.round((y + blocks.stage.y) * blocks.scale + canvasTop) + 'px';
myBlock.label.style.display = '';
myBlock.label.focus();
} else {
labelElem.innerHTML = '<textarea id="' + 'numberLabel' +
'" style="position: absolute; ' +
'-webkit-user-select: text;-moz-user-select: text;-ms-user-select: text;" ' +
'class="number", ' +
'onkeypress="if(event.keyCode==13){return false;}"' +
'cols="8", rows="1", maxlength="8">' +
myBlock.value + '</textarea>';
myBlock.label = docById('numberLabel');
myBlock.label.addEventListener(
'change',
function() {
labelChanged(myBlock);
});
myBlock.label.style.left = Math.round((x + blocks.stage.x) * blocks.scale + canvasLeft) + 'px';
myBlock.label.style.top = Math.round((y + blocks.stage.y) * blocks.scale + canvasTop) + 'px';
myBlock.label.style.display = '';
myBlock.label.focus();
}
} else {
if (!blocks.inLongPress) {
var topBlock = blocks.findTopBlock(thisBlock);
console.log('running from ' + blocks.blockList[topBlock].name);
blocks.logo.runLogoCommands(topBlock);
}
}
}
});
myBlock.container.on('mousedown', function(event) {
hideDOMLabel();
// Track time for detecting long pause...
// but only for top block in stack
if (myBlock.connections[0] == null) {
var d = new Date();
blocks.time = d.getTime();
blocks.timeOut = setTimeout(function() {
blocks.triggerLongPress(myBlock);
}, LONGPRESSTIME);
}
// Always show the trash when there is a block selected.
trashcan.show();
// Bump the bitmap in front of its siblings.
blocks.stage.setChildIndex(myBlock.container, blocks.stage.getNumChildren() - 1);
if (myBlock.collapseContainer != null) {
blocks.stage.setChildIndex(myBlock.collapseContainer, blocks.stage.getNumChildren() - 1);
}
moved = false;
var offset = {
x: myBlock.container.x - Math.round(event.stageX / blocks.scale),
y: myBlock.container.y - Math.round(event.stageY / blocks.scale)
};
myBlock.container.on('mouseout', function(event) {
if (!blocks.inLongPress) {
mouseoutCallback(blocks, myBlock, event, moved);
}
moved = false;
});
myBlock.container.on('pressup', function(event) {
if (!blocks.inLongPress) {
mouseoutCallback(blocks, myBlock, event, moved);
}
moved = false;
});
myBlock.container.on('pressmove', function(event) {
// FIXME: More voodoo
event.nativeEvent.preventDefault();
// FIXME: need to remove timer
if (blocks.timeOut != null) {
clearTimeout(blocks.timeOut);
blocks.timeOut = null;
}
if (!moved && myBlock.label != null) {
myBlock.label.style.display = 'none';
}
moved = true;
var oldX = myBlock.container.x;
var oldY = myBlock.container.y;
myBlock.container.x = Math.round(event.stageX / blocks.scale) + offset.x;
myBlock.container.y = Math.round(event.stageY / blocks.scale) + offset.y;
myBlock.x = myBlock.container.x;
myBlock.y = myBlock.container.y;
var dx = Math.round(myBlock.container.x - oldX);
var dy = Math.round(myBlock.container.y - oldY);
// If we are over the trash, warn the user.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
trashcan.highlight();
} else {
trashcan.unhighlight();
}
if (myBlock.isValueBlock() && myBlock.name != 'media') {
// Ensure text is on top
var z = myBlock.container.getNumChildren() - 1;
myBlock.container.setChildIndex(myBlock.text, z);
} else if (myBlock.collapseContainer != null) {
myBlock.collapseContainer.x = myBlock.container.x + COLLAPSEBUTTONXOFF;
myBlock.collapseContainer.y = myBlock.container.y + COLLAPSEBUTTONYOFF;
}
// Move any connected blocks.
blocks.findDragGroup(thisBlock)
if (blocks.dragGroup.length > 0) {
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
if (b != 0) {
blocks.moveBlockRelative(blk, dx, dy);
}
}
}
blocks.refreshCanvas();
});
});
myBlock.container.on('mouseout', function(event) {
if (!blocks.inLongPress) {
mouseoutCallback(blocks, myBlock, event, moved);
}
});
}
function hideDOMLabel() {
var textLabel = docById('textLabel');
if (textLabel != null) {
textLabel.style.display = 'none';
}
var numberLabel = docById('numberLabel');
if (numberLabel != null) {
numberLabel.style.display = 'none';
}
}
function displayMsg(blocks, text) {
return;
var msgContainer = blocks.msgText.parent;
msgContainer.visible = true;
blocks.msgText.text = text;
msgContainer.updateCache();
blocks.stage.setChildIndex(msgContainer, blocks.stage.getNumChildren() - 1);
}
function mouseoutCallback(blocks, myBlock, event, moved) {
var thisBlock = blocks.blockList.indexOf(myBlock);
// Always hide the trash when there is no block selected.
// FIXME: need to remove timer
if (blocks.timeOut != null) {
clearTimeout(blocks.timeOut);
blocks.timeOut = null;
}
trashcan.hide();
if (moved) {
// Check if block is in the trash.
if (trashcan.overTrashcan(event.stageX / blocks.scale, event.stageY / blocks.scale)) {
sendStackToTrash(blocks, myBlock);
} else {
// Otherwise, process move.
blocks.blockMoved(thisBlock);
}
}
if (blocks.activeBlock != myBlock) {
return;
}
blocks.unhighlight(null);
blocks.activeBlock = null;
blocks.refreshCanvas();
}
function sendStackToTrash(blocks, myBlock) {
var thisBlock = blocks.blockList.indexOf(myBlock);
// disconnect block
var b = myBlock.connections[0];
if (b != null) {
for (var c in blocks.blockList[b].connections) {
if (blocks.blockList[b].connections[c] == thisBlock) {
blocks.blockList[b].connections[c] = null;
break;
}
}
myBlock.connections[0] = null;
}
if (myBlock.name == 'start') {
turtle = myBlock.value;
if (turtle != null) {
console.log('putting turtle ' + turtle + ' in the trash');
blocks.turtles.turtleList[turtle].trash = true;
blocks.turtles.turtleList[turtle].container.visible = false;
} else {
console.log('null turtle');
}
}
if (myBlock.name == 'action') {
var actionArg = blocks.blockList[myBlock.connections[1]];
var actionName = actionArg.value;
for (var blockId = 0; blockId < blocks.blockList.length; blockId++) {
var myBlk = blocks.blockList[blockId];
var blkParent = blocks.blockList[myBlk.connections[0]];
if (blkParent == null) {
continue;
}
if (['do', 'action'].indexOf(blkParent.name) != -1) {
continue;
}
var blockValue = myBlk.value;
if (blockValue == _('action')) {
continue;
}
if (blockValue == actionName) {
blkParent.hide();
myBlk.hide();
myBlk.trash = true;
blkParent.trash = true;
}
}
var blockPalette = blocks.palettes.dict['blocks'];
var blockRemoved = false;
for (var blockId = 0; blockId < blockPalette.protoList.length; blockId++) {
var block = blockPalette.protoList[blockId];
if (block.name == 'do' && block.defaults[0] != _('action') && block.defaults[0] == actionName) {
blockPalette.protoList.splice(blockPalette.protoList.indexOf(block), 1);
delete blocks.protoBlockDict['myDo_' + actionName];
blockPalette.y = 0;
blockRemoved = true;
}
}
// Force an update if a block was removed.
if (blockRemoved) {
regeneratePalette(blockPalette);
}
}
// put drag group in trash
blocks.findDragGroup(thisBlock);
for (var b = 0; b < blocks.dragGroup.length; b++) {
var blk = blocks.dragGroup[b];
console.log('putting ' + blocks.blockList[blk].name + ' in the trash');
blocks.blockList[blk].trash = true;
blocks.blockList[blk].hide();
blocks.refreshCanvas();
}
}
function makeBitmap(data, name, callback, args) {
// Async creation of bitmap from SVG data
// Works with Chrome, Safari, Firefox (untested on IE)
var img = new Image();
img.onload = function() {
bitmap = new createjs.Bitmap(img);
callback(name, bitmap, args);
}
img.src = 'data:image/svg+xml;base64,' + window.btoa(
unescape(encodeURIComponent(data)));
}
function regeneratePalette(palette) {
palette.visible = false;
palette.hideMenuItems();
palette.protoContainers = {};
palette.protoBackgrounds = {};
palette.palettes.updatePalettes();
}
| tweak thumbnail position
| js/blocks.js | tweak thumbnail position | <ide><path>s/blocks.js
<ide> bitmap.scaleX = bitmap.scaleY = bitmap.scale = MEDIASAFEAREA[3] / image.height;
<ide> }
<ide> me.container.addChild(bitmap);
<del> bitmap.x = MEDIASAFEAREA[0];
<add> bitmap.x = MEDIASAFEAREA[0] - 10;
<ide> bitmap.y = MEDIASAFEAREA[1];
<ide> me.container.updateCache();
<ide> me.blocks.refreshCanvas();
<ide> }
<ide>
<ide> myBlock.container.addChild(bitmap);
<del> bitmap.x = MEDIASAFEAREA[0];
<add> bitmap.x = MEDIASAFEAREA[0] - 10;
<ide> bitmap.y = MEDIASAFEAREA[1];
<ide>
<ide> myBlock.container.updateCache(); |
|
Java | apache-2.0 | 630c6cdacd080fbaeca6b38c2c44e5037bacbcb0 | 0 | Spartanflyer/Sunshine-Version-2,bwdur/Sunshine | /*
* Copyright (C) 2014 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.example.android.sunshine.app.data;
import android.provider.BaseColumns;
import android.text.format.Time;
/**
* Defines table and column names for the weather database.
*/
public class WeatherContract {
// To make it easy to query for the exact date, we normalize all dates that go into
// the database to the start of the the Julian day at UTC.
public static long normalizeDate(long startDate) {
// normalize the start date to the beginning of the (UTC) day
Time time = new Time();
time.setToNow();
int julianDay = Time.getJulianDay(startDate, time.gmtoff);
return time.setJulianDay(julianDay);
}
/*
Inner class that defines the contents of the location table
*/
public static final class LocationEntry implements BaseColumns {
public static final String TABLE_NAME = "location";
// The location setting string is what will be sent to openweathermap
// as the location query.
public static final String COLUMN_LOCATION_SETTING = "location_setting";
// Human readable location string, provided by the API. Because for styling,
// "Mountain View" is more recognizable than 94043.
public static final String COLUMN_CITY_NAME = "city_name";
// In order to uniquely pinpoint the location on the map when we launch the
// map intent, we store the latitude and longitude as returned by openweathermap.
public static final String COLUMN_COORD_LAT = "coord_lat";
public static final String COLUMN_COORD_LONG = "coord_long";
}
/* Inner class that defines the contents of the weather table */
public static final class WeatherEntry implements BaseColumns {
public static final String TABLE_NAME = "weather";
// Column with the foreign key into the location table.
public static final String COLUMN_LOC_KEY = "location_id";
// Date, stored as long in milliseconds since the epoch
public static final String COLUMN_DATE = "date";
// Weather id as returned by API, to identify the icon to be used
public static final String COLUMN_WEATHER_ID = "weather_id";
// Short description and long description of the weather, as provided by API.
// e.g "clear" vs "sky is clear".
public static final String COLUMN_SHORT_DESC = "short_desc";
// Min and max temperatures for the day (stored as floats)
public static final String COLUMN_MIN_TEMP = "min";
public static final String COLUMN_MAX_TEMP = "max";
// Humidity is stored as a float representing percentage
public static final String COLUMN_HUMIDITY = "humidity";
// Humidity is stored as a float representing percentage
public static final String COLUMN_PRESSURE = "pressure";
// Windspeed is stored as a float representing windspeed mph
public static final String COLUMN_WIND_SPEED = "wind";
// Degrees are meteorological degrees (e.g, 0 is north, 180 is south). Stored as floats.
public static final String COLUMN_DEGREES = "degrees";
}
}
| app/src/main/java/com/example/android/sunshine/app/data/WeatherContract.java | /*
* Copyright (C) 2014 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.example.android.sunshine.app.data;
import android.provider.BaseColumns;
import android.text.format.Time;
/**
* Defines table and column names for the weather database.
*/
public class WeatherContract {
// To make it easy to query for the exact date, we normalize all dates that go into
// the database to the start of the the Julian day at UTC.
public static long normalizeDate(long startDate) {
// normalize the start date to the beginning of the (UTC) day
Time time = new Time();
time.setToNow();
int julianDay = Time.getJulianDay(startDate, time.gmtoff);
return time.setJulianDay(julianDay);
}
/*
Inner class that defines the table contents of the location table
Students: This is where you will add the strings. (Similar to what has been
done for WeatherEntry)
*/
public static final class LocationEntry implements BaseColumns {
public static final String TABLE_NAME = "location";
}
/* Inner class that defines the table contents of the weather table */
public static final class WeatherEntry implements BaseColumns {
public static final String TABLE_NAME = "weather";
// Column with the foreign key into the location table.
public static final String COLUMN_LOC_KEY = "location_id";
// Date, stored as long in milliseconds since the epoch
public static final String COLUMN_DATE = "date";
// Weather id as returned by API, to identify the icon to be used
public static final String COLUMN_WEATHER_ID = "weather_id";
// Short description and long description of the weather, as provided by API.
// e.g "clear" vs "sky is clear".
public static final String COLUMN_SHORT_DESC = "short_desc";
// Min and max temperatures for the day (stored as floats)
public static final String COLUMN_MIN_TEMP = "min";
public static final String COLUMN_MAX_TEMP = "max";
// Humidity is stored as a float representing percentage
public static final String COLUMN_HUMIDITY = "humidity";
// Humidity is stored as a float representing percentage
public static final String COLUMN_PRESSURE = "pressure";
// Windspeed is stored as a float representing windspeed mph
public static final String COLUMN_WIND_SPEED = "wind";
// Degrees are meteorological degrees (e.g, 0 is north, 180 is south). Stored as floats.
public static final String COLUMN_DEGREES = "degrees";
}
}
| 4.03 Define constants in Contract
| app/src/main/java/com/example/android/sunshine/app/data/WeatherContract.java | 4.03 Define constants in Contract | <ide><path>pp/src/main/java/com/example/android/sunshine/app/data/WeatherContract.java
<ide> }
<ide>
<ide> /*
<del> Inner class that defines the table contents of the location table
<del> Students: This is where you will add the strings. (Similar to what has been
<del> done for WeatherEntry)
<add> Inner class that defines the contents of the location table
<ide> */
<ide> public static final class LocationEntry implements BaseColumns {
<add>
<ide> public static final String TABLE_NAME = "location";
<ide>
<add> // The location setting string is what will be sent to openweathermap
<add> // as the location query.
<add> public static final String COLUMN_LOCATION_SETTING = "location_setting";
<add>
<add> // Human readable location string, provided by the API. Because for styling,
<add> // "Mountain View" is more recognizable than 94043.
<add> public static final String COLUMN_CITY_NAME = "city_name";
<add>
<add> // In order to uniquely pinpoint the location on the map when we launch the
<add> // map intent, we store the latitude and longitude as returned by openweathermap.
<add> public static final String COLUMN_COORD_LAT = "coord_lat";
<add> public static final String COLUMN_COORD_LONG = "coord_long";
<ide> }
<ide>
<del> /* Inner class that defines the table contents of the weather table */
<add> /* Inner class that defines the contents of the weather table */
<ide> public static final class WeatherEntry implements BaseColumns {
<ide>
<ide> public static final String TABLE_NAME = "weather"; |
|
Java | mit | 656a7ba172991ffce6a6469c44c6c3fa68e6a55a | 0 | Haruki/FilmzRestServer,Haruki/FilmzRestServer,Haruki/FilmzRestServer | package gl.hb.filmzrestserver.resources;
import com.codahale.metrics.annotation.Timed;
import gl.hb.filmzrestserver.api.Film;
import gl.hb.filmzrestserver.dao.FilmzDao;
import gl.hb.filmzrestserver.dao.mapper.FilmzMapper;
import gl.hb.filmzrestserver.resources.beans.FilmzBean;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Optional;
/**
* Created by Homer on 08.01.2017.
*/
@Path("/filmz")
@Produces(MediaType.APPLICATION_JSON)
public class FilmzResource {
private Logger logger = LoggerFactory.getLogger(FilmzResource.class);
private FilmzDao filmzDao;
public FilmzResource(FilmzDao filmzDao) {
logger.debug("Instanciated: FilmzResource.");
this.filmzDao = filmzDao;
}
@GET
@Timed
@Path("/{movieid}")
public Film getFilmById(@PathParam("movieid") Optional<Integer> id) {
logger.debug("Triggered: getFilmById.");
Film result = filmzDao.findFilmById(id.orElse(1));
if (result != null) {
return result;
} else {
throw new WebApplicationException(404);
}
}
@GET
@Timed
@Path("/find")
public Film getFilmByImdbCode(@QueryParam("imdbCode") Optional<String> imdbCode) {
logger.debug("Triggered: getFilmByImdbCode");
Film result = filmzDao.findFilmByImdbCode(imdbCode.get());
if (result != null) {
return result;
} else {
throw new WebApplicationException(404);
}
}
@PUT
@Timed
@Path("/{movieid}/seen")
public Film setSeen(@PathParam("movieid") Optional<Integer> id) {
logger.debug("Triggered: setSeen.");
if (id.isPresent()) {
filmzDao.setSeenById(id.get());
return filmzDao.findFilmById(id.get());
} else {
throw new WebApplicationException(404);
}
}
@POST
@Timed
public Response insertFilm(@BeanParam FilmzBean filmzBean, @Context UriInfo uriInfo) {
logger.debug("Triggered: insertFilm.");
if (filmzBean.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
String releaseDateUnixTime = filmzBean.releaseDate.orElse(null);
Long releaseDateLong = Long.parseLong(releaseDateUnixTime);
LocalDate releaseDate;
if (releaseDateUnixTime != null) {
releaseDate =
Instant.ofEpochMilli(releaseDateLong).atZone(ZoneId.systemDefault()).toLocalDate();
} else {
throw new WebApplicationException("releaseDate is invalid", 400);
}
this.filmzDao.insertFilm(filmzBean.imdbCode.orElse(null),
filmzBean.imdbRating.orElse(null),
filmzBean.nameOriginal.orElse(null),
filmzBean.nameDeutsch.orElse(null),
releaseDate);
Film film = filmzDao.findFilmByImdbCode(filmzBean.imdbCode.get());
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(Integer.toString(film.getMovieId()));
return Response.created(builder.build()).entity(film).build();
}
}
| src/main/java/gl/hb/filmzrestserver/resources/FilmzResource.java | package gl.hb.filmzrestserver.resources;
import com.codahale.metrics.annotation.Timed;
import gl.hb.filmzrestserver.api.Film;
import gl.hb.filmzrestserver.dao.FilmzDao;
import gl.hb.filmzrestserver.dao.mapper.FilmzMapper;
import gl.hb.filmzrestserver.resources.beans.FilmzBean;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Optional;
/**
* Created by Homer on 08.01.2017.
*/
@Path("/filmz")
@Produces(MediaType.APPLICATION_JSON)
public class FilmzResource {
private Logger logger = LoggerFactory.getLogger(FilmzResource.class);
private FilmzDao filmzDao;
public FilmzResource(FilmzDao filmzDao) {
logger.debug("Instanciated: FilmzResource.");
this.filmzDao = filmzDao;
}
@GET
@Timed
@Path("/{movieid}")
public Film getFilmById(@PathParam("movieid") Optional<Integer> id) {
logger.debug("Triggered: getFilmById.");
Film result = filmzDao.findFilmById(id.orElse(1));
if (result != null) {
return result;
} else {
throw new WebApplicationException(404);
}
}
@GET
@Timed
@Path("/find")
public Film getFilmByImdbCode(@QueryParam("imdbCode") Optional<String> imdbCode) {
logger.debug("Triggered: getFilmByImdbCode");
Film result = filmzDao.findFilmByImdbCode(imdbCode.get());
if (result != null) {
return result;
} else {
throw new WebApplicationException(404);
}
}
@PUT
@Timed
@Path("/{movieid}/seen")
public Film setSeen(@PathParam("movieid") Optional<Integer> id) {
logger.debug("Triggered: setSeen.");
if (id.isPresent()) {
filmzDao.setSeenById(id.get());
return filmzDao.findFilmById(id.get());
} else {
return null;
}
}
@POST
@Timed
public Response insertFilm(@BeanParam FilmzBean filmzBean, @Context UriInfo uriInfo) {
logger.debug("Triggered: insertFilm.");
if (filmzBean.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
String releaseDateUnixTime = filmzBean.releaseDate.orElse(null);
Long releaseDateLong = Long.parseLong(releaseDateUnixTime);
LocalDate releaseDate;
if (releaseDateUnixTime != null) {
releaseDate =
Instant.ofEpochMilli(releaseDateLong).atZone(ZoneId.systemDefault()).toLocalDate();
} else {
throw new WebApplicationException("releaseDate is invalid", 400);
}
this.filmzDao.insertFilm(filmzBean.imdbCode.orElse(null),
filmzBean.imdbRating.orElse(null),
filmzBean.nameOriginal.orElse(null),
filmzBean.nameDeutsch.orElse(null),
releaseDate);
Film film = filmzDao.findFilmByImdbCode(filmzBean.imdbCode.get());
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(Integer.toString(film.getMovieId()));
return Response.created(builder.build()).entity(film).build();
}
}
| FilmzResource angepasst
| src/main/java/gl/hb/filmzrestserver/resources/FilmzResource.java | FilmzResource angepasst | <ide><path>rc/main/java/gl/hb/filmzrestserver/resources/FilmzResource.java
<ide> filmzDao.setSeenById(id.get());
<ide> return filmzDao.findFilmById(id.get());
<ide> } else {
<del> return null;
<add> throw new WebApplicationException(404);
<ide> }
<ide> }
<ide> |
|
Java | epl-1.0 | 0c4d88a8f4714f7087bc10702eec6e7b2a600bd6 | 0 | StBurcher/hawkbit,bsinno/hawkbit,eclipse/hawkbit,stormc/hawkbit,StBurcher/hawkbit,eclipse/hawkbit,eclipse/hawkbit,bsinno/hawkbit,eclipse/hawkbit,stormc/hawkbit,stormc/hawkbit,StBurcher/hawkbit,bsinno/hawkbit | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.amqp;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.api.HostnameResolver;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey;
import org.eclipse.hawkbit.dmf.amqp.api.MessageType;
import org.eclipse.hawkbit.dmf.json.model.ActionStatus;
import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus;
import org.eclipse.hawkbit.dmf.json.model.DownloadResponse;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.helper.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.security.SecurityTokenGenerator;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.cache.Cache;
import org.springframework.http.HttpStatus;
import com.google.common.eventbus.EventBus;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@RunWith(MockitoJUnitRunner.class)
@Features("Component Tests - Device Management Federation API")
@Stories("AmqpMessage Handler Service Test")
public class AmqpMessageHandlerServiceTest {
private static final String TENANT = "DEFAULT";
private AmqpMessageHandlerService amqpMessageHandlerService;
private MessageConverter messageConverter;
@Mock
private ControllerManagement controllerManagementMock;
@Mock
private EntityFactory entityFactoryMock;
@Mock
private ArtifactManagement artifactManagementMock;
@Mock
private AmqpControllerAuthentfication authenticationManagerMock;
@Mock
private ArtifactRepository artifactRepositoryMock;
@Mock
private Cache cacheMock;
@Mock
private HostnameResolver hostnameResolverMock;
@Mock
private EventBus eventBus;
@Mock
private RabbitTemplate rabbitTemplate;
@Mock
private SystemSecurityContext systemSecurityContextMock;
@Before
public void before() throws Exception {
messageConverter = new Jackson2JsonMessageConverter();
when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter);
amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate);
amqpMessageHandlerService.setControllerManagement(controllerManagementMock);
amqpMessageHandlerService.setAuthenticationManager(authenticationManagerMock);
amqpMessageHandlerService.setArtifactManagement(artifactManagementMock);
amqpMessageHandlerService.setCache(cacheMock);
amqpMessageHandlerService.setHostnameResolver(hostnameResolverMock);
amqpMessageHandlerService.setEventBus(eventBus);
amqpMessageHandlerService.setEntityFactory(entityFactoryMock);
amqpMessageHandlerService.setSystemSecurityContext(systemSecurityContextMock);
}
@Test
@Description("Tests not allowed content-type in message")
public void testWrongContentType() {
final MessageProperties messageProperties = new MessageProperties();
messageProperties.setContentType("xml");
final Message message = new Message(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to worng content type");
} catch (final AmqpRejectAndDontRequeueException e) {
}
}
@Test
@Description("Tests the creation of a target/thing by calling the same method that incoming RabbitMQ messages would access.")
public void testCreateThing() {
final String knownThingId = "1";
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
final Message message = messageConverter.toMessage(new byte[0], messageProperties);
final ArgumentCaptor<String> targetIdCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
when(controllerManagementMock.findOrRegisterTargetIfItDoesNotexist(targetIdCaptor.capture(),
uriCaptor.capture())).thenReturn(null);
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
// verify
assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId);
assertThat(uriCaptor.getValue().toString()).as("Uri is not right").isEqualTo("amqp://vHost/MyTest");
}
@Test
@Description("Tests the creation of a thing without a 'reply to' header in message.")
public void testCreateThingWitoutReplyTo() {
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED, null);
messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
final Message message = messageConverter.toMessage("", messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no replyTo header was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the creation of a target/thing without a thingID by calling the same method that incoming RabbitMQ messages would access.")
public void testCreateThingWithoutID() {
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
final Message message = messageConverter.toMessage(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no thingID was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the call of the same method that incoming RabbitMQ messages would access with an unknown message type.")
public void testUnknownMessageType() {
final String type = "bumlux";
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
messageProperties.setHeader(MessageHeaderKey.THING_ID, "");
final Message message = messageConverter.toMessage(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, type, TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to unknown message type");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests a invalid message without event topic")
public void testInvalidEventTopic() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
final Message message = new Message(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to unknown message type");
} catch (final AmqpRejectAndDontRequeueException e) {
}
try {
messageProperties.setHeader(MessageHeaderKey.TOPIC, "wrongTopic");
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to unknown topic");
} catch (final AmqpRejectAndDontRequeueException e) {
}
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.CANCEL_DOWNLOAD.name());
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted because there was no event topic");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void testUpdateActionStatusWithoutActionId() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus();
actionUpdateStatus.setActionStatus(ActionStatus.DOWNLOAD);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no action id was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void testUpdateActionStatusWithoutExistActionId() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.DOWNLOAD);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no action id was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests that an download request is denied for an artifact which does not exists")
public void authenticationRequestDeniedForArtifactWhichDoesNotExists() {
final MessageProperties messageProperties = createMessageProperties(null);
final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345"));
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
messageProperties);
// test
final Message onMessage = amqpMessageHandlerService.onAuthenticationRequest(message);
// verify
final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage);
assertThat(downloadResponse).as("Message body should not null").isNotNull();
assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
.isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
@Description("Tests that an download request is denied for an artifact which is not assigned to the requested target")
public void authenticationRequestDeniedForArtifactWhichIsNotAssignedToTarget() {
final MessageProperties messageProperties = createMessageProperties(null);
final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345"));
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
messageProperties);
final LocalArtifact localArtifactMock = mock(LocalArtifact.class);
when(artifactManagementMock.findFirstLocalArtifactsBySHA1(anyString())).thenReturn(localArtifactMock);
when(controllerManagementMock.getActionForDownloadByTargetAndSoftwareModule(anyObject(), anyObject()))
.thenThrow(EntityNotFoundException.class);
// test
final Message onMessage = amqpMessageHandlerService.onAuthenticationRequest(message);
// verify
final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage);
assertThat(downloadResponse).as("Message body should not null").isNotNull();
assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
.isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
@Description("Tests that an download request is allowed for an artifact which exists and assigned to the requested target")
public void authenticationRequestAllowedForArtifactWhichExistsAndAssignedToTarget() throws MalformedURLException {
final MessageProperties messageProperties = createMessageProperties(null);
final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345"));
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
messageProperties);
// mock
final LocalArtifact localArtifactMock = mock(LocalArtifact.class);
final DbArtifact dbArtifactMock = mock(DbArtifact.class);
when(artifactManagementMock.findFirstLocalArtifactsBySHA1(anyString())).thenReturn(localArtifactMock);
when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), localArtifactMock))
.thenReturn(true);
when(artifactManagementMock.loadLocalArtifactBinary(localArtifactMock)).thenReturn(dbArtifactMock);
when(dbArtifactMock.getArtifactId()).thenReturn("artifactId");
when(dbArtifactMock.getSize()).thenReturn(1L);
when(dbArtifactMock.getHashes()).thenReturn(new DbArtifactHash("sha1", "md5"));
when(hostnameResolverMock.resolveHostname()).thenReturn(new URL("http://localhost"));
// test
final Message onMessage = amqpMessageHandlerService.onAuthenticationRequest(message);
// verify
final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage);
assertThat(downloadResponse).as("Message body should not null").isNotNull();
assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
.isEqualTo(HttpStatus.OK.value());
assertThat(downloadResponse.getArtifact().getSize()).as("Wrong artifact size in message body").isEqualTo(1L);
assertThat(downloadResponse.getArtifact().getHashes().getSha1()).as("Wrong sha1 hash").isEqualTo("sha1");
assertThat(downloadResponse.getArtifact().getHashes().getMd5()).as("Wrong md5 hash").isEqualTo("md5");
assertThat(downloadResponse.getDownloadUrl()).as("download url is wrong")
.startsWith("http://localhost/api/v1/downloadserver/downloadId/");
}
@Test
@Description("Tests TODO")
public void lookupNextUpdateActionAfterFinished() throws IllegalAccessException {
// Mock
final Action action = createActionWithTarget(22L, Status.FINISHED);
when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action);
when(controllerManagementMock.addUpdateActionStatus(Matchers.any())).thenReturn(action);
when(entityFactoryMock.generateActionStatus()).thenReturn(new JpaActionStatus());
// for the test the same action can be used
final List<Action> actionList = new ArrayList<>();
actionList.add(action);
when(controllerManagementMock.findActionByTargetAndActive(Matchers.any())).thenReturn(actionList);
final List<SoftwareModule> softwareModuleList = createSoftwareModuleList();
when(controllerManagementMock.findSoftwareModulesByDistributionSet(Matchers.any()))
.thenReturn(softwareModuleList);
when(systemSecurityContextMock.runAsSystem(anyObject())).thenReturn("securityToken");
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.FINISHED, 23L);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
// test
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
// verify
final ArgumentCaptor<TargetAssignDistributionSetEvent> captorTargetAssignDistributionSetEvent = ArgumentCaptor
.forClass(TargetAssignDistributionSetEvent.class);
verify(eventBus, times(1)).post(captorTargetAssignDistributionSetEvent.capture());
final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = captorTargetAssignDistributionSetEvent
.getValue();
assertThat(targetAssignDistributionSetEvent.getControllerId()).as("event has wrong controller id")
.isEqualTo("target1");
assertThat(targetAssignDistributionSetEvent.getTargetToken()).as("targetoken not filled correctly")
.isEqualTo(action.getTarget().getSecurityToken());
assertThat(targetAssignDistributionSetEvent.getActionId()).as("event has wrong action id").isEqualTo(22L);
assertThat(targetAssignDistributionSetEvent.getSoftwareModules()).as("event has wrong sofware modules")
.isEqualTo(softwareModuleList);
}
private ActionUpdateStatus createActionUpdateStatus(final ActionStatus status) {
return createActionUpdateStatus(status, 2L);
}
private ActionUpdateStatus createActionUpdateStatus(final ActionStatus status, final Long id) {
final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus();
actionUpdateStatus.setActionId(id);
actionUpdateStatus.setSoftwareModuleId(Long.valueOf(2));
actionUpdateStatus.setActionStatus(status);
return actionUpdateStatus;
}
private MessageProperties createMessageProperties(final MessageType type) {
return createMessageProperties(type, "MyTest");
}
private MessageProperties createMessageProperties(final MessageType type, final String replyTo) {
final MessageProperties messageProperties = new MessageProperties();
if (type != null) {
messageProperties.setHeader(MessageHeaderKey.TYPE, type.name());
}
messageProperties.setHeader(MessageHeaderKey.TENANT, TENANT);
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
messageProperties.setReplyTo(replyTo);
return messageProperties;
}
private List<SoftwareModule> createSoftwareModuleList() {
final List<SoftwareModule> softwareModuleList = new ArrayList<>();
final JpaSoftwareModule softwareModule = new JpaSoftwareModule();
softwareModule.setId(777L);
softwareModuleList.add(softwareModule);
return softwareModuleList;
}
private Action createActionWithTarget(final Long targetId, final Status status) throws IllegalAccessException {
// is needed for the creation of targets
initalizeSecurityTokenGenerator();
// Mock
final JpaAction actionMock = mock(JpaAction.class);
final JpaTarget targetMock = mock(JpaTarget.class);
final TargetInfo targetInfoMock = mock(TargetInfo.class);
when(actionMock.getId()).thenReturn(targetId);
when(actionMock.getStatus()).thenReturn(status);
when(actionMock.getTenant()).thenReturn("DEFAULT");
when(actionMock.getTarget()).thenReturn(targetMock);
when(targetMock.getControllerId()).thenReturn("target1");
when(targetMock.getSecurityToken()).thenReturn("securityToken");
when(targetMock.getTargetInfo()).thenReturn(targetInfoMock);
when(targetInfoMock.getAddress()).thenReturn(null);
return actionMock;
}
private void initalizeSecurityTokenGenerator() throws IllegalAccessException {
final SecurityTokenGeneratorHolder instance = SecurityTokenGeneratorHolder.getInstance();
final Field[] fields = instance.getClass().getDeclaredFields();
for (final Field field : fields) {
if (field.getType().isAssignableFrom(SecurityTokenGenerator.class)) {
field.setAccessible(true);
field.set(instance, new SecurityTokenGenerator());
}
}
}
}
| hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.amqp;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.api.HostnameResolver;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey;
import org.eclipse.hawkbit.dmf.amqp.api.MessageType;
import org.eclipse.hawkbit.dmf.json.model.ActionStatus;
import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus;
import org.eclipse.hawkbit.dmf.json.model.DownloadResponse;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.helper.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.security.SecurityTokenGenerator;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.cache.Cache;
import org.springframework.http.HttpStatus;
import com.google.common.eventbus.EventBus;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@RunWith(MockitoJUnitRunner.class)
@Features("Component Tests - Device Management Federation API")
@Stories("AmqpMessage Handler Service Test")
public class AmqpMessageHandlerServiceTest {
private static final String TENANT = "DEFAULT";
private AmqpMessageHandlerService amqpMessageHandlerService;
private MessageConverter messageConverter;
@Mock
private ControllerManagement controllerManagementMock;
@Mock
private EntityFactory entityFactoryMock;
@Mock
private ArtifactManagement artifactManagementMock;
@Mock
private AmqpControllerAuthentfication authenticationManagerMock;
@Mock
private ArtifactRepository artifactRepositoryMock;
@Mock
private Cache cacheMock;
@Mock
private HostnameResolver hostnameResolverMock;
@Mock
private EventBus eventBus;
@Mock
private RabbitTemplate rabbitTemplate;
@Mock
private SystemSecurityContext systemSecurityContextMock;
@Before
public void before() throws Exception {
messageConverter = new Jackson2JsonMessageConverter();
when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter);
amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate);
amqpMessageHandlerService.setControllerManagement(controllerManagementMock);
amqpMessageHandlerService.setAuthenticationManager(authenticationManagerMock);
amqpMessageHandlerService.setArtifactManagement(artifactManagementMock);
amqpMessageHandlerService.setCache(cacheMock);
amqpMessageHandlerService.setHostnameResolver(hostnameResolverMock);
amqpMessageHandlerService.setEventBus(eventBus);
amqpMessageHandlerService.setEntityFactory(entityFactoryMock);
amqpMessageHandlerService.setSystemSecurityContext(systemSecurityContextMock);
}
@Test
@Description("Tests not allowed content-type in message")
public void testWrongContentType() {
final MessageProperties messageProperties = new MessageProperties();
messageProperties.setContentType("xml");
final Message message = new Message(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to worng content type");
} catch (final IllegalArgumentException e) {
}
}
@Test
@Description("Tests the creation of a target/thing by calling the same method that incoming RabbitMQ messages would access.")
public void testCreateThing() {
final String knownThingId = "1";
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
final Message message = messageConverter.toMessage(new byte[0], messageProperties);
final ArgumentCaptor<String> targetIdCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
when(controllerManagementMock.findOrRegisterTargetIfItDoesNotexist(targetIdCaptor.capture(),
uriCaptor.capture())).thenReturn(null);
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
// verify
assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId);
assertThat(uriCaptor.getValue().toString()).as("Uri is not right").isEqualTo("amqp://vHost/MyTest");
}
@Test
@Description("Tests the creation of a thing without a 'reply to' header in message.")
public void testCreateThingWitoutReplyTo() {
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED, null);
messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
final Message message = messageConverter.toMessage("", messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no replyTo header was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the creation of a target/thing without a thingID by calling the same method that incoming RabbitMQ messages would access.")
public void testCreateThingWithoutID() {
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
final Message message = messageConverter.toMessage(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no thingID was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the call of the same method that incoming RabbitMQ messages would access with an unknown message type.")
public void testUnknownMessageType() {
final String type = "bumlux";
final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
messageProperties.setHeader(MessageHeaderKey.THING_ID, "");
final Message message = messageConverter.toMessage(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, type, TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to unknown message type");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests a invalid message without event topic")
public void testInvalidEventTopic() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
final Message message = new Message(new byte[0], messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to unknown message type");
} catch (final AmqpRejectAndDontRequeueException e) {
}
try {
messageProperties.setHeader(MessageHeaderKey.TOPIC, "wrongTopic");
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted due to unknown topic");
} catch (final AmqpRejectAndDontRequeueException e) {
}
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.CANCEL_DOWNLOAD.name());
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted because there was no event topic");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void testUpdateActionStatusWithoutActionId() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus();
actionUpdateStatus.setActionStatus(ActionStatus.DOWNLOAD);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no action id was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void testUpdateActionStatusWithoutExistActionId() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.DOWNLOAD);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
try {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
fail("IllegalArgumentException was excepeted since no action id was set");
} catch (final AmqpRejectAndDontRequeueException exception) {
// test ok - exception was excepted
}
}
@Test
@Description("Tests that an download request is denied for an artifact which does not exists")
public void authenticationRequestDeniedForArtifactWhichDoesNotExists() {
final MessageProperties messageProperties = createMessageProperties(null);
final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345"));
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
messageProperties);
// test
final Message onMessage = amqpMessageHandlerService.onAuthenticationRequest(message);
// verify
final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage);
assertThat(downloadResponse).as("Message body should not null").isNotNull();
assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
.isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
@Description("Tests that an download request is denied for an artifact which is not assigned to the requested target")
public void authenticationRequestDeniedForArtifactWhichIsNotAssignedToTarget() {
final MessageProperties messageProperties = createMessageProperties(null);
final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345"));
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
messageProperties);
final LocalArtifact localArtifactMock = mock(LocalArtifact.class);
when(artifactManagementMock.findFirstLocalArtifactsBySHA1(anyString())).thenReturn(localArtifactMock);
when(controllerManagementMock.getActionForDownloadByTargetAndSoftwareModule(anyObject(), anyObject()))
.thenThrow(EntityNotFoundException.class);
// test
final Message onMessage = amqpMessageHandlerService.onAuthenticationRequest(message);
// verify
final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage);
assertThat(downloadResponse).as("Message body should not null").isNotNull();
assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
.isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
@Description("Tests that an download request is allowed for an artifact which exists and assigned to the requested target")
public void authenticationRequestAllowedForArtifactWhichExistsAndAssignedToTarget() throws MalformedURLException {
final MessageProperties messageProperties = createMessageProperties(null);
final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345"));
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
messageProperties);
// mock
final LocalArtifact localArtifactMock = mock(LocalArtifact.class);
final DbArtifact dbArtifactMock = mock(DbArtifact.class);
when(artifactManagementMock.findFirstLocalArtifactsBySHA1(anyString())).thenReturn(localArtifactMock);
when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), localArtifactMock))
.thenReturn(true);
when(artifactManagementMock.loadLocalArtifactBinary(localArtifactMock)).thenReturn(dbArtifactMock);
when(dbArtifactMock.getArtifactId()).thenReturn("artifactId");
when(dbArtifactMock.getSize()).thenReturn(1L);
when(dbArtifactMock.getHashes()).thenReturn(new DbArtifactHash("sha1", "md5"));
when(hostnameResolverMock.resolveHostname()).thenReturn(new URL("http://localhost"));
// test
final Message onMessage = amqpMessageHandlerService.onAuthenticationRequest(message);
// verify
final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage);
assertThat(downloadResponse).as("Message body should not null").isNotNull();
assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
.isEqualTo(HttpStatus.OK.value());
assertThat(downloadResponse.getArtifact().getSize()).as("Wrong artifact size in message body").isEqualTo(1L);
assertThat(downloadResponse.getArtifact().getHashes().getSha1()).as("Wrong sha1 hash").isEqualTo("sha1");
assertThat(downloadResponse.getArtifact().getHashes().getMd5()).as("Wrong md5 hash").isEqualTo("md5");
assertThat(downloadResponse.getDownloadUrl()).as("download url is wrong")
.startsWith("http://localhost/api/v1/downloadserver/downloadId/");
}
@Test
@Description("Tests TODO")
public void lookupNextUpdateActionAfterFinished() throws IllegalAccessException {
// Mock
final Action action = createActionWithTarget(22L, Status.FINISHED);
when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action);
when(controllerManagementMock.addUpdateActionStatus(Matchers.any())).thenReturn(action);
when(entityFactoryMock.generateActionStatus()).thenReturn(new JpaActionStatus());
// for the test the same action can be used
final List<Action> actionList = new ArrayList<>();
actionList.add(action);
when(controllerManagementMock.findActionByTargetAndActive(Matchers.any())).thenReturn(actionList);
final List<SoftwareModule> softwareModuleList = createSoftwareModuleList();
when(controllerManagementMock.findSoftwareModulesByDistributionSet(Matchers.any()))
.thenReturn(softwareModuleList);
when(systemSecurityContextMock.runAsSystem(anyObject())).thenReturn("securityToken");
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.FINISHED, 23L);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
// test
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
// verify
final ArgumentCaptor<TargetAssignDistributionSetEvent> captorTargetAssignDistributionSetEvent = ArgumentCaptor
.forClass(TargetAssignDistributionSetEvent.class);
verify(eventBus, times(1)).post(captorTargetAssignDistributionSetEvent.capture());
final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = captorTargetAssignDistributionSetEvent
.getValue();
assertThat(targetAssignDistributionSetEvent.getControllerId()).as("event has wrong controller id")
.isEqualTo("target1");
assertThat(targetAssignDistributionSetEvent.getTargetToken()).as("targetoken not filled correctly")
.isEqualTo(action.getTarget().getSecurityToken());
assertThat(targetAssignDistributionSetEvent.getActionId()).as("event has wrong action id").isEqualTo(22L);
assertThat(targetAssignDistributionSetEvent.getSoftwareModules()).as("event has wrong sofware modules")
.isEqualTo(softwareModuleList);
}
private ActionUpdateStatus createActionUpdateStatus(final ActionStatus status) {
return createActionUpdateStatus(status, 2L);
}
private ActionUpdateStatus createActionUpdateStatus(final ActionStatus status, final Long id) {
final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus();
actionUpdateStatus.setActionId(id);
actionUpdateStatus.setSoftwareModuleId(Long.valueOf(2));
actionUpdateStatus.setActionStatus(status);
return actionUpdateStatus;
}
private MessageProperties createMessageProperties(final MessageType type) {
return createMessageProperties(type, "MyTest");
}
private MessageProperties createMessageProperties(final MessageType type, final String replyTo) {
final MessageProperties messageProperties = new MessageProperties();
if (type != null) {
messageProperties.setHeader(MessageHeaderKey.TYPE, type.name());
}
messageProperties.setHeader(MessageHeaderKey.TENANT, TENANT);
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
messageProperties.setReplyTo(replyTo);
return messageProperties;
}
private List<SoftwareModule> createSoftwareModuleList() {
final List<SoftwareModule> softwareModuleList = new ArrayList<>();
final JpaSoftwareModule softwareModule = new JpaSoftwareModule();
softwareModule.setId(777L);
softwareModuleList.add(softwareModule);
return softwareModuleList;
}
private Action createActionWithTarget(final Long targetId, final Status status) throws IllegalAccessException {
// is needed for the creation of targets
initalizeSecurityTokenGenerator();
// Mock
final JpaAction actionMock = mock(JpaAction.class);
final JpaTarget targetMock = mock(JpaTarget.class);
final TargetInfo targetInfoMock = mock(TargetInfo.class);
when(actionMock.getId()).thenReturn(targetId);
when(actionMock.getStatus()).thenReturn(status);
when(actionMock.getTenant()).thenReturn("DEFAULT");
when(actionMock.getTarget()).thenReturn(targetMock);
when(targetMock.getControllerId()).thenReturn("target1");
when(targetMock.getSecurityToken()).thenReturn("securityToken");
when(targetMock.getTargetInfo()).thenReturn(targetInfoMock);
when(targetInfoMock.getAddress()).thenReturn(null);
return actionMock;
}
private void initalizeSecurityTokenGenerator() throws IllegalAccessException {
final SecurityTokenGeneratorHolder instance = SecurityTokenGeneratorHolder.getInstance();
final Field[] fields = instance.getClass().getDeclaredFields();
for (final Field field : fields) {
if (field.getType().isAssignableFrom(SecurityTokenGenerator.class)) {
field.setAccessible(true);
field.set(instance, new SecurityTokenGenerator());
}
}
}
}
| Fixed test.
Signed-off-by: Kai Zimmermann <[email protected]> | hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java | Fixed test. | <ide><path>awkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java
<ide> try {
<ide> amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
<ide> fail("IllegalArgumentException was excepeted due to worng content type");
<del> } catch (final IllegalArgumentException e) {
<add> } catch (final AmqpRejectAndDontRequeueException e) {
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 3b0faf486a29f9f49d84cc198be90c01375b53b1 | 0 | enternoescape/sagetv,webernissle/sagetv,jusjoken/sagetv,jfthibert/sagetv,jason-bean/sagetv,webernissle/sagetv,google/sagetv,OpenSageTV/sagetv,webernissle/sagetv,gasinger/sagetv,JustFred51/sagetv,google/sagetv,JREkiwi/sagetv,skiingwiz/sagetv,tmiranda1962/sagetv-1,BartokW/sagetv,rflitcroft/sagetv,skiingwiz/sagetv,tmiranda1962/sagetv-1,troll5501/sagetv,jusjoken/sagetv,jason-bean/sagetv,BartokW/sagetv,rflitcroft/sagetv,JustFred51/sagetv,stuckless/sagetv,JREkiwi/sagetv,skiingwiz/sagetv,andyvshr/sagetv,jlverhagen/sagetv,andyvshr/sagetv,troll5501/sagetv,OpenSageTV/sagetv,stuckless/sagetv,rflitcroft/sagetv,troll5501/sagetv,andyvshr/sagetv,jusjoken/sagetv,gasinger/sagetv,skiingwiz/sagetv,jusjoken/sagetv,tmiranda1962/sagetv-1,tmiranda1962/sagetv-1,jlverhagen/sagetv,jfthibert/sagetv,JustFred51/sagetv,webernissle/sagetv,jlverhagen/sagetv,JustFred51/sagetv,jfthibert/sagetv,troll5501/sagetv,JREkiwi/sagetv,jason-bean/sagetv,BartokW/sagetv,JREkiwi/sagetv,OpenSageTV/sagetv,gasinger/sagetv,OpenSageTV/sagetv,enternoescape/sagetv,stuckless/sagetv,andyvshr/sagetv,gasinger/sagetv,enternoescape/sagetv,jason-bean/sagetv,BartokW/sagetv,rflitcroft/sagetv,jfthibert/sagetv,google/sagetv,enternoescape/sagetv,google/sagetv,stuckless/sagetv,jlverhagen/sagetv | /*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sage;
public class IOUtils
{
private IOUtils()
{
}
public static String getFileExtension(java.io.File f)
{
String s = f == null ? "" : f.toString();
int idx = s.lastIndexOf('.');
if (idx < 0)
return "";
else
return s.substring(idx + 1);
}
// Returns the size of all files contained within the directory & recursively beneath
public static long getDirectorySize(java.io.File f)
{
return getDirectorySize(f, new java.util.HashSet());
}
private static long getDirectorySize(java.io.File f, java.util.HashSet done)
{
// protect against infinite recursion due to symbolic links on Linux
java.io.File realF = f;
try
{
// On Linux we need to resolve symbolic links or we could recurse forever
realF = f.getCanonicalFile();
}
catch (java.io.IOException e){}
if (!done.add(realF)) return 0;
long rv = 0;
java.io.File[] kids = f.listFiles();
for (int i = 0; kids != null && i < kids.length; i++)
{
if (kids[i].isFile())
rv += kids[i].length();
else if (kids[i].isDirectory())
rv += getDirectorySize(kids[i]);
}
return rv;
}
// Returns the all files contained within the directory & recursively beneath. Does NOT return directories
public static java.io.File[] listFilesRecursive(java.io.File f)
{
return listFilesRecursive(f, true);
}
public static java.io.File[] listFilesRecursive(java.io.File f, boolean includeAllFileTypes)
{
java.util.ArrayList rv = new java.util.ArrayList();
listFilesRecursive(f, rv, new java.util.HashSet(), includeAllFileTypes);
return (java.io.File[]) rv.toArray(new java.io.File[0]);
}
private static void listFilesRecursive(java.io.File f, java.util.ArrayList rv, java.util.HashSet done, boolean includeAllFileTypes)
{
// protect against infinite recursion due to symbolic links on Linux
java.io.File realF = f;
try
{
// On Linux we need to resolve symbolic links or we could recurse forever
realF = f.getCanonicalFile();
}
catch (java.io.IOException e){}
if (!done.add(realF)) return;
java.io.File[] kids = f.listFiles();
for (int i = 0; kids != null && i < kids.length; i++)
{
if (kids[i].isFile())
{
if (includeAllFileTypes || Seeker.getInstance().hasImportableFileExtension(kids[i].getName()))
rv.add(kids[i]);
}
else if (kids[i].isDirectory())
listFilesRecursive(kids[i], rv, done, includeAllFileTypes);
}
}
// Returns the all files contained within the directory & recursively beneath. Does NOT return directories
public static java.io.File[] listServerFilesRecursive(java.io.File f)
{
return listServerFilesRecursive(f, true);
}
public static java.io.File[] listServerFilesRecursive(java.io.File f, boolean includeAllFileTypes)
{
if (!Sage.client) return new java.io.File[0];
java.net.Socket sock = null;
java.io.DataOutputStream outStream = null;
java.io.DataInputStream inStream = null;
try
{
sock = new java.net.Socket();
sock.connect(new java.net.InetSocketAddress(Sage.preferredServer, 7818), 5000);
sock.setSoTimeout(30000);
//sock.setTcpNoDelay(true);
outStream = new java.io.DataOutputStream(new java.io.BufferedOutputStream(sock.getOutputStream()));
inStream = new java.io.DataInputStream(new java.io.BufferedInputStream(sock.getInputStream()));
// First request access to it since it's probably not in the media filesystem
boolean gotMSAccess = false;
if (NetworkClient.getSN().requestMediaServerAccess(f, true))
{
gotMSAccess = true;
}
outStream.write((includeAllFileTypes ? "LISTRECURSIVEALLW " : "LISTRECURSIVEW").getBytes(sage.Sage.BYTE_CHARSET));
outStream.write(f.toString().getBytes("UTF-16BE"));
outStream.write("\r\n".getBytes(sage.Sage.BYTE_CHARSET));
outStream.flush();
String str = sage.Sage.readLineBytes(inStream);
if (!"OK".equals(str))
throw new java.io.IOException("Error doing remote recursive dir listing of:" + str);
// get the size
str = sage.Sage.readLineBytes(inStream);
int numFiles = Integer.parseInt(str);
java.io.File[] rv = new java.io.File[numFiles];
for (int i = 0; i < numFiles; i++)
{
rv[i] = new java.io.File(sage.MediaServer.convertToUnicode(sage.Sage.readLineBytes(inStream)));
}
if (gotMSAccess)
{
NetworkClient.getSN().requestMediaServerAccess(f, false);
}
return rv;
}
catch (java.io.IOException e)
{
if (Sage.DBG) System.out.println("ERROR downloading recursive directory listing from server of :" + e + " for dir: " + f);
return new java.io.File[0];
}
finally
{
try{
if (sock != null)
sock.close();
}catch (Exception e1){}
try{
if (outStream != null)
outStream.close();
}catch (Exception e2){}
try{
if (inStream != null)
inStream.close();
}catch (Exception e3){}
}
}
// Returns the list of all files contained within the specified directory
public static String[] listServerFiles(java.io.File f)
{
if (!Sage.client) return Pooler.EMPTY_STRING_ARRAY;
java.net.Socket sock = null;
java.io.DataOutputStream outStream = null;
java.io.DataInputStream inStream = null;
try
{
sock = new java.net.Socket();
sock.connect(new java.net.InetSocketAddress(Sage.preferredServer, 7818), 5000);
sock.setSoTimeout(30000);
//sock.setTcpNoDelay(true);
outStream = new java.io.DataOutputStream(new java.io.BufferedOutputStream(sock.getOutputStream()));
inStream = new java.io.DataInputStream(new java.io.BufferedInputStream(sock.getInputStream()));
// First request access to it since it's probably not in the media filesystem
boolean gotMSAccess = false;
if (NetworkClient.getSN().requestMediaServerAccess(f, true))
{
gotMSAccess = true;
}
outStream.write("LISTW ".getBytes(sage.Sage.BYTE_CHARSET));
outStream.write(f.toString().getBytes("UTF-16BE"));
outStream.write("\r\n".getBytes(sage.Sage.BYTE_CHARSET));
outStream.flush();
String str = sage.Sage.readLineBytes(inStream);
if (!"OK".equals(str))
throw new java.io.IOException("Error doing remote recursive dir listing of:" + str);
// get the size
str = sage.Sage.readLineBytes(inStream);
int numFiles = Integer.parseInt(str);
String[] rv = new String[numFiles];
for (int i = 0; i < numFiles; i++)
{
rv[i] = sage.MediaServer.convertToUnicode(sage.Sage.readLineBytes(inStream));
}
if (gotMSAccess)
{
NetworkClient.getSN().requestMediaServerAccess(f, false);
}
return rv;
}
catch (java.io.IOException e)
{
if (Sage.DBG) System.out.println("ERROR downloading recursive directory listing from server of :" + e + " for dir: " + f);
return Pooler.EMPTY_STRING_ARRAY;
}
finally
{
try{
if (sock != null)
sock.close();
}catch (Exception e1){}
try{
if (outStream != null)
outStream.close();
}catch (Exception e2){}
try{
if (inStream != null)
inStream.close();
}catch (Exception e3){}
}
}
public static java.io.File getRootDirectory(java.io.File f)
{
if (f == null) return null;
int numParents = 0;
java.io.File currParent = f;
while (currParent.getParentFile() != null)
{
currParent = currParent.getParentFile();
numParents++;
}
if (Sage.EMBEDDED)
{
String pathStr = f.getAbsolutePath();
boolean useOurCheck = false;
if (pathStr.startsWith("/var/media/") || pathStr.startsWith("/tmp/external/"))
{
numParents -= 3;
useOurCheck = true;
}
else if (pathStr.startsWith("/tmp/sagetv_shares/"))
{
numParents -= 4;
useOurCheck = true;
}
if (useOurCheck)
{
while (numParents-- > 0 && f != null)
f = f.getParentFile();
return f;
}
}
if (currParent.toString().equals("\\\\") || (Sage.MAC_OS_X && f.toString().startsWith("/Volumes")))
{
// UNC Pathname, add the computer name and share name to get the actual root folder
// or on Mac we need to protect the /Volumes directory
numParents -= 2;
while (numParents-- > 0)
f = f.getParentFile();
return f;
}
else
return currParent;
}
public static void copyFile(java.io.File srcFile, java.io.File destFile) throws java.io.IOException
{
java.io.FileOutputStream fos = null;
java.io.OutputStream outStream = null;
java.io.InputStream inStream = null;
try
{
outStream = new java.io.BufferedOutputStream(fos = new
java.io.FileOutputStream(destFile));
inStream = new java.io.BufferedInputStream(new
java.io.FileInputStream(srcFile));
byte[] buf = new byte[65536];
int numRead = inStream.read(buf);
while (numRead != -1)
{
outStream.write(buf, 0, numRead);
numRead = inStream.read(buf);
}
}
finally
{
try
{
if (inStream != null)
{
inStream.close();
inStream = null;
}
}
catch (java.io.IOException e) {}
try
{
if (outStream != null)
{
outStream.flush();
fos.getFD().sync();
outStream.close();
outStream = null;
}
}
catch (java.io.IOException e) {}
}
// Preserve the file timestamp on the copy as well
destFile.setLastModified(srcFile.lastModified());
}
public static String exec(String[] cmdArray)
{
return exec(cmdArray, true, true);
}
public static String exec(String[] cmdArray, final boolean getStderr, final boolean getStdout)
{
return exec(cmdArray, getStderr, getStdout, false);
}
public static String exec(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways)
{
return exec(cmdArray, getStderr, getStdout, controlRunaways, null);
}
public static String exec(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways,
java.io.File workingDir)
{
return (String) exec(cmdArray, getStderr, getStdout, controlRunaways, workingDir, false);
}
public static java.io.ByteArrayOutputStream execByteOutput(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways,
java.io.File workingDir)
{
return (java.io.ByteArrayOutputStream) exec(cmdArray, getStderr, getStdout, controlRunaways, workingDir, true);
}
private static Object exec(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways,
java.io.File workingDir, boolean byteOutput)
{
final long timeLimit = controlRunaways ? Sage.getLong("control_runaway_exec_time_limit", 60000) : 0;
final long sizeLimit = controlRunaways ? Sage.getLong("control_runaway_exec_size_limit", 1024*1024) : 0;
try
{
final Process procy = Runtime.getRuntime().exec(cmdArray, null, workingDir);
final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(1024);
final long startTime = Sage.time();
Thread the = new Thread("InputStreamConsumer")
{
public void run()
{
try
{
java.io.InputStream buf = procy.getInputStream();
String s;
do
{
int c = buf.read();
if (c == -1)
break;
else if (getStdout)
baos.write(c);
if (sizeLimit > 0 && baos.size() > sizeLimit)
{
if (Sage.DBG) System.out.println("NOTICE: Forcibly terminating spawned process due to runaway memory detection!");
procy.destroy();
break;
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the.setDaemon(true);
the.start();
Thread the2 = new Thread("ErrorStreamConsumer")
{
public void run()
{
try
{
java.io.InputStream buf = procy.getErrorStream();
String s;
do
{
int c = buf.read();
if (c == -1)
break;
else if (getStderr)
baos.write(c);
if (sizeLimit > 0 && baos.size() > sizeLimit)
{
if (Sage.DBG) System.out.println("NOTICE: Forcibly terminating spawned process due to runaway memory detection!");
procy.destroy();
break;
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the2.setDaemon(true);
the2.start();
if (controlRunaways)
{
final boolean[] doneWaitin = new boolean[1];
doneWaitin[0] = false;
Pooler.execute(new Runnable()
{
public void run()
{
try
{
procy.waitFor();
}
catch (Exception e)
{
}
finally
{
synchronized (doneWaitin)
{
doneWaitin[0] = true;
doneWaitin.notifyAll();
}
}
}
});
synchronized (doneWaitin)
{
while (!doneWaitin[0] && Sage.time() - startTime < timeLimit)
{
doneWaitin.wait(Math.max(1, timeLimit - (Sage.time() - startTime)));
}
if (!doneWaitin[0])
{
if (Sage.DBG) System.out.println("NOTICE: Forcibly terminating spawned process due to runaway execution detection!");
procy.destroy();
}
}
}
else
procy.waitFor();
the.join(1000);
the2.join(1000);
if (byteOutput)
{
return baos;
}
if (Sage.EMBEDDED)
{
// If we don't use the default encoding here then some chars don't get converted right and the string is truncated.
// The test case is the Aeon Flux .mov file in DemoContent
return baos.toString();
}
try
{
return baos.toString(Sage.I18N_CHARSET);
}
catch (java.io.UnsupportedEncodingException uee)
{
// just use the default encoding
return baos.toString();
}
}
catch (Exception e)
{
if (byteOutput)
return null;
return e.toString();
}
}
public static int exec2(String[] cmdArray)
{
return exec3(cmdArray, true);
}
public static int exec2(String[] cmdArray, boolean waitForExit)
{
return exec3(cmdArray, waitForExit);
}
public static int exec2(String cmd)
{
return exec3(cmd, true);
}
public static int exec2(String cmd, boolean waitForExit)
{
return exec3(cmd, waitForExit);
}
private static int exec3(Object obj, boolean waitForExit)
{
if (Sage.DBG) System.out.println("Executing process: " +
((obj instanceof String[]) ? java.util.Arrays.asList((String[])obj) : obj));
try
{
final Process procy = obj instanceof String[] ?
Runtime.getRuntime().exec((String[])obj) : Runtime.getRuntime().exec((String) obj);
if (Sage.DBG) System.out.println("Started process object: " + procy);
Thread the = new Thread("InputStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(procy.getInputStream()));
String s;
do
{
s = buf.readLine();
if (s == null)
break;
else
{
if (Sage.DBG) System.out.println("STDOUT:" + procy + ": " + s);
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the.setDaemon(true);
the.start();
Thread the2 = new Thread("ErrorStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(procy.getErrorStream()));
String s;
do
{
s = buf.readLine();
if (s == null)
break;
else
{
if (Sage.DBG) System.out.println("STDERR:" + procy + ": " + s);
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the2.setDaemon(true);
the2.start();
if (waitForExit)
{
procy.waitFor();
the.join(1000);
the2.join(1000);
return procy.exitValue();
}
else
return 0;
}
catch (Exception e)
{
if (Sage.DBG) System.out.println("Error executing process " +
((obj instanceof String[]) ? (((String[])obj)[0]) : obj) + " : " + e);
return -1;
}
}
public static boolean deleteDirectory(java.io.File dir)
{
if (dir == null) return false;
java.io.File[] kids = dir.listFiles();
boolean rv = true;
for (int i = 0; i < kids.length; i++)
{
if (kids[i].isDirectory())
{
rv &= deleteDirectory(kids[i]);
}
else if (!kids[i].delete())
rv = false;
}
return dir.delete() && rv;
}
public static String getFileAsString(java.io.File file)
{
java.io.BufferedReader buffRead = null;
StringBuffer sb = new StringBuffer();
try
{
buffRead = new java.io.BufferedReader(new java.io.FileReader(file));
char[] cbuf = new char[4096];
int numRead = buffRead.read(cbuf);
while (numRead != -1)
{
sb.append(cbuf, 0, numRead);
numRead = buffRead.read(cbuf);
}
}
catch (java.io.IOException e)
{
System.out.println("Error reading file " + file + " of: " + e);
}
finally
{
if (buffRead != null)
{
try{buffRead.close();}catch(Exception e){}
buffRead = null;
}
}
return sb.toString();
}
public static String convertPlatformPathChars(String str)
{
StringBuffer sb = null;
int strlen = str.length();
char replaceChar = java.io.File.separatorChar;
char testChar = (replaceChar == '/') ? '\\' : '/';
for (int i = 0; i < strlen; i++)
{
char c = str.charAt(i);
if (c == testChar)
{
if (sb == null)
{
sb = new StringBuffer(str.length());
sb.append(str.substring(0, i));
}
sb.append(replaceChar);
}
else if (sb != null)
sb.append(c);
}
if (sb == null)
return str;
else
return sb.toString();
}
public static java.net.InetAddress getSubnetMask()
{
return getSubnetMask(null);
}
public static java.net.InetAddress getSubnetMask(java.net.InetAddress adapterAddr)
{
if (Sage.EMBEDDED)
{
try
{
String eth0Info = IOUtils.exec(new String[] { "ifconfig", "eth0" });
int idx0 = eth0Info.indexOf("Mask:");
if (idx0 != -1)
{
int idx1 = eth0Info.indexOf("\n", idx0);
if (idx1 != -1)
{
return java.net.InetAddress.getByName(eth0Info.substring(idx0 + "Mask:".length(), idx1).trim());
}
}
return java.net.InetAddress.getByName("255.255.255.0");
}catch(Throwable e)
{
System.out.println("ERROR:" + e);
}
return null;
}
else
{
String ipAddrInfo = exec(new String[] { Sage.WINDOWS_OS ? "ipconfig" : "ifconfig"});
java.util.regex.Pattern patty = java.util.regex.Pattern.compile("255\\.255\\.[0-9]+\\.[0-9]+");
java.util.regex.Matcher matchy = patty.matcher(ipAddrInfo);
try
{
int adapterIndex = (adapterAddr == null) ? -1 : ipAddrInfo.indexOf(adapterAddr.getHostAddress());
while (matchy.find())
{
String currMatch = matchy.group();
if ("255.255.255.255".equals(currMatch))
continue; // ignore the subnet masks that restrict all since they're not what we want
// Make sure we're on the network adapter of interest
if (matchy.start() > adapterIndex)
return java.net.InetAddress.getByName(currMatch);
}
return java.net.InetAddress.getByName("255.255.255.0");
}
catch (java.net.UnknownHostException e)
{
throw new RuntimeException(e);
}
}
}
// This returns the 40-byte MAC address
public static byte[] getMACAddress()
{
final String[] macBuf = new String[1];
try {
macBuf[0] = sage.Sage.getMACAddress0();
if(macBuf[0] != null) {
byte[] rv = new byte[6];
// The first digit is NOT always zero, don't skip it!
for (int i = 0; i < macBuf[0].length(); i+=3)
{
rv[(i/3)] = (byte)(Integer.parseInt(macBuf[0].substring(i, i+2), 16) & 0xFF);
}
return rv;
}
} catch(Throwable t) {}
try
{
String forcedMAC = Sage.get("forced_mac_address", null);
if (forcedMAC != null && forcedMAC.length() > 0)
{
if (Sage.DBG) System.out.println("Using forced MAC address of: " + forcedMAC);
macBuf[0] = forcedMAC;
}
else
{
String prefix;
final Process procy = Runtime.getRuntime().exec(Sage.WINDOWS_OS ? "ipconfig /all" : "ifconfig", null, null);
final java.util.regex.Pattern pat;// = java.util.regex.Pattern.compile(MiniClient.WINDOWS_OS ?
//"Physical Address(\\. )*\\: (\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit})" :
//"(\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit})");
if (Sage.WINDOWS_OS)
prefix = "";
else if (Sage.MAC_OS_X)
prefix = "ether";
else
prefix = ""; // no prefix for linux since language changes the label
pat = java.util.regex.Pattern.compile(prefix + " ((\\p{XDigit}{2}[:-]){5}\\p{XDigit}{2})");
Thread the = new Thread("InputStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(
procy.getInputStream()));
String s;
macBuf[0] = null;
while ((s = buf.readLine()) != null)
{
java.util.regex.Matcher m = pat.matcher(s);
// in case there's multiple adapters we only want the first one
if (macBuf[0] == null && m.find())
{
macBuf[0] = m.group(1);
}
}
buf.close();
}
catch (Exception e){}
}
};
the.setDaemon(true);
the.start();
Thread the2 = new Thread("ErrorStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(
procy.getErrorStream()));
while (buf.readLine() != null);
buf.close();
}
catch (Exception e){}
}
};
the2.setDaemon(true);
the2.start();
the.join();
the2.join();
procy.waitFor();
}
if (macBuf[0] != null)
{
byte[] rv = new byte[6];
// The first digit is NOT always zero, so don't skip it
for (int i = 0; i < macBuf[0].length(); i+=3)
{
rv[(i/3)] = (byte)(Integer.parseInt(macBuf[0].substring(i, i+2), 16) & 0xFF);
}
return rv;
}
else
return null;
}
catch (Exception e)
{
System.out.println("Error getting MAC address of:" + e);
return null;
}
}
// Returns true if this socket connection came from the localhost
public static boolean isLocalhostSocket(java.net.Socket sake)
{
byte[] localIP = sake.getLocalAddress().getAddress();
byte[] remoteIP = sake.getInetAddress().getAddress();
return ((remoteIP[0] == 127 && remoteIP[1] == 0 && remoteIP[2] == 0 && remoteIP[3] == 1) ||
(remoteIP[0] == localIP[0] && remoteIP[1] == localIP[1] && remoteIP[2] == localIP[2] && remoteIP[3] == localIP[3]));
}
public static boolean safeEquals(Object o1, Object o2)
{
return (o1 == o2) || (o1 != null && o2 != null && o1.equals(o2));
}
// This returns a UTF-8 string on Windows, otherwise it just returns the string.
// This is used for passing filenames to non-Unicode apps like FFMPEG
public static String getLibAVFilenameString(String s)
{
if (Sage.WINDOWS_OS)
{
// If any non-ASCII characters are in this string; then create a temp file and put it in there instead.
// This works around an issue where the Windows OS will do a codepage conversion on the UTF-8 values we're passing
// on the command line. And also the Java bug where it doesn't send Unicode parameters to other processes.
// We still write the bytes in the temp file as UTF-8 format though.
boolean hasUni = false;
for (int i = 0; i < s.length(); i++)
{
int c = s.charAt(i) & 0xFFFF;
if (c > 127)
{
hasUni = true;
break;
}
}
if (hasUni)
{
try
{
java.io.File tmpFile = java.io.File.createTempFile("stvfm", ".txt");
tmpFile.deleteOnExit();
byte[] strBytes = s.getBytes("UTF-8");
java.io.OutputStream os = new java.io.FileOutputStream(tmpFile);
os.write(strBytes);
os.close();
return tmpFile.getAbsolutePath();
} catch (java.io.IOException ex)
{
if (Sage.DBG) System.out.println("Error creating temp file for UTF-8 parameter passing:" + ex);
return s;
}
}
else
return s;
}
else
return s;
}
public static boolean safemkdirs(java.io.File f)
{
if (Sage.MAC_OS_X)
{
String fstr = f.toString();
if (!fstr.startsWith("/Volumes/"))
return f.mkdirs();
// We can create all the dirs up until the one below Volumes
java.util.Stack dirStack = new java.util.Stack();
java.io.File currParent = null;
while (true)
{
currParent = f.getParentFile();
if (currParent == null)
return false;
if (currParent.getName().equals("Volumes"))
{
// We found the volumes root parent so we break out and create all the dirs on the stack
break;
}
dirStack.push(f);
f = currParent;
}
while (!dirStack.isEmpty())
{
if (!((java.io.File) dirStack.pop()).mkdir())
return false;
}
return true;
}
else
return f.mkdirs();
}
// Requires positive x
static int stringSize(long x)
{
long p = 10;
for (int i=1; i<19; i++)
{
if (x < p)
return i;
p = 10*p;
}
return 19;
}
final static byte[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
final static byte [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static byte [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
private static final byte[] LONG_MIN_VALUE_STRING_BYTES = "-9223372036854775808".getBytes();
// Returns the number of bytes written into the array
public static int printLongInByteArray(long i, byte[] dest, int offset)
{
if (i == Long.MIN_VALUE)
{
System.arraycopy(LONG_MIN_VALUE_STRING_BYTES, 0, dest, offset, LONG_MIN_VALUE_STRING_BYTES.length);
return LONG_MIN_VALUE_STRING_BYTES.length;
}
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
long q;
int r;
int charPos = size + offset;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
dest[--charPos] = DigitOnes[r];
dest[--charPos] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int)i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
dest[--charPos] = DigitOnes[r];
dest[--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16+3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
dest[--charPos] = digits[r];
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) {
dest[--charPos] = (byte)sign;
}
return size;
}
public static boolean isLocalhostAddress(java.net.InetAddress inetAddress)
{
byte[] remoteIP = inetAddress.getAddress();
if (remoteIP[0] == 127 && remoteIP[1] == 0 && remoteIP[2] == 0 && remoteIP[3] == 1)
return true;
try
{
byte[] localIP = java.net.InetAddress.getLocalHost().getAddress();
return (remoteIP[0] == localIP[0] && remoteIP[1] == localIP[1] && remoteIP[2] == localIP[2] && remoteIP[3] == localIP[3]);
}
catch (Exception e)
{
System.out.println("ERROR getting localhost address of:" + e);
}
return false;
}
static int _IOC_NRBITS = 8;
static int _IOC_TYPEBITS = 8;
static int _IOC_SIZEBITS = 14;
static int _IOC_DIRBITS = 2;
static int _IOC_NRMASK = ((1 << _IOC_NRBITS)-1);
static int _IOC_TYPEMASK = ((1 << _IOC_TYPEBITS)-1);
static int _IOC_SIZEMASK = ((1 << _IOC_SIZEBITS)-1);
static int _IOC_DIRMASK = ((1 << _IOC_DIRBITS)-1);
static int _IOC_NRSHIFT = 0;
static int _IOC_TYPESHIFT = (_IOC_NRSHIFT+_IOC_NRBITS);
static int _IOC_SIZESHIFT = (_IOC_TYPESHIFT+_IOC_TYPEBITS);
static int _IOC_DIRSHIFT = (_IOC_SIZESHIFT+_IOC_SIZEBITS);
static int _IOC_NONE = 0;
static int _IOC_WRITE = 1;
static int _IOC_READ = 2;
static int _IOW(int type, int nr, int size)
{
int dir=_IOC_WRITE;
return (((dir) << _IOC_DIRSHIFT) |
((type) << _IOC_TYPESHIFT) |
((nr) << _IOC_NRSHIFT) |
((size) << _IOC_SIZESHIFT));
}
static int IOCTL_USB_CONNECTINFO = _IOW('U', 17, 8 /* struct usb_connectinfo */);
static long getUSBHWID()
{
// First get what is supposed to be the serial number; and then verify it exists
String targetSerial = exec(new String[] { "tbutil", "getserial" });
// Now convert this to the 64-bit long for the targetSerialID
long targetSerialID = 0;
int targetBitOffset = 0;
try
{
int idx = 0;
long currRead = targetSerial.charAt(idx++);
while (true)
{
currRead = Integer.parseInt(((char) currRead) + "", 16);
targetSerialID = targetSerialID ^ ((currRead & 0xF) << targetBitOffset);
if (idx >= targetSerial.length())
break;
currRead = targetSerial.charAt(idx++);
targetBitOffset += 4;
targetBitOffset = targetBitOffset % 64;
}
}
catch (Exception nfe)
{
}
// Check in /sys/bus/usb/devices to find anything in there that has a 'serial' field; but only check the ones
// that start with a number.
String[] usbdevids = new java.io.File("/sys/bus/usb/devices").list();
for (int i = 0; usbdevids != null && i < usbdevids.length; i++)
{
//System.out.println("Checking USB Dev ID=" + usbdevids[i]);
if (Character.isDigit(usbdevids[i].charAt(0)))
{
// Check for the 'serial' field
java.io.File serialFile = new java.io.File("/sys/bus/usb/devices/" + usbdevids[i] + "/serial");
if (serialFile.isFile())
{
//System.out.println("Serial exists for this device...");
int usbMajor = Integer.parseInt(usbdevids[i].substring(0, 1));
java.io.Reader inReader = null;
int usbMinor = -1;
try
{
inReader = new java.io.FileReader("/sys/bus/usb/devices/" + usbdevids[i] + "/devnum");
usbMinor = Integer.parseInt(((char)inReader.read()) + "");
inReader.close();
inReader = null;
}
catch (Exception e)
{
continue;
}
java.text.DecimalFormat leadZeros = new java.text.DecimalFormat("000");
//System.out.println("USB dev num " + usbMajor + "-" + usbMinor);
String verificationDevice = "/dev/bus/usb/" + leadZeros.format(usbMajor) + "/" + leadZeros.format(usbMinor);
//System.out.println("Verifying w/ device:" + verificationDevice);
int usb_fd = -1;
byte[] buf1 = new byte[8];
byte[] desc = new byte[18];
try
{
usb_fd = jtux.UFile.open(verificationDevice, jtux.UConstant.O_RDWR);
//System.out.println("ioctl "+IOCTL_USB_CONNECTINFO);
int retval = jtux.UFile.ioctl(usb_fd, IOCTL_USB_CONNECTINFO, buf1);
if(retval<0)
{
//System.out.println("Error "+retval);
continue;
}
else
{
//these bufs create the 'devnum', but you'll need to check endian in java.nio.Buffer
int checkedDevNum = 0;
if(java.nio.ByteOrder.nativeOrder() != java.nio.ByteOrder.BIG_ENDIAN)
checkedDevNum = ((buf1[3] & 0xFF) << 24) | ((buf1[2] & 0xFF) << 16) | ((buf1[1] & 0xFF) << 8) | (buf1[0] & 0xFF);
else
checkedDevNum = ((buf1[0] & 0xFF) << 24) | ((buf1[1] & 0xFF) << 16) | ((buf1[2] & 0xFF) << 8) | (buf1[3] & 0xFF);
//System.out.println("checked dev num=" + checkedDevNum);
if (checkedDevNum != usbMinor)
continue;
}
jtux.UFile.read(usb_fd, desc, 18);
// also make sure the serial index is non-zero
//System.out.println("Manuf index "+ (desc[14]&0xFF) +
// " Product index "+ (desc[15]&0xFF) +
// " Serial index "+ (desc[16]&0xFF));
if ((desc[16] & 0xFF) == 0)
continue;
}
catch (jtux.UErrorException e)
{
//System.out.println(e);
continue;
}
finally
{
try
{
jtux.UFile.close(usb_fd);
}
catch (jtux.UErrorException e1)
{
}
usb_fd=-1;
}
// Now read the serial and convert it to a 64-bit integer to return
long rv = 0;
int rvBitOffset = 0;
try
{
inReader = new java.io.FileReader("/sys/bus/usb/devices/" + usbdevids[i] + "/serial");
long currRead = inReader.read();
while (currRead != -1)
{
currRead = Integer.parseInt(((char) currRead) + "", 16);
rv = rv ^ ((currRead & 0xF) << rvBitOffset);
//System.out.println("Updating HWID rv=" + rv + " currRead=" + currRead + " rvBitOffset=" + rvBitOffset);
currRead = inReader.read();
rvBitOffset += 4;
rvBitOffset = rvBitOffset % 64;
}
inReader.close();
inReader = null;
}
catch (NumberFormatException nfe)
{
// This can happen reading the line terminator
if (inReader != null)
{
try
{
inReader.close();
inReader = null;
}
catch (Exception e2){}
}
}
catch (Exception e)
{
continue;
}
if (targetSerialID != 0 && Math.abs(targetSerialID) != Math.abs(rv))
continue;
return Math.abs(rv);
}
}
}
return 0;
}
public static final int SMB_MOUNT_EXISTS = 0;
public static final int SMB_MOUNT_SUCCEEDED = 1;
public static final int SMB_MOUNT_FAILED = -1;
public static int doSMBMount(String smbPath, String localPath)
{
if (smbPath.startsWith("smb://"))
smbPath = smbPath.substring(4);
// Check if the mount is already done
String grepStr;
if (Sage.EMBEDDED)
grepStr = "mount -t cifs | grep -i \"" + localPath + "\"";
else
grepStr = "mount -t smbfs | grep -i \"" + localPath + "\"";
if (IOUtils.exec2(new String[] { "sh", "-c", grepStr }) == 0)
{
//if (Sage.DBG) System.out.println("SMB Mount already exists");
return SMB_MOUNT_EXISTS;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Path: " + smbPath + " " + localPath);
new java.io.File(localPath).mkdirs();
// Extract any authentication information
String smbUser = null;
String smbPass = null;
int authIdx = smbPath.indexOf('@');
if (authIdx != -1)
{
int colonIdx = smbPath.indexOf(':');
if (colonIdx != -1)
{
smbUser = smbPath.substring(2, colonIdx);
smbPass = smbPath.substring(colonIdx + 1, authIdx);
smbPath = "//" + smbPath.substring(authIdx + 1);
}
}
if (!Sage.EMBEDDED)
{
String smbOptions;
if (Sage.LINUX_OS)
{
if (smbUser != null)
smbOptions = "username=" + smbUser + ",password=" + smbPass + ",iocharset=utf8";
else
smbOptions = "guest,iocharset=utf8";
}
else
{
if (smbUser != null)
smbOptions = smbUser + ":" + smbPass;
else
smbOptions = "guest:";
}
// check to see if property exists if it doesn't check for smbmount with "which" command
if (Sage.getRawProperties().getWithNoDefault("smbmount_present") == null)
{
String result = IOUtils.exec(new String[] {"which", "smbmount"});
// if nothing returned from "which" command then smbmount is not present so set property false
if (result == null || result.isEmpty())
{
Sage.putBoolean("smbmount_present", false);
} else {
Sage.putBoolean("smbmount_present", true);
}
}
// set execution variable based on property value
String execSMBMount = Sage.getBoolean("smbmount_present", true) ?
"smbmount" : "mount.cifs";
if (IOUtils.exec2(Sage.LINUX_OS ? new String[] { execSMBMount, smbPath, localPath , "-o", smbOptions } :
new String[] { "mount_smbfs", "-N", "//" + smbOptions + "@" + smbPath.substring(2), localPath}) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Failed");
return SMB_MOUNT_FAILED;
}
}
else
{
// Resolve the SMB name to an IP address since we don't have proper NetBIOS resolution on this
// device.
String netbiosName = smbPath.substring(2, smbPath.indexOf('/', 3));
String smbShareName = smbPath.substring(smbPath.indexOf('/', 3) + 1);
if (smbShareName.endsWith("/"))
smbShareName = smbShareName.substring(0, smbShareName.length() - 1);
String tmpSmbPath = smbPath;
try
{
tmpSmbPath = "//" + jcifs.netbios.NbtAddress.getByName(netbiosName).getHostAddress() +
smbPath.substring(smbPath.indexOf('/', 3));
if (Sage.DBG) System.out.println("Updated SMB path with IP address to be: " + tmpSmbPath);
}
catch (java.net.UnknownHostException uhe)
{
if (Sage.DBG) System.out.println("Error with NETBIOS naming lookup of:" + uhe);
uhe.printStackTrace();
// If we can't resolve the netbios name then there's no way the mount will succeed so don't bother
// since sometimes mount.cifs can hang if it can't resolve something appropriately
return SMB_MOUNT_FAILED;
}
String smbOptions;
if (Sage.LINUX_OS)
{
if (smbUser != null)
smbOptions = "username=" + smbUser + ",password=" + smbPass + ",iocharset=utf8,nounix";
else
smbOptions = "guest,iocharset=utf8,nounix";
}
else
{
if (smbUser != null)
smbOptions = smbUser + ":" + smbPass;
else
smbOptions = "guest:";
}
int smbRes;
if ((smbRes = IOUtils.exec2(Sage.LINUX_OS ? new String[] { "mount.cifs", tmpSmbPath, localPath , "-o", smbOptions } :
new String[] { "mount_smbfs", "-N", "//" + smbOptions + "@" + smbPath.substring(2), localPath})) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Failed res=" + smbRes);
if (Sage.LINUX_OS && smbUser == null)
{
if (Sage.DBG) System.out.println("Retrying SMB mount with share access...");
smbOptions = "username=share,guest,iocharset=utf8";
if ((smbRes = IOUtils.exec2(new String[] { "mount.cifs", tmpSmbPath, localPath , "-o", smbOptions })) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("Retrying SMB mount with share access(2)...");
smbOptions = "username=" + smbShareName + ",guest,iocharset=utf8";
if ((smbRes = IOUtils.exec2(new String[] { "mount.cifs", tmpSmbPath, localPath , "-o", smbOptions })) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Failed res=" + smbRes);
return SMB_MOUNT_FAILED;
}
}
}
return SMB_MOUNT_FAILED;
}
}
}
}
public static final int NFS_MOUNT_EXISTS = 0;
public static final int NFS_MOUNT_SUCCEEDED = 1;
public static final int NFS_MOUNT_FAILED = -1;
public static int doNFSMount(String nfsPath, String localPath)
{
if (!Sage.LINUX_OS) return NFS_MOUNT_FAILED;
if (nfsPath.startsWith("nfs://"))
nfsPath = nfsPath.substring(6);
// Check if the mount is already done
if (IOUtils.exec2(new String[] { "sh", "-c", "mount -t nfs | grep -i \"" + localPath + "\"" }) == 0)
{
//if (Sage.DBG) System.out.println("NFS Mount already exists");
return NFS_MOUNT_EXISTS;
}
else
{
if (Sage.DBG) System.out.println("NFS Mount Path: " + nfsPath + " " + localPath);
new java.io.File(localPath).mkdirs();
String nfsOptions = "nolock,tcp,rsize=32768,wsize=32768,noatime";
int nfsRes = IOUtils.exec2(new String[] {"mount", "-t", "nfs", nfsPath, localPath, "-o", nfsOptions});
if (nfsRes == 0)
{
if (Sage.DBG) System.out.println("NFS Mount Succeeded");
return NFS_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("NFS Mount Failed res=" + nfsRes);
return NFS_MOUNT_FAILED;
}
}
}
public static boolean undoMount(String currPath)
{
return IOUtils.exec2(new String[] { "umount", currPath}) == 0;
}
public static String convertSMBURLToUNCPath(String smbPath)
{
StringBuffer sb = new StringBuffer("\\\\" + smbPath.substring("smb://".length()));
for (int i = 0; i < sb.length(); i++)
if (sb.charAt(i) == '/')
sb.setCharAt(i, '\\');
return sb.toString();
}
// Creates a java.io.BufferedReader for the specified file and checks the first two bytes for the Unicode BOM and sets the
// charset accordingly; otherwise if there's no BOM it'll use the passed in defaultCharset
public static java.io.BufferedReader openReaderDetectCharset(String filePath, String defaultCharset) throws java.io.IOException
{
return openReaderDetectCharset(new java.io.File(filePath), defaultCharset);
}
public static java.io.BufferedReader openReaderDetectCharset(java.io.File filePath, String defaultCharset) throws java.io.IOException
{
java.io.FileInputStream fis = null;
try
{
fis = new java.io.FileInputStream(filePath);
int b1 = fis.read();
int b2 = fis.read();
// Check for big/little endian unicode marker; otherwise use the default charset to open
String targetCharset = defaultCharset;
if (b1 == 0xFF && b2 == 0xFE)
targetCharset = "UTF-16LE";
else if (b1 == 0xFE && b2 == 0xFF)
targetCharset = "UTF-16BE";
else if (Sage.I18N_CHARSET.equals(defaultCharset))
{
// Read 16k of data to verify that we have the proper charset if we think it's UTF8
byte[] extraData = new byte[16384];
extraData[0] = (byte)(b1 & 0xFF);
extraData[1] = (byte)(b2 & 0xFF);
int dataLen = 2 + fis.read(extraData, 2, extraData.length - 2);
boolean utf8valid = true;
for (int i = 0; i < dataLen && utf8valid; i++)
{
int c = extraData[i] & 0xFF;
if (c <= 127)
continue;
if (i + 1 >= dataLen)
{
break;
}
switch (c >> 4)
{
case 12: case 13:
/* 110x xxxx 10xx xxxx*/
i++;
c = extraData[i] & 0xFF;
if ((c & 0xC0) != 0x80)
utf8valid = false;
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
i++;
c = extraData[i] & 0xFF;
if ((c & 0xC0) != 0x80 || i + 1 >= dataLen)
utf8valid = false;
else
{
i++;
c = extraData[i] & 0xFF;
if ((c & 0xC0) != 0x80)
utf8valid = false;
}
break;
default:
/* 10xx xxxx, 1111 xxxx */
utf8valid = false;
break;
}
}
if (!utf8valid)
{
if (Sage.DBG) System.out.println("Charset autodetection found invalid UTF8 data in the file; switching to default charset instead");
// Cp1252 is a superset of ISO-8859-1; so it's preferable to use it since it'll decode more characters...BUT we really should
// just use the platform default instead; that's generally what people will be using from a text editor.
// And embedded doesn't support Cp1252, so we need to remove that from there and just use ISO-8859-1
targetCharset = Sage.EMBEDDED ? Sage.BYTE_CHARSET : null;
}
}
fis.close();
if (targetCharset == null)
return new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(filePath)));
else
return new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(filePath), targetCharset));
}
catch (java.io.IOException e)
{
if (fis != null)
fis.close();
throw e;
}
}
public static String calcMD5(java.io.File f)
{
if (f != null && f.isFile())
{
java.io.FileInputStream fis = null;
try
{
fis = new java.io.FileInputStream(f);
java.security.MessageDigest algorithm = null;
algorithm = java.security.MessageDigest.getInstance("MD5");
algorithm.reset();
byte[] buf = new byte[32768];
int numRead = fis.read(buf);
while (numRead > 0)
{
algorithm.update(buf, 0, numRead);
numRead = fis.read(buf);
}
byte[] digest = algorithm.digest();
StringBuffer finalSum = new StringBuffer();
for (int i = 0; i < digest.length; i++)
{
if (((int) (digest[i] & 0xFF)) <= 0x0F)
{
finalSum.append('0');
}
finalSum.append(Integer.toHexString((int)(digest[i] & 0xFF)));
}
return finalSum.toString().toUpperCase();
}
catch (Exception e)
{
/*if (Sage.DBG)*/ System.out.println("ERROR calculating MD5Sum of:" + e);
return null;
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (Exception e)
{}
}
}
}
else
return null;
}
public static final String[] VFAT_MOUNTABLE_PARTITION_TYPES = { "6", "b", "c", "e", "f" };
public static final String[] NTFS_MOUNTABLE_PARTITION_TYPES = { "7" };
public static boolean isExternalDriveMounted(String devPath, String mountPath)
{
return (IOUtils.exec2(new String[] { "sh", "-c", "mount | grep -i \"" + mountPath + " type\"" }) == 0);
}
public static boolean mountExternalDrive(String devPath, String mountPath)
{
return mountExternalDrive(devPath, mountPath, false);
}
public static boolean mountExternalDrive(String devPath, String mountPath, boolean optimizePerformance)
{
if (!Sage.LINUX_OS) return false;
// Check to see if it's already mounted
if (isExternalDriveMounted(devPath, mountPath))
{
if (Sage.DBG) System.out.println("Ignoring mount for " + devPath + " because it's already mounted at: " + mountPath);
return true;
}
// First use 'sfdisk' to determine the partition type so we know if we should
// mount it w/ the '-o utf8' option or not
String partNum = devPath.substring(devPath.length() - 1);
String sfRes = IOUtils.exec(new String[] { "sfdisk", "-c", "/dev/" + devPath.substring(0, devPath.length() - 1), partNum});
sfRes = sfRes.trim();
if ("83".equals(sfRes) && optimizePerformance)
{
// Special options for mounting ext4 drives (this should fail if it's not ext4 since the 83 flag just means ext2/3/4)
if (IOUtils.exec2(new String[] {"mount", "-t", "ext4", "/dev/" + devPath, mountPath, "-o", "noatime,barrier=0,data=writeback"}) == 0)
return true;
}
// If we have a failure; then keep going and try all the possible ways to mount the drive.
for (int i = 0; i < VFAT_MOUNTABLE_PARTITION_TYPES.length; i++)
{
if (sfRes.equals(VFAT_MOUNTABLE_PARTITION_TYPES[i]))
{
if (IOUtils.exec2(new String[] {"mount", "-t", "vfat", "/dev/" + devPath, mountPath, "-o", "utf8,noatime"}) == 0)
return true;
}
}
for (int i = 0; i < NTFS_MOUNTABLE_PARTITION_TYPES.length; i++)
{
if (sfRes.equals(NTFS_MOUNTABLE_PARTITION_TYPES[i]))
{
if (Sage.EMBEDDED)
{
if (IOUtils.exec2(new String[] {"/usr/local/bin/ntfs-3g", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
else if (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
}
if (devPath.length() == 3)
{
// This is for NTFS mounting since we mount the disk and not the partitions
if (Sage.EMBEDDED)
{
if (IOUtils.exec2(new String[] {"/usr/local/bin/ntfs-3g", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
else
{
if (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
}
if (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath, "-o", "noatime"}) == 0)
return true;
return (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath}) == 0);
}
// Reads a newline (\r\n or \n) terminated string (w/out returning the newline). rv can be used as a temp buffer, buf is the buffer used for reading the data and may already contain
// extra data in it before calling this method, the SocketChannel passed in MUST be a blocking socket. Extra data may be in the buf after returning from this method call.
public static String readLineBytes(java.nio.channels.SocketChannel s, java.nio.ByteBuffer buf, long timeout, StringBuffer rv) throws java.io.InterruptedIOException, java.io.IOException
{
if (rv == null)
rv = new StringBuffer();
else
rv.setLength(0);
boolean needsFlip = true;
if (buf.hasRemaining() && buf.position() > 0)
needsFlip = false;
else
buf.clear();
int readRes = 0;
TimeoutHandler.registerTimeout(timeout, s);
try
{
if ((!buf.hasRemaining() || buf.position() == 0) && (readRes = s.read(buf)) <= 0)
{
throw new java.io.EOFException();
}
}
finally
{
TimeoutHandler.clearTimeout(s);
}
if (needsFlip)
buf.flip();
int currByte = (buf.get() & 0xFF);
while (true)
{
if (currByte == '\r')
{
if (!buf.hasRemaining())
{
buf.clear();
TimeoutHandler.registerTimeout(timeout, s);
try
{
if ((readRes = s.read(buf)) <= 0)
{
throw new java.io.EOFException();
}
}
finally
{
TimeoutHandler.clearTimeout(s);
}
buf.flip();
}
currByte = (buf.get() & 0xFF);
if (currByte == '\n')
{
return rv.toString();
}
rv.append('\r');
}
else if (currByte == '\n')
{
return rv.toString();
}
rv.append((char)currByte);
if (!buf.hasRemaining())
{
buf.clear();
TimeoutHandler.registerTimeout(timeout, s);
try
{
if ((readRes = s.read(buf)) <= 0)
{
throw new java.io.EOFException();
}
}
finally
{
TimeoutHandler.clearTimeout(s);
}
buf.flip();
}
currByte = (buf.get() & 0xFF);
}
}
// Downloads all of the specified files from a SageTV server to the target destination files. Only allowed with
// SageTVClient mode
public static void downloadFilesFromSageTVServer(java.io.File[] srcFiles, java.io.File[] dstFiles) throws java.io.IOException
{
if (!Sage.client) throw new java.io.IOException("Cannot download files from SageTV server since we are not in client mode!");
java.net.Socket sock = null;;
java.io.DataOutputStream outStream = null;
java.io.DataInputStream inStream = null;
java.io.OutputStream fileOut = null;
try
{
sock = new java.net.Socket();
sock.connect(new java.net.InetSocketAddress(Sage.preferredServer, 7818), 5000);
sock.setSoTimeout(30000);
//sock.setTcpNoDelay(true);
outStream = new java.io.DataOutputStream(new java.io.BufferedOutputStream(sock.getOutputStream()));
inStream = new java.io.DataInputStream(new java.io.BufferedInputStream(sock.getInputStream()));
byte[] xferBuf = new byte[32768];
for (int i = 0; i < srcFiles.length; i++)
{
// Always request file access since this is generally not used for MediaFile objects
NetworkClient.getSN().requestMediaServerAccess(srcFiles[i], true);
outStream.write("OPENW ".getBytes(Sage.BYTE_CHARSET));
outStream.write(srcFiles[i].toString().getBytes("UTF-16BE"));
outStream.write("\r\n".getBytes(Sage.BYTE_CHARSET));
outStream.flush();
String str = Sage.readLineBytes(inStream);
if (!"OK".equals(str))
throw new java.io.IOException("Error opening remote file of:" + str);
// get the size
outStream.write("SIZE\r\n".getBytes(Sage.BYTE_CHARSET));
outStream.flush();
str = Sage.readLineBytes(inStream);
long remoteSize = Long.parseLong(str.substring(0, str.indexOf(' ')));
fileOut = new java.io.FileOutputStream(dstFiles[i]);
outStream.write(("READ 0 " + remoteSize + "\r\n").getBytes(Sage.BYTE_CHARSET));
outStream.flush();
while (remoteSize > 0)
{
int currRead = (int)Math.min(xferBuf.length, remoteSize);
inStream.readFully(xferBuf, 0, currRead);
fileOut.write(xferBuf, 0, currRead);
remoteSize -= currRead;
}
fileOut.close();
fileOut = null;
// CLOSE happens automatically when you open a new file
//outStream.write("CLOSE\r\n".getBytes(Sage.BYTE_CHARSET));
//outStream.flush();
NetworkClient.getSN().requestMediaServerAccess(srcFiles[i], false);
}
}
finally
{
try{
if (sock != null)
sock.close();
}catch (Exception e1){}
try{
if (outStream != null)
outStream.close();
}catch (Exception e2){}
try{
if (inStream != null)
inStream.close();
}catch (Exception e3){}
try{
if (fileOut != null)
fileOut.close();
}catch (Exception e4){}
}
}
// This uses the old MVP server which as part of the protocol will return the MAC address of the other system
public static String getServerMacAddress(String hostname)
{
// Strip off any port that may be there
if (hostname.indexOf(":") != -1)
hostname = hostname.substring(0, hostname.indexOf(":"));
if (Sage.DBG) System.out.println("Requested to find MAC address of server at: " + hostname);
java.net.DatagramSocket sock = null;
try
{
sock = new java.net.DatagramSocket(16882); // they always come back on this port
java.net.DatagramPacket pack = new java.net.DatagramPacket(new byte[50], 50);
byte[] data = pack.getData();
data[3] = 1;
String localIP;
if (Sage.WINDOWS_OS || Sage.MAC_OS_X)
localIP = java.net.InetAddress.getLocalHost().getHostAddress();
else
localIP = LinuxUtils.getIPAddress();
if (Sage.DBG) System.out.println("Local IP is " + localIP);
int idx = localIP.indexOf('.');
data[16] = (byte)(Integer.parseInt(localIP.substring(0, idx)) & 0xFF);
localIP = localIP.substring(idx + 1);
idx = localIP.indexOf('.');
data[17] = (byte)(Integer.parseInt(localIP.substring(0, idx)) & 0xFF);
localIP = localIP.substring(idx + 1);
idx = localIP.indexOf('.');
data[18] = (byte)(Integer.parseInt(localIP.substring(0, idx)) & 0xFF);
localIP = localIP.substring(idx + 1);
data[19] = (byte)(Integer.parseInt(localIP) & 0xFF);
pack.setLength(50);
// Find the broadcast address for this subnet.
pack.setAddress(java.net.InetAddress.getByName(hostname));
pack.setPort(16881);
sock.send(pack);
sock.setSoTimeout(3000);
sock.receive(pack);
if (pack.getLength() >= 20)
{
if (Sage.DBG) System.out.println("MAC discovery packet received:" + pack);
String mac = (((data[8] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[8] & 0xFF, 16) + ":" +
(((data[9] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[9] & 0xFF, 16) + ":" +
(((data[10] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[10] & 0xFF, 16) + ":" +
(((data[11] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[11] & 0xFF, 16) + ":" +
(((data[12] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[12] & 0xFF, 16) + ":" +
(((data[13] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[13] & 0xFF, 16);
if (Sage.DBG) System.out.println("Resulting MAC=" + mac);
return mac;
}
}
catch (Exception e)
{
//System.out.println("Error discovering servers:" + e);
}
finally
{
if (sock != null)
{
try
{
sock.close();
}catch (Exception e){}
sock = null;
}
}
return null;
}
public static void sendWOLPacket(String macAddress)
{
// Strip off any port that may be there
if (Sage.DBG) System.out.println("Sending out WOL packet to MAC address: " + macAddress);
java.net.DatagramSocket sock = null;
try
{
sock = new java.net.DatagramSocket(9); // WOL is on port 9
java.net.DatagramPacket pack = new java.net.DatagramPacket(new byte[102], 102);
byte[] data = pack.getData();
data[0] = (byte)0xFF;
data[1] = (byte)0xFF;
data[2] = (byte)0xFF;
data[3] = (byte)0xFF;
data[4] = (byte)0xFF;
data[5] = (byte)0xFF;
byte[] macBytes = new byte[6];
java.util.StringTokenizer macToker = new java.util.StringTokenizer(macAddress, ":-");
for (int i = 0; i < macBytes.length; i++)
{
macBytes[i] = (byte)(Integer.parseInt(macToker.nextToken(), 16) & 0xFF);
}
for (int i = 0; i < 16; i++)
{
System.arraycopy(macBytes, 0, data, 6*(i + 1), 6);
}
String localIP;
if (Sage.WINDOWS_OS || Sage.MAC_OS_X)
localIP = java.net.InetAddress.getLocalHost().getHostAddress();
else
localIP = LinuxUtils.getIPAddress();
if (Sage.DBG) System.out.println("Local IP is " + localIP);
int lastDot = localIP.lastIndexOf('.');
String broadcastIP = localIP.substring(0, lastDot) + ".255";
if (Sage.DBG) System.out.println("Broadcast IP is " + broadcastIP);
pack.setLength(102);
pack.setAddress(java.net.InetAddress.getByName(broadcastIP));
pack.setPort(9);
sock.send(pack);
}
catch (Exception e)
{
//System.out.println("Error discovering servers:" + e);
}
finally
{
if (sock != null)
{
try
{
sock.close();
}catch (Exception e){}
sock = null;
}
}
}
public static byte[] getFileAsBytes(java.io.File f)
{
try
{
java.io.InputStream is = new java.io.FileInputStream(f);
byte[] rv = new byte[(int)f.length()];
int numRead = is.read(rv);
while (numRead < rv.length)
{
int currRead = is.read(rv, numRead, rv.length - numRead);
if (currRead < 0)
break;
numRead += currRead;
}
is.close();
return rv;
}
catch (java.io.IOException e)
{
if (Sage.DBG) System.out.println("ERROR reading file " + f + " of:" + e);
return null;
}
}
}
| java/sage/IOUtils.java | /*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sage;
public class IOUtils
{
private IOUtils()
{
}
public static String getFileExtension(java.io.File f)
{
String s = f == null ? "" : f.toString();
int idx = s.lastIndexOf('.');
if (idx < 0)
return "";
else
return s.substring(idx + 1);
}
// Returns the size of all files contained within the directory & recursively beneath
public static long getDirectorySize(java.io.File f)
{
return getDirectorySize(f, new java.util.HashSet());
}
private static long getDirectorySize(java.io.File f, java.util.HashSet done)
{
// protect against infinite recursion due to symbolic links on Linux
java.io.File realF = f;
try
{
// On Linux we need to resolve symbolic links or we could recurse forever
realF = f.getCanonicalFile();
}
catch (java.io.IOException e){}
if (!done.add(realF)) return 0;
long rv = 0;
java.io.File[] kids = f.listFiles();
for (int i = 0; kids != null && i < kids.length; i++)
{
if (kids[i].isFile())
rv += kids[i].length();
else if (kids[i].isDirectory())
rv += getDirectorySize(kids[i]);
}
return rv;
}
// Returns the all files contained within the directory & recursively beneath. Does NOT return directories
public static java.io.File[] listFilesRecursive(java.io.File f)
{
return listFilesRecursive(f, true);
}
public static java.io.File[] listFilesRecursive(java.io.File f, boolean includeAllFileTypes)
{
java.util.ArrayList rv = new java.util.ArrayList();
listFilesRecursive(f, rv, new java.util.HashSet(), includeAllFileTypes);
return (java.io.File[]) rv.toArray(new java.io.File[0]);
}
private static void listFilesRecursive(java.io.File f, java.util.ArrayList rv, java.util.HashSet done, boolean includeAllFileTypes)
{
// protect against infinite recursion due to symbolic links on Linux
java.io.File realF = f;
try
{
// On Linux we need to resolve symbolic links or we could recurse forever
realF = f.getCanonicalFile();
}
catch (java.io.IOException e){}
if (!done.add(realF)) return;
java.io.File[] kids = f.listFiles();
for (int i = 0; kids != null && i < kids.length; i++)
{
if (kids[i].isFile())
{
if (includeAllFileTypes || Seeker.getInstance().hasImportableFileExtension(kids[i].getName()))
rv.add(kids[i]);
}
else if (kids[i].isDirectory())
listFilesRecursive(kids[i], rv, done, includeAllFileTypes);
}
}
// Returns the all files contained within the directory & recursively beneath. Does NOT return directories
public static java.io.File[] listServerFilesRecursive(java.io.File f)
{
return listServerFilesRecursive(f, true);
}
public static java.io.File[] listServerFilesRecursive(java.io.File f, boolean includeAllFileTypes)
{
if (!Sage.client) return new java.io.File[0];
java.net.Socket sock = null;
java.io.DataOutputStream outStream = null;
java.io.DataInputStream inStream = null;
try
{
sock = new java.net.Socket();
sock.connect(new java.net.InetSocketAddress(Sage.preferredServer, 7818), 5000);
sock.setSoTimeout(30000);
//sock.setTcpNoDelay(true);
outStream = new java.io.DataOutputStream(new java.io.BufferedOutputStream(sock.getOutputStream()));
inStream = new java.io.DataInputStream(new java.io.BufferedInputStream(sock.getInputStream()));
// First request access to it since it's probably not in the media filesystem
boolean gotMSAccess = false;
if (NetworkClient.getSN().requestMediaServerAccess(f, true))
{
gotMSAccess = true;
}
outStream.write((includeAllFileTypes ? "LISTRECURSIVEALLW " : "LISTRECURSIVEW").getBytes(sage.Sage.BYTE_CHARSET));
outStream.write(f.toString().getBytes("UTF-16BE"));
outStream.write("\r\n".getBytes(sage.Sage.BYTE_CHARSET));
outStream.flush();
String str = sage.Sage.readLineBytes(inStream);
if (!"OK".equals(str))
throw new java.io.IOException("Error doing remote recursive dir listing of:" + str);
// get the size
str = sage.Sage.readLineBytes(inStream);
int numFiles = Integer.parseInt(str);
java.io.File[] rv = new java.io.File[numFiles];
for (int i = 0; i < numFiles; i++)
{
rv[i] = new java.io.File(sage.MediaServer.convertToUnicode(sage.Sage.readLineBytes(inStream)));
}
if (gotMSAccess)
{
NetworkClient.getSN().requestMediaServerAccess(f, false);
}
return rv;
}
catch (java.io.IOException e)
{
if (Sage.DBG) System.out.println("ERROR downloading recursive directory listing from server of :" + e + " for dir: " + f);
return new java.io.File[0];
}
finally
{
try{
if (sock != null)
sock.close();
}catch (Exception e1){}
try{
if (outStream != null)
outStream.close();
}catch (Exception e2){}
try{
if (inStream != null)
inStream.close();
}catch (Exception e3){}
}
}
// Returns the list of all files contained within the specified directory
public static String[] listServerFiles(java.io.File f)
{
if (!Sage.client) return Pooler.EMPTY_STRING_ARRAY;
java.net.Socket sock = null;
java.io.DataOutputStream outStream = null;
java.io.DataInputStream inStream = null;
try
{
sock = new java.net.Socket();
sock.connect(new java.net.InetSocketAddress(Sage.preferredServer, 7818), 5000);
sock.setSoTimeout(30000);
//sock.setTcpNoDelay(true);
outStream = new java.io.DataOutputStream(new java.io.BufferedOutputStream(sock.getOutputStream()));
inStream = new java.io.DataInputStream(new java.io.BufferedInputStream(sock.getInputStream()));
// First request access to it since it's probably not in the media filesystem
boolean gotMSAccess = false;
if (NetworkClient.getSN().requestMediaServerAccess(f, true))
{
gotMSAccess = true;
}
outStream.write("LISTW ".getBytes(sage.Sage.BYTE_CHARSET));
outStream.write(f.toString().getBytes("UTF-16BE"));
outStream.write("\r\n".getBytes(sage.Sage.BYTE_CHARSET));
outStream.flush();
String str = sage.Sage.readLineBytes(inStream);
if (!"OK".equals(str))
throw new java.io.IOException("Error doing remote recursive dir listing of:" + str);
// get the size
str = sage.Sage.readLineBytes(inStream);
int numFiles = Integer.parseInt(str);
String[] rv = new String[numFiles];
for (int i = 0; i < numFiles; i++)
{
rv[i] = sage.MediaServer.convertToUnicode(sage.Sage.readLineBytes(inStream));
}
if (gotMSAccess)
{
NetworkClient.getSN().requestMediaServerAccess(f, false);
}
return rv;
}
catch (java.io.IOException e)
{
if (Sage.DBG) System.out.println("ERROR downloading recursive directory listing from server of :" + e + " for dir: " + f);
return Pooler.EMPTY_STRING_ARRAY;
}
finally
{
try{
if (sock != null)
sock.close();
}catch (Exception e1){}
try{
if (outStream != null)
outStream.close();
}catch (Exception e2){}
try{
if (inStream != null)
inStream.close();
}catch (Exception e3){}
}
}
public static java.io.File getRootDirectory(java.io.File f)
{
if (f == null) return null;
int numParents = 0;
java.io.File currParent = f;
while (currParent.getParentFile() != null)
{
currParent = currParent.getParentFile();
numParents++;
}
if (Sage.EMBEDDED)
{
String pathStr = f.getAbsolutePath();
boolean useOurCheck = false;
if (pathStr.startsWith("/var/media/") || pathStr.startsWith("/tmp/external/"))
{
numParents -= 3;
useOurCheck = true;
}
else if (pathStr.startsWith("/tmp/sagetv_shares/"))
{
numParents -= 4;
useOurCheck = true;
}
if (useOurCheck)
{
while (numParents-- > 0 && f != null)
f = f.getParentFile();
return f;
}
}
if (currParent.toString().equals("\\\\") || (Sage.MAC_OS_X && f.toString().startsWith("/Volumes")))
{
// UNC Pathname, add the computer name and share name to get the actual root folder
// or on Mac we need to protect the /Volumes directory
numParents -= 2;
while (numParents-- > 0)
f = f.getParentFile();
return f;
}
else
return currParent;
}
public static void copyFile(java.io.File srcFile, java.io.File destFile) throws java.io.IOException
{
java.io.FileOutputStream fos = null;
java.io.OutputStream outStream = null;
java.io.InputStream inStream = null;
try
{
outStream = new java.io.BufferedOutputStream(fos = new
java.io.FileOutputStream(destFile));
inStream = new java.io.BufferedInputStream(new
java.io.FileInputStream(srcFile));
byte[] buf = new byte[65536];
int numRead = inStream.read(buf);
while (numRead != -1)
{
outStream.write(buf, 0, numRead);
numRead = inStream.read(buf);
}
}
finally
{
try
{
if (inStream != null)
{
inStream.close();
inStream = null;
}
}
catch (java.io.IOException e) {}
try
{
if (outStream != null)
{
outStream.flush();
fos.getFD().sync();
outStream.close();
outStream = null;
}
}
catch (java.io.IOException e) {}
}
// Preserve the file timestamp on the copy as well
destFile.setLastModified(srcFile.lastModified());
}
public static String exec(String[] cmdArray)
{
return exec(cmdArray, true, true);
}
public static String exec(String[] cmdArray, final boolean getStderr, final boolean getStdout)
{
return exec(cmdArray, getStderr, getStdout, false);
}
public static String exec(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways)
{
return exec(cmdArray, getStderr, getStdout, controlRunaways, null);
}
public static String exec(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways,
java.io.File workingDir)
{
return (String) exec(cmdArray, getStderr, getStdout, controlRunaways, workingDir, false);
}
public static java.io.ByteArrayOutputStream execByteOutput(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways,
java.io.File workingDir)
{
return (java.io.ByteArrayOutputStream) exec(cmdArray, getStderr, getStdout, controlRunaways, workingDir, true);
}
private static Object exec(String[] cmdArray, final boolean getStderr, final boolean getStdout, final boolean controlRunaways,
java.io.File workingDir, boolean byteOutput)
{
final long timeLimit = controlRunaways ? Sage.getLong("control_runaway_exec_time_limit", 60000) : 0;
final long sizeLimit = controlRunaways ? Sage.getLong("control_runaway_exec_size_limit", 1024*1024) : 0;
try
{
final Process procy = Runtime.getRuntime().exec(cmdArray, null, workingDir);
final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(1024);
final long startTime = Sage.time();
Thread the = new Thread("InputStreamConsumer")
{
public void run()
{
try
{
java.io.InputStream buf = procy.getInputStream();
String s;
do
{
int c = buf.read();
if (c == -1)
break;
else if (getStdout)
baos.write(c);
if (sizeLimit > 0 && baos.size() > sizeLimit)
{
if (Sage.DBG) System.out.println("NOTICE: Forcibly terminating spawned process due to runaway memory detection!");
procy.destroy();
break;
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the.setDaemon(true);
the.start();
Thread the2 = new Thread("ErrorStreamConsumer")
{
public void run()
{
try
{
java.io.InputStream buf = procy.getErrorStream();
String s;
do
{
int c = buf.read();
if (c == -1)
break;
else if (getStderr)
baos.write(c);
if (sizeLimit > 0 && baos.size() > sizeLimit)
{
if (Sage.DBG) System.out.println("NOTICE: Forcibly terminating spawned process due to runaway memory detection!");
procy.destroy();
break;
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the2.setDaemon(true);
the2.start();
if (controlRunaways)
{
final boolean[] doneWaitin = new boolean[1];
doneWaitin[0] = false;
Pooler.execute(new Runnable()
{
public void run()
{
try
{
procy.waitFor();
}
catch (Exception e)
{
}
finally
{
synchronized (doneWaitin)
{
doneWaitin[0] = true;
doneWaitin.notifyAll();
}
}
}
});
synchronized (doneWaitin)
{
while (!doneWaitin[0] && Sage.time() - startTime < timeLimit)
{
doneWaitin.wait(Math.max(1, timeLimit - (Sage.time() - startTime)));
}
if (!doneWaitin[0])
{
if (Sage.DBG) System.out.println("NOTICE: Forcibly terminating spawned process due to runaway execution detection!");
procy.destroy();
}
}
}
else
procy.waitFor();
the.join(1000);
the2.join(1000);
if (byteOutput)
{
return baos;
}
if (Sage.EMBEDDED)
{
// If we don't use the default encoding here then some chars don't get converted right and the string is truncated.
// The test case is the Aeon Flux .mov file in DemoContent
return baos.toString();
}
try
{
return baos.toString(Sage.I18N_CHARSET);
}
catch (java.io.UnsupportedEncodingException uee)
{
// just use the default encoding
return baos.toString();
}
}
catch (Exception e)
{
if (byteOutput)
return null;
return e.toString();
}
}
public static int exec2(String[] cmdArray)
{
return exec3(cmdArray, true);
}
public static int exec2(String[] cmdArray, boolean waitForExit)
{
return exec3(cmdArray, waitForExit);
}
public static int exec2(String cmd)
{
return exec3(cmd, true);
}
public static int exec2(String cmd, boolean waitForExit)
{
return exec3(cmd, waitForExit);
}
private static int exec3(Object obj, boolean waitForExit)
{
if (Sage.DBG) System.out.println("Executing process: " +
((obj instanceof String[]) ? java.util.Arrays.asList((String[])obj) : obj));
try
{
final Process procy = obj instanceof String[] ?
Runtime.getRuntime().exec((String[])obj) : Runtime.getRuntime().exec((String) obj);
if (Sage.DBG) System.out.println("Started process object: " + procy);
Thread the = new Thread("InputStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(procy.getInputStream()));
String s;
do
{
s = buf.readLine();
if (s == null)
break;
else
{
if (Sage.DBG) System.out.println("STDOUT:" + procy + ": " + s);
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the.setDaemon(true);
the.start();
Thread the2 = new Thread("ErrorStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(procy.getErrorStream()));
String s;
do
{
s = buf.readLine();
if (s == null)
break;
else
{
if (Sage.DBG) System.out.println("STDERR:" + procy + ": " + s);
}
}while (true);
buf.close();
}
catch (Exception e){}
}
};
the2.setDaemon(true);
the2.start();
if (waitForExit)
{
procy.waitFor();
the.join(1000);
the2.join(1000);
return procy.exitValue();
}
else
return 0;
}
catch (Exception e)
{
if (Sage.DBG) System.out.println("Error executing process " +
((obj instanceof String[]) ? (((String[])obj)[0]) : obj) + " : " + e);
return -1;
}
}
public static boolean deleteDirectory(java.io.File dir)
{
if (dir == null) return false;
java.io.File[] kids = dir.listFiles();
boolean rv = true;
for (int i = 0; i < kids.length; i++)
{
if (kids[i].isDirectory())
{
rv &= deleteDirectory(kids[i]);
}
else if (!kids[i].delete())
rv = false;
}
return dir.delete() && rv;
}
public static String getFileAsString(java.io.File file)
{
java.io.BufferedReader buffRead = null;
StringBuffer sb = new StringBuffer();
try
{
buffRead = new java.io.BufferedReader(new java.io.FileReader(file));
char[] cbuf = new char[4096];
int numRead = buffRead.read(cbuf);
while (numRead != -1)
{
sb.append(cbuf, 0, numRead);
numRead = buffRead.read(cbuf);
}
}
catch (java.io.IOException e)
{
System.out.println("Error reading file " + file + " of: " + e);
}
finally
{
if (buffRead != null)
{
try{buffRead.close();}catch(Exception e){}
buffRead = null;
}
}
return sb.toString();
}
public static String convertPlatformPathChars(String str)
{
StringBuffer sb = null;
int strlen = str.length();
char replaceChar = java.io.File.separatorChar;
char testChar = (replaceChar == '/') ? '\\' : '/';
for (int i = 0; i < strlen; i++)
{
char c = str.charAt(i);
if (c == testChar)
{
if (sb == null)
{
sb = new StringBuffer(str.length());
sb.append(str.substring(0, i));
}
sb.append(replaceChar);
}
else if (sb != null)
sb.append(c);
}
if (sb == null)
return str;
else
return sb.toString();
}
public static java.net.InetAddress getSubnetMask()
{
return getSubnetMask(null);
}
public static java.net.InetAddress getSubnetMask(java.net.InetAddress adapterAddr)
{
if (Sage.EMBEDDED)
{
try
{
String eth0Info = IOUtils.exec(new String[] { "ifconfig", "eth0" });
int idx0 = eth0Info.indexOf("Mask:");
if (idx0 != -1)
{
int idx1 = eth0Info.indexOf("\n", idx0);
if (idx1 != -1)
{
return java.net.InetAddress.getByName(eth0Info.substring(idx0 + "Mask:".length(), idx1).trim());
}
}
return java.net.InetAddress.getByName("255.255.255.0");
}catch(Throwable e)
{
System.out.println("ERROR:" + e);
}
return null;
}
else
{
String ipAddrInfo = exec(new String[] { Sage.WINDOWS_OS ? "ipconfig" : "ifconfig"});
java.util.regex.Pattern patty = java.util.regex.Pattern.compile("255\\.255\\.[0-9]+\\.[0-9]+");
java.util.regex.Matcher matchy = patty.matcher(ipAddrInfo);
try
{
int adapterIndex = (adapterAddr == null) ? -1 : ipAddrInfo.indexOf(adapterAddr.getHostAddress());
while (matchy.find())
{
String currMatch = matchy.group();
if ("255.255.255.255".equals(currMatch))
continue; // ignore the subnet masks that restrict all since they're not what we want
// Make sure we're on the network adapter of interest
if (matchy.start() > adapterIndex)
return java.net.InetAddress.getByName(currMatch);
}
return java.net.InetAddress.getByName("255.255.255.0");
}
catch (java.net.UnknownHostException e)
{
throw new RuntimeException(e);
}
}
}
// This returns the 40-byte MAC address
public static byte[] getMACAddress()
{
final String[] macBuf = new String[1];
try {
macBuf[0] = sage.Sage.getMACAddress0();
if(macBuf[0] != null) {
byte[] rv = new byte[6];
// The first digit is NOT always zero, don't skip it!
for (int i = 0; i < macBuf[0].length(); i+=3)
{
rv[(i/3)] = (byte)(Integer.parseInt(macBuf[0].substring(i, i+2), 16) & 0xFF);
}
return rv;
}
} catch(Throwable t) {}
try
{
String forcedMAC = Sage.get("forced_mac_address", null);
if (forcedMAC != null && forcedMAC.length() > 0)
{
if (Sage.DBG) System.out.println("Using forced MAC address of: " + forcedMAC);
macBuf[0] = forcedMAC;
}
else
{
String prefix;
final Process procy = Runtime.getRuntime().exec(Sage.WINDOWS_OS ? "ipconfig /all" : "ifconfig", null, null);
final java.util.regex.Pattern pat;// = java.util.regex.Pattern.compile(MiniClient.WINDOWS_OS ?
//"Physical Address(\\. )*\\: (\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit}\\-\\p{XDigit}\\p{XDigit})" :
//"(\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit}\\:\\p{XDigit}\\p{XDigit})");
if (Sage.WINDOWS_OS)
prefix = "";
else if (Sage.MAC_OS_X)
prefix = "ether";
else
prefix = ""; // no prefix for linux since language changes the label
pat = java.util.regex.Pattern.compile(prefix + " ((\\p{XDigit}{2}[:-]){5}\\p{XDigit}{2})");
Thread the = new Thread("InputStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(
procy.getInputStream()));
String s;
macBuf[0] = null;
while ((s = buf.readLine()) != null)
{
java.util.regex.Matcher m = pat.matcher(s);
// in case there's multiple adapters we only want the first one
if (macBuf[0] == null && m.find())
{
macBuf[0] = m.group(1);
}
}
buf.close();
}
catch (Exception e){}
}
};
the.setDaemon(true);
the.start();
Thread the2 = new Thread("ErrorStreamConsumer")
{
public void run()
{
try
{
java.io.BufferedReader buf = new java.io.BufferedReader(new java.io.InputStreamReader(
procy.getErrorStream()));
while (buf.readLine() != null);
buf.close();
}
catch (Exception e){}
}
};
the2.setDaemon(true);
the2.start();
the.join();
the2.join();
procy.waitFor();
}
if (macBuf[0] != null)
{
byte[] rv = new byte[6];
// The first digit is NOT always zero, so don't skip it
for (int i = 0; i < macBuf[0].length(); i+=3)
{
rv[(i/3)] = (byte)(Integer.parseInt(macBuf[0].substring(i, i+2), 16) & 0xFF);
}
return rv;
}
else
return null;
}
catch (Exception e)
{
System.out.println("Error getting MAC address of:" + e);
return null;
}
}
// Returns true if this socket connection came from the localhost
public static boolean isLocalhostSocket(java.net.Socket sake)
{
byte[] localIP = sake.getLocalAddress().getAddress();
byte[] remoteIP = sake.getInetAddress().getAddress();
return ((remoteIP[0] == 127 && remoteIP[1] == 0 && remoteIP[2] == 0 && remoteIP[3] == 1) ||
(remoteIP[0] == localIP[0] && remoteIP[1] == localIP[1] && remoteIP[2] == localIP[2] && remoteIP[3] == localIP[3]));
}
public static boolean safeEquals(Object o1, Object o2)
{
return (o1 == o2) || (o1 != null && o2 != null && o1.equals(o2));
}
// This returns a UTF-8 string on Windows, otherwise it just returns the string.
// This is used for passing filenames to non-Unicode apps like FFMPEG
public static String getLibAVFilenameString(String s)
{
if (Sage.WINDOWS_OS)
{
// If any non-ASCII characters are in this string; then create a temp file and put it in there instead.
// This works around an issue where the Windows OS will do a codepage conversion on the UTF-8 values we're passing
// on the command line. And also the Java bug where it doesn't send Unicode parameters to other processes.
// We still write the bytes in the temp file as UTF-8 format though.
boolean hasUni = false;
for (int i = 0; i < s.length(); i++)
{
int c = s.charAt(i) & 0xFFFF;
if (c > 127)
{
hasUni = true;
break;
}
}
if (hasUni)
{
try
{
java.io.File tmpFile = java.io.File.createTempFile("stvfm", ".txt");
tmpFile.deleteOnExit();
byte[] strBytes = s.getBytes("UTF-8");
java.io.OutputStream os = new java.io.FileOutputStream(tmpFile);
os.write(strBytes);
os.close();
return tmpFile.getAbsolutePath();
} catch (java.io.IOException ex)
{
if (Sage.DBG) System.out.println("Error creating temp file for UTF-8 parameter passing:" + ex);
return s;
}
}
else
return s;
}
else
return s;
}
public static boolean safemkdirs(java.io.File f)
{
if (Sage.MAC_OS_X)
{
String fstr = f.toString();
if (!fstr.startsWith("/Volumes/"))
return f.mkdirs();
// We can create all the dirs up until the one below Volumes
java.util.Stack dirStack = new java.util.Stack();
java.io.File currParent = null;
while (true)
{
currParent = f.getParentFile();
if (currParent == null)
return false;
if (currParent.getName().equals("Volumes"))
{
// We found the volumes root parent so we break out and create all the dirs on the stack
break;
}
dirStack.push(f);
f = currParent;
}
while (!dirStack.isEmpty())
{
if (!((java.io.File) dirStack.pop()).mkdir())
return false;
}
return true;
}
else
return f.mkdirs();
}
// Requires positive x
static int stringSize(long x)
{
long p = 10;
for (int i=1; i<19; i++)
{
if (x < p)
return i;
p = 10*p;
}
return 19;
}
final static byte[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
final static byte [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static byte [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
private static final byte[] LONG_MIN_VALUE_STRING_BYTES = "-9223372036854775808".getBytes();
// Returns the number of bytes written into the array
public static int printLongInByteArray(long i, byte[] dest, int offset)
{
if (i == Long.MIN_VALUE)
{
System.arraycopy(LONG_MIN_VALUE_STRING_BYTES, 0, dest, offset, LONG_MIN_VALUE_STRING_BYTES.length);
return LONG_MIN_VALUE_STRING_BYTES.length;
}
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
long q;
int r;
int charPos = size + offset;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
dest[--charPos] = DigitOnes[r];
dest[--charPos] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int)i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
dest[--charPos] = DigitOnes[r];
dest[--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16+3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
dest[--charPos] = digits[r];
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) {
dest[--charPos] = (byte)sign;
}
return size;
}
public static boolean isLocalhostAddress(java.net.InetAddress inetAddress)
{
byte[] remoteIP = inetAddress.getAddress();
if (remoteIP[0] == 127 && remoteIP[1] == 0 && remoteIP[2] == 0 && remoteIP[3] == 1)
return true;
try
{
byte[] localIP = java.net.InetAddress.getLocalHost().getAddress();
return (remoteIP[0] == localIP[0] && remoteIP[1] == localIP[1] && remoteIP[2] == localIP[2] && remoteIP[3] == localIP[3]);
}
catch (Exception e)
{
System.out.println("ERROR getting localhost address of:" + e);
}
return false;
}
static int _IOC_NRBITS = 8;
static int _IOC_TYPEBITS = 8;
static int _IOC_SIZEBITS = 14;
static int _IOC_DIRBITS = 2;
static int _IOC_NRMASK = ((1 << _IOC_NRBITS)-1);
static int _IOC_TYPEMASK = ((1 << _IOC_TYPEBITS)-1);
static int _IOC_SIZEMASK = ((1 << _IOC_SIZEBITS)-1);
static int _IOC_DIRMASK = ((1 << _IOC_DIRBITS)-1);
static int _IOC_NRSHIFT = 0;
static int _IOC_TYPESHIFT = (_IOC_NRSHIFT+_IOC_NRBITS);
static int _IOC_SIZESHIFT = (_IOC_TYPESHIFT+_IOC_TYPEBITS);
static int _IOC_DIRSHIFT = (_IOC_SIZESHIFT+_IOC_SIZEBITS);
static int _IOC_NONE = 0;
static int _IOC_WRITE = 1;
static int _IOC_READ = 2;
static int _IOW(int type, int nr, int size)
{
int dir=_IOC_WRITE;
return (((dir) << _IOC_DIRSHIFT) |
((type) << _IOC_TYPESHIFT) |
((nr) << _IOC_NRSHIFT) |
((size) << _IOC_SIZESHIFT));
}
static int IOCTL_USB_CONNECTINFO = _IOW('U', 17, 8 /* struct usb_connectinfo */);
static long getUSBHWID()
{
// First get what is supposed to be the serial number; and then verify it exists
String targetSerial = exec(new String[] { "tbutil", "getserial" });
// Now convert this to the 64-bit long for the targetSerialID
long targetSerialID = 0;
int targetBitOffset = 0;
try
{
int idx = 0;
long currRead = targetSerial.charAt(idx++);
while (true)
{
currRead = Integer.parseInt(((char) currRead) + "", 16);
targetSerialID = targetSerialID ^ ((currRead & 0xF) << targetBitOffset);
if (idx >= targetSerial.length())
break;
currRead = targetSerial.charAt(idx++);
targetBitOffset += 4;
targetBitOffset = targetBitOffset % 64;
}
}
catch (Exception nfe)
{
}
// Check in /sys/bus/usb/devices to find anything in there that has a 'serial' field; but only check the ones
// that start with a number.
String[] usbdevids = new java.io.File("/sys/bus/usb/devices").list();
for (int i = 0; usbdevids != null && i < usbdevids.length; i++)
{
//System.out.println("Checking USB Dev ID=" + usbdevids[i]);
if (Character.isDigit(usbdevids[i].charAt(0)))
{
// Check for the 'serial' field
java.io.File serialFile = new java.io.File("/sys/bus/usb/devices/" + usbdevids[i] + "/serial");
if (serialFile.isFile())
{
//System.out.println("Serial exists for this device...");
int usbMajor = Integer.parseInt(usbdevids[i].substring(0, 1));
java.io.Reader inReader = null;
int usbMinor = -1;
try
{
inReader = new java.io.FileReader("/sys/bus/usb/devices/" + usbdevids[i] + "/devnum");
usbMinor = Integer.parseInt(((char)inReader.read()) + "");
inReader.close();
inReader = null;
}
catch (Exception e)
{
continue;
}
java.text.DecimalFormat leadZeros = new java.text.DecimalFormat("000");
//System.out.println("USB dev num " + usbMajor + "-" + usbMinor);
String verificationDevice = "/dev/bus/usb/" + leadZeros.format(usbMajor) + "/" + leadZeros.format(usbMinor);
//System.out.println("Verifying w/ device:" + verificationDevice);
int usb_fd = -1;
byte[] buf1 = new byte[8];
byte[] desc = new byte[18];
try
{
usb_fd = jtux.UFile.open(verificationDevice, jtux.UConstant.O_RDWR);
//System.out.println("ioctl "+IOCTL_USB_CONNECTINFO);
int retval = jtux.UFile.ioctl(usb_fd, IOCTL_USB_CONNECTINFO, buf1);
if(retval<0)
{
//System.out.println("Error "+retval);
continue;
}
else
{
//these bufs create the 'devnum', but you'll need to check endian in java.nio.Buffer
int checkedDevNum = 0;
if(java.nio.ByteOrder.nativeOrder() != java.nio.ByteOrder.BIG_ENDIAN)
checkedDevNum = ((buf1[3] & 0xFF) << 24) | ((buf1[2] & 0xFF) << 16) | ((buf1[1] & 0xFF) << 8) | (buf1[0] & 0xFF);
else
checkedDevNum = ((buf1[0] & 0xFF) << 24) | ((buf1[1] & 0xFF) << 16) | ((buf1[2] & 0xFF) << 8) | (buf1[3] & 0xFF);
//System.out.println("checked dev num=" + checkedDevNum);
if (checkedDevNum != usbMinor)
continue;
}
jtux.UFile.read(usb_fd, desc, 18);
// also make sure the serial index is non-zero
//System.out.println("Manuf index "+ (desc[14]&0xFF) +
// " Product index "+ (desc[15]&0xFF) +
// " Serial index "+ (desc[16]&0xFF));
if ((desc[16] & 0xFF) == 0)
continue;
}
catch (jtux.UErrorException e)
{
//System.out.println(e);
continue;
}
finally
{
try
{
jtux.UFile.close(usb_fd);
}
catch (jtux.UErrorException e1)
{
}
usb_fd=-1;
}
// Now read the serial and convert it to a 64-bit integer to return
long rv = 0;
int rvBitOffset = 0;
try
{
inReader = new java.io.FileReader("/sys/bus/usb/devices/" + usbdevids[i] + "/serial");
long currRead = inReader.read();
while (currRead != -1)
{
currRead = Integer.parseInt(((char) currRead) + "", 16);
rv = rv ^ ((currRead & 0xF) << rvBitOffset);
//System.out.println("Updating HWID rv=" + rv + " currRead=" + currRead + " rvBitOffset=" + rvBitOffset);
currRead = inReader.read();
rvBitOffset += 4;
rvBitOffset = rvBitOffset % 64;
}
inReader.close();
inReader = null;
}
catch (NumberFormatException nfe)
{
// This can happen reading the line terminator
if (inReader != null)
{
try
{
inReader.close();
inReader = null;
}
catch (Exception e2){}
}
}
catch (Exception e)
{
continue;
}
if (targetSerialID != 0 && Math.abs(targetSerialID) != Math.abs(rv))
continue;
return Math.abs(rv);
}
}
}
return 0;
}
public static final int SMB_MOUNT_EXISTS = 0;
public static final int SMB_MOUNT_SUCCEEDED = 1;
public static final int SMB_MOUNT_FAILED = -1;
public static int doSMBMount(String smbPath, String localPath)
{
if (smbPath.startsWith("smb://"))
smbPath = smbPath.substring(4);
// Check if the mount is already done
String grepStr;
if (Sage.EMBEDDED)
grepStr = "mount -t cifs | grep -i \"" + localPath + "\"";
else
grepStr = "mount -t smbfs | grep -i \"" + localPath + "\"";
if (IOUtils.exec2(new String[] { "sh", "-c", grepStr }) == 0)
{
//if (Sage.DBG) System.out.println("SMB Mount already exists");
return SMB_MOUNT_EXISTS;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Path: " + smbPath + " " + localPath);
new java.io.File(localPath).mkdirs();
// Extract any authentication information
String smbUser = null;
String smbPass = null;
int authIdx = smbPath.indexOf('@');
if (authIdx != -1)
{
int colonIdx = smbPath.indexOf(':');
if (colonIdx != -1)
{
smbUser = smbPath.substring(2, colonIdx);
smbPass = smbPath.substring(colonIdx + 1, authIdx);
smbPath = "//" + smbPath.substring(authIdx + 1);
}
}
if (!Sage.EMBEDDED)
{
String smbOptions;
if (Sage.LINUX_OS)
{
if (smbUser != null)
smbOptions = "username=" + smbUser + ",password=" + smbPass + ",iocharset=utf8";
else
smbOptions = "guest,iocharset=utf8";
}
else
{
if (smbUser != null)
smbOptions = smbUser + ":" + smbPass;
else
smbOptions = "guest:";
}
if (IOUtils.exec2(Sage.LINUX_OS ? new String[] { "smbmount", smbPath, localPath , "-o", smbOptions } :
new String[] { "mount_smbfs", "-N", "//" + smbOptions + "@" + smbPath.substring(2), localPath}) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Failed");
return SMB_MOUNT_FAILED;
}
}
else
{
// Resolve the SMB name to an IP address since we don't have proper NetBIOS resolution on this
// device.
String netbiosName = smbPath.substring(2, smbPath.indexOf('/', 3));
String smbShareName = smbPath.substring(smbPath.indexOf('/', 3) + 1);
if (smbShareName.endsWith("/"))
smbShareName = smbShareName.substring(0, smbShareName.length() - 1);
String tmpSmbPath = smbPath;
try
{
tmpSmbPath = "//" + jcifs.netbios.NbtAddress.getByName(netbiosName).getHostAddress() +
smbPath.substring(smbPath.indexOf('/', 3));
if (Sage.DBG) System.out.println("Updated SMB path with IP address to be: " + tmpSmbPath);
}
catch (java.net.UnknownHostException uhe)
{
if (Sage.DBG) System.out.println("Error with NETBIOS naming lookup of:" + uhe);
uhe.printStackTrace();
// If we can't resolve the netbios name then there's no way the mount will succeed so don't bother
// since sometimes mount.cifs can hang if it can't resolve something appropriately
return SMB_MOUNT_FAILED;
}
String smbOptions;
if (Sage.LINUX_OS)
{
if (smbUser != null)
smbOptions = "username=" + smbUser + ",password=" + smbPass + ",iocharset=utf8,nounix";
else
smbOptions = "guest,iocharset=utf8,nounix";
}
else
{
if (smbUser != null)
smbOptions = smbUser + ":" + smbPass;
else
smbOptions = "guest:";
}
int smbRes;
if ((smbRes = IOUtils.exec2(Sage.LINUX_OS ? new String[] { "mount.cifs", tmpSmbPath, localPath , "-o", smbOptions } :
new String[] { "mount_smbfs", "-N", "//" + smbOptions + "@" + smbPath.substring(2), localPath})) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Failed res=" + smbRes);
if (Sage.LINUX_OS && smbUser == null)
{
if (Sage.DBG) System.out.println("Retrying SMB mount with share access...");
smbOptions = "username=share,guest,iocharset=utf8";
if ((smbRes = IOUtils.exec2(new String[] { "mount.cifs", tmpSmbPath, localPath , "-o", smbOptions })) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("Retrying SMB mount with share access(2)...");
smbOptions = "username=" + smbShareName + ",guest,iocharset=utf8";
if ((smbRes = IOUtils.exec2(new String[] { "mount.cifs", tmpSmbPath, localPath , "-o", smbOptions })) == 0)
{
if (Sage.DBG) System.out.println("SMB Mount Succeeded");
return SMB_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("SMB Mount Failed res=" + smbRes);
return SMB_MOUNT_FAILED;
}
}
}
return SMB_MOUNT_FAILED;
}
}
}
}
public static final int NFS_MOUNT_EXISTS = 0;
public static final int NFS_MOUNT_SUCCEEDED = 1;
public static final int NFS_MOUNT_FAILED = -1;
public static int doNFSMount(String nfsPath, String localPath)
{
if (!Sage.LINUX_OS) return NFS_MOUNT_FAILED;
if (nfsPath.startsWith("nfs://"))
nfsPath = nfsPath.substring(6);
// Check if the mount is already done
if (IOUtils.exec2(new String[] { "sh", "-c", "mount -t nfs | grep -i \"" + localPath + "\"" }) == 0)
{
//if (Sage.DBG) System.out.println("NFS Mount already exists");
return NFS_MOUNT_EXISTS;
}
else
{
if (Sage.DBG) System.out.println("NFS Mount Path: " + nfsPath + " " + localPath);
new java.io.File(localPath).mkdirs();
String nfsOptions = "nolock,tcp,rsize=32768,wsize=32768,noatime";
int nfsRes = IOUtils.exec2(new String[] {"mount", "-t", "nfs", nfsPath, localPath, "-o", nfsOptions});
if (nfsRes == 0)
{
if (Sage.DBG) System.out.println("NFS Mount Succeeded");
return NFS_MOUNT_SUCCEEDED;
}
else
{
if (Sage.DBG) System.out.println("NFS Mount Failed res=" + nfsRes);
return NFS_MOUNT_FAILED;
}
}
}
public static boolean undoMount(String currPath)
{
return IOUtils.exec2(new String[] { "umount", currPath}) == 0;
}
public static String convertSMBURLToUNCPath(String smbPath)
{
StringBuffer sb = new StringBuffer("\\\\" + smbPath.substring("smb://".length()));
for (int i = 0; i < sb.length(); i++)
if (sb.charAt(i) == '/')
sb.setCharAt(i, '\\');
return sb.toString();
}
// Creates a java.io.BufferedReader for the specified file and checks the first two bytes for the Unicode BOM and sets the
// charset accordingly; otherwise if there's no BOM it'll use the passed in defaultCharset
public static java.io.BufferedReader openReaderDetectCharset(String filePath, String defaultCharset) throws java.io.IOException
{
return openReaderDetectCharset(new java.io.File(filePath), defaultCharset);
}
public static java.io.BufferedReader openReaderDetectCharset(java.io.File filePath, String defaultCharset) throws java.io.IOException
{
java.io.FileInputStream fis = null;
try
{
fis = new java.io.FileInputStream(filePath);
int b1 = fis.read();
int b2 = fis.read();
// Check for big/little endian unicode marker; otherwise use the default charset to open
String targetCharset = defaultCharset;
if (b1 == 0xFF && b2 == 0xFE)
targetCharset = "UTF-16LE";
else if (b1 == 0xFE && b2 == 0xFF)
targetCharset = "UTF-16BE";
else if (Sage.I18N_CHARSET.equals(defaultCharset))
{
// Read 16k of data to verify that we have the proper charset if we think it's UTF8
byte[] extraData = new byte[16384];
extraData[0] = (byte)(b1 & 0xFF);
extraData[1] = (byte)(b2 & 0xFF);
int dataLen = 2 + fis.read(extraData, 2, extraData.length - 2);
boolean utf8valid = true;
for (int i = 0; i < dataLen && utf8valid; i++)
{
int c = extraData[i] & 0xFF;
if (c <= 127)
continue;
if (i + 1 >= dataLen)
{
break;
}
switch (c >> 4)
{
case 12: case 13:
/* 110x xxxx 10xx xxxx*/
i++;
c = extraData[i] & 0xFF;
if ((c & 0xC0) != 0x80)
utf8valid = false;
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
i++;
c = extraData[i] & 0xFF;
if ((c & 0xC0) != 0x80 || i + 1 >= dataLen)
utf8valid = false;
else
{
i++;
c = extraData[i] & 0xFF;
if ((c & 0xC0) != 0x80)
utf8valid = false;
}
break;
default:
/* 10xx xxxx, 1111 xxxx */
utf8valid = false;
break;
}
}
if (!utf8valid)
{
if (Sage.DBG) System.out.println("Charset autodetection found invalid UTF8 data in the file; switching to default charset instead");
// Cp1252 is a superset of ISO-8859-1; so it's preferable to use it since it'll decode more characters...BUT we really should
// just use the platform default instead; that's generally what people will be using from a text editor.
// And embedded doesn't support Cp1252, so we need to remove that from there and just use ISO-8859-1
targetCharset = Sage.EMBEDDED ? Sage.BYTE_CHARSET : null;
}
}
fis.close();
if (targetCharset == null)
return new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(filePath)));
else
return new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(filePath), targetCharset));
}
catch (java.io.IOException e)
{
if (fis != null)
fis.close();
throw e;
}
}
public static String calcMD5(java.io.File f)
{
if (f != null && f.isFile())
{
java.io.FileInputStream fis = null;
try
{
fis = new java.io.FileInputStream(f);
java.security.MessageDigest algorithm = null;
algorithm = java.security.MessageDigest.getInstance("MD5");
algorithm.reset();
byte[] buf = new byte[32768];
int numRead = fis.read(buf);
while (numRead > 0)
{
algorithm.update(buf, 0, numRead);
numRead = fis.read(buf);
}
byte[] digest = algorithm.digest();
StringBuffer finalSum = new StringBuffer();
for (int i = 0; i < digest.length; i++)
{
if (((int) (digest[i] & 0xFF)) <= 0x0F)
{
finalSum.append('0');
}
finalSum.append(Integer.toHexString((int)(digest[i] & 0xFF)));
}
return finalSum.toString().toUpperCase();
}
catch (Exception e)
{
/*if (Sage.DBG)*/ System.out.println("ERROR calculating MD5Sum of:" + e);
return null;
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (Exception e)
{}
}
}
}
else
return null;
}
public static final String[] VFAT_MOUNTABLE_PARTITION_TYPES = { "6", "b", "c", "e", "f" };
public static final String[] NTFS_MOUNTABLE_PARTITION_TYPES = { "7" };
public static boolean isExternalDriveMounted(String devPath, String mountPath)
{
return (IOUtils.exec2(new String[] { "sh", "-c", "mount | grep -i \"" + mountPath + " type\"" }) == 0);
}
public static boolean mountExternalDrive(String devPath, String mountPath)
{
return mountExternalDrive(devPath, mountPath, false);
}
public static boolean mountExternalDrive(String devPath, String mountPath, boolean optimizePerformance)
{
if (!Sage.LINUX_OS) return false;
// Check to see if it's already mounted
if (isExternalDriveMounted(devPath, mountPath))
{
if (Sage.DBG) System.out.println("Ignoring mount for " + devPath + " because it's already mounted at: " + mountPath);
return true;
}
// First use 'sfdisk' to determine the partition type so we know if we should
// mount it w/ the '-o utf8' option or not
String partNum = devPath.substring(devPath.length() - 1);
String sfRes = IOUtils.exec(new String[] { "sfdisk", "-c", "/dev/" + devPath.substring(0, devPath.length() - 1), partNum});
sfRes = sfRes.trim();
if ("83".equals(sfRes) && optimizePerformance)
{
// Special options for mounting ext4 drives (this should fail if it's not ext4 since the 83 flag just means ext2/3/4)
if (IOUtils.exec2(new String[] {"mount", "-t", "ext4", "/dev/" + devPath, mountPath, "-o", "noatime,barrier=0,data=writeback"}) == 0)
return true;
}
// If we have a failure; then keep going and try all the possible ways to mount the drive.
for (int i = 0; i < VFAT_MOUNTABLE_PARTITION_TYPES.length; i++)
{
if (sfRes.equals(VFAT_MOUNTABLE_PARTITION_TYPES[i]))
{
if (IOUtils.exec2(new String[] {"mount", "-t", "vfat", "/dev/" + devPath, mountPath, "-o", "utf8,noatime"}) == 0)
return true;
}
}
for (int i = 0; i < NTFS_MOUNTABLE_PARTITION_TYPES.length; i++)
{
if (sfRes.equals(NTFS_MOUNTABLE_PARTITION_TYPES[i]))
{
if (Sage.EMBEDDED)
{
if (IOUtils.exec2(new String[] {"/usr/local/bin/ntfs-3g", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
else if (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
}
if (devPath.length() == 3)
{
// This is for NTFS mounting since we mount the disk and not the partitions
if (Sage.EMBEDDED)
{
if (IOUtils.exec2(new String[] {"/usr/local/bin/ntfs-3g", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
else
{
if (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath, "-o", "nls=utf8,noatime"}) == 0)
return true;
}
}
if (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath, "-o", "noatime"}) == 0)
return true;
return (IOUtils.exec2(new String[] {"mount", "/dev/" + devPath, mountPath}) == 0);
}
// Reads a newline (\r\n or \n) terminated string (w/out returning the newline). rv can be used as a temp buffer, buf is the buffer used for reading the data and may already contain
// extra data in it before calling this method, the SocketChannel passed in MUST be a blocking socket. Extra data may be in the buf after returning from this method call.
public static String readLineBytes(java.nio.channels.SocketChannel s, java.nio.ByteBuffer buf, long timeout, StringBuffer rv) throws java.io.InterruptedIOException, java.io.IOException
{
if (rv == null)
rv = new StringBuffer();
else
rv.setLength(0);
boolean needsFlip = true;
if (buf.hasRemaining() && buf.position() > 0)
needsFlip = false;
else
buf.clear();
int readRes = 0;
TimeoutHandler.registerTimeout(timeout, s);
try
{
if ((!buf.hasRemaining() || buf.position() == 0) && (readRes = s.read(buf)) <= 0)
{
throw new java.io.EOFException();
}
}
finally
{
TimeoutHandler.clearTimeout(s);
}
if (needsFlip)
buf.flip();
int currByte = (buf.get() & 0xFF);
while (true)
{
if (currByte == '\r')
{
if (!buf.hasRemaining())
{
buf.clear();
TimeoutHandler.registerTimeout(timeout, s);
try
{
if ((readRes = s.read(buf)) <= 0)
{
throw new java.io.EOFException();
}
}
finally
{
TimeoutHandler.clearTimeout(s);
}
buf.flip();
}
currByte = (buf.get() & 0xFF);
if (currByte == '\n')
{
return rv.toString();
}
rv.append('\r');
}
else if (currByte == '\n')
{
return rv.toString();
}
rv.append((char)currByte);
if (!buf.hasRemaining())
{
buf.clear();
TimeoutHandler.registerTimeout(timeout, s);
try
{
if ((readRes = s.read(buf)) <= 0)
{
throw new java.io.EOFException();
}
}
finally
{
TimeoutHandler.clearTimeout(s);
}
buf.flip();
}
currByte = (buf.get() & 0xFF);
}
}
// Downloads all of the specified files from a SageTV server to the target destination files. Only allowed with
// SageTVClient mode
public static void downloadFilesFromSageTVServer(java.io.File[] srcFiles, java.io.File[] dstFiles) throws java.io.IOException
{
if (!Sage.client) throw new java.io.IOException("Cannot download files from SageTV server since we are not in client mode!");
java.net.Socket sock = null;;
java.io.DataOutputStream outStream = null;
java.io.DataInputStream inStream = null;
java.io.OutputStream fileOut = null;
try
{
sock = new java.net.Socket();
sock.connect(new java.net.InetSocketAddress(Sage.preferredServer, 7818), 5000);
sock.setSoTimeout(30000);
//sock.setTcpNoDelay(true);
outStream = new java.io.DataOutputStream(new java.io.BufferedOutputStream(sock.getOutputStream()));
inStream = new java.io.DataInputStream(new java.io.BufferedInputStream(sock.getInputStream()));
byte[] xferBuf = new byte[32768];
for (int i = 0; i < srcFiles.length; i++)
{
// Always request file access since this is generally not used for MediaFile objects
NetworkClient.getSN().requestMediaServerAccess(srcFiles[i], true);
outStream.write("OPENW ".getBytes(Sage.BYTE_CHARSET));
outStream.write(srcFiles[i].toString().getBytes("UTF-16BE"));
outStream.write("\r\n".getBytes(Sage.BYTE_CHARSET));
outStream.flush();
String str = Sage.readLineBytes(inStream);
if (!"OK".equals(str))
throw new java.io.IOException("Error opening remote file of:" + str);
// get the size
outStream.write("SIZE\r\n".getBytes(Sage.BYTE_CHARSET));
outStream.flush();
str = Sage.readLineBytes(inStream);
long remoteSize = Long.parseLong(str.substring(0, str.indexOf(' ')));
fileOut = new java.io.FileOutputStream(dstFiles[i]);
outStream.write(("READ 0 " + remoteSize + "\r\n").getBytes(Sage.BYTE_CHARSET));
outStream.flush();
while (remoteSize > 0)
{
int currRead = (int)Math.min(xferBuf.length, remoteSize);
inStream.readFully(xferBuf, 0, currRead);
fileOut.write(xferBuf, 0, currRead);
remoteSize -= currRead;
}
fileOut.close();
fileOut = null;
// CLOSE happens automatically when you open a new file
//outStream.write("CLOSE\r\n".getBytes(Sage.BYTE_CHARSET));
//outStream.flush();
NetworkClient.getSN().requestMediaServerAccess(srcFiles[i], false);
}
}
finally
{
try{
if (sock != null)
sock.close();
}catch (Exception e1){}
try{
if (outStream != null)
outStream.close();
}catch (Exception e2){}
try{
if (inStream != null)
inStream.close();
}catch (Exception e3){}
try{
if (fileOut != null)
fileOut.close();
}catch (Exception e4){}
}
}
// This uses the old MVP server which as part of the protocol will return the MAC address of the other system
public static String getServerMacAddress(String hostname)
{
// Strip off any port that may be there
if (hostname.indexOf(":") != -1)
hostname = hostname.substring(0, hostname.indexOf(":"));
if (Sage.DBG) System.out.println("Requested to find MAC address of server at: " + hostname);
java.net.DatagramSocket sock = null;
try
{
sock = new java.net.DatagramSocket(16882); // they always come back on this port
java.net.DatagramPacket pack = new java.net.DatagramPacket(new byte[50], 50);
byte[] data = pack.getData();
data[3] = 1;
String localIP;
if (Sage.WINDOWS_OS || Sage.MAC_OS_X)
localIP = java.net.InetAddress.getLocalHost().getHostAddress();
else
localIP = LinuxUtils.getIPAddress();
if (Sage.DBG) System.out.println("Local IP is " + localIP);
int idx = localIP.indexOf('.');
data[16] = (byte)(Integer.parseInt(localIP.substring(0, idx)) & 0xFF);
localIP = localIP.substring(idx + 1);
idx = localIP.indexOf('.');
data[17] = (byte)(Integer.parseInt(localIP.substring(0, idx)) & 0xFF);
localIP = localIP.substring(idx + 1);
idx = localIP.indexOf('.');
data[18] = (byte)(Integer.parseInt(localIP.substring(0, idx)) & 0xFF);
localIP = localIP.substring(idx + 1);
data[19] = (byte)(Integer.parseInt(localIP) & 0xFF);
pack.setLength(50);
// Find the broadcast address for this subnet.
pack.setAddress(java.net.InetAddress.getByName(hostname));
pack.setPort(16881);
sock.send(pack);
sock.setSoTimeout(3000);
sock.receive(pack);
if (pack.getLength() >= 20)
{
if (Sage.DBG) System.out.println("MAC discovery packet received:" + pack);
String mac = (((data[8] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[8] & 0xFF, 16) + ":" +
(((data[9] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[9] & 0xFF, 16) + ":" +
(((data[10] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[10] & 0xFF, 16) + ":" +
(((data[11] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[11] & 0xFF, 16) + ":" +
(((data[12] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[12] & 0xFF, 16) + ":" +
(((data[13] & 0xFF) < 16) ? "0" : "") + Integer.toString(data[13] & 0xFF, 16);
if (Sage.DBG) System.out.println("Resulting MAC=" + mac);
return mac;
}
}
catch (Exception e)
{
//System.out.println("Error discovering servers:" + e);
}
finally
{
if (sock != null)
{
try
{
sock.close();
}catch (Exception e){}
sock = null;
}
}
return null;
}
public static void sendWOLPacket(String macAddress)
{
// Strip off any port that may be there
if (Sage.DBG) System.out.println("Sending out WOL packet to MAC address: " + macAddress);
java.net.DatagramSocket sock = null;
try
{
sock = new java.net.DatagramSocket(9); // WOL is on port 9
java.net.DatagramPacket pack = new java.net.DatagramPacket(new byte[102], 102);
byte[] data = pack.getData();
data[0] = (byte)0xFF;
data[1] = (byte)0xFF;
data[2] = (byte)0xFF;
data[3] = (byte)0xFF;
data[4] = (byte)0xFF;
data[5] = (byte)0xFF;
byte[] macBytes = new byte[6];
java.util.StringTokenizer macToker = new java.util.StringTokenizer(macAddress, ":-");
for (int i = 0; i < macBytes.length; i++)
{
macBytes[i] = (byte)(Integer.parseInt(macToker.nextToken(), 16) & 0xFF);
}
for (int i = 0; i < 16; i++)
{
System.arraycopy(macBytes, 0, data, 6*(i + 1), 6);
}
String localIP;
if (Sage.WINDOWS_OS || Sage.MAC_OS_X)
localIP = java.net.InetAddress.getLocalHost().getHostAddress();
else
localIP = LinuxUtils.getIPAddress();
if (Sage.DBG) System.out.println("Local IP is " + localIP);
int lastDot = localIP.lastIndexOf('.');
String broadcastIP = localIP.substring(0, lastDot) + ".255";
if (Sage.DBG) System.out.println("Broadcast IP is " + broadcastIP);
pack.setLength(102);
pack.setAddress(java.net.InetAddress.getByName(broadcastIP));
pack.setPort(9);
sock.send(pack);
}
catch (Exception e)
{
//System.out.println("Error discovering servers:" + e);
}
finally
{
if (sock != null)
{
try
{
sock.close();
}catch (Exception e){}
sock = null;
}
}
}
public static byte[] getFileAsBytes(java.io.File f)
{
try
{
java.io.InputStream is = new java.io.FileInputStream(f);
byte[] rv = new byte[(int)f.length()];
int numRead = is.read(rv);
while (numRead < rv.length)
{
int currRead = is.read(rv, numRead, rv.length - numRead);
if (currRead < 0)
break;
numRead += currRead;
}
is.close();
return rv;
}
catch (java.io.IOException e)
{
if (Sage.DBG) System.out.println("ERROR reading file " + f + " of:" + e);
return null;
}
}
}
| Added files via upload
Added code to check for smbmount command and use mount.cifs if it wasn't found. Uses a property entry so that the check is only done once as long as the property exists | java/sage/IOUtils.java | Added files via upload | <ide><path>ava/sage/IOUtils.java
<ide> else
<ide> smbOptions = "guest:";
<ide> }
<del> if (IOUtils.exec2(Sage.LINUX_OS ? new String[] { "smbmount", smbPath, localPath , "-o", smbOptions } :
<add> // check to see if property exists if it doesn't check for smbmount with "which" command
<add> if (Sage.getRawProperties().getWithNoDefault("smbmount_present") == null)
<add> {
<add> String result = IOUtils.exec(new String[] {"which", "smbmount"});
<add> // if nothing returned from "which" command then smbmount is not present so set property false
<add> if (result == null || result.isEmpty())
<add> {
<add> Sage.putBoolean("smbmount_present", false);
<add> } else {
<add> Sage.putBoolean("smbmount_present", true);
<add> }
<add> }
<add> // set execution variable based on property value
<add> String execSMBMount = Sage.getBoolean("smbmount_present", true) ?
<add> "smbmount" : "mount.cifs";
<add> if (IOUtils.exec2(Sage.LINUX_OS ? new String[] { execSMBMount, smbPath, localPath , "-o", smbOptions } :
<ide> new String[] { "mount_smbfs", "-N", "//" + smbOptions + "@" + smbPath.substring(2), localPath}) == 0)
<ide> {
<ide> if (Sage.DBG) System.out.println("SMB Mount Succeeded"); |
|
Java | lgpl-2.1 | b3e2a7b63e057d399efb32781293905351f9b5d1 | 0 | MinecraftForge/ForgeGradle,MinecraftForge/ForgeGradle | package net.minecraftforge.gradle.common.diff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import net.minecraftforge.gradle.common.diff.ContextualPatch.Mode;
import net.minecraftforge.gradle.common.util.Utils;
public class ZipContext implements PatchContextProvider {
private final ZipFile zip;
private final Map<String, List<String>> modified = new HashMap<>();
private final Set<String> delete = new HashSet<>();
private final Map<String, byte[]> binary = new HashMap<>();
public ZipContext(ZipFile zip) {
this.zip = zip;
}
@Override
public List<String> getData(ContextualPatch.SinglePatch patch) throws IOException {
if (modified.containsKey(patch.targetPath))
return modified.get(patch.targetPath);
ZipEntry entry = zip.getEntry(patch.targetPath);
if (entry == null || patch.binary)
return null;
try (InputStream input = zip.getInputStream(entry)) {
return new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}
}
@Override
public void setData(ContextualPatch.SinglePatch patch, List<String> data) throws IOException {
if (patch.mode == Mode.DELETE || (patch.binary && patch.hunks.length == 0)) {
delete.add(patch.targetPath);
binary.remove(patch.targetPath);
modified.remove(patch.targetPath);
} else {
delete.remove(patch.targetPath);
if (patch.binary) {
binary.put(patch.targetPath, Utils.base64DecodeStringList(patch.hunks[0].lines));
modified.remove(patch.targetPath);
} else {
if (!patch.noEndingNewline) {
data.add("");
}
modified.put(patch.targetPath, data);
binary.remove(patch.targetPath);
}
}
}
public void save(File file) throws IOException {
Set<String> files = new HashSet<>();
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
files.add(entries.nextElement().getName());
}
files.addAll(modified.keySet());
files.addAll(delete);
files.addAll(binary.keySet());
List<String> sorted = new ArrayList<>(files);
Collections.sort(sorted);
File parent = file.getParentFile();
if (!parent.exists())
parent.mkdirs();
try (FileOutputStream fos = new FileOutputStream(file);
ZipOutputStream out = new ZipOutputStream(fos)) {
for (String key : sorted) {
if (delete.contains(key)) {
continue; // It's Deleted, so NOOP
}
putNextEntry(out, key);
if (binary.containsKey(key)) {
out.write(binary.get(key));
} else if (modified.containsKey(key)) {
out.write(String.join("\n", modified.get(key)).getBytes(StandardCharsets.UTF_8));
} else {
try (InputStream ein = zip.getInputStream(zip.getEntry(key))) {
IOUtils.copy(ein, out);
}
}
out.closeEntry();
}
}
}
private void putNextEntry(ZipOutputStream zip, String name) throws IOException {
ZipEntry entry = new ZipEntry(name);
entry.setTime(0);
zip.putNextEntry(entry);
}
}
| src/common/java/net/minecraftforge/gradle/common/diff/ZipContext.java | package net.minecraftforge.gradle.common.diff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import net.minecraftforge.gradle.common.diff.ContextualPatch.Mode;
import net.minecraftforge.gradle.common.util.Utils;
public class ZipContext implements PatchContextProvider {
private final ZipFile zip;
private final Map<String, List<String>> modified = new HashMap<>();
private final Set<String> delete = new HashSet<>();
private final Map<String, byte[]> binary = new HashMap<>();
public ZipContext(ZipFile zip) {
this.zip = zip;
}
@Override
public List<String> getData(ContextualPatch.SinglePatch patch) throws IOException {
if (modified.containsKey(patch.targetPath))
return modified.get(patch.targetPath);
ZipEntry entry = zip.getEntry(patch.targetPath);
if (entry == null || patch.binary)
return null;
try (InputStream input = zip.getInputStream(entry)) {
return new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}
}
@Override
public void setData(ContextualPatch.SinglePatch patch, List<String> data) throws IOException {
if (patch.mode == Mode.DELETE || (patch.binary && patch.hunks.length == 0)) {
delete.add(patch.targetPath);
binary.remove(patch.targetPath);
modified.remove(patch.targetPath);
} else {
delete.remove(patch.targetPath);
if (patch.binary) {
binary.put(patch.targetPath, Utils.base64DecodeStringList(patch.hunks[0].lines));
modified.remove(patch.targetPath);
} else {
if (!patch.noEndingNewline) {
data.add("");
}
modified.put(patch.targetPath, data);
binary.remove(patch.targetPath);
}
}
}
public void save(File file) throws IOException {
Set<String> files = new HashSet<>();
zip.entries().asIterator().forEachRemaining(e -> files.add(e.getName()));
files.addAll(modified.keySet());
files.addAll(delete);
files.addAll(binary.keySet());
List<String> sorted = new ArrayList<>(files);
Collections.sort(sorted);
File parent = file.getParentFile();
if (!parent.exists())
parent.mkdirs();
try (FileOutputStream fos = new FileOutputStream(file);
ZipOutputStream out = new ZipOutputStream(fos)) {
for (String key : sorted) {
if (delete.contains(key)) {
continue; // It's Deleted, so NOOP
}
putNextEntry(out, key);
if (binary.containsKey(key)) {
out.write(binary.get(key));
} else if (modified.containsKey(key)) {
out.write(String.join("\n", modified.get(key)).getBytes(StandardCharsets.UTF_8));
} else {
try (InputStream ein = zip.getInputStream(zip.getEntry(key))) {
IOUtils.copy(ein, out);
}
}
out.closeEntry();
}
}
}
private void putNextEntry(ZipOutputStream zip, String name) throws IOException {
ZipEntry entry = new ZipEntry(name);
entry.setTime(0);
zip.putNextEntry(entry);
}
}
| Fixed accidental J9 dependency
| src/common/java/net/minecraftforge/gradle/common/diff/ZipContext.java | Fixed accidental J9 dependency | <ide><path>rc/common/java/net/minecraftforge/gradle/common/diff/ZipContext.java
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<add>import java.util.Enumeration;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide>
<ide> public void save(File file) throws IOException {
<ide> Set<String> files = new HashSet<>();
<del> zip.entries().asIterator().forEachRemaining(e -> files.add(e.getName()));
<add> for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
<add> files.add(entries.nextElement().getName());
<add> }
<ide> files.addAll(modified.keySet());
<ide> files.addAll(delete);
<ide> files.addAll(binary.keySet()); |
|
Java | apache-2.0 | c1f3921e84bdbbd6e540fe4907c5a0ac1dec2229 | 0 | UweTrottmann/trakt-java | package com.uwetrottmann.trakt.v2;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.junit.Test;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.security.SecureRandom;
import static org.assertj.core.api.Assertions.assertThat;
/**
* This test should NOT be run with the regular test suite. It requires a valid, temporary (!) auth code to be set.
*/
public class AuthTest extends BaseTestCase {
private static final String TEST_CLIENT_SECRET = "";
private static final String TEST_AUTH_CODE = "";
private static final String TEST_REDIRECT_URI = "http://localhost";
private static final String TEST_USERNAME = "sgtest";
@Test
public void test_getAccessTokenRequest() throws OAuthSystemException {
if (TEST_CLIENT_SECRET.isEmpty() || TEST_AUTH_CODE.isEmpty()) {
System.out.print("Skipping test_getAccessTokenRequest test, no valid auth data");
return;
}
OAuthClientRequest request = TraktV2.getAccessTokenRequest(TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TEST_REDIRECT_URI, TEST_AUTH_CODE);
assertThat(request).isNotNull();
assertThat(request.getLocationUri()).startsWith(TraktV2.OAUTH2_TOKEN_URL);
System.out.println("Generated Token Request URI: " + request.getLocationUri());
}
@Test
public void test_getAccessToken() throws OAuthProblemException, OAuthSystemException {
if (TEST_CLIENT_SECRET.isEmpty() || TEST_AUTH_CODE.isEmpty()) {
System.out.print("Skipping test_getAccessTokenRequest test, no valid auth data");
return;
}
OAuthAccessTokenResponse response = TraktV2.getAccessToken(
TEST_CLIENT_ID, TEST_CLIENT_SECRET, TEST_REDIRECT_URI, TEST_AUTH_CODE);
assertThat(response.getAccessToken()).isNotEmpty();
assertThat(response.getRefreshToken()).isNotEmpty();
System.out.println("Retrieved access token: " + response.getAccessToken());
System.out.println("Retrieved refresh token: " + response.getRefreshToken());
System.out.println("Retrieved scope: " + response.getScope());
System.out.println("Retrieved expires in: " + response.getExpiresIn() + " seconds");
}
@Test
public void test_getAuthorizationRequest() throws OAuthSystemException, URISyntaxException {
String sampleState = new BigInteger(130, new SecureRandom()).toString(32);
OAuthClientRequest request = TraktV2.getAuthorizationRequest(TEST_CLIENT_ID, TEST_REDIRECT_URI, sampleState,
TEST_USERNAME);
assertThat(request).isNotNull();
assertThat(request.getLocationUri()).startsWith(TraktV2.OAUTH2_AUTHORIZATION_URL);
// trakt does not support scopes, so don't send one (server sets default scope)
assertThat(request.getLocationUri()).doesNotContain("scope");
System.out.println("Get an auth code at the following URI: " + request.getLocationUri());
}
}
| src/test/java/com/uwetrottmann/trakt/v2/AuthTest.java | package com.uwetrottmann.trakt.v2;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.junit.Test;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.security.SecureRandom;
import static org.assertj.core.api.Assertions.assertThat;
/**
* This test should NOT be run with the regular test suite. It requires a valid, temporary (!) auth code to be set.
*/
public class AuthTest extends BaseTestCase {
private static final String TEST_CLIENT_SECRET = "";
private static final String TEST_AUTH_CODE = "";
private static final String TEST_REDIRECT_URI = "http://localhost";
private static final String TEST_USERNAME = "sgtest";
@Test
public void test_getAccessTokenRequest() throws OAuthSystemException {
if (TEST_CLIENT_SECRET.isEmpty() || TEST_AUTH_CODE.isEmpty()) {
System.out.print("Skipping test_getAccessTokenRequest test, no valid auth data");
return;
}
OAuthClientRequest request = TraktV2.getAccessTokenRequest(TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TEST_REDIRECT_URI, TEST_AUTH_CODE);
assertThat(request).isNotNull();
assertThat(request.getLocationUri()).startsWith(TraktV2.OAUTH2_TOKEN_URL);
System.out.println("Generated Token Request URI: " + request.getLocationUri());
}
@Test
public void test_getAccessToken() throws OAuthProblemException, OAuthSystemException {
if (TEST_CLIENT_SECRET.isEmpty() || TEST_AUTH_CODE.isEmpty()) {
System.out.print("Skipping test_getAccessTokenRequest test, no valid auth data");
return;
}
OAuthAccessTokenResponse response = TraktV2.getAccessToken(
TEST_CLIENT_ID, TEST_CLIENT_SECRET, TEST_REDIRECT_URI, TEST_AUTH_CODE);
assertThat(response.getAccessToken()).isNotEmpty();
assertThat(response.getRefreshToken()).isNull(); // trakt does not supply refresh tokens
System.out.println("Retrieved access token: " + response.getAccessToken());
System.out.println("Retrieved refresh token: " + response.getRefreshToken());
System.out.println("Retrieved scope: " + response.getScope());
System.out.println("Retrieved expires in: " + response.getExpiresIn());
}
@Test
public void test_getAuthorizationRequest() throws OAuthSystemException, URISyntaxException {
String sampleState = new BigInteger(130, new SecureRandom()).toString(32);
OAuthClientRequest request = TraktV2.getAuthorizationRequest(TEST_CLIENT_ID, TEST_REDIRECT_URI, sampleState,
TEST_USERNAME);
assertThat(request).isNotNull();
assertThat(request.getLocationUri()).startsWith(TraktV2.OAUTH2_AUTHORIZATION_URL);
// trakt does not support scopes, so don't send one (server sets default scope)
assertThat(request.getLocationUri()).doesNotContain("scope");
System.out.println("Get an auth code at the following URI: " + request.getLocationUri());
}
}
| trakt now supports refresh tokens.
| src/test/java/com/uwetrottmann/trakt/v2/AuthTest.java | trakt now supports refresh tokens. | <ide><path>rc/test/java/com/uwetrottmann/trakt/v2/AuthTest.java
<ide> OAuthAccessTokenResponse response = TraktV2.getAccessToken(
<ide> TEST_CLIENT_ID, TEST_CLIENT_SECRET, TEST_REDIRECT_URI, TEST_AUTH_CODE);
<ide> assertThat(response.getAccessToken()).isNotEmpty();
<del> assertThat(response.getRefreshToken()).isNull(); // trakt does not supply refresh tokens
<add> assertThat(response.getRefreshToken()).isNotEmpty();
<ide> System.out.println("Retrieved access token: " + response.getAccessToken());
<ide> System.out.println("Retrieved refresh token: " + response.getRefreshToken());
<ide> System.out.println("Retrieved scope: " + response.getScope());
<del> System.out.println("Retrieved expires in: " + response.getExpiresIn());
<add> System.out.println("Retrieved expires in: " + response.getExpiresIn() + " seconds");
<ide> }
<ide>
<ide> @Test |
|
JavaScript | mit | a247fe9b27ec57152f07aaa5dfc79f633d2b6d10 | 0 | inway/bootstrap,coliff/bootstrap,inway/bootstrap,twbs/bootstrap,m5o/bootstrap,tjkohli/bootstrap,m5o/bootstrap,inway/bootstrap,tjkohli/bootstrap,twbs/bootstrap,coliff/bootstrap | /**
* --------------------------------------------------------------------------
* Bootstrap (v5.1.3): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
import {
defineJQueryPlugin,
getElementFromSelector,
getNextActiveElement,
isRTL,
isVisible,
reflow,
triggerTransitionEnd
} from './util/index'
import EventHandler from './dom/event-handler'
import Manipulator from './dom/manipulator'
import SelectorEngine from './dom/selector-engine'
import Swipe from './util/swipe'
import BaseComponent from './base-component'
/**
* Constants
*/
const NAME = 'carousel'
const DATA_KEY = 'bs.carousel'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const ARROW_LEFT_KEY = 'ArrowLeft'
const ARROW_RIGHT_KEY = 'ArrowRight'
const TOUCHEVENT_COMPAT_WAIT = 500 // Time for mouse compat events to fire after touch
const ORDER_NEXT = 'next'
const ORDER_PREV = 'prev'
const DIRECTION_LEFT = 'left'
const DIRECTION_RIGHT = 'right'
const EVENT_SLIDE = `slide${EVENT_KEY}`
const EVENT_SLID = `slid${EVENT_KEY}`
const EVENT_KEYDOWN = `keydown${EVENT_KEY}`
const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`
const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`
const EVENT_DRAG_START = `dragstart${EVENT_KEY}`
const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
const CLASS_NAME_CAROUSEL = 'carousel'
const CLASS_NAME_ACTIVE = 'active'
const CLASS_NAME_SLIDE = 'slide'
const CLASS_NAME_END = 'carousel-item-end'
const CLASS_NAME_START = 'carousel-item-start'
const CLASS_NAME_NEXT = 'carousel-item-next'
const CLASS_NAME_PREV = 'carousel-item-prev'
const SELECTOR_ACTIVE = '.active'
const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'
const SELECTOR_ITEM = '.carousel-item'
const SELECTOR_ITEM_IMG = '.carousel-item img'
const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'
const SELECTOR_INDICATORS = '.carousel-indicators'
const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'
const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'
const KEY_TO_DIRECTION = {
[ARROW_LEFT_KEY]: DIRECTION_RIGHT,
[ARROW_RIGHT_KEY]: DIRECTION_LEFT
}
const Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true,
touch: true
}
const DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean',
touch: 'boolean'
}
/**
* Class definition
*/
class Carousel extends BaseComponent {
constructor(element, config) {
super(element, config)
this._items = null
this._interval = null
this._activeElement = null
this._isPaused = false
this._isSliding = false
this.touchTimeout = null
this._swipeHelper = null
this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element)
this._addEventListeners()
}
// Getters
static get Default() {
return Default
}
static get DefaultType() {
return DefaultType
}
static get NAME() {
return NAME
}
// Public
next() {
this._slide(ORDER_NEXT)
}
nextWhenVisible() {
// FIXME TODO use `document.visibilityState`
// Don't call next when the page isn't visible
// or the carousel or its parent isn't visible
if (!document.hidden && isVisible(this._element)) {
this.next()
}
}
prev() {
this._slide(ORDER_PREV)
}
pause(event) {
if (!event) {
this._isPaused = true
}
if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
triggerTransitionEnd(this._element)
this.cycle(true)
}
this._clearInterval()
}
cycle(event) {
if (!event) {
this._isPaused = false
}
this._clearInterval()
if (this._config.interval && !this._isPaused) {
this._updateInterval()
this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval)
}
}
to(index) {
this._activeElement = this._getActive()
const activeIndex = this._getItemIndex(this._activeElement)
if (index > this._items.length - 1 || index < 0) {
return
}
if (this._isSliding) {
EventHandler.one(this._element, EVENT_SLID, () => this.to(index))
return
}
if (activeIndex === index) {
this.pause()
this.cycle()
return
}
const order = index > activeIndex ?
ORDER_NEXT :
ORDER_PREV
this._slide(order, this._items[index])
}
dispose() {
if (this._swipeHelper) {
this._swipeHelper.dispose()
}
super.dispose()
}
// Private
_configAfterMerge(config) {
config.defaultInterval = config.interval
return config
}
_addEventListeners() {
if (this._config.keyboard) {
EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event))
}
if (this._config.pause === 'hover') {
EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event))
EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event))
}
if (this._config.touch && Swipe.isSupported()) {
this._addTouchEventListeners()
}
}
_addTouchEventListeners() {
for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) {
EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault())
}
const endCallBack = () => {
if (this._config.pause !== 'hover') {
return
}
// If it's a touch-enabled device, mouseenter/leave are fired as
// part of the mouse compatibility events on first tap - the carousel
// would stop cycling until user tapped out of it;
// here, we listen for touchend, explicitly pause the carousel
// (as if it's the second time we tap on it, mouseenter compat event
// is NOT fired) and after a timeout (to allow for mouse compatibility
// events to fire) we explicitly restart cycling
this.pause()
if (this.touchTimeout) {
clearTimeout(this.touchTimeout)
}
this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval)
}
const swipeConfig = {
leftCallback: () => this._slide(DIRECTION_LEFT),
rightCallback: () => this._slide(DIRECTION_RIGHT),
endCallback: endCallBack
}
this._swipeHelper = new Swipe(this._element, swipeConfig)
}
_keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return
}
const direction = KEY_TO_DIRECTION[event.key]
if (direction) {
event.preventDefault()
this._slide(direction)
}
}
_getItemIndex(element) {
this._items = element && element.parentNode ?
SelectorEngine.find(SELECTOR_ITEM, element.parentNode) :
[]
return this._items.indexOf(element)
}
_getItemByOrder(order, activeElement) {
const isNext = order === ORDER_NEXT
return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap)
}
_triggerSlideEvent(relatedTarget, eventDirectionName) {
const targetIndex = this._getItemIndex(relatedTarget)
const fromIndex = this._getItemIndex(this._getActive())
return EventHandler.trigger(this._element, EVENT_SLIDE, {
relatedTarget,
direction: eventDirectionName,
from: fromIndex,
to: targetIndex
})
}
_setActiveIndicatorElement(element) {
if (!this._indicatorsElement) {
return
}
const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement)
activeIndicator.classList.remove(CLASS_NAME_ACTIVE)
activeIndicator.removeAttribute('aria-current')
const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${this._getItemIndex(element)}"]`, this._indicatorsElement)
if (newActiveIndicator) {
newActiveIndicator.classList.add(CLASS_NAME_ACTIVE)
newActiveIndicator.setAttribute('aria-current', 'true')
}
}
_updateInterval() {
const element = this._activeElement || this._getActive()
if (!element) {
return
}
const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10)
this._config.interval = elementInterval || this._config.defaultInterval
}
_slide(directionOrOrder, element) {
const order = this._directionToOrder(directionOrOrder)
const activeElement = this._getActive()
const activeElementIndex = this._getItemIndex(activeElement)
const nextElement = element || this._getItemByOrder(order, activeElement)
const nextElementIndex = this._getItemIndex(nextElement)
const isCycling = Boolean(this._interval)
const isNext = order === ORDER_NEXT
const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END
const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV
const eventDirectionName = this._orderToDirection(order)
if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE)) {
this._isSliding = false
return
}
if (this._isSliding) {
return
}
const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName)
if (slideEvent.defaultPrevented) {
return
}
if (!activeElement || !nextElement) {
// Some weirdness is happening, so we bail
return
}
this._isSliding = true
if (isCycling) {
this.pause()
}
this._setActiveIndicatorElement(nextElement)
this._activeElement = nextElement
const triggerSlidEvent = () => {
EventHandler.trigger(this._element, EVENT_SLID, {
relatedTarget: nextElement,
direction: eventDirectionName,
from: activeElementIndex,
to: nextElementIndex
})
}
if (this._element.classList.contains(CLASS_NAME_SLIDE)) {
nextElement.classList.add(orderClassName)
reflow(nextElement)
activeElement.classList.add(directionalClassName)
nextElement.classList.add(directionalClassName)
const completeCallBack = () => {
nextElement.classList.remove(directionalClassName, orderClassName)
nextElement.classList.add(CLASS_NAME_ACTIVE)
activeElement.classList.remove(CLASS_NAME_ACTIVE, orderClassName, directionalClassName)
this._isSliding = false
setTimeout(triggerSlidEvent, 0)
}
this._queueCallback(completeCallBack, activeElement, true)
} else {
activeElement.classList.remove(CLASS_NAME_ACTIVE)
nextElement.classList.add(CLASS_NAME_ACTIVE)
this._isSliding = false
triggerSlidEvent()
}
if (isCycling) {
this.cycle()
}
}
_getActive() {
return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)
}
_clearInterval() {
if (this._interval) {
clearInterval(this._interval)
this._interval = null
}
}
_directionToOrder(direction) {
if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
return direction
}
if (isRTL()) {
return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT
}
return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV
}
_orderToDirection(order) {
if (![ORDER_NEXT, ORDER_PREV].includes(order)) {
return order
}
if (isRTL()) {
return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT
}
return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT
}
// Static
static carouselInterface(element, config) {
const data = Carousel.getOrCreateInstance(element, config)
let { _config } = data
if (typeof config === 'object') {
_config = {
..._config,
...config
}
}
const action = typeof config === 'string' ? config : _config.slide
if (typeof config === 'number') {
data.to(config)
} else if (typeof action === 'string') {
if (typeof data[action] === 'undefined') {
throw new TypeError(`No method named "${action}"`)
}
data[action]()
} else if (_config.interval && _config.ride) {
data.pause()
data.cycle()
}
}
static jQueryInterface(config) {
return this.each(function () {
Carousel.carouselInterface(this, config)
})
}
static dataApiClickHandler(event) {
const target = getElementFromSelector(this)
if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
return
}
const config = {
...Manipulator.getDataAttributes(this)
}
const slideIndex = this.getAttribute('data-bs-slide-to')
if (slideIndex) {
config.interval = false
}
Carousel.carouselInterface(target, config)
if (slideIndex) {
Carousel.getInstance(target).to(slideIndex)
}
event.preventDefault()
}
}
/**
* Data API implementation
*/
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler)
EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE)
for (const carousel of carousels) {
Carousel.getOrCreateInstance(carousel)
}
})
/**
* jQuery
*/
defineJQueryPlugin(Carousel)
export default Carousel
| js/src/carousel.js | /**
* --------------------------------------------------------------------------
* Bootstrap (v5.1.3): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
import {
defineJQueryPlugin,
getElementFromSelector,
getNextActiveElement,
isRTL,
isVisible,
reflow,
triggerTransitionEnd
} from './util/index'
import EventHandler from './dom/event-handler'
import Manipulator from './dom/manipulator'
import SelectorEngine from './dom/selector-engine'
import Swipe from './util/swipe'
import BaseComponent from './base-component'
/**
* Constants
*/
const NAME = 'carousel'
const DATA_KEY = 'bs.carousel'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const ARROW_LEFT_KEY = 'ArrowLeft'
const ARROW_RIGHT_KEY = 'ArrowRight'
const TOUCHEVENT_COMPAT_WAIT = 500 // Time for mouse compat events to fire after touch
const ORDER_NEXT = 'next'
const ORDER_PREV = 'prev'
const DIRECTION_LEFT = 'left'
const DIRECTION_RIGHT = 'right'
const EVENT_SLIDE = `slide${EVENT_KEY}`
const EVENT_SLID = `slid${EVENT_KEY}`
const EVENT_KEYDOWN = `keydown${EVENT_KEY}`
const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`
const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`
const EVENT_DRAG_START = `dragstart${EVENT_KEY}`
const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
const CLASS_NAME_CAROUSEL = 'carousel'
const CLASS_NAME_ACTIVE = 'active'
const CLASS_NAME_SLIDE = 'slide'
const CLASS_NAME_END = 'carousel-item-end'
const CLASS_NAME_START = 'carousel-item-start'
const CLASS_NAME_NEXT = 'carousel-item-next'
const CLASS_NAME_PREV = 'carousel-item-prev'
const SELECTOR_ACTIVE = '.active'
const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'
const SELECTOR_ITEM = '.carousel-item'
const SELECTOR_ITEM_IMG = '.carousel-item img'
const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'
const SELECTOR_INDICATORS = '.carousel-indicators'
const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'
const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'
const KEY_TO_DIRECTION = {
[ARROW_LEFT_KEY]: DIRECTION_RIGHT,
[ARROW_RIGHT_KEY]: DIRECTION_LEFT
}
const Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true,
touch: true
}
const DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean',
touch: 'boolean'
}
/**
* Class definition
*/
class Carousel extends BaseComponent {
constructor(element, config) {
super(element, config)
this._items = null
this._interval = null
this._activeElement = null
this._isPaused = false
this._isSliding = false
this.touchTimeout = null
this._swipeHelper = null
this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element)
this._addEventListeners()
}
// Getters
static get Default() {
return Default
}
static get DefaultType() {
return DefaultType
}
static get NAME() {
return NAME
}
// Public
next() {
this._slide(ORDER_NEXT)
}
nextWhenVisible() {
// FIXME TODO use `document.visibilityState`
// Don't call next when the page isn't visible
// or the carousel or its parent isn't visible
if (!document.hidden && isVisible(this._element)) {
this.next()
}
}
prev() {
this._slide(ORDER_PREV)
}
pause(event) {
if (!event) {
this._isPaused = true
}
if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
triggerTransitionEnd(this._element)
this.cycle(true)
}
this._clearInterval()
}
cycle(event) {
if (!event) {
this._isPaused = false
}
this._clearInterval()
if (this._config.interval && !this._isPaused) {
this._updateInterval()
this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval)
}
}
to(index) {
this._activeElement = this._getActive()
const activeIndex = this._getItemIndex(this._activeElement)
if (index > this._items.length - 1 || index < 0) {
return
}
if (this._isSliding) {
EventHandler.one(this._element, EVENT_SLID, () => this.to(index))
return
}
if (activeIndex === index) {
this.pause()
this.cycle()
return
}
const order = index > activeIndex ?
ORDER_NEXT :
ORDER_PREV
this._slide(order, this._items[index])
}
dispose() {
if (this._swipeHelper) {
this._swipeHelper.dispose()
}
super.dispose()
}
// Private
_configAfterMerge(config) {
config.defaultInterval = config.interval
return config
}
_addEventListeners() {
if (this._config.keyboard) {
EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event))
}
if (this._config.pause === 'hover') {
EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event))
EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event))
}
if (this._config.touch && Swipe.isSupported()) {
this._addTouchEventListeners()
}
}
_addTouchEventListeners() {
for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) {
EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault())
}
const endCallBack = () => {
if (this._config.pause !== 'hover') {
return
}
// If it's a touch-enabled device, mouseenter/leave are fired as
// part of the mouse compatibility events on first tap - the carousel
// would stop cycling until user tapped out of it;
// here, we listen for touchend, explicitly pause the carousel
// (as if it's the second time we tap on it, mouseenter compat event
// is NOT fired) and after a timeout (to allow for mouse compatibility
// events to fire) we explicitly restart cycling
this.pause()
if (this.touchTimeout) {
clearTimeout(this.touchTimeout)
}
this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval)
}
const swipeConfig = {
leftCallback: () => this._slide(DIRECTION_LEFT),
rightCallback: () => this._slide(DIRECTION_RIGHT),
endCallback: endCallBack
}
this._swipeHelper = new Swipe(this._element, swipeConfig)
}
_keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return
}
const direction = KEY_TO_DIRECTION[event.key]
if (direction) {
event.preventDefault()
this._slide(direction)
}
}
_getItemIndex(element) {
this._items = element && element.parentNode ?
SelectorEngine.find(SELECTOR_ITEM, element.parentNode) :
[]
return this._items.indexOf(element)
}
_getItemByOrder(order, activeElement) {
const isNext = order === ORDER_NEXT
return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap)
}
_triggerSlideEvent(relatedTarget, eventDirectionName) {
const targetIndex = this._getItemIndex(relatedTarget)
const fromIndex = this._getItemIndex(this._getActive())
return EventHandler.trigger(this._element, EVENT_SLIDE, {
relatedTarget,
direction: eventDirectionName,
from: fromIndex,
to: targetIndex
})
}
_setActiveIndicatorElement(element) {
if (!this._indicatorsElement) {
return
}
const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement)
activeIndicator.classList.remove(CLASS_NAME_ACTIVE)
activeIndicator.removeAttribute('aria-current')
const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${this._getItemIndex(element)}"]`, this._indicatorsElement)
if (newActiveIndicator) {
newActiveIndicator.classList.add(CLASS_NAME_ACTIVE)
newActiveIndicator.setAttribute('aria-current', 'true')
}
}
_updateInterval() {
const element = this._activeElement || this._getActive()
if (!element) {
return
}
const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10)
this._config.interval = elementInterval || this._config.defaultInterval
}
_slide(directionOrOrder, element) {
const order = this._directionToOrder(directionOrOrder)
const activeElement = this._getActive()
const activeElementIndex = this._getItemIndex(activeElement)
const nextElement = element || this._getItemByOrder(order, activeElement)
const nextElementIndex = this._getItemIndex(nextElement)
const isCycling = Boolean(this._interval)
const isNext = order === ORDER_NEXT
const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END
const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV
const eventDirectionName = this._orderToDirection(order)
if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE)) {
this._isSliding = false
return
}
if (this._isSliding) {
return
}
const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName)
if (slideEvent.defaultPrevented) {
return
}
if (!activeElement || !nextElement) {
// Some weirdness is happening, so we bail
return
}
this._isSliding = true
if (isCycling) {
this.pause()
}
this._setActiveIndicatorElement(nextElement)
this._activeElement = nextElement
const triggerSlidEvent = () => {
EventHandler.trigger(this._element, EVENT_SLID, {
relatedTarget: nextElement,
direction: eventDirectionName,
from: activeElementIndex,
to: nextElementIndex
})
}
if (this._element.classList.contains(CLASS_NAME_SLIDE)) {
nextElement.classList.add(orderClassName)
reflow(nextElement)
activeElement.classList.add(directionalClassName)
nextElement.classList.add(directionalClassName)
const completeCallBack = () => {
nextElement.classList.remove(directionalClassName, orderClassName)
nextElement.classList.add(CLASS_NAME_ACTIVE)
activeElement.classList.remove(CLASS_NAME_ACTIVE, orderClassName, directionalClassName)
this._isSliding = false
setTimeout(triggerSlidEvent, 0)
}
this._queueCallback(completeCallBack, activeElement, true)
} else {
activeElement.classList.remove(CLASS_NAME_ACTIVE)
nextElement.classList.add(CLASS_NAME_ACTIVE)
this._isSliding = false
triggerSlidEvent()
}
if (isCycling) {
this.cycle()
}
}
_getActive() {
return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)
}
_clearInterval() {
if (this._interval) {
clearInterval(this._interval)
this._interval = null
}
}
_directionToOrder(direction) {
if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
return direction
}
if (isRTL()) {
return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT
}
return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV
}
_orderToDirection(order) {
if (![ORDER_NEXT, ORDER_PREV].includes(order)) {
return order
}
if (isRTL()) {
return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT
}
return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT
}
// Static
static carouselInterface(element, config) {
const data = Carousel.getOrCreateInstance(element, config)
let { _config } = data
if (typeof config === 'object') {
_config = {
..._config,
...config
}
}
const action = typeof config === 'string' ? config : _config.slide
if (typeof config === 'number') {
data.to(config)
} else if (typeof action === 'string') {
if (typeof data[action] === 'undefined') {
throw new TypeError(`No method named "${action}"`)
}
data[action]()
} else if (_config.interval && _config.ride) {
data.pause()
data.cycle()
}
}
static jQueryInterface(config) {
return this.each(function () {
Carousel.carouselInterface(this, config)
})
}
static dataApiClickHandler(event) {
const target = getElementFromSelector(this)
if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
return
}
const config = {
...Manipulator.getDataAttributes(this)
}
const slideIndex = this.getAttribute('data-bs-slide-to')
if (slideIndex) {
config.interval = false
}
Carousel.carouselInterface(target, config)
if (slideIndex) {
Carousel.getInstance(target).to(slideIndex)
}
event.preventDefault()
}
}
/**
* Data API implementation
*/
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler)
EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE)
for (const carousel of carousels) {
Carousel.carouselInterface(carousel, Carousel.getInstance(carousel))
}
})
/**
* jQuery
*/
defineJQueryPlugin(Carousel)
export default Carousel
| Carousel: simplify initialization on document load, using `getOrCreateInstance`
| js/src/carousel.js | Carousel: simplify initialization on document load, using `getOrCreateInstance` | <ide><path>s/src/carousel.js
<ide> const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE)
<ide>
<ide> for (const carousel of carousels) {
<del> Carousel.carouselInterface(carousel, Carousel.getInstance(carousel))
<add> Carousel.getOrCreateInstance(carousel)
<ide> }
<ide> })
<ide> |
|
Java | epl-1.0 | 124524b69f8ebcb5e5c421098606dbb7eb307851 | 0 | Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse | package org.eclipse.scanning.test.event.queues;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.eclipse.scanning.api.event.EventException;
import org.eclipse.scanning.api.event.IEventService;
import org.eclipse.scanning.api.event.bean.BeanEvent;
import org.eclipse.scanning.api.event.bean.IBeanListener;
import org.eclipse.scanning.api.event.core.ISubscriber;
import org.eclipse.scanning.api.event.queues.IQueue;
import org.eclipse.scanning.api.event.queues.IQueueControllerService;
import org.eclipse.scanning.api.event.queues.IQueueService;
import org.eclipse.scanning.api.event.queues.beans.QueueBean;
import org.eclipse.scanning.api.event.queues.beans.Queueable;
import org.eclipse.scanning.api.event.queues.beans.SubTaskAtom;
import org.eclipse.scanning.api.event.queues.beans.TaskBean;
import org.eclipse.scanning.api.event.status.Status;
import org.eclipse.scanning.event.queues.QueueProcessorFactory;
import org.eclipse.scanning.event.queues.ServicesHolder;
import org.eclipse.scanning.test.BrokerTest;
import org.eclipse.scanning.test.event.queues.dummy.DummyAtom;
import org.eclipse.scanning.test.event.queues.dummy.DummyAtomProcessor;
import org.eclipse.scanning.test.event.queues.dummy.DummyBean;
import org.eclipse.scanning.test.event.queues.dummy.DummyBeanProcessor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class QueueServiceIntegrationPluginTest extends BrokerTest {
protected static IQueueService queueService;
protected static IQueueControllerService queueControl;
private String qRoot = "fake-queue-root";
private DummyBean dummyB;
private DummyAtom dummyA;
@Before
public void setup() throws Exception {
//FOR TESTS ONLY
QueueProcessorFactory.registerProcessor(DummyAtomProcessor.class);
QueueProcessorFactory.registerProcessor(DummyBeanProcessor.class);
//Configure the queue service
queueService = ServicesHolder.getQueueService();
queueService.setUri(uri);
queueService.setQueueRoot(qRoot);
queueService.init();
//Configure the queue controller service
queueControl = ServicesHolder.getQueueControllerService();
queueControl.init();
//Above here - spring will make the calls
queueControl.startQueueService();
}
@After
public void tearDown() throws EventException {
queueControl.stopQueueService(false);
}
@Test
public void testRunningBean() throws EventException {
dummyB = new DummyBean("Bob", 50);
queueControl.submit(dummyB, queueService.getJobQueueID());
try {
waitForBeanFinalStatus(dummyB, queueService.getJobQueueID());//FIXME Put this on the QueueController
} catch (Exception e) {
// It's only a test...
e.printStackTrace();
}
List<QueueBean> statusSet = queueService.getJobQueue().getConsumer().getStatusSet();
assertEquals(1, statusSet.size());
assertEquals(Status.COMPLETE, statusSet.get(0).getStatus());
assertEquals(dummyB.getUniqueId(), statusSet.get(0).getUniqueId());
}
@Test
public void testTaskBean() throws EventException {
TaskBean task = new TaskBean();
task.setName("Test Task");
SubTaskAtom subTask = new SubTaskAtom();
subTask.setName("Test SubTask");
dummyA = new DummyAtom("Gregor", 70);
subTask.addAtom(dummyA);
task.addAtom(subTask);
queueControl.submit(task, queueService.getJobQueueID());
try {
// Thread.sleep(1000000);
waitForBeanFinalStatus(dummyB, queueService.getJobQueueID());//FIXME Put this on the QueueController
} catch (Exception e) {
// It's only a test...
e.printStackTrace();
}
List<QueueBean> statusSet = queueService.getJobQueue().getConsumer().getStatusSet();
assertEquals(1, statusSet.size());
assertEquals(Status.COMPLETE, statusSet.get(0).getStatus());
assertEquals(task.getUniqueId(), statusSet.get(0).getUniqueId());
}
/**
* Same as below, but does not check for final state and waits for 10s
*/
private void waitForBeanStatus(Queueable bean, Status state, String queueID) throws EventException, InterruptedException {
waitForBeanStatus(bean, state, queueID, false, 10000);
}
/**
* Same as below, but checks for isFinal and waits 10s
*/
private void waitForBeanFinalStatus(Queueable bean, String queueID) throws EventException, InterruptedException {
waitForBeanStatus(bean, null, queueID, true, 1000000);
}
/**
* Timeout is in ms
*/
private void waitForBeanStatus(Queueable bean, Status state, String queueID, boolean isFinal, long timeout)
throws EventException, InterruptedException {
final CountDownLatch statusLatch = new CountDownLatch(1);
//Get the queue we're interested in
IQueue<Queueable> queue = queueService.getQueue(queueID);
//Create a subscriber configured to listen for our bean
IEventService evServ = ServicesHolder.getEventService();
ISubscriber<IBeanListener<Queueable>> statusSubsc = evServ.createSubscriber(uri, queue.getStatusTopicName());
statusSubsc.addListener(new IBeanListener<Queueable>() {
@Override
public void beanChangePerformed(BeanEvent<Queueable> evt) {
Queueable evtBean = evt.getBean();
if (evtBean.getUniqueId().equals(bean.getUniqueId())) {
if ((evtBean.getStatus() == state) || (evtBean.getStatus().isFinal() && isFinal)) {
statusLatch.countDown();
}
}
}
});
//We may get stuck if the consumer finishes processing faster than the test works through
//If so, we need to test for a non-empty status set with last bean status equal to our expectation
//Once finished, check whether the latch was released or timedout
boolean released = statusLatch.await(timeout, TimeUnit.MILLISECONDS);
if (released) {
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~\n Final state reached\n~~~~~~~~~~~~~~~~~~~~~~~~~");
} else {
System.out.println("#########################\n No final state reported\n#########################");
}
statusSubsc.disconnect();
}
}
| org.eclipse.scanning.test/src/org/eclipse/scanning/test/event/queues/QueueServiceIntegrationPluginTest.java | package org.eclipse.scanning.test.event.queues;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.eclipse.scanning.api.event.EventException;
import org.eclipse.scanning.api.event.IEventService;
import org.eclipse.scanning.api.event.bean.BeanEvent;
import org.eclipse.scanning.api.event.bean.IBeanListener;
import org.eclipse.scanning.api.event.core.ISubscriber;
import org.eclipse.scanning.api.event.queues.IQueue;
import org.eclipse.scanning.api.event.queues.IQueueControllerService;
import org.eclipse.scanning.api.event.queues.IQueueService;
import org.eclipse.scanning.api.event.queues.beans.QueueBean;
import org.eclipse.scanning.api.event.queues.beans.Queueable;
import org.eclipse.scanning.api.event.queues.beans.SubTaskAtom;
import org.eclipse.scanning.api.event.queues.beans.TaskBean;
import org.eclipse.scanning.api.event.status.Status;
import org.eclipse.scanning.event.queues.QueueProcessorFactory;
import org.eclipse.scanning.event.queues.ServicesHolder;
import org.eclipse.scanning.test.BrokerTest;
import org.eclipse.scanning.test.event.queues.dummy.DummyAtom;
import org.eclipse.scanning.test.event.queues.dummy.DummyAtomProcessor;
import org.eclipse.scanning.test.event.queues.dummy.DummyBean;
import org.eclipse.scanning.test.event.queues.dummy.DummyBeanProcessor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class QueueServiceIntegrationPluginTest extends BrokerTest {
protected static IQueueService queueService;
protected static IQueueControllerService queueControl;
private String qRoot = "fake-queue-root";
private DummyBean dummyB;
private DummyAtom dummyA;
@Before
public void setup() throws Exception {
//FOR TESTS ONLY
QueueProcessorFactory.registerProcessor(DummyAtomProcessor.class);
QueueProcessorFactory.registerProcessor(DummyBeanProcessor.class);
//Configure the queue service
queueService = ServicesHolder.getQueueService();
queueService.setUri(uri);
queueService.setQueueRoot(qRoot);
queueService.init();
//Configure the queue controller service
queueControl = ServicesHolder.getQueueControllerService();
queueControl.init();
//Above here - spring will make the calls
queueControl.startQueueService();
}
@After
public void tearDown() throws EventException {
queueControl.stopQueueService(false);
}
@Test
public void testRunningBean() throws EventException {
dummyB = new DummyBean("Bob", 50);
queueControl.submit(dummyB, queueService.getJobQueueID());
try {
waitForBeanFinalStatus(dummyB, queueService.getJobQueueID());//FIXME Put this on the QueueController
} catch (Exception e) {
// It's only a test...
e.printStackTrace();
}
List<QueueBean> statusSet = queueService.getJobQueue().getConsumer().getStatusSet();
assertEquals(1, statusSet.size());
assertEquals(Status.COMPLETE, statusSet.get(0).getStatus());
assertEquals(dummyB.getUniqueId(), statusSet.get(0).getUniqueId());
}
@Test
public void testTaskBean() throws EventException {
TaskBean task = new TaskBean();
task.setName("Test Task");
SubTaskAtom subTask = new SubTaskAtom();
subTask.setName("Test SubTask");
dummyA = new DummyAtom("Gregor", 70);
subTask.addAtom(dummyA);
task.addAtom(subTask);
queueControl.submit(task, queueService.getJobQueueID());
try {
Thread.sleep(1000000);
} catch (Exception e) {
// It's only a test...
e.printStackTrace();
}
List<QueueBean> statusSet = queueService.getJobQueue().getConsumer().getStatusSet();
assertEquals(1, statusSet.size());
assertEquals(Status.COMPLETE, statusSet.get(0).getStatus());
assertEquals(task.getUniqueId(), statusSet.get(0).getUniqueId());
}
/**
* Same as below, but does not check for final state and waits for 10s
*/
private void waitForBeanStatus(Queueable bean, Status state, String queueID) throws EventException, InterruptedException {
waitForBeanStatus(bean, state, queueID, false, 10000);
}
/**
* Same as below, but checks for isFinal and waits 10s
*/
private void waitForBeanFinalStatus(Queueable bean, String queueID) throws EventException, InterruptedException {
waitForBeanStatus(bean, null, queueID, true, 10000);
}
/**
* Timeout is in ms
*/
private void waitForBeanStatus(Queueable bean, Status state, String queueID, boolean isFinal, long timeout)
throws EventException, InterruptedException {
final CountDownLatch statusLatch = new CountDownLatch(1);
//Get the queue we're interested in
IQueue<Queueable> queue = queueService.getQueue(queueID);
//Create a subscriber configured to listen for our bean
IEventService evServ = ServicesHolder.getEventService();
ISubscriber<IBeanListener<Queueable>> statusSubsc = evServ.createSubscriber(uri, queue.getStatusTopicName());
statusSubsc.addListener(new IBeanListener<Queueable>() {
@Override
public void beanChangePerformed(BeanEvent<Queueable> evt) {
Queueable evtBean = evt.getBean();
if (evtBean.getUniqueId().equals(bean.getUniqueId())) {
if ((evtBean.getStatus() == state) || (evtBean.getStatus().isFinal() && isFinal)) {
statusLatch.countDown();
}
}
}
});
//We may get stuck if the consumer finishes processing faster than the test works through
//If so, we need to test for a non-empty status set with last bean status equal to our expectation
//Once finished, check whether the latch was released or timedout
boolean released = statusLatch.await(timeout, TimeUnit.MILLISECONDS);
if (released) {
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~\n Final state reached\n~~~~~~~~~~~~~~~~~~~~~~~~~");
} else {
System.out.println("#########################\n No final state reported\n#########################");
}
statusSubsc.disconnect();
}
}
| Adds wait to testTaskBean instead of sleep. N.B. Long sleep in timeout.
Signed-off-by: Michael Wharmby <[email protected]> | org.eclipse.scanning.test/src/org/eclipse/scanning/test/event/queues/QueueServiceIntegrationPluginTest.java | Adds wait to testTaskBean instead of sleep. N.B. Long sleep in timeout. | <ide><path>rg.eclipse.scanning.test/src/org/eclipse/scanning/test/event/queues/QueueServiceIntegrationPluginTest.java
<ide> queueControl.submit(task, queueService.getJobQueueID());
<ide>
<ide> try {
<del> Thread.sleep(1000000);
<add>// Thread.sleep(1000000);
<add> waitForBeanFinalStatus(dummyB, queueService.getJobQueueID());//FIXME Put this on the QueueController
<ide> } catch (Exception e) {
<ide> // It's only a test...
<ide> e.printStackTrace();
<ide> * Same as below, but checks for isFinal and waits 10s
<ide> */
<ide> private void waitForBeanFinalStatus(Queueable bean, String queueID) throws EventException, InterruptedException {
<del> waitForBeanStatus(bean, null, queueID, true, 10000);
<add> waitForBeanStatus(bean, null, queueID, true, 1000000);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 526ea78c82b2d466d663ef4d9734545bb31c686a | 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 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller;
import com.yahoo.config.application.api.DeploymentInstanceSpec;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ContainerEndpoint;
import com.yahoo.vespa.hosted.controller.api.integration.dns.Record;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordData;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordName;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.Endpoint.Port;
import com.yahoo.vespa.hosted.controller.application.EndpointList;
import com.yahoo.vespa.hosted.controller.dns.NameServiceQueue.Priority;
import com.yahoo.vespa.hosted.controller.rotation.RotationLock;
import com.yahoo.vespa.hosted.controller.rotation.RotationRepository;
import com.yahoo.vespa.hosted.controller.routing.RoutingId;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicies;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* The routing controller encapsulates state and methods for inspecting and manipulating DNS-level routing of traffic
* in a system.
*
* The one stop shop for all your routing needs!
*
* @author mpolden
*/
public class RoutingController {
private final Controller controller;
private final RoutingPolicies routingPolicies;
private final RotationRepository rotationRepository;
public RoutingController(Controller controller, RotationsConfig rotationsConfig) {
this.controller = Objects.requireNonNull(controller, "controller must be non-null");
this.routingPolicies = new RoutingPolicies(controller);
this.rotationRepository = new RotationRepository(rotationsConfig, controller.applications(),
controller.curator());
}
public RoutingPolicies policies() {
return routingPolicies;
}
public RotationRepository rotations() {
return rotationRepository;
}
/** Returns zone-scoped endpoints for given deployment */
public EndpointList endpointsOf(DeploymentId deployment) {
var endpoints = new LinkedHashSet<Endpoint>();
for (var policy : routingPolicies.get(deployment).values()) {
if (!policy.status().isActive()) continue;
for (var routingMethod : controller.zoneRegistry().routingMethods(policy.id().zone())) {
endpoints.add(policy.endpointIn(controller.system(), routingMethod));
}
}
if (endpoints.isEmpty()) { // TODO(mpolden): Remove this once all applications have deployed once
controller.serviceRegistry().routingGenerator().clusterEndpoints(deployment)
.forEach((cluster, url) -> endpoints.add(Endpoint.of(deployment.applicationId())
.target(cluster, deployment.zoneId())
.routingMethod(RoutingMethod.shared)
.on(Port.fromRoutingMethod(RoutingMethod.shared))
.in(controller.system())));
}
return EndpointList.copyOf(endpoints);
}
/** Returns global-scoped endpoints for given instance */
public EndpointList endpointsOf(ApplicationId instance) {
return endpointsOf(controller.applications().requireInstance(instance));
}
/** Returns global-scoped endpoints for given instance */
// TODO(mpolden): Add a endpointsOf(Instance, DeploymentId) variant of this that only returns global endpoint of
// which deployment is a member
public EndpointList endpointsOf(Instance instance) {
var endpoints = new LinkedHashSet<Endpoint>();
// Add global endpoints provided by rotations
for (var rotation : instance.rotations()) {
EndpointList.global(RoutingId.of(instance.id(), rotation.endpointId()),
controller.system(), systemRoutingMethods())
.requiresRotation()
.forEach(endpoints::add);
}
// Add global endpoints provided by routing policices
for (var policy : routingPolicies.get(instance.id()).values()) {
if (!policy.status().isActive()) continue;
for (var endpointId : policy.endpoints()) {
EndpointList.global(RoutingId.of(instance.id(), endpointId),
controller.system(), systemRoutingMethods())
.not().requiresRotation()
.forEach(endpoints::add);
}
}
return EndpointList.copyOf(endpoints);
}
/** Returns all non-global endpoints and corresponding cluster IDs for given deployments, grouped by their zone */
public Map<ZoneId, Map<URI, ClusterSpec.Id>> zoneEndpointsOf(Collection<DeploymentId> deployments) {
var endpoints = new TreeMap<ZoneId, Map<URI, ClusterSpec.Id>>(Comparator.comparing(ZoneId::value));
for (var deployment : deployments) {
var zoneEndpoints = endpointsOf(deployment).scope(Endpoint.Scope.zone).asList().stream()
.collect(Collectors.toUnmodifiableMap(Endpoint::url,
endpoint -> ClusterSpec.Id.from(endpoint.name())));
if (!zoneEndpoints.isEmpty()) {
endpoints.put(deployment.zoneId(), zoneEndpoints);
}
}
return Collections.unmodifiableMap(endpoints);
}
/** Change status of all global endpoints for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
endpointsOf(deployment.applicationId()).requiresRotation().primary().ifPresent(endpoint -> {
try {
controller.serviceRegistry().configServer().setGlobalRotationStatus(deployment, endpoint.upstreamIdOf(deployment), status);
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + endpoint + " in " + deployment, e);
}
});
}
/** Get global endpoint status for given deployment */
public Map<Endpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
var routingEndpoints = new LinkedHashMap<Endpoint, EndpointStatus>();
endpointsOf(deployment.applicationId()).requiresRotation().primary().ifPresent(endpoint -> {
var upstreamName = endpoint.upstreamIdOf(deployment);
var status = controller.serviceRegistry().configServer().getGlobalRotationStatus(deployment, upstreamName);
routingEndpoints.put(endpoint, status);
});
return Collections.unmodifiableMap(routingEndpoints);
}
/**
* Assigns one or more global rotations to given application, if eligible. The given application is implicitly
* stored, ensuring that the assigned rotation(s) are persisted when this returns.
*/
public LockedApplication assignRotations(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
controller.applications().store(application); // store assigned rotation even if deployment fails
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
public Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
boolean registerLegacyNames = deploymentSpec.instance(instance.name())
.flatMap(DeploymentInstanceSpec::globalServiceId)
.isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = endpointsOf(instance).named(assignedRotation.endpointId()).requiresRotation();
// Skip rotations which do not apply to this zone. Legacy names always point to all zones
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
// Omit legacy DNS names when assigning rotations using <endpoints/> syntax
if (!registerLegacyNames) {
endpoints = endpoints.not().legacy();
}
// Register names in DNS
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
// Include rotation ID as a valid name of this container endpoint (required by global routing health checks)
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
/** Remove endpoints in DNS for all rotations assigned to given instance */
public void removeEndpointsInDns(Instance instance) {
endpointsOf(instance).requiresRotation()
.forEach(endpoint -> controller.nameServiceForwarder()
.removeRecords(Record.Type.CNAME,
RecordName.from(endpoint.dnsName()),
Priority.normal));
}
/** Returns all routing methods supported by this system */
private List<RoutingMethod> systemRoutingMethods() {
return controller.zoneRegistry().zones().all().ids().stream()
.flatMap(zone -> controller.zoneRegistry().routingMethods(zone).stream())
.distinct()
.collect(Collectors.toUnmodifiableList());
}
}
| controller-server/src/main/java/com/yahoo/vespa/hosted/controller/RoutingController.java | // Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller;
import com.yahoo.config.application.api.DeploymentInstanceSpec;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ContainerEndpoint;
import com.yahoo.vespa.hosted.controller.api.integration.dns.Record;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordData;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordName;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.Endpoint.Port;
import com.yahoo.vespa.hosted.controller.application.EndpointList;
import com.yahoo.vespa.hosted.controller.dns.NameServiceQueue.Priority;
import com.yahoo.vespa.hosted.controller.rotation.RotationLock;
import com.yahoo.vespa.hosted.controller.rotation.RotationRepository;
import com.yahoo.vespa.hosted.controller.routing.RoutingId;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicies;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* The routing controller encapsulates state and methods for inspecting and manipulating DNS-level routing of traffic
* in a system.
*
* The one stop shop for all your routing needs!
*
* @author mpolden
*/
public class RoutingController {
private final Controller controller;
private final RoutingPolicies routingPolicies;
private final RotationRepository rotationRepository;
public RoutingController(Controller controller, RotationsConfig rotationsConfig) {
this.controller = Objects.requireNonNull(controller, "controller must be non-null");
this.routingPolicies = new RoutingPolicies(controller);
this.rotationRepository = new RotationRepository(rotationsConfig, controller.applications(),
controller.curator());
}
public RoutingPolicies policies() {
return routingPolicies;
}
public RotationRepository rotations() {
return rotationRepository;
}
/** Returns zone-scoped endpoints for given deployment */
public EndpointList endpointsOf(DeploymentId deployment) {
var endpoints = new LinkedHashSet<Endpoint>();
for (var policy : routingPolicies.get(deployment).values()) {
if (!policy.status().isActive()) continue;
for (var routingMethod : controller.zoneRegistry().routingMethods(policy.id().zone())) {
endpoints.add(policy.endpointIn(controller.system(), routingMethod));
}
}
if (endpoints.isEmpty()) { // TODO(mpolden): Remove this once all applications have deployed once
controller.serviceRegistry().routingGenerator().clusterEndpoints(deployment)
.forEach((cluster, url) -> endpoints.add(Endpoint.of(deployment.applicationId())
.target(cluster, deployment.zoneId())
.routingMethod(RoutingMethod.shared)
.on(Port.fromRoutingMethod(RoutingMethod.shared))
.in(controller.system())));
}
return EndpointList.copyOf(endpoints);
}
/** Returns global-scoped endpoints for given instance */
public EndpointList endpointsOf(ApplicationId instance) {
return endpointsOf(controller.applications().requireInstance(instance));
}
/** Returns global-scoped endpoints for given instance */
public EndpointList endpointsOf(Instance instance) {
var endpoints = new LinkedHashSet<Endpoint>();
// Add global endpoints provided by rotations
for (var rotation : instance.rotations()) {
EndpointList.global(RoutingId.of(instance.id(), rotation.endpointId()),
controller.system(), systemRoutingMethods())
.requiresRotation()
.forEach(endpoints::add);
}
// Add global endpoints provided by routing policices
for (var policy : routingPolicies.get(instance.id()).values()) {
if (!policy.status().isActive()) continue;
for (var endpointId : policy.endpoints()) {
EndpointList.global(RoutingId.of(instance.id(), endpointId),
controller.system(), systemRoutingMethods())
.not().requiresRotation()
.forEach(endpoints::add);
}
}
return EndpointList.copyOf(endpoints);
}
/** Returns all non-global endpoints and corresponding cluster IDs for given deployments, grouped by their zone */
public Map<ZoneId, Map<URI, ClusterSpec.Id>> zoneEndpointsOf(Collection<DeploymentId> deployments) {
var endpoints = new TreeMap<ZoneId, Map<URI, ClusterSpec.Id>>(Comparator.comparing(ZoneId::value));
for (var deployment : deployments) {
var zoneEndpoints = endpointsOf(deployment).scope(Endpoint.Scope.zone).asList().stream()
.collect(Collectors.toUnmodifiableMap(Endpoint::url,
endpoint -> ClusterSpec.Id.from(endpoint.name())));
if (!zoneEndpoints.isEmpty()) {
endpoints.put(deployment.zoneId(), zoneEndpoints);
}
}
return Collections.unmodifiableMap(endpoints);
}
/** Change status of all global endpoints for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
endpointsOf(deployment.applicationId()).requiresRotation().primary().ifPresent(endpoint -> {
try {
controller.serviceRegistry().configServer().setGlobalRotationStatus(deployment, endpoint.upstreamIdOf(deployment), status);
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + endpoint + " in " + deployment, e);
}
});
}
/** Get global endpoint status for given deployment */
public Map<Endpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
var routingEndpoints = new LinkedHashMap<Endpoint, EndpointStatus>();
endpointsOf(deployment.applicationId()).requiresRotation().primary().ifPresent(endpoint -> {
var upstreamName = endpoint.upstreamIdOf(deployment);
var status = controller.serviceRegistry().configServer().getGlobalRotationStatus(deployment, upstreamName);
routingEndpoints.put(endpoint, status);
});
return Collections.unmodifiableMap(routingEndpoints);
}
/**
* Assigns one or more global rotations to given application, if eligible. The given application is implicitly
* stored, ensuring that the assigned rotation(s) are persisted when this returns.
*/
public LockedApplication assignRotations(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
controller.applications().store(application); // store assigned rotation even if deployment fails
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
public Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
boolean registerLegacyNames = deploymentSpec.instance(instance.name())
.flatMap(DeploymentInstanceSpec::globalServiceId)
.isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = endpointsOf(instance).named(assignedRotation.endpointId()).requiresRotation();
// Skip rotations which do not apply to this zone. Legacy names always point to all zones
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
// Omit legacy DNS names when assigning rotations using <endpoints/> syntax
if (!registerLegacyNames) {
endpoints = endpoints.not().legacy();
}
// Register names in DNS
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
// Include rotation ID as a valid name of this container endpoint (required by global routing health checks)
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
/** Remove endpoints in DNS for all rotations assigned to given instance */
public void removeEndpointsInDns(Instance instance) {
endpointsOf(instance).requiresRotation()
.forEach(endpoint -> controller.nameServiceForwarder()
.removeRecords(Record.Type.CNAME,
RecordName.from(endpoint.dnsName()),
Priority.normal));
}
/** Returns all routing methods supported by this system */
private List<RoutingMethod> systemRoutingMethods() {
return controller.zoneRegistry().zones().all().ids().stream()
.flatMap(zone -> controller.zoneRegistry().routingMethods(zone).stream())
.distinct()
.collect(Collectors.toUnmodifiableList());
}
}
| Add TODO
| controller-server/src/main/java/com/yahoo/vespa/hosted/controller/RoutingController.java | Add TODO | <ide><path>ontroller-server/src/main/java/com/yahoo/vespa/hosted/controller/RoutingController.java
<ide> }
<ide>
<ide> /** Returns global-scoped endpoints for given instance */
<add> // TODO(mpolden): Add a endpointsOf(Instance, DeploymentId) variant of this that only returns global endpoint of
<add> // which deployment is a member
<ide> public EndpointList endpointsOf(Instance instance) {
<ide> var endpoints = new LinkedHashSet<Endpoint>();
<ide> // Add global endpoints provided by rotations |
|
Java | apache-2.0 | abdbd0583f93e47910705be5597070220cdb5d98 | 0 | Uwe-Fuchs/open-ur | package org.openur.remoting.webservice.config;
import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.env.Environment;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ImportResource("classpath:/springDataAppContext.xml")
@EnableJpaRepositories(basePackages = { "org.openur.module.persistence.rdbms.repository" })
public class JpaRepositorySpringConfig
{
@Inject
protected Environment env;
public DataSource dataSource()
{
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource(env.getProperty("database.jndiName", "java:comp/env/jdbc/open_ur"));
return dataSource;
}
@Bean
public EntityManagerFactory entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setJpaVendorAdapter(jpaVendorAdapter());
em.setPackagesToScan("org.openur.module.persistence");
em.afterPropertiesSet();
return em.getObject();
}
@Bean
public PersistenceExceptionTranslator hibernateExceptionTranslator()
{
return new HibernateExceptionTranslator();
}
@Bean
public HibernateJpaVendorAdapter jpaVendorAdapter()
{
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(env.getProperty("database.showSql", Boolean.class, Boolean.FALSE));
adapter.setDatabasePlatform(env.getProperty("database.databasePlatform", "org.hibernate.dialect.MySQL5InnoDBDialect"));
return adapter;
}
@Bean(name = "transactionManager")
public JpaTransactionManager transactionManager()
{
return new JpaTransactionManager(entityManagerFactory());
}
}
| open_ur-remoting/open_ur-remoting-webservice-app/src/main/java/org/openur/remoting/webservice/config/JpaRepositorySpringConfig.java | package org.openur.remoting.webservice.config;
import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.env.Environment;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ImportResource("classpath:/springDataAppContext.xml")
@EnableJpaRepositories(basePackages = { "org.openur.module.persistence.rdbms.repository" })
public class JpaRepositorySpringConfig
{
@Inject
protected Environment env;
public DataSource dataSource()
{
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/open_ur");
return dataSource;
}
@Bean
public EntityManagerFactory entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setJpaVendorAdapter(jpaVendorAdapter());
em.setPackagesToScan("org.openur.module.persistence");
em.afterPropertiesSet();
return em.getObject();
}
@Bean
public PersistenceExceptionTranslator hibernateExceptionTranslator()
{
return new HibernateExceptionTranslator();
}
@Bean
public HibernateJpaVendorAdapter jpaVendorAdapter()
{
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(env.getProperty("database.showSql", Boolean.class, Boolean.FALSE));
adapter.setDatabasePlatform(env.getProperty("database.databasePlatform", "org.hibernate.dialect.MySQL5InnoDBDialect"));
return adapter;
}
@Bean(name = "transactionManager")
public JpaTransactionManager transactionManager()
{
return new JpaTransactionManager(entityManagerFactory());
}
}
| get database-jndi-name from properties or system-property, set default-value.
| open_ur-remoting/open_ur-remoting-webservice-app/src/main/java/org/openur/remoting/webservice/config/JpaRepositorySpringConfig.java | get database-jndi-name from properties or system-property, set default-value. | <ide><path>pen_ur-remoting/open_ur-remoting-webservice-app/src/main/java/org/openur/remoting/webservice/config/JpaRepositorySpringConfig.java
<ide> {
<ide> final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
<ide> dsLookup.setResourceRef(true);
<del> DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/open_ur");
<add> DataSource dataSource = dsLookup.getDataSource(env.getProperty("database.jndiName", "java:comp/env/jdbc/open_ur"));
<ide>
<ide> return dataSource;
<ide> } |
|
Java | bsd-3-clause | db6904eb2816af097523e0377aadb7dada0c3441 | 0 | NCIP/cagrid-core,NCIP/cagrid-core,NCIP/cagrid-core,NCIP/cagrid-core | package org.cagrid.tests.data.styles.cacore42.story;
import gov.nih.nci.cagrid.common.Utils;
import java.io.File;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.tests.data.styles.cacore42.steps.SdkDatabaseStep;
import org.cagrid.tests.data.styles.cacore42.steps.SdkDatabaseStep.DatabaseOperation;
import org.junit.After;
import org.junit.Test;
public class SDK42DataServiceSystemTests {
private static Log LOG = LogFactory.getLog(SDK42DataServiceSystemTests.class);
private long lastTime = 0;
private File tempApplicationDir = null;
@Test
public void sdk42DataServiceSystemTests() throws Throwable {
// create a temporary directory for the SDK application to package things in
tempApplicationDir = File.createTempFile("SdkExample", "temp");
tempApplicationDir.delete();
tempApplicationDir.mkdirs();
LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath());
// create the caCORE SDK example project
splitTime();
LOG.debug("Running caCORE SDK example project creation story");
CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir);
createExampleStory.runBare();
// create and run a caGrid Data Service using the SDK's local API
splitTime();
LOG.debug("Running data service using local API story");
SDK42StyleLocalApiStory localApiStory = new SDK42StyleLocalApiStory();
localApiStory.runBare();
// create and run a caGrid Data Service using the SDK's remote API
splitTime();
LOG.debug("Running data service using remote API story");
SDK42StyleRemoteApiStory remoteApiStory = new SDK42StyleRemoteApiStory();
remoteApiStory.runBare();
}
@After
public void cleanUp() {
LOG.debug("Cleaning up after tests");
// tear down the sdk example database
try {
new SdkDatabaseStep(DatabaseOperation.DESTROY).runStep();
} catch (Exception ex) {
LOG.warn("Error destroying SDK example project database: " + ex.getMessage());
ex.printStackTrace();
}
// throw away the temp sdk dir
LOG.debug("Deleting temp application base dir: " + tempApplicationDir.getAbsolutePath());
Utils.deleteDir(tempApplicationDir);
}
private void splitTime() {
if (lastTime == 0) {
LOG.debug("Timer started");
} else {
LOG.debug("Time elapsed: "
+ (System.currentTimeMillis() - lastTime) / 1000D + " sec");
}
lastTime = System.currentTimeMillis();
}
public static void main(String[] args) {
TestRunner runner = new TestRunner();
TestResult result = runner.doRun(new TestSuite(SDK42DataServiceSystemTests.class));
System.exit(result.errorCount() + result.failureCount());
}
}
| integration-tests/projects/sdk42StyleTests/src/org/cagrid/tests/data/styles/cacore42/story/SDK42DataServiceSystemTests.java | package org.cagrid.tests.data.styles.cacore42.story;
import gov.nih.nci.cagrid.common.Utils;
import java.io.File;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.tests.data.styles.cacore42.steps.SdkDatabaseStep;
import org.cagrid.tests.data.styles.cacore42.steps.SdkDatabaseStep.DatabaseOperation;
import org.junit.After;
import org.junit.Test;
public class SDK42DataServiceSystemTests {
private static Log LOG = LogFactory.getLog(SDK42DataServiceSystemTests.class);
private long lastTime = 0;
private File tempApplicationDir = null;
@Test
public void sdk42DataServiceSystemTests() throws Throwable {
// create a temporary directory for the SDK application to package things in
tempApplicationDir = File.createTempFile("SdkExample", "temp");
LOG.debug("Creating temp application base dir: " + tempApplicationDir.getAbsolutePath());
tempApplicationDir.mkdirs();
// create the caCORE SDK example project
splitTime();
LOG.debug("Running caCORE SDK example project creation story");
CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir);
createExampleStory.runBare();
// create and run a caGrid Data Service using the SDK's local API
splitTime();
LOG.debug("Running data service using local API story");
SDK42StyleLocalApiStory localApiStory = new SDK42StyleLocalApiStory();
localApiStory.runBare();
// create and run a caGrid Data Service using the SDK's remote API
splitTime();
LOG.debug("Running data service using remote API story");
SDK42StyleRemoteApiStory remoteApiStory = new SDK42StyleRemoteApiStory();
remoteApiStory.runBare();
}
@After
public void cleanUp() {
LOG.debug("Cleaning up after tests");
// tear down the sdk example database
try {
new SdkDatabaseStep(DatabaseOperation.DESTROY).runStep();
} catch (Exception ex) {
LOG.warn("Error destroying SDK example project database: " + ex.getMessage());
ex.printStackTrace();
}
// throw away the temp sdk dir
LOG.debug("Deleting temp application base dir: " + tempApplicationDir.getAbsolutePath());
Utils.deleteDir(tempApplicationDir);
}
private void splitTime() {
if (lastTime == 0) {
LOG.debug("Timer started");
} else {
LOG.debug("Time elapsed: "
+ (System.currentTimeMillis() - lastTime) / 1000D + " sec");
}
lastTime = System.currentTimeMillis();
}
public static void main(String[] args) {
TestRunner runner = new TestRunner();
TestResult result = runner.doRun(new TestSuite(SDK42DataServiceSystemTests.class));
System.exit(result.errorCount() + result.failureCount());
}
}
|
git-svn-id: https://ncisvn.nci.nih.gov/svn/cagrid/trunk/cagrid/Software/core@14827 dd7b0c16-3c94-4492-92de-414b6a06f0b1
| integration-tests/projects/sdk42StyleTests/src/org/cagrid/tests/data/styles/cacore42/story/SDK42DataServiceSystemTests.java | <ide><path>ntegration-tests/projects/sdk42StyleTests/src/org/cagrid/tests/data/styles/cacore42/story/SDK42DataServiceSystemTests.java
<ide> public void sdk42DataServiceSystemTests() throws Throwable {
<ide> // create a temporary directory for the SDK application to package things in
<ide> tempApplicationDir = File.createTempFile("SdkExample", "temp");
<del> LOG.debug("Creating temp application base dir: " + tempApplicationDir.getAbsolutePath());
<add> tempApplicationDir.delete();
<ide> tempApplicationDir.mkdirs();
<add> LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath());
<ide>
<ide> // create the caCORE SDK example project
<ide> splitTime(); |
||
Java | apache-2.0 | 8835cd5dbde41f4b7df9aafcba876e75d5bafb9e | 0 | wardev/orekit,liscju/Orekit,ProjectPersephone/Orekit,attatrol/Orekit,attatrol/Orekit,CS-SI/Orekit,Yakushima/Orekit,CS-SI/Orekit,petrushy/Orekit,liscju/Orekit,Yakushima/Orekit,ProjectPersephone/Orekit,petrushy/Orekit | /* Copyright 2002-2014 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.propagation.conversion;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractParameterizable;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.errors.OrekitException;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.analytical.tle.TLE;
import org.orekit.propagation.analytical.tle.TLEPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;
/** Builder for TLEPropagator.
* @author Pascal Parraud
* @since 6.0
*/
public class TLEPropagatorBuilder extends AbstractParameterizable
implements PropagatorBuilder {
/** Parameter name for B* coefficient. */
public static final String B_STAR = "BSTAR";
/** Satellite number. */
private final int satelliteNumber;
/** Classification (U for unclassified). */
private final char classification;
/** Launch year (all digits). */
private final int launchYear;
/** Launch number. */
private final int launchNumber;
/** Launch piece. */
private final String launchPiece;
/** Element number. */
private final int elementNumber;
/** Revolution number at epoch. */
private final int revolutionNumberAtEpoch;
/** Central attraction coefficient (m<sup>3</sup>/s<sup>2</sup>). */
private final double mu;
/** TEME frame. */
private final Frame frame;
/** List of the free parameters names. */
private Collection<String> freeParameters;
/** Ballistic coefficient. */
private double bStar;
/** Build a new instance.
* @param satelliteNumber satellite number
* @param classification classification (U for unclassified)
* @param launchYear launch year (all digits)
* @param launchNumber launch number
* @param launchPiece launch piece
* @param elementNumber element number
* @param revolutionNumberAtEpoch revolution number at epoch
* @throws OrekitException if the TEME frame cannot be set
*/
public TLEPropagatorBuilder(final int satelliteNumber,
final char classification,
final int launchYear,
final int launchNumber,
final String launchPiece,
final int elementNumber,
final int revolutionNumberAtEpoch) throws OrekitException {
super(B_STAR);
this.satelliteNumber = satelliteNumber;
this.classification = classification;
this.launchYear = launchYear;
this.launchNumber = launchNumber;
this.launchPiece = launchPiece;
this.elementNumber = elementNumber;
this.revolutionNumberAtEpoch = revolutionNumberAtEpoch;
this.bStar = 0.0;
this.mu = TLEPropagator.getMU();
this.frame = FramesFactory.getTEME();
}
/** {@inheritDoc} */
public Propagator buildPropagator(final AbsoluteDate date, final double[] parameters)
throws OrekitException {
if (parameters.length != (freeParameters.size() + 6)) {
throw OrekitException.createIllegalArgumentException(LocalizedFormats.DIMENSIONS_MISMATCH);
}
final KeplerianOrbit orb = new KeplerianOrbit(new PVCoordinates(new Vector3D(parameters[0],
parameters[1],
parameters[2]),
new Vector3D(parameters[3],
parameters[4],
parameters[5])),
frame, date, mu);
final Iterator<String> freeItr = freeParameters.iterator();
for (int i = 6; i < parameters.length; i++) {
final String free = freeItr.next();
for (String available : getParametersNames()) {
if (free.equals(available)) {
setParameter(free, parameters[i]);
}
}
}
final TLE tle = new TLE(satelliteNumber, classification, launchYear, launchNumber, launchPiece,
TLE.DEFAULT, elementNumber, date,
orb.getKeplerianMeanMotion(), 0.0, 0.0,
orb.getE(), MathUtils.normalizeAngle(orb.getI(), FastMath.PI),
MathUtils.normalizeAngle(orb.getPerigeeArgument(), FastMath.PI),
MathUtils.normalizeAngle(orb.getRightAscensionOfAscendingNode(), FastMath.PI),
MathUtils.normalizeAngle(orb.getMeanAnomaly(), FastMath.PI),
revolutionNumberAtEpoch, bStar);
return TLEPropagator.selectExtrapolator(tle);
}
/** {@inheritDoc} */
public Frame getFrame() {
return frame;
}
/** {@inheritDoc} */
public void setFreeParameters(final Collection<String> parameters)
throws IllegalArgumentException {
freeParameters = new ArrayList<String>();
for (String name : parameters) {
complainIfNotSupported(name);
}
freeParameters.addAll(parameters);
}
/** {@inheritDoc} */
public double getParameter(final String name)
throws IllegalArgumentException {
complainIfNotSupported(name);
return bStar;
}
/** {@inheritDoc} */
public void setParameter(final String name, final double value)
throws IllegalArgumentException {
complainIfNotSupported(name);
bStar = value * 1.e-4;
}
}
| src/main/java/org/orekit/propagation/conversion/TLEPropagatorBuilder.java | /* Copyright 2002-2014 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.propagation.conversion;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractParameterizable;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.errors.OrekitException;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.analytical.tle.TLE;
import org.orekit.propagation.analytical.tle.TLEPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;
/** Builder for TLEPropagator.
* @author Pascal Parraud
* @since 6.0
*/
public class TLEPropagatorBuilder extends AbstractParameterizable
implements PropagatorBuilder {
/** Parameter name for B* coefficient. */
public static final String B_STAR = "BSTAR";
/** Satellite number. */
private final int satelliteNumber;
/** Classification (U for unclassified). */
private final char classification;
/** Launch year (all digits). */
private final int launchYear;
/** Launch number. */
private final int launchNumber;
/** Launch piece. */
private final String launchPiece;
/** Element number. */
private final int elementNumber;
/** Revolution number at epoch. */
private final int revolutionNumberAtEpoch;
/** Central attraction coefficient (m<sup>3</sup>/s<sup>2</sup>). */
private final double mu;
/** TEME frame. */
private final Frame frame;
/** List of the free parameters names. */
private Collection<String> freeParameters;
/** Ballistic coefficient. */
private double bStar;
/** Build a new instance.
* @param satelliteNumber satellite number
* @param classification classification (U for unclassified)
* @param launchYear launch year (all digits)
* @param launchNumber launch number
* @param launchPiece launch piece
* @param elementNumber element number
* @param revolutionNumberAtEpoch revolution number at epoch
* @throws OrekitException if the TEME frame cannot be set
*/
public TLEPropagatorBuilder(final int satelliteNumber,
final char classification,
final int launchYear,
final int launchNumber,
final String launchPiece,
final int elementNumber,
final int revolutionNumberAtEpoch) throws OrekitException {
super(B_STAR);
this.satelliteNumber = satelliteNumber;
this.classification = classification;
this.launchYear = launchYear;
this.launchNumber = launchNumber;
this.launchPiece = launchPiece;
this.elementNumber = elementNumber;
this.revolutionNumberAtEpoch = revolutionNumberAtEpoch;
this.bStar = 0.0;
this.mu = TLEPropagator.getMU();
this.frame = FramesFactory.getTEME();
}
/** {@inheritDoc} */
public Propagator buildPropagator(final AbsoluteDate date, final double[] parameters)
throws OrekitException {
if (parameters.length != (freeParameters.size() + 6)) {
throw OrekitException.createIllegalArgumentException(LocalizedFormats.DIMENSIONS_MISMATCH);
}
final KeplerianOrbit orb = new KeplerianOrbit(new PVCoordinates(new Vector3D(parameters[0],
parameters[1],
parameters[2]),
new Vector3D(parameters[3],
parameters[4],
parameters[5])),
frame, date, mu);
final Iterator<String> freeItr = freeParameters.iterator();
for (int i = 6; i < parameters.length; i++) {
final String free = freeItr.next();
for (String available : getParametersNames()) {
if (free.equals(available)) {
setParameter(free, parameters[i]);
}
}
}
final TLE tle = new TLE(satelliteNumber, classification, launchYear, launchNumber, launchPiece,
TLE.DEFAULT, elementNumber, date,
orb.getKeplerianMeanMotion(), 0.0, 0.0,
orb.getE(), MathUtils.normalizeAngle(orb.getI(), FastMath.PI),
MathUtils.normalizeAngle(orb.getPerigeeArgument(), FastMath.PI),
MathUtils.normalizeAngle(orb.getRightAscensionOfAscendingNode(), FastMath.PI),
MathUtils.normalizeAngle(orb.getMeanAnomaly(), FastMath.PI),
revolutionNumberAtEpoch, bStar);
return TLEPropagator.selectExtrapolator(tle);
}
/** {@inheritDoc} */
public Frame getFrame() {
return frame;
}
/** {@inheritDoc} */
public void setFreeParameters(final Collection<String> parameters)
throws IllegalArgumentException {
freeParameters = new ArrayList<String>();
for (String name : parameters) {
complainIfNotSupported(name);
}
freeParameters.addAll(parameters);
}
/** {@inheritDoc} */
public double getParameter(final String name)
throws IllegalArgumentException {
complainIfNotSupported(name);
return bStar;
}
/** {@inheritDoc} */
public void setParameter(final String name, final double value)
throws IllegalArgumentException {
complainIfNotSupported(name);
bStar = value * 1.e-4;
}
}
| Fixed checkstyle warning. | src/main/java/org/orekit/propagation/conversion/TLEPropagatorBuilder.java | Fixed checkstyle warning. | <ide><path>rc/main/java/org/orekit/propagation/conversion/TLEPropagatorBuilder.java
<ide> final Iterator<String> freeItr = freeParameters.iterator();
<ide> for (int i = 6; i < parameters.length; i++) {
<ide> final String free = freeItr.next();
<del> for (String available : getParametersNames()) {
<del> if (free.equals(available)) {
<del> setParameter(free, parameters[i]);
<del> }
<add> for (String available : getParametersNames()) {
<add> if (free.equals(available)) {
<add> setParameter(free, parameters[i]);
<ide> }
<add> }
<ide> }
<ide>
<ide> final TLE tle = new TLE(satelliteNumber, classification, launchYear, launchNumber, launchPiece, |
|
Java | mit | 05c4314dc1c393749d7cc0de37544424ed9abb0a | 0 | leanix/leanix-sdk-java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 LeanIX GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.leanix.api.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import net.leanix.api.UsersApi;
import net.leanix.api.models.User;
import org.junit.Test;
import java.util.List;
public class UsersApiTest extends TestBase
{
protected UsersApi getApi() throws Exception
{
UsersApi api = getUsersApi();
return api;
}
@Test
public void testGetList() throws Exception
{
List<User> users = this.getApi().getUsers(false);
// Only 1 user should be in the database after the workspace was created
assertEquals(1, users.size());
}
@Test
public void testGet() throws Exception
{
List<User> users = this.getApi().getUsers(false);
// We expect to have at least 1 user
assertTrue(users.size() > 0);
User curUser = users.get(0);
User user = this.getApi().getUser(curUser.getID(), false);
// We should have at least one user
assertNotNull(user);
}
}
| src/test/java/net/leanix/api/test/UsersApiTest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 LeanIX GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.leanix.api.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import net.leanix.api.UsersApi;
import net.leanix.api.models.User;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class UsersApiTest extends TestBase
{
final Logger logger = LoggerFactory.getLogger(UsersApiTest.class);
protected UsersApi getApi() throws Exception
{
UsersApi api = getUsersApi();
return api;
}
@Test
public void testGetList() throws Exception
{
List<User> users = this.getApi().getUsers(false);
// Only 1 user should be in the database after the workspace was created
assertTrue(users.size() == 1);
}
@Test
public void testGet() throws Exception
{
List<User> users = this.getApi().getUsers(false);
// We expect to have at least 1 user
assertTrue(users.size() > 0);
User curUser = users.get(0);
User user = this.getApi().getUser(curUser.getID(), false);
// We should have at least one user
assertNotNull(user);
}
}
| improve assertion in test for better diagnose of CI build test failure
| src/test/java/net/leanix/api/test/UsersApiTest.java | improve assertion in test for better diagnose of CI build test failure | <ide><path>rc/test/java/net/leanix/api/test/UsersApiTest.java
<ide>
<ide> package net.leanix.api.test;
<ide>
<add>import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertNotNull;
<ide> import static org.junit.Assert.assertTrue;
<ide>
<ide> import net.leanix.api.models.User;
<ide>
<ide> import org.junit.Test;
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<ide>
<ide> import java.util.List;
<ide>
<ide> public class UsersApiTest extends TestBase
<ide> {
<del> final Logger logger = LoggerFactory.getLogger(UsersApiTest.class);
<del>
<ide> protected UsersApi getApi() throws Exception
<ide> {
<ide> UsersApi api = getUsersApi();
<ide> List<User> users = this.getApi().getUsers(false);
<ide>
<ide> // Only 1 user should be in the database after the workspace was created
<del> assertTrue(users.size() == 1);
<add> assertEquals(1, users.size());
<ide> }
<ide>
<ide> @Test |
|
Java | mit | 1ed784b3af5138f520f3d0f33c4c41f1b50eb631 | 0 | evokly/kafka-connect-mqtt | /**
* Copyright 2016 Evokly S.A.
* See LICENSE file for License
**/
package com.evokly.kafka.connect.mqtt;
import com.evokly.kafka.connect.mqtt.util.Version;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.source.SourceTask;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/**
* MqttSourceTask is a Kafka Connect SourceTask implementation that reads
* from MQTT and generates Kafka Connect records.
*/
public class MqttSourceTask extends SourceTask implements MqttCallback {
private static final Logger log = LoggerFactory.getLogger(MqttSourceConnector.class);
MqttClient mClient;
String mKafkaTopic;
String mMqttClientId;
Queue<MqttSourceInterceptMessage> mQueue = new LinkedList<>();
/**
* Get the version of this task. Usually this should be the same as the corresponding
* {@link MqttSourceConnector} class's version.
*
* @return the version, formatted as a String
*/
@Override
public String version() {
return Version.getVersion();
}
/**
* Start the task.
*
* @param props initial configuration
*/
@Override
public void start(Map<String, String> props) {
log.info("Start a MqttSourceTask");
mMqttClientId = props.get(MqttSourceConstant.MQTT_CLIENT_ID) != null
? props.get(MqttSourceConstant.MQTT_CLIENT_ID) : MqttClient.generateClientId();
// Setup Kafka
mKafkaTopic = props.get(MqttSourceConstant.KAFKA_TOPIC);
// Setup MQTT Connect Options
MqttConnectOptions connectOptions = new MqttConnectOptions();
if (props.get(MqttSourceConstant.MQTT_CLEAN_SESSION) != null) {
connectOptions.setCleanSession(
props.get(MqttSourceConstant.MQTT_CLEAN_SESSION).contains("true"));
}
if (props.get(MqttSourceConstant.MQTT_CONNECTION_TIMEOUT) != null) {
connectOptions.setConnectionTimeout(
Integer.parseInt(props.get(MqttSourceConstant.MQTT_CONNECTION_TIMEOUT)));
}
if (props.get(MqttSourceConstant.MQTT_KEEP_ALIVE_INTERVAL) != null) {
connectOptions.setKeepAliveInterval(
Integer.parseInt(props.get(MqttSourceConstant.MQTT_KEEP_ALIVE_INTERVAL)));
}
if (props.get(MqttSourceConstant.MQTT_SERVER_URIS) != null) {
connectOptions.setServerURIs(
props.get(MqttSourceConstant.MQTT_SERVER_URIS).split(","));
}
// Connect to Broker
try {
// Address of the server to connect to, specified as a URI, is overridden using
// MqttConnectOptions#setServerURIs(String[]) bellow.
mClient = new MqttClient("tcp://127.0.0.1:1883", mMqttClientId,
new MemoryPersistence());
mClient.setCallback(this);
mClient.connect(connectOptions);
log.info("[{}] Connected to Broker", mMqttClientId);
} catch (MqttException e) {
log.error("[{}] Connection to Broker failed!", mMqttClientId, e);
}
// Setup topic
try {
String topic = props.get(MqttSourceConstant.MQTT_TOPIC);
Integer qos = Integer.parseInt(props.get(MqttSourceConstant.MQTT_QUALITY_OF_SERVICE));
mClient.subscribe(topic, qos);
log.info("[{}] Subscribe to '{}' with QoS '{}'", mMqttClientId, topic,
qos.toString());
} catch (MqttException e) {
log.error("[{}] Subscribe failed! ", mMqttClientId, e);
}
}
/**
* Stop this task.
*/
@Override
public void stop() {
log.info("Stoping the MqttSourceTask");
try {
mClient.disconnect();
log.info("[{}] Disconnected from Broker.", mMqttClientId);
} catch (MqttException e) {
log.error("[{}] Disconnecting from Broker failed!", mMqttClientId, e);
}
}
/**
* Poll this SourceTask for new records. This method should block if no data is currently
* available.
*
* @return a list of source records
*
* @throws InterruptedException thread is waiting, sleeping, or otherwise occupied,
* and the thread is interrupted, either before or during the
* activity
*/
@Override
public List<SourceRecord> poll() throws InterruptedException {
log.trace("[{}] Polling new data if exists.", mMqttClientId);
if (mQueue.isEmpty()) {
// block if no data is currently available
Thread.sleep(1000);
}
List<SourceRecord> records = new ArrayList<>();
while (mQueue.peek() != null) {
MqttSourceInterceptMessage message = mQueue.poll();
log.debug("[{}] Polling new data from queue for '{}' topic.",
mMqttClientId, mKafkaTopic);
records.add(new SourceRecord(null, null, mKafkaTopic, null,
Schema.STRING_SCHEMA, message.getTopic(),
Schema.BYTES_SCHEMA, message.getMessage()));
}
return records;
}
/**
* This method is called when the connection to the server is lost.
*
* @param cause the reason behind the loss of connection.
*/
@Override
public void connectionLost(Throwable cause) {
log.error("MQTT connection lost!", cause);
}
/**
* Called when delivery for a message has been completed, and all acknowledgments have been
* received.
*
* @param token the delivery token associated with the message.
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Nothing to implement.
}
/**
* This method is called when a message arrives from the server.
*
* @param topic name of the topic on the message was published to
* @param message the actual message.
*
* @throws Exception if a terminal error has occurred, and the client should be
* shut down.
*/
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
log.debug("[{}] New message on '{}' arrived.", mMqttClientId, topic);
this.mQueue.add(new MqttSourceInterceptMessage(topic, message));
}
}
| src/main/java/com/evokly/kafka/connect/mqtt/MqttSourceTask.java | /**
* Copyright 2016 Evokly S.A.
* See LICENSE file for License
**/
package com.evokly.kafka.connect.mqtt;
import com.evokly.kafka.connect.mqtt.util.Version;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.source.SourceTask;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/**
* MqttSourceTask is a Kafka Connect SourceTask implementation that reads
* from MQTT and generates Kafka Connect records.
*/
public class MqttSourceTask extends SourceTask implements MqttCallback {
private static final Logger log = LoggerFactory.getLogger(MqttSourceConnector.class);
MqttClient mClient;
String mKafkaTopic;
String mMqttClientId;
Queue<MqttSourceInterceptMessage> mQueue = new LinkedList<>();
/**
* Get the version of this task. Usually this should be the same as the corresponding
* {@link MqttSourceConnector} class's version.
*
* @return the version, formatted as a String
*/
@Override
public String version() {
return Version.getVersion();
}
/**
* Start the task.
*
* @param props initial configuration
*/
@Override
public void start(Map<String, String> props) {
log.info("Start a MqttSourceTask");
mMqttClientId = props.get(MqttSourceConstant.MQTT_CLIENT_ID) != null
? props.get(MqttSourceConstant.MQTT_CLIENT_ID) : MqttClient.generateClientId();
// Setup Kafka
mKafkaTopic = props.get(MqttSourceConstant.KAFKA_TOPIC);
// Setup MQTT Connect Options
MqttConnectOptions connectOptions = new MqttConnectOptions();
if (props.get(MqttSourceConstant.MQTT_CLEAN_SESSION) != null) {
connectOptions.setCleanSession(
props.get(MqttSourceConstant.MQTT_CLEAN_SESSION).contains("true"));
}
if (props.get(MqttSourceConstant.MQTT_CONNECTION_TIMEOUT) != null) {
connectOptions.setConnectionTimeout(
Integer.parseInt(props.get(MqttSourceConstant.MQTT_CONNECTION_TIMEOUT)));
}
if (props.get(MqttSourceConstant.MQTT_KEEP_ALIVE_INTERVAL) != null) {
connectOptions.setKeepAliveInterval(
Integer.parseInt(props.get(MqttSourceConstant.MQTT_KEEP_ALIVE_INTERVAL)));
}
if (props.get(MqttSourceConstant.MQTT_SERVER_URIS) != null) {
connectOptions.setServerURIs(
props.get(MqttSourceConstant.MQTT_SERVER_URIS).split(","));
}
// Connect to Broker
try {
// Address of the server to connect to, specified as a URI, is overridden using
// MqttConnectOptions#setServerURIs(String[]) bellow.
mClient = new MqttClient("tcp://127.0.0.1:1883", mMqttClientId,
new MemoryPersistence());
mClient.setCallback(this);
mClient.connect(connectOptions);
log.info("[{}] Connected to Broker", mMqttClientId);
} catch (MqttException e) {
log.error("[{}] Connection to Broker failed!", mMqttClientId, e);
}
// Setup topic
try {
String topic = props.get(MqttSourceConstant.MQTT_TOPIC);
Integer qos = Integer.parseInt(props.get(MqttSourceConstant.MQTT_QUALITY_OF_SERVICE));
mClient.subscribe(topic, qos);
log.info("[{}] Subscribe to '{}' with QoS '{}'", mMqttClientId, topic,
qos.toString());
} catch (MqttException e) {
log.error("[{}] Subscribe failed! ", mMqttClientId, e);
}
}
/**
* Stop this task.
*/
@Override
public void stop() {
log.info("Stoping the MqttSourceTask");
try {
mClient.disconnect();
log.info("[{}] Disconnected from Broker.", mMqttClientId);
} catch (MqttException e) {
log.error("[{}] Disconnecting from Broker failed!", mMqttClientId, e);
}
}
/**
* Poll this SourceTask for new records. This method should block if no data is currently
* available.
*
* @return a list of source records
*
* @throws InterruptedException thread is waiting, sleeping, or otherwise occupied,
* and the thread is interrupted, either before or during the
* activity
*/
@Override
public List<SourceRecord> poll() throws InterruptedException {
log.trace("[{}] Polling new data if exists.", mMqttClientId);
if (mQueue.isEmpty()) {
// no message to process
return null;
}
List<SourceRecord> records = new ArrayList<>();
while (mQueue.peek() != null) {
MqttSourceInterceptMessage message = mQueue.poll();
log.debug("[{}] Polling new data from queue for '{}' topic.",
mMqttClientId, mKafkaTopic);
records.add(new SourceRecord(null, null, mKafkaTopic, null,
Schema.STRING_SCHEMA, message.getTopic(),
Schema.BYTES_SCHEMA, message.getMessage()));
}
return records;
}
/**
* This method is called when the connection to the server is lost.
*
* @param cause the reason behind the loss of connection.
*/
@Override
public void connectionLost(Throwable cause) {
log.error("MQTT connection lost!", cause);
}
/**
* Called when delivery for a message has been completed, and all acknowledgments have been
* received.
*
* @param token the delivery token associated with the message.
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Nothing to implement.
}
/**
* This method is called when a message arrives from the server.
*
* @param topic name of the topic on the message was published to
* @param message the actual message.
*
* @throws Exception if a terminal error has occurred, and the client should be
* shut down.
*/
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
log.debug("[{}] New message on '{}' arrived.", mMqttClientId, topic);
this.mQueue.add(new MqttSourceInterceptMessage(topic, message));
}
}
| feat(Task): block poll method if no data is currently available
| src/main/java/com/evokly/kafka/connect/mqtt/MqttSourceTask.java | feat(Task): block poll method if no data is currently available | <ide><path>rc/main/java/com/evokly/kafka/connect/mqtt/MqttSourceTask.java
<ide> log.trace("[{}] Polling new data if exists.", mMqttClientId);
<ide>
<ide> if (mQueue.isEmpty()) {
<del> // no message to process
<del> return null;
<add> // block if no data is currently available
<add> Thread.sleep(1000);
<ide> }
<ide>
<ide> List<SourceRecord> records = new ArrayList<>(); |
|
Java | mit | 86b3334f6b8facacbf420056844c85c225204b3d | 0 | alecw/picard,nh13/picard,alecw/picard,nh13/picard,annkupi/picard,alecw/picard,broadinstitute/picard,annkupi/picard,annkupi/picard,alecw/picard,broadinstitute/picard,nh13/picard,broadinstitute/picard,nh13/picard,broadinstitute/picard,annkupi/picard,broadinstitute/picard | package picard.analysis;
import htsjdk.samtools.AlignmentBlock;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.filter.SamRecordFilter;
import htsjdk.samtools.filter.SecondaryAlignmentFilter;
import htsjdk.samtools.metrics.MetricBase;
import htsjdk.samtools.metrics.MetricsFile;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFileWalker;
import htsjdk.samtools.util.*;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.CommandLineProgramProperties;
import picard.cmdline.Option;
import picard.cmdline.programgroups.Metrics;
import picard.cmdline.StandardOptionDefinitions;
import picard.util.MathUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
* Computes a number of metrics that are useful for evaluating coverage and performance of whole genome sequencing experiments.
*
* @author tfennell
*/
@CommandLineProgramProperties(
usage = "Computes a number of metrics that are useful for evaluating coverage and performance of " +
"whole genome sequencing experiments.",
usageShort = "Writes whole genome sequencing-related metrics for a SAM or BAM file",
programGroup = Metrics.class
)
public class CollectWgsMetrics extends CommandLineProgram {
@Option(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "Input SAM or BAM file.")
public File INPUT;
@Option(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "Output metrics file.")
public File OUTPUT;
@Option(shortName = StandardOptionDefinitions.REFERENCE_SHORT_NAME, doc = "The reference sequence fasta aligned to.")
public File REFERENCE_SEQUENCE;
@Option(shortName = "MQ", doc = "Minimum mapping quality for a read to contribute coverage.", overridable = true)
public int MINIMUM_MAPPING_QUALITY = 20;
@Option(shortName = "Q", doc = "Minimum base quality for a base to contribute coverage.", overridable = true)
public int MINIMUM_BASE_QUALITY = 20;
@Option(shortName = "CAP", doc = "Treat bases with coverage exceeding this value as if they had coverage at this value.", overridable = true)
public int COVERAGE_CAP = 250;
@Option(doc = "For debugging purposes, stop after processing this many genomic bases.")
public long STOP_AFTER = -1;
@Option(doc = "Determines whether to include the base quality histogram in the metrics file.")
public boolean INCLUDE_BQ_HISTOGRAM = false;
@Option(doc="If true, count unpaired reads, and paired reads with one end unmapped")
public boolean COUNT_UNPAIRED = false;
private final Log log = Log.getInstance(CollectWgsMetrics.class);
/** Metrics for evaluating the performance of whole genome sequencing experiments. */
public static class WgsMetrics extends MetricBase {
/** The number of non-N bases in the genome reference over which coverage will be evaluated. */
public long GENOME_TERRITORY;
/** The mean coverage in bases of the genome territory, after all filters are applied. */
public double MEAN_COVERAGE;
/** The standard deviation of coverage of the genome after all filters are applied. */
public double SD_COVERAGE;
/** The median coverage in bases of the genome territory, after all filters are applied. */
public double MEDIAN_COVERAGE;
/** The median absolute deviation of coverage of the genome after all filters are applied. */
public double MAD_COVERAGE;
/** The fraction of aligned bases that were filtered out because they were in reads with low mapping quality (default is < 20). */
public double PCT_EXC_MAPQ;
/** The fraction of aligned bases that were filtered out because they were in reads marked as duplicates. */
public double PCT_EXC_DUPE;
/** The fraction of aligned bases that were filtered out because they were in reads without a mapped mate pair. */
public double PCT_EXC_UNPAIRED;
/** The fraction of aligned bases that were filtered out because they were of low base quality (default is < 20). */
public double PCT_EXC_BASEQ;
/** The fraction of aligned bases that were filtered out because they were the second observation from an insert with overlapping reads. */
public double PCT_EXC_OVERLAP;
/** The fraction of aligned bases that were filtered out because they would have raised coverage above the capped value (default cap = 250x). */
public double PCT_EXC_CAPPED;
/** The total fraction of aligned bases excluded due to all filters. */
public double PCT_EXC_TOTAL;
/** The fraction of bases that attained at least 5X sequence coverage in post-filtering bases. */
public double PCT_5X;
/** The fraction of bases that attained at least 10X sequence coverage in post-filtering bases. */
public double PCT_10X;
/** The fraction of bases that attained at least 15X sequence coverage in post-filtering bases. */
public double PCT_15X;
/** The fraction of bases that attained at least 20X sequence coverage in post-filtering bases. */
public double PCT_20X;
/** The fraction of bases that attained at least 25X sequence coverage in post-filtering bases. */
public double PCT_25X;
/** The fraction of bases that attained at least 30X sequence coverage in post-filtering bases. */
public double PCT_30X;
/** The fraction of bases that attained at least 40X sequence coverage in post-filtering bases. */
public double PCT_40X;
/** The fraction of bases that attained at least 50X sequence coverage in post-filtering bases. */
public double PCT_50X;
/** The fraction of bases that attained at least 60X sequence coverage in post-filtering bases. */
public double PCT_60X;
/** The fraction of bases that attained at least 70X sequence coverage in post-filtering bases. */
public double PCT_70X;
/** The fraction of bases that attained at least 80X sequence coverage in post-filtering bases. */
public double PCT_80X;
/** The fraction of bases that attained at least 90X sequence coverage in post-filtering bases. */
public double PCT_90X;
/** The fraction of bases that attained at least 100X sequence coverage in post-filtering bases. */
public double PCT_100X;
}
public static void main(final String[] args) {
new CollectWgsMetrics().instanceMainWithExit(args);
}
@Override
protected int doWork() {
IOUtil.assertFileIsReadable(INPUT);
IOUtil.assertFileIsWritable(OUTPUT);
IOUtil.assertFileIsReadable(REFERENCE_SEQUENCE);
// Setup all the inputs
final ProgressLogger progress = new ProgressLogger(log, 10000000, "Processed", "loci");
final ReferenceSequenceFileWalker refWalker = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE);
final SamReader in = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT);
final SamLocusIterator iterator = getLocusIterator(in);
final List<SamRecordFilter> filters = new ArrayList<SamRecordFilter>();
final CountingFilter dupeFilter = new CountingDuplicateFilter();
final CountingFilter mapqFilter = new CountingMapQFilter(MINIMUM_MAPPING_QUALITY);
final CountingPairedFilter pairFilter = new CountingPairedFilter();
filters.add(mapqFilter);
filters.add(dupeFilter);
if (!COUNT_UNPAIRED) {
filters.add(pairFilter);
}
filters.add(new SecondaryAlignmentFilter()); // Not a counting filter because we never want to count reads twice
iterator.setSamFilters(filters);
iterator.setEmitUncoveredLoci(true);
iterator.setMappingQualityScoreCutoff(0); // Handled separately because we want to count bases
iterator.setQualityScoreCutoff(0); // Handled separately because we want to count bases
iterator.setIncludeNonPfReads(false);
final int max = COVERAGE_CAP;
final long[] HistogramArray = new long[max + 1];
final long[] baseQHistogramArray = new long[Byte.MAX_VALUE];
final boolean usingStopAfter = STOP_AFTER > 0;
final long stopAfter = STOP_AFTER - 1;
long counter = 0;
long basesExcludedByBaseq = 0;
long basesExcludedByOverlap = 0;
long basesExcludedByCapping = 0;
// Loop through all the loci
while (iterator.hasNext()) {
final SamLocusIterator.LocusInfo info = iterator.next();
// Check that the reference is not N
final ReferenceSequence ref = refWalker.get(info.getSequenceIndex());
final byte base = ref.getBases()[info.getPosition() - 1];
if (base == 'N') continue;
// Figure out the coverage while not counting overlapping reads twice, and excluding various things
final HashSet<String> readNames = new HashSet<String>(info.getRecordAndPositions().size());
int pileupSize = 0;
for (final SamLocusIterator.RecordAndOffset recs : info.getRecordAndPositions()) {
if (recs.getBaseQuality() < MINIMUM_BASE_QUALITY) { ++basesExcludedByBaseq; continue; }
if (!readNames.add(recs.getRecord().getReadName())) { ++basesExcludedByOverlap; continue; }
pileupSize++;
if (pileupSize <= max) {
baseQHistogramArray[recs.getRecord().getBaseQualities()[recs.getOffset()]]++;
}
}
final int depth = Math.min(readNames.size(), max);
if (depth < readNames.size()) basesExcludedByCapping += readNames.size() - max;
HistogramArray[depth]++;
// Record progress and perhaps stop
progress.record(info.getSequenceName(), info.getPosition());
if (usingStopAfter && ++counter > stopAfter) break;
}
// Construct and write the outputs
final Histogram<Integer> histo = new Histogram<Integer>("coverage", "count");
for (int i = 0; i < HistogramArray.length; ++i) {
histo.increment(i, HistogramArray[i]);
}
// Construct and write the outputs
final Histogram<Integer> baseQHisto = new Histogram<Integer>("value", "baseq_count");
for (int i=0; i<baseQHistogramArray.length; ++i) {
baseQHisto.increment(i, baseQHistogramArray[i]);
}
final WgsMetrics metrics = generateWgsMetrics();
metrics.GENOME_TERRITORY = (long) histo.getSumOfValues();
metrics.MEAN_COVERAGE = histo.getMean();
metrics.SD_COVERAGE = histo.getStandardDeviation();
metrics.MEDIAN_COVERAGE = histo.getMedian();
metrics.MAD_COVERAGE = histo.getMedianAbsoluteDeviation();
final long basesExcludedByDupes = getBasesExcludedBy(dupeFilter);
final long basesExcludedByMapq = getBasesExcludedBy(mapqFilter);
final long basesExcludedByPairing = getBasesExcludedBy(pairFilter);
final double total = histo.getSum();
final double totalWithExcludes = total + basesExcludedByDupes + basesExcludedByMapq + basesExcludedByPairing + basesExcludedByBaseq + basesExcludedByOverlap + basesExcludedByCapping;
metrics.PCT_EXC_DUPE = basesExcludedByDupes / totalWithExcludes;
metrics.PCT_EXC_MAPQ = basesExcludedByMapq / totalWithExcludes;
metrics.PCT_EXC_UNPAIRED = basesExcludedByPairing / totalWithExcludes;
metrics.PCT_EXC_BASEQ = basesExcludedByBaseq / totalWithExcludes;
metrics.PCT_EXC_OVERLAP = basesExcludedByOverlap / totalWithExcludes;
metrics.PCT_EXC_CAPPED = basesExcludedByCapping / totalWithExcludes;
metrics.PCT_EXC_TOTAL = (totalWithExcludes - total) / totalWithExcludes;
metrics.PCT_5X = MathUtil.sum(HistogramArray, 5, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_10X = MathUtil.sum(HistogramArray, 10, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_15X = MathUtil.sum(HistogramArray, 15, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_20X = MathUtil.sum(HistogramArray, 20, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_25X = MathUtil.sum(HistogramArray, 25, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_30X = MathUtil.sum(HistogramArray, 30, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_40X = MathUtil.sum(HistogramArray, 40, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_50X = MathUtil.sum(HistogramArray, 50, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_60X = MathUtil.sum(HistogramArray, 60, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_70X = MathUtil.sum(HistogramArray, 70, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_80X = MathUtil.sum(HistogramArray, 80, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_90X = MathUtil.sum(HistogramArray, 90, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_100X = MathUtil.sum(HistogramArray, 100, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
final MetricsFile<WgsMetrics, Integer> out = getMetricsFile();
out.addMetric(metrics);
out.addHistogram(histo);
if (INCLUDE_BQ_HISTOGRAM) {
out.addHistogram(baseQHisto);
}
out.write(OUTPUT);
return 0;
}
protected WgsMetrics generateWgsMetrics() {
return new WgsMetrics();
}
protected long getBasesExcludedBy(final CountingFilter filter) {
return filter.getFilteredBases();
}
protected SamLocusIterator getLocusIterator(final SamReader in) {
return new SamLocusIterator(in);
}
}
/**
* A SamRecordFilter that counts the number of aligned bases in the reads which it filters out. Abstract and designed
* to be subclassed to implement the desired filter.
*/
abstract class CountingFilter implements SamRecordFilter {
private long filteredRecords = 0;
private long filteredBases = 0;
/** Gets the number of records that have been filtered out thus far. */
public long getFilteredRecords() { return this.filteredRecords; }
/** Gets the number of bases that have been filtered out thus far. */
public long getFilteredBases() { return this.filteredBases; }
@Override
public final boolean filterOut(final SAMRecord record) {
final boolean filteredOut = reallyFilterOut(record);
if (filteredOut) {
++filteredRecords;
for (final AlignmentBlock block : record.getAlignmentBlocks()) {
this.filteredBases += block.getLength();
}
}
return filteredOut;
}
abstract public boolean reallyFilterOut(final SAMRecord record);
@Override
public boolean filterOut(final SAMRecord first, final SAMRecord second) {
throw new UnsupportedOperationException();
}
}
/** Counting filter that discards reads that have been marked as duplicates. */
class CountingDuplicateFilter extends CountingFilter {
@Override
public boolean reallyFilterOut(final SAMRecord record) { return record.getDuplicateReadFlag(); }
}
/** Counting filter that discards reads below a configurable mapping quality threshold. */
class CountingMapQFilter extends CountingFilter {
private final int minMapq;
CountingMapQFilter(final int minMapq) { this.minMapq = minMapq; }
@Override
public boolean reallyFilterOut(final SAMRecord record) { return record.getMappingQuality() < minMapq; }
}
/** Counting filter that discards reads that are unpaired in sequencing and paired reads who's mates are not mapped. */
class CountingPairedFilter extends CountingFilter {
@Override
public boolean reallyFilterOut(final SAMRecord record) { return !record.getReadPairedFlag() || record.getMateUnmappedFlag(); }
}
| src/java/picard/analysis/CollectWgsMetrics.java | package picard.analysis;
import htsjdk.samtools.AlignmentBlock;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.filter.SamRecordFilter;
import htsjdk.samtools.filter.SecondaryAlignmentFilter;
import htsjdk.samtools.metrics.MetricBase;
import htsjdk.samtools.metrics.MetricsFile;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFileWalker;
import htsjdk.samtools.util.*;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.CommandLineProgramProperties;
import picard.cmdline.Option;
import picard.cmdline.programgroups.Metrics;
import picard.cmdline.StandardOptionDefinitions;
import picard.util.MathUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
* Computes a number of metrics that are useful for evaluating coverage and performance of whole genome sequencing experiments.
*
* @author tfennell
*/
@CommandLineProgramProperties(
usage = "Computes a number of metrics that are useful for evaluating coverage and performance of " +
"whole genome sequencing experiments.",
usageShort = "Writes whole genome sequencing-related metrics for a SAM or BAM file",
programGroup = Metrics.class
)
public class CollectWgsMetrics extends CommandLineProgram {
@Option(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "Input SAM or BAM file.")
public File INPUT;
@Option(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "Output metrics file.")
public File OUTPUT;
@Option(shortName = StandardOptionDefinitions.REFERENCE_SHORT_NAME, doc = "The reference sequence fasta aligned to.")
public File REFERENCE_SEQUENCE;
@Option(shortName = "MQ", doc = "Minimum mapping quality for a read to contribute coverage.", overridable = true)
public int MINIMUM_MAPPING_QUALITY = 20;
@Option(shortName = "Q", doc = "Minimum base quality for a base to contribute coverage.", overridable = true)
public int MINIMUM_BASE_QUALITY = 20;
@Option(shortName = "CAP", doc = "Treat bases with coverage exceeding this value as if they had coverage at this value.", overridable = true)
public int COVERAGE_CAP = 250;
@Option(doc = "For debugging purposes, stop after processing this many genomic bases.")
public long STOP_AFTER = -1;
@Option(doc = "Determines whether to include the base quality histogram in the metrics file.")
public boolean INCLUDE_BQ_HISTOGRAM = false;
private final Log log = Log.getInstance(CollectWgsMetrics.class);
/** Metrics for evaluating the performance of whole genome sequencing experiments. */
public static class WgsMetrics extends MetricBase {
/** The number of non-N bases in the genome reference over which coverage will be evaluated. */
public long GENOME_TERRITORY;
/** The mean coverage in bases of the genome territory, after all filters are applied. */
public double MEAN_COVERAGE;
/** The standard deviation of coverage of the genome after all filters are applied. */
public double SD_COVERAGE;
/** The median coverage in bases of the genome territory, after all filters are applied. */
public double MEDIAN_COVERAGE;
/** The median absolute deviation of coverage of the genome after all filters are applied. */
public double MAD_COVERAGE;
/** The fraction of aligned bases that were filtered out because they were in reads with low mapping quality (default is < 20). */
public double PCT_EXC_MAPQ;
/** The fraction of aligned bases that were filtered out because they were in reads marked as duplicates. */
public double PCT_EXC_DUPE;
/** The fraction of aligned bases that were filtered out because they were in reads without a mapped mate pair. */
public double PCT_EXC_UNPAIRED;
/** The fraction of aligned bases that were filtered out because they were of low base quality (default is < 20). */
public double PCT_EXC_BASEQ;
/** The fraction of aligned bases that were filtered out because they were the second observation from an insert with overlapping reads. */
public double PCT_EXC_OVERLAP;
/** The fraction of aligned bases that were filtered out because they would have raised coverage above the capped value (default cap = 250x). */
public double PCT_EXC_CAPPED;
/** The total fraction of aligned bases excluded due to all filters. */
public double PCT_EXC_TOTAL;
/** The fraction of bases that attained at least 5X sequence coverage in post-filtering bases. */
public double PCT_5X;
/** The fraction of bases that attained at least 10X sequence coverage in post-filtering bases. */
public double PCT_10X;
/** The fraction of bases that attained at least 15X sequence coverage in post-filtering bases. */
public double PCT_15X;
/** The fraction of bases that attained at least 20X sequence coverage in post-filtering bases. */
public double PCT_20X;
/** The fraction of bases that attained at least 25X sequence coverage in post-filtering bases. */
public double PCT_25X;
/** The fraction of bases that attained at least 30X sequence coverage in post-filtering bases. */
public double PCT_30X;
/** The fraction of bases that attained at least 40X sequence coverage in post-filtering bases. */
public double PCT_40X;
/** The fraction of bases that attained at least 50X sequence coverage in post-filtering bases. */
public double PCT_50X;
/** The fraction of bases that attained at least 60X sequence coverage in post-filtering bases. */
public double PCT_60X;
/** The fraction of bases that attained at least 70X sequence coverage in post-filtering bases. */
public double PCT_70X;
/** The fraction of bases that attained at least 80X sequence coverage in post-filtering bases. */
public double PCT_80X;
/** The fraction of bases that attained at least 90X sequence coverage in post-filtering bases. */
public double PCT_90X;
/** The fraction of bases that attained at least 100X sequence coverage in post-filtering bases. */
public double PCT_100X;
}
public static void main(final String[] args) {
new CollectWgsMetrics().instanceMainWithExit(args);
}
@Override
protected int doWork() {
IOUtil.assertFileIsReadable(INPUT);
IOUtil.assertFileIsWritable(OUTPUT);
IOUtil.assertFileIsReadable(REFERENCE_SEQUENCE);
// Setup all the inputs
final ProgressLogger progress = new ProgressLogger(log, 10000000, "Processed", "loci");
final ReferenceSequenceFileWalker refWalker = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE);
final SamReader in = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT);
final SamLocusIterator iterator = getLocusIterator(in);
final List<SamRecordFilter> filters = new ArrayList<SamRecordFilter>();
final CountingFilter dupeFilter = new CountingDuplicateFilter();
final CountingFilter mapqFilter = new CountingMapQFilter(MINIMUM_MAPPING_QUALITY);
final CountingPairedFilter pairFilter = new CountingPairedFilter();
filters.add(mapqFilter);
filters.add(dupeFilter);
filters.add(pairFilter);
filters.add(new SecondaryAlignmentFilter()); // Not a counting filter because we never want to count reads twice
iterator.setSamFilters(filters);
iterator.setEmitUncoveredLoci(true);
iterator.setMappingQualityScoreCutoff(0); // Handled separately because we want to count bases
iterator.setQualityScoreCutoff(0); // Handled separately because we want to count bases
iterator.setIncludeNonPfReads(false);
final int max = COVERAGE_CAP;
final long[] HistogramArray = new long[max + 1];
final long[] baseQHistogramArray = new long[Byte.MAX_VALUE];
final boolean usingStopAfter = STOP_AFTER > 0;
final long stopAfter = STOP_AFTER - 1;
long counter = 0;
long basesExcludedByBaseq = 0;
long basesExcludedByOverlap = 0;
long basesExcludedByCapping = 0;
// Loop through all the loci
while (iterator.hasNext()) {
final SamLocusIterator.LocusInfo info = iterator.next();
// Check that the reference is not N
final ReferenceSequence ref = refWalker.get(info.getSequenceIndex());
final byte base = ref.getBases()[info.getPosition() - 1];
if (base == 'N') continue;
// Figure out the coverage while not counting overlapping reads twice, and excluding various things
final HashSet<String> readNames = new HashSet<String>(info.getRecordAndPositions().size());
int pileupSize = 0;
for (final SamLocusIterator.RecordAndOffset recs : info.getRecordAndPositions()) {
if (recs.getBaseQuality() < MINIMUM_BASE_QUALITY) { ++basesExcludedByBaseq; continue; }
if (!readNames.add(recs.getRecord().getReadName())) { ++basesExcludedByOverlap; continue; }
pileupSize++;
if (pileupSize <= max) {
baseQHistogramArray[recs.getRecord().getBaseQualities()[recs.getOffset()]]++;
}
}
final int depth = Math.min(readNames.size(), max);
if (depth < readNames.size()) basesExcludedByCapping += readNames.size() - max;
HistogramArray[depth]++;
// Record progress and perhaps stop
progress.record(info.getSequenceName(), info.getPosition());
if (usingStopAfter && ++counter > stopAfter) break;
}
// Construct and write the outputs
final Histogram<Integer> histo = new Histogram<Integer>("coverage", "count");
for (int i = 0; i < HistogramArray.length; ++i) {
histo.increment(i, HistogramArray[i]);
}
// Construct and write the outputs
final Histogram<Integer> baseQHisto = new Histogram<Integer>("value", "baseq_count");
for (int i=0; i<baseQHistogramArray.length; ++i) {
baseQHisto.increment(i, baseQHistogramArray[i]);
}
final WgsMetrics metrics = generateWgsMetrics();
metrics.GENOME_TERRITORY = (long) histo.getSumOfValues();
metrics.MEAN_COVERAGE = histo.getMean();
metrics.SD_COVERAGE = histo.getStandardDeviation();
metrics.MEDIAN_COVERAGE = histo.getMedian();
metrics.MAD_COVERAGE = histo.getMedianAbsoluteDeviation();
final long basesExcludedByDupes = getBasesExcludedBy(dupeFilter);
final long basesExcludedByMapq = getBasesExcludedBy(mapqFilter);
final long basesExcludedByPairing = getBasesExcludedBy(pairFilter);
final double total = histo.getSum();
final double totalWithExcludes = total + basesExcludedByDupes + basesExcludedByMapq + basesExcludedByPairing + basesExcludedByBaseq + basesExcludedByOverlap + basesExcludedByCapping;
metrics.PCT_EXC_DUPE = basesExcludedByDupes / totalWithExcludes;
metrics.PCT_EXC_MAPQ = basesExcludedByMapq / totalWithExcludes;
metrics.PCT_EXC_UNPAIRED = basesExcludedByPairing / totalWithExcludes;
metrics.PCT_EXC_BASEQ = basesExcludedByBaseq / totalWithExcludes;
metrics.PCT_EXC_OVERLAP = basesExcludedByOverlap / totalWithExcludes;
metrics.PCT_EXC_CAPPED = basesExcludedByCapping / totalWithExcludes;
metrics.PCT_EXC_TOTAL = (totalWithExcludes - total) / totalWithExcludes;
metrics.PCT_5X = MathUtil.sum(HistogramArray, 5, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_10X = MathUtil.sum(HistogramArray, 10, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_15X = MathUtil.sum(HistogramArray, 15, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_20X = MathUtil.sum(HistogramArray, 20, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_25X = MathUtil.sum(HistogramArray, 25, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_30X = MathUtil.sum(HistogramArray, 30, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_40X = MathUtil.sum(HistogramArray, 40, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_50X = MathUtil.sum(HistogramArray, 50, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_60X = MathUtil.sum(HistogramArray, 60, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_70X = MathUtil.sum(HistogramArray, 70, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_80X = MathUtil.sum(HistogramArray, 80, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_90X = MathUtil.sum(HistogramArray, 90, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
metrics.PCT_100X = MathUtil.sum(HistogramArray, 100, HistogramArray.length) / (double) metrics.GENOME_TERRITORY;
final MetricsFile<WgsMetrics, Integer> out = getMetricsFile();
out.addMetric(metrics);
out.addHistogram(histo);
if (INCLUDE_BQ_HISTOGRAM) {
out.addHistogram(baseQHisto);
}
out.write(OUTPUT);
return 0;
}
protected WgsMetrics generateWgsMetrics() {
return new WgsMetrics();
}
protected long getBasesExcludedBy(final CountingFilter filter) {
return filter.getFilteredBases();
}
protected SamLocusIterator getLocusIterator(final SamReader in) {
return new SamLocusIterator(in);
}
}
/**
* A SamRecordFilter that counts the number of aligned bases in the reads which it filters out. Abstract and designed
* to be subclassed to implement the desired filter.
*/
abstract class CountingFilter implements SamRecordFilter {
private long filteredRecords = 0;
private long filteredBases = 0;
/** Gets the number of records that have been filtered out thus far. */
public long getFilteredRecords() { return this.filteredRecords; }
/** Gets the number of bases that have been filtered out thus far. */
public long getFilteredBases() { return this.filteredBases; }
@Override
public final boolean filterOut(final SAMRecord record) {
final boolean filteredOut = reallyFilterOut(record);
if (filteredOut) {
++filteredRecords;
for (final AlignmentBlock block : record.getAlignmentBlocks()) {
this.filteredBases += block.getLength();
}
}
return filteredOut;
}
abstract public boolean reallyFilterOut(final SAMRecord record);
@Override
public boolean filterOut(final SAMRecord first, final SAMRecord second) {
throw new UnsupportedOperationException();
}
}
/** Counting filter that discards reads that have been marked as duplicates. */
class CountingDuplicateFilter extends CountingFilter {
@Override
public boolean reallyFilterOut(final SAMRecord record) { return record.getDuplicateReadFlag(); }
}
/** Counting filter that discards reads below a configurable mapping quality threshold. */
class CountingMapQFilter extends CountingFilter {
private final int minMapq;
CountingMapQFilter(final int minMapq) { this.minMapq = minMapq; }
@Override
public boolean reallyFilterOut(final SAMRecord record) { return record.getMappingQuality() < minMapq; }
}
/** Counting filter that discards reads that are unpaired in sequencing and paired reads who's mates are not mapped. */
class CountingPairedFilter extends CountingFilter {
@Override
public boolean reallyFilterOut(final SAMRecord record) { return !record.getReadPairedFlag() || record.getMateUnmappedFlag(); }
}
| Add option to count unpaired reads in CollectWgsMetrics.
| src/java/picard/analysis/CollectWgsMetrics.java | Add option to count unpaired reads in CollectWgsMetrics. | <ide><path>rc/java/picard/analysis/CollectWgsMetrics.java
<ide>
<ide> @Option(doc = "Determines whether to include the base quality histogram in the metrics file.")
<ide> public boolean INCLUDE_BQ_HISTOGRAM = false;
<add>
<add> @Option(doc="If true, count unpaired reads, and paired reads with one end unmapped")
<add> public boolean COUNT_UNPAIRED = false;
<ide>
<ide> private final Log log = Log.getInstance(CollectWgsMetrics.class);
<ide>
<ide> final CountingPairedFilter pairFilter = new CountingPairedFilter();
<ide> filters.add(mapqFilter);
<ide> filters.add(dupeFilter);
<del> filters.add(pairFilter);
<add> if (!COUNT_UNPAIRED) {
<add> filters.add(pairFilter);
<add> }
<ide> filters.add(new SecondaryAlignmentFilter()); // Not a counting filter because we never want to count reads twice
<ide> iterator.setSamFilters(filters);
<ide> iterator.setEmitUncoveredLoci(true); |
|
Java | mit | 16f4781682a5a0a2c931080ba8ffcf8e04f5580f | 0 | anagav/TinkerRocks | package com.tinkerrocks.storage;
import com.tinkerrocks.structure.*;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by ashishn on 8/5/15.
*/
public class VertexDB extends StorageAbstractClass implements VertexStorage {
public void close() {
if (rocksDB != null)
this.rocksDB.close();
}
@SuppressWarnings("unchecked")
public <V> void setProperty(byte[] id, String key, V value, VertexProperty.Cardinality cardinality) {
byte[] record_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR.getBytes(), key.getBytes());
try {
if (cardinality == VertexProperty.Cardinality.single) {
put(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key, serialize(value));
put(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key, StorageConstants.V_PROPERTY_SINGLE_TYPE);
}
if (cardinality == VertexProperty.Cardinality.list || cardinality == VertexProperty.Cardinality.set) {
byte[] oldData = this.rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key);
byte[] oldType = this.rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key);
ArrayList<V> results;
if (!Utils.compare(oldType, StorageConstants.V_PROPERTY_LIST_TYPE)) {
results = new ArrayList<>();
} else {
results = (ArrayList<V>) deserialize(oldData, ArrayList.class);
}
if (cardinality == VertexProperty.Cardinality.set && results.contains(value)) {
return;
}
results.add(value);
put(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key, serialize(results));
put(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key, StorageConstants.V_PROPERTY_LIST_TYPE);
}
} catch (RocksDBException e) {
e.printStackTrace();
}
}
public void addEdge(byte[] vertexId, Edge edge, Vertex inVertex) throws RocksDBException {
put(getColumn(VERTEX_COLUMNS.OUT_EDGES), Utils.merge(vertexId,
StorageConstants.PROPERTY_SEPARATOR.getBytes(), (byte[]) edge.id()), (byte[]) inVertex.id());
put(getColumn(VERTEX_COLUMNS.IN_EDGES), Utils.merge((byte[]) inVertex.id(),
StorageConstants.PROPERTY_SEPARATOR.getBytes(), (byte[]) edge.id()), vertexId);
}
@SuppressWarnings("unchecked")
public <V> List<VertexProperty<V>> getProperties(RocksElement rocksVertex, List<byte[]> propertyKeys) throws Exception {
List<VertexProperty<V>> results = new ArrayList<>();
if (propertyKeys == null) {
propertyKeys = new ArrayList<>();
}
if (propertyKeys.size() == 0) {
RocksIterator rocksIterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.PROPERTIES));
byte[] seek_key = Utils.merge((byte[]) rocksVertex.id(), StorageConstants.PROPERTY_SEPARATOR.getBytes());
final List<byte[]> finalPropertyKeys = propertyKeys;
Utils.RocksIterUtil(rocksIterator, seek_key, (key, value) -> {
if (value != null)
finalPropertyKeys.add(Utils.slice(key, seek_key.length, key.length));
return true;
});
}
for (byte[] property : propertyKeys) {
byte[] lookup_key = Utils.merge((byte[]) rocksVertex.id(), StorageConstants.PROPERTY_SEPARATOR.getBytes(),
property);
byte[] type = rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), lookup_key);
byte[] value = rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTIES), lookup_key);
if (Utils.compare(type, StorageConstants.V_PROPERTY_SINGLE_TYPE)) {
results.add(new RocksVertexProperty<>(rocksVertex, new String(property), (V) deserialize(value, Object.class)));
}
if (Utils.compare(type, StorageConstants.V_PROPERTY_LIST_TYPE)) {
List<V> values = deserialize(value, List.class);
results.addAll(values.stream().map(inner_value -> new RocksVertexProperty<V>(rocksVertex, new String(property), inner_value))
.collect(Collectors.toList()));
}
}
return results;
}
private void put(byte[] key, byte[] value) throws RocksDBException {
this.put(null, key, value);
}
private void put(ColumnFamilyHandle columnFamilyHandle, byte[] key, byte[] value) throws RocksDBException {
if (columnFamilyHandle != null)
this.rocksDB.put(columnFamilyHandle, StorageConfigFactory.getWriteOptions(), key, value);
else
this.rocksDB.put(StorageConfigFactory.getWriteOptions(), key, value);
}
private byte[] get(byte[] key) {
try {
return this.get(null, key);
} catch (RocksDBException e) {
e.printStackTrace();
}
return null;
}
private byte[] get(ColumnFamilyHandle columnFamilyHandle, byte[] key) throws RocksDBException {
if (key == null) {
return null;
}
if (columnFamilyHandle != null)
return this.rocksDB.get(columnFamilyHandle, StorageConfigFactory.getReadOptions(), key);
else
return this.rocksDB.get(StorageConfigFactory.getReadOptions(), key);
}
public List<byte[]> getEdgeIDs(byte[] id, Direction direction, HashSet<String> edgeLabels) {
List<byte[]> edgeIds = new ArrayList<>();
RocksIterator iterator;
byte[] seek_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR.getBytes());
try {
if (direction == Direction.BOTH || direction == Direction.IN) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.IN_EDGES));
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
if (edgeLabels.size() == 0) {
edgeIds.add(Utils.slice(key, seek_key.length));
} else {
byte[] edgeId = Utils.slice(key, seek_key.length);
String edgeLabel = this.rocksGraph.getStorageHandler().getEdgeDB().getLabel(edgeId);
if (edgeLabels.contains(edgeLabel)) {
edgeIds.add(edgeId);
}
}
return true;
});
}
if (direction == Direction.BOTH || direction == Direction.OUT) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.OUT_EDGES));
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
if (edgeLabels.size() == 0) {
edgeIds.add(Utils.slice(key, seek_key.length));
} else {
byte[] edgeId = Utils.slice(key, seek_key.length);
String edgeLabel = this.rocksGraph.getStorageHandler().getEdgeDB().getLabel(edgeId);
if (edgeLabels.contains(edgeLabel)) {
edgeIds.add(edgeId);
}
}
return true;
});
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
return edgeIds;
}
public RocksVertex vertex(byte[] id, RocksGraph rocksGraph) throws Exception {
return getVertex(id, rocksGraph);
}
public void remove(RocksVertex rocksVertex) throws RocksDBException {
this.rocksDB.remove((byte[]) rocksVertex.id());
}
public enum VERTEX_COLUMNS {
PROPERTIES("PROPERTIES"),
PROPERTY_TYPE("PROPERTY_TYPE"),
OUT_EDGES("OUT_EDGES"),
IN_EDGES("IN_EDGES"),
OUT_EDGE_LABELS("OUT_EDGE_LABELS"),
IN_EDGE_LABELS("IN_EDGE_LABELS");
String value;
VERTEX_COLUMNS(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
RocksDB rocksDB;
List<ColumnFamilyHandle> columnFamilyHandleList;
List<ColumnFamilyDescriptor> columnFamilyDescriptors;
public VertexDB(RocksGraph rocksGraph) throws RocksDBException {
super(rocksGraph);
RocksDB.loadLibrary();
columnFamilyDescriptors = new ArrayList<>(VERTEX_COLUMNS.values().length);
columnFamilyHandleList = new ArrayList<>(VERTEX_COLUMNS.values().length);
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, StorageConfigFactory.getColumnFamilyOptions()));
for (VERTEX_COLUMNS vertex_columns : VERTEX_COLUMNS.values()) {
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(vertex_columns.getValue().getBytes(),
StorageConfigFactory.getColumnFamilyOptions()));
}
this.rocksDB = RocksDB.open(StorageConfigFactory.getDBOptions(), getDbPath() + "/vertices", columnFamilyDescriptors, columnFamilyHandleList);
this.rocksDB.enableFileDeletions(true);
}
public ColumnFamilyHandle getColumn(VERTEX_COLUMNS vertex_column) {
return columnFamilyHandleList.get(vertex_column.ordinal() + 1);
}
public void addVertex(byte[] idValue, String label, Object[] keyValues) throws RocksDBException {
if (exists(idValue)) {
throw Graph.Exceptions.vertexWithIdAlreadyExists(new String(idValue));
}
put(idValue, label.getBytes());
if (keyValues == null || keyValues.length == 0) {
return;
}
Map<String, Object> properties = ElementHelper.asMap(keyValues);
for (Map.Entry<String, Object> property : properties.entrySet()) {
setProperty(idValue, property.getKey(), property.getValue(), VertexProperty.Cardinality.single);
}
}
private boolean exists(byte[] idValue) throws RocksDBException {
return (this.rocksDB.get(idValue) != null);
}
public List<Vertex> vertices(List<byte[]> vertexIds, RocksGraph rocksGraph) throws RocksDBException {
if (vertexIds == null) {
RocksIterator iterator = this.rocksDB.newIterator();
vertexIds = new ArrayList<>();
iterator.seekToFirst();
try {
while (iterator.isValid()) {
vertexIds.add(iterator.key());
iterator.next();
}
} finally {
iterator.dispose();
}
}
return vertexIds.stream().map(bytes -> getVertex(bytes, rocksGraph)).
filter(rocksVertex -> rocksVertex != null).collect(Collectors.toList());
}
public RocksVertex getVertex(byte[] vertexId, RocksGraph rocksGraph) {
try {
if (rocksDB.get(vertexId) == null) {
return null;
}
return new RocksVertex(vertexId, getLabel(vertexId), rocksGraph);
} catch (RocksDBException ex) {
ex.printStackTrace();
}
return null;
}
public String getLabel(byte[] vertexid) throws RocksDBException {
byte[] result = this.rocksDB.get(vertexid);
if (result == null) {
throw Graph.Exceptions.elementNotFound(Vertex.class, new String(vertexid));
}
return new String(result);
}
}
| src/main/java/com/tinkerrocks/storage/VertexDB.java | package com.tinkerrocks.storage;
import com.tinkerrocks.structure.*;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by ashishn on 8/5/15.
*/
public class VertexDB extends StorageAbstractClass implements VertexStorage {
public void close() {
if (rocksDB != null)
this.rocksDB.close();
}
@SuppressWarnings("unchecked")
public <V> void setProperty(byte[] id, String key, V value, VertexProperty.Cardinality cardinality) {
byte[] record_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR.getBytes(), key.getBytes());
try {
if (cardinality == VertexProperty.Cardinality.single) {
put(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key, serialize(value));
put(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key, StorageConstants.V_PROPERTY_SINGLE_TYPE);
}
if (cardinality == VertexProperty.Cardinality.list || cardinality == VertexProperty.Cardinality.set) {
byte[] oldData = this.rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key);
byte[] oldType = this.rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key);
ArrayList<V> results;
if (!Utils.compare(oldType, StorageConstants.V_PROPERTY_LIST_TYPE)) {
results = new ArrayList<>();
} else {
results = (ArrayList<V>) deserialize(oldData, ArrayList.class);
}
if (cardinality == VertexProperty.Cardinality.set && results.contains(value)) {
return;
}
results.add(value);
put(getColumn(VERTEX_COLUMNS.PROPERTIES), record_key, serialize(results));
put(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), record_key, StorageConstants.V_PROPERTY_LIST_TYPE);
}
} catch (RocksDBException e) {
e.printStackTrace();
}
}
public void addEdge(byte[] vertexId, Edge edge, Vertex inVertex) throws RocksDBException {
put(getColumn(VERTEX_COLUMNS.OUT_EDGES), Utils.merge(vertexId,
StorageConstants.PROPERTY_SEPARATOR.getBytes(), (byte[]) edge.id()), (byte[]) inVertex.id());
put(getColumn(VERTEX_COLUMNS.IN_EDGES), Utils.merge((byte[]) inVertex.id(),
StorageConstants.PROPERTY_SEPARATOR.getBytes(), (byte[]) edge.id()), vertexId);
}
@SuppressWarnings("unchecked")
public <V> List<VertexProperty<V>> getProperties(RocksElement rocksVertex, List<byte[]> propertyKeys) throws Exception {
List<VertexProperty<V>> results = new ArrayList<>();
if (propertyKeys == null) {
propertyKeys = new ArrayList<>();
}
if (propertyKeys.size() == 0) {
RocksIterator rocksIterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.PROPERTIES));
byte[] seek_key = Utils.merge((byte[]) rocksVertex.id(), StorageConstants.PROPERTY_SEPARATOR.getBytes());
final List<byte[]> finalPropertyKeys = propertyKeys;
Utils.RocksIterUtil(rocksIterator, seek_key, (key, value) -> {
if (value != null)
finalPropertyKeys.add(Utils.slice(key, seek_key.length, key.length));
return true;
});
}
for (byte[] property : propertyKeys) {
byte[] lookup_key = Utils.merge((byte[]) rocksVertex.id(), StorageConstants.PROPERTY_SEPARATOR.getBytes(),
property);
byte[] type = rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTY_TYPE), lookup_key);
byte[] value = rocksDB.get(getColumn(VERTEX_COLUMNS.PROPERTIES), lookup_key);
if (Utils.compare(type, StorageConstants.V_PROPERTY_SINGLE_TYPE)) {
results.add(new RocksVertexProperty<>(rocksVertex, new String(property), (V) deserialize(value, Object.class)));
}
if (Utils.compare(type, StorageConstants.V_PROPERTY_LIST_TYPE)) {
List<V> values = deserialize(value, List.class);
results.addAll(values.stream().map(inner_value -> new RocksVertexProperty<V>(rocksVertex, new String(property), inner_value))
.collect(Collectors.toList()));
}
}
return results;
}
private void put(byte[] key, byte[] value) throws RocksDBException {
this.put(null, key, value);
}
private void put(ColumnFamilyHandle columnFamilyHandle, byte[] key, byte[] value) throws RocksDBException {
if (columnFamilyHandle != null)
this.rocksDB.put(columnFamilyHandle, StorageConfigFactory.getWriteOptions(), key, value);
else
this.rocksDB.put(StorageConfigFactory.getWriteOptions(), key, value);
}
private byte[] get(byte[] key) {
try {
return this.get(null, key);
} catch (RocksDBException e) {
e.printStackTrace();
}
return null;
}
private byte[] get(ColumnFamilyHandle columnFamilyHandle, byte[] key) throws RocksDBException {
if (key == null) {
return null;
}
if (columnFamilyHandle != null)
return this.rocksDB.get(columnFamilyHandle, StorageConfigFactory.getReadOptions(), key);
else
return this.rocksDB.get(StorageConfigFactory.getReadOptions(), key);
}
public List<byte[]> getEdgeIDs(byte[] id, Direction direction, HashSet<String> edgeLabels) {
List<byte[]> edgeIds = new ArrayList<>(50);
RocksIterator iterator;
byte[] seek_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR.getBytes());
try {
if (direction == Direction.BOTH || direction == Direction.IN) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.IN_EDGES));
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
if (edgeLabels.size() == 0) {
edgeIds.add(Utils.slice(key, seek_key.length));
} else {
byte[] edgeId = Utils.slice(key, seek_key.length);
String edgeLabel = this.rocksGraph.getStorageHandler().getEdgeDB().getLabel(edgeId);
if (edgeLabels.contains(edgeLabel)) {
edgeIds.add(edgeId);
}
}
return true;
});
}
if (direction == Direction.BOTH || direction == Direction.OUT) {
iterator = this.rocksDB.newIterator(getColumn(VERTEX_COLUMNS.OUT_EDGES));
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
if (edgeLabels.size() == 0) {
edgeIds.add(Utils.slice(key, seek_key.length));
} else {
byte[] edgeId = Utils.slice(key, seek_key.length);
String edgeLabel = this.rocksGraph.getStorageHandler().getEdgeDB().getLabel(edgeId);
if (edgeLabels.contains(edgeLabel)) {
edgeIds.add(edgeId);
}
}
return true;
});
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
return edgeIds;
}
public RocksVertex vertex(byte[] id, RocksGraph rocksGraph) throws Exception {
return getVertex(id, rocksGraph);
}
public void remove(RocksVertex rocksVertex) throws RocksDBException {
this.rocksDB.remove((byte[]) rocksVertex.id());
}
public enum VERTEX_COLUMNS {
PROPERTIES("PROPERTIES"),
PROPERTY_TYPE("PROPERTY_TYPE"),
OUT_EDGES("OUT_EDGES"),
IN_EDGES("IN_EDGES"),
OUT_EDGE_LABELS("OUT_EDGE_LABELS"),
IN_EDGE_LABELS("IN_EDGE_LABELS");
String value;
VERTEX_COLUMNS(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
RocksDB rocksDB;
List<ColumnFamilyHandle> columnFamilyHandleList;
List<ColumnFamilyDescriptor> columnFamilyDescriptors;
public VertexDB(RocksGraph rocksGraph) throws RocksDBException {
super(rocksGraph);
RocksDB.loadLibrary();
columnFamilyDescriptors = new ArrayList<>(VERTEX_COLUMNS.values().length);
columnFamilyHandleList = new ArrayList<>(VERTEX_COLUMNS.values().length);
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, StorageConfigFactory.getColumnFamilyOptions()));
for (VERTEX_COLUMNS vertex_columns : VERTEX_COLUMNS.values()) {
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(vertex_columns.getValue().getBytes(),
StorageConfigFactory.getColumnFamilyOptions()));
}
this.rocksDB = RocksDB.open(StorageConfigFactory.getDBOptions(), getDbPath() + "/vertices", columnFamilyDescriptors, columnFamilyHandleList);
this.rocksDB.enableFileDeletions(true);
}
public ColumnFamilyHandle getColumn(VERTEX_COLUMNS vertex_column) {
return columnFamilyHandleList.get(vertex_column.ordinal() + 1);
}
public void addVertex(byte[] idValue, String label, Object[] keyValues) throws RocksDBException {
if (exists(idValue)) {
throw Graph.Exceptions.vertexWithIdAlreadyExists(new String(idValue));
}
put(idValue, label.getBytes());
if (keyValues == null || keyValues.length == 0) {
return;
}
Map<String, Object> properties = ElementHelper.asMap(keyValues);
for (Map.Entry<String, Object> property : properties.entrySet()) {
setProperty(idValue, property.getKey(), property.getValue(), VertexProperty.Cardinality.single);
}
}
private boolean exists(byte[] idValue) throws RocksDBException {
return (this.rocksDB.get(idValue) != null);
}
public List<Vertex> vertices(List<byte[]> vertexIds, RocksGraph rocksGraph) throws RocksDBException {
if (vertexIds == null) {
RocksIterator iterator = this.rocksDB.newIterator();
vertexIds = new ArrayList<>();
iterator.seekToFirst();
try {
while (iterator.isValid()) {
vertexIds.add(iterator.key());
iterator.next();
}
} finally {
iterator.dispose();
}
}
return vertexIds.stream().map(bytes -> getVertex(bytes, rocksGraph)).
filter(rocksVertex -> rocksVertex != null).collect(Collectors.toList());
}
public RocksVertex getVertex(byte[] vertexId, RocksGraph rocksGraph) {
try {
if (rocksDB.get(vertexId) == null) {
return null;
}
return new RocksVertex(vertexId, getLabel(vertexId), rocksGraph);
} catch (RocksDBException ex) {
ex.printStackTrace();
}
return null;
}
public String getLabel(byte[] vertexid) throws RocksDBException {
byte[] result = this.rocksDB.get(vertexid);
if (result == null) {
throw Graph.Exceptions.elementNotFound(Vertex.class, new String(vertexid));
}
return new String(result);
}
}
| fixes
| src/main/java/com/tinkerrocks/storage/VertexDB.java | fixes | <ide><path>rc/main/java/com/tinkerrocks/storage/VertexDB.java
<ide>
<ide>
<ide> public List<byte[]> getEdgeIDs(byte[] id, Direction direction, HashSet<String> edgeLabels) {
<del> List<byte[]> edgeIds = new ArrayList<>(50);
<add> List<byte[]> edgeIds = new ArrayList<>();
<ide> RocksIterator iterator;
<ide> byte[] seek_key = Utils.merge(id, StorageConstants.PROPERTY_SEPARATOR.getBytes());
<ide> |
|
Java | apache-2.0 | b6c99cb4d938ba4ec225045d3ca3ac8cb44ff6cb | 0 | MatthewTamlin/Spyglass | package com.matthewtamlin.spyglass.processors.code_generation;
import com.matthewtamlin.spyglass.annotations.call_handler_annotations.SpecificEnumHandler;
import com.matthewtamlin.spyglass.annotations.call_handler_annotations.SpecificFlagHandler;
import com.matthewtamlin.spyglass.annotations.default_annotations.DefaultToBoolean;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.BooleanHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.ColorHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.ColorStateListHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.DimensionHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.DrawableHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.EnumConstantHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.EnumOrdinalHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.FloatHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.FractionHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.IntegerHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.StringHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.TextArrayHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.TextHandler;
import com.matthewtamlin.spyglass.processors.annotation_utils.AnnotationMirrorUtil;
import com.matthewtamlin.spyglass.processors.functional.ParametrisedSupplier;
import com.matthewtamlin.spyglass.processors.util.EnumUtil;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import java.util.HashMap;
import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.util.Elements;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PUBLIC;
public class CallerComponentGenerator {
public static final String SHOULD_CALL_METHOD_METHOD_NAME = "shouldCallMethod";
public static final String VALUE_IS_AVAILABLE_METHOD_NAME = "valueIsAvailable";
public static final String GET_VALUE_METHOD_NAME = "getValue";
public static final String GET_DEFAULT_VALUE_METHOD_NAME = "getDefaultValue";
private static final TypeName ENUM_UTIL_TYPE_NAME = ClassName.get(EnumUtil.class);
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
shouldCallMethodMethodBodySuppliers;
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
valueIsAvailableBodySuppliers;
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
getValueMethodBodySuppliers;
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
getDefaultValueMethodBodySuppliers;
private final Elements elementsUtil;
{
shouldCallMethodMethodBodySuppliers = new HashMap<>();
shouldCallMethodMethodBodySuppliers.put(
SpecificEnumHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int ordinal = getValueFromAnnotationMirror(object, "ordinal");
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"(value1 == 1) && (value2 == 2)")
.add("\n")
.beginControlFlow("if (defaultConsistentlyReturned)")
.addStatement("return false")
.nextControlFlow("else")
.addStatement("return value1 == $L", ordinal)
.endControlFlow()
.build();
}
}
);
shouldCallMethodMethodBodySuppliers.put(
SpecificFlagHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int handledFlags = getValueFromAnnotationMirror(object, "handledFlags");
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.beginControlFlow("if (defaultConsistentlyReturned)")
.addStatement("return false")
.nextControlFlow("else")
.addStatement("return (value1 & $L) > 0", handledFlags)
.endControlFlow()
.build();
}
}
);
}
{
valueIsAvailableBodySuppliers = new HashMap<>();
valueIsAvailableBodySuppliers.put(
BooleanHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final boolean value1 = attrs.getBoolean($L, false)", getAttributeId(object))
.addStatement("final boolean value2 = attrs.getBoolean($L, true)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == false && value2 == true")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
ColorHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getColor($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getColor($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
ColorStateListHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getColorStateList($L) != null", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
DimensionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final float value1 = attrs.getDimension($L, Float.NEGATIVE_INFINITY)",
getAttributeId(object))
.addStatement("final float value2 = attrs.getDimension($L, Float.POSITIVE_INFINITY)",
getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == Float.NEGATIVE_INFINITY && value2 == Float.POSITIVE_INFINITY")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
DrawableHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getDrawable($L) != null", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
EnumConstantHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = array.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = array.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
EnumOrdinalHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = array.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = array.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
FloatHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final float value1 = attrs.getFloat($L, Float.NEGATIVE_INFINITY)",
getAttributeId(object))
.addStatement("final float value2 = attrs.getFloat($L, Float.POSITIVE_INFINITY)",
getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == Float.NEGATIVE_INFINITY && value2 == Float.POSITIVE_INFINITY")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
FractionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final float value1 = attrs.getFraction(" +
"$L, 1, 1, Float.NEGATIVE_INFINITY)", getAttributeId(object))
.addStatement("final float value2 = attrs.getFraction(" +
"$L, 1, 1, Float.POSITIVE_INFINITY)", getAttributeId(object))
.addStatement("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == Float.NEGATIVE_INFINITY && value2 == Float.POSITIVE_INFINITY")
.addStatement("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
IntegerHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getInt($L, 2)", getAttributeId(object))
.addStatement("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.addStatement("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
StringHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.hasValue($L)", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
TextArrayHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getTextArray($L) != null", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
TextHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getText($L) != null", getAttributeId(object))
.build();
}
}
);
}
{
getValueMethodBodySuppliers = new HashMap<>();
getValueMethodBodySuppliers.put(
BooleanHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock.
builder()
.add("return attrs.getBoolean($L, false)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
ColorHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getColor($L, 1)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
ColorStateListHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getColorStateList($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
DimensionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getDimension($L, Float.NEGATIVE_INFINITY)",
getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
DrawableHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getDrawable($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
EnumConstantHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final Class<? extends Enum> enumClass = getValueFromAnnotationMirror(object, "enumClass");
return CodeBlock
.builder()
.addStatement("final int ordinal = attrs.getInt($L, 0)", getAttributeId(object))
.addStatement("return $T.getEnumConstant($L, ordinal)", ENUM_UTIL_TYPE_NAME, enumClass)
.build();
}
}
);
getValueMethodBodySuppliers.put(
EnumOrdinalHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return array.getInt($L, 1)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
FloatHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getFloat($L, Float.NEGATIVE_INFINITY)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
FractionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int baseMultiplier = getValueFromAnnotationMirror(object, "baseMultiplier");
final int parentMultiplier = getValueFromAnnotationMirror(object, "parentMultiplier");
return CodeBlock
.builder()
.addStatement(
"return attrs.getFraction($L, $L, $L, Float.NEGATIVE_INFINITY)",
getAttributeId(object),
baseMultiplier,
parentMultiplier)
.build();
}
}
);
getValueMethodBodySuppliers.put(
IntegerHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getInt($L, 1)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
StringHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getString($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
TextArrayHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getTextArray($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
TextHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getText($L)", getAttributeId(object))
.build();
}
}
);
}
{
getDefaultValueMethodBodySuppliers = new HashMap<>();
getDefaultValueMethodBodySuppliers.put(
DefaultToBoolean.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int value = getValueFromAnnotationMirror(object, "value");
return CodeBlock
.builder()
.add("return $L", value)
.build();
}
}
);
}
public CallerComponentGenerator(final Elements elementsUtil) {
this.elementsUtil = checkNotNull(elementsUtil, "Argument \'elementsUtil\' cannot be null.");
}
/**
* Returns a method spec equivalent to the following:
* <pre>{@code
* public boolean shouldCallMethod(TypedArray attrs) {
* // Some implementation, varies
* }}</pre>
* <p>
* The body is dynamically generated based on the attr checks defined by the supplied attribute.
*
* @param anno
* the annotation to base the method body on, not null
*
* @return the method spec, not null
*
* @throws IllegalArgumentException
* if {@code annotation} is null
*/
public MethodSpec generateShouldCallMethodSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!shouldCallMethodMethodBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a mirror of a call handler annotation.");
}
final CodeBlock methodBody = shouldCallMethodMethodBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("shouldCallMethod")
.addModifiers(PUBLIC)
.returns(boolean.class)
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs", FINAL)
.addCode(methodBody)
.build();
}
public MethodSpec generateValueIsAvailableSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!valueIsAvailableBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a mirror of a value handler annotation.");
}
final CodeBlock methodBody = valueIsAvailableBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("valueIsAvailable")
.addModifiers(PUBLIC)
.returns(boolean.class)
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs")
.addCode(methodBody)
.build();
}
public MethodSpec generateGetValueSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!getValueMethodBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a mirror of a value handler annotation.");
}
final CodeBlock methodBody = getValueMethodBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("getValue")
.addModifiers(PUBLIC)
.returns(Object.class)
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs")
.addCode(methodBody)
.build();
}
public MethodSpec generateGetDefaultValueSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!getDefaultValueMethodBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a default annotation.");
}
final CodeBlock methodBody = getDefaultValueMethodBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("getDefaultValue")
.addModifiers(PUBLIC)
.returns(Object.class)
.addParameter(AndroidClassNames.CONTEXT, "context")
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs")
.addCode(methodBody)
.build();
}
@SuppressWarnings("unchecked") // Unchecked exceptions are managed externally
private <T> T getValueFromAnnotationMirror(final AnnotationMirror mirror, final String key) {
final AnnotationValue value = AnnotationMirrorUtil.getAnnotationValueWithDefaults(mirror, key, elementsUtil);
if (value == null) {
return null;
}
return (T) value.getValue();
}
private String getAttributeId(final AnnotationMirror mirror) {
final AnnotationValue value = AnnotationMirrorUtil.getAnnotationValueWithDefaults(
mirror,
"attributeId",
elementsUtil);
return value.toString();
}
} | processors/src/main/java/com/matthewtamlin/spyglass/processors/code_generation/CallerComponentGenerator.java | package com.matthewtamlin.spyglass.processors.code_generation;
import com.matthewtamlin.spyglass.annotations.call_handler_annotations.SpecificEnumHandler;
import com.matthewtamlin.spyglass.annotations.call_handler_annotations.SpecificFlagHandler;
import com.matthewtamlin.spyglass.annotations.default_annotations.DefaultToBoolean;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.BooleanHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.ColorHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.ColorStateListHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.DimensionHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.DrawableHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.EnumConstantHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.EnumOrdinalHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.FloatHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.FractionHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.IntegerHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.StringHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.TextArrayHandler;
import com.matthewtamlin.spyglass.annotations.value_handler_annotations.TextHandler;
import com.matthewtamlin.spyglass.processors.annotation_utils.AnnotationMirrorUtil;
import com.matthewtamlin.spyglass.processors.functional.ParametrisedSupplier;
import com.matthewtamlin.spyglass.processors.util.EnumUtil;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import java.util.HashMap;
import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.util.Elements;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PUBLIC;
public class CallerComponentGenerator {
public static final String SHOULD_CALL_METHOD_METHOD_NAME = "shouldCallMethod";
public static final String VALUE_IS_AVAILABLE_METHOD_NAME = "valueIsAvailable";
public static final String GET_VALUE_METHOD_NAME = "getValue";
public static final String GET_DEFAULT_VALUE_METHOD_NAME = "getDefaultValue";
private static final TypeName ENUM_UTIL_TYPE_NAME = ClassName.get(EnumUtil.class);
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
shouldCallMethodMethodBodySuppliers;
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
valueIsAvailableBodySuppliers;
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
getValueMethodBodySuppliers;
private final Map<String, ParametrisedSupplier<AnnotationMirror, CodeBlock>>
getDefaultValueMethodBodySuppliers;
private final Elements elementsUtil;
{
shouldCallMethodMethodBodySuppliers = new HashMap<>();
shouldCallMethodMethodBodySuppliers.put(
SpecificEnumHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int ordinal = getValueFromAnnotationMirror(object, "ordinal");
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"(value1 == 1) && (value2 == 2)")
.add("\n")
.beginControlFlow("if (defaultConsistentlyReturned)")
.addStatement("return false")
.nextControlFlow("else")
.addStatement("return value1 == $L", ordinal)
.endControlFlow()
.build();
}
}
);
shouldCallMethodMethodBodySuppliers.put(
SpecificFlagHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int handledFlags = getValueFromAnnotationMirror(object, "handledFlags");
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.beginControlFlow("if (defaultConsistentlyReturned)")
.addStatement("return false")
.nextControlFlow("else")
.addStatement("return (value1 & $L) > 0", handledFlags)
.endControlFlow()
.build();
}
}
);
}
{
valueIsAvailableBodySuppliers = new HashMap<>();
valueIsAvailableBodySuppliers.put(
BooleanHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final boolean value1 = attrs.getBoolean($L, false)", getAttributeId(object))
.addStatement("final boolean value2 = attrs.getBoolean($L, true)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == false && value2 == true")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
ColorHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getColor($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getColor($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
ColorStateListHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getColorStateList($L) != null", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
DimensionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final float value1 = attrs.getDimension($L, Float.NEGATIVE_INFINITY)",
getAttributeId(object))
.addStatement("final float value2 = attrs.getDimension($L, Float.POSITIVE_INFINITY)",
getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == Float.NEGATIVE_INFINITY && value2 == Float.POSITIVE_INFINITY")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
DrawableHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getDrawable($L) != null", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
EnumConstantHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = array.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = array.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
EnumOrdinalHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = array.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = array.getInt($L, 2)", getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
FloatHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final float value1 = attrs.getFloat($L, Float.NEGATIVE_INFINITY)",
getAttributeId(object))
.addStatement("final float value2 = attrs.getFloat($L, Float.POSITIVE_INFINITY)",
getAttributeId(object))
.add("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == Float.NEGATIVE_INFINITY && value2 == Float.POSITIVE_INFINITY")
.add("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
FractionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final float value1 = attrs.getFraction(" +
"$L, 1, 1, Float.NEGATIVE_INFINITY)", getAttributeId(object))
.addStatement("final float value2 = attrs.getFraction(" +
"$L, 1, 1, Float.POSITIVE_INFINITY)", getAttributeId(object))
.addStatement("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == Float.NEGATIVE_INFINITY && value2 == Float.POSITIVE_INFINITY")
.addStatement("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
IntegerHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("final int value1 = attrs.getInt($L, 1)", getAttributeId(object))
.addStatement("final int value2 = attrs.getInt($L, 2)", getAttributeId(object))
.addStatement("\n")
.addStatement("final boolean defaultConsistentlyReturned = " +
"value1 == 1 && value2 == 2")
.addStatement("\n")
.addStatement("return !defaultConsistentlyReturned")
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
StringHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.hasValue($L)", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
TextArrayHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getTextArray($L) != null", getAttributeId(object))
.build();
}
}
);
valueIsAvailableBodySuppliers.put(
TextHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getText($L) != null", getAttributeId(object))
.build();
}
}
);
}
{
getValueMethodBodySuppliers = new HashMap<>();
getValueMethodBodySuppliers.put(
BooleanHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock.
builder()
.add("return attrs.getBoolean($L, false)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
ColorHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getColor($L, 1)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
ColorStateListHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getColorStateList($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
DimensionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getDimension($L, Float.NEGATIVE_INFINITY)",
getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
DrawableHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getDrawable($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
EnumConstantHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final Class<? extends Enum> enumClass = getValueFromAnnotationMirror(object, "enumClass");
return CodeBlock
.builder()
.addStatement("final int ordinal = attrs.getInt($L, 0)", getAttributeId(object))
.addStatement("return $T.getEnumConstant($L, ordinal)", ENUM_UTIL_TYPE_NAME, enumClass)
.build();
}
}
);
getValueMethodBodySuppliers.put(
EnumOrdinalHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return array.getInt($L, 1)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
FloatHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getFloat($L, Float.NEGATIVE_INFINITY)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
FractionHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int baseMultiplier = getValueFromAnnotationMirror(object, "baseMultiplier");
final int parentMultiplier = getValueFromAnnotationMirror(object, "parentMultiplier");
return CodeBlock
.builder()
.addStatement(
"return attrs.getFraction($L, $L, $L, Float.NEGATIVE_INFINITY)",
getAttributeId(object),
baseMultiplier,
parentMultiplier)
.build();
}
}
);
getValueMethodBodySuppliers.put(
IntegerHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int getAttributeId(object) = getValueFromAnnotationMirror(object, "getAttributeId(object)");
return CodeBlock
.builder()
.addStatement("return attrs.getInt($L, 1)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
StringHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getString($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
TextArrayHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getTextArray($L)", getAttributeId(object))
.build();
}
}
);
getValueMethodBodySuppliers.put(
TextHandler.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
return CodeBlock
.builder()
.addStatement("return attrs.getText($L)", getAttributeId(object))
.build();
}
}
);
}
{
getDefaultValueMethodBodySuppliers = new HashMap<>();
getDefaultValueMethodBodySuppliers.put(
DefaultToBoolean.class.getName(),
new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
final int value = getValueFromAnnotationMirror(object, "value");
return CodeBlock
.builder()
.add("return $L", value)
.build();
}
}
);
}
public CallerComponentGenerator(final Elements elementsUtil) {
this.elementsUtil = checkNotNull(elementsUtil, "Argument \'elementsUtil\' cannot be null.");
}
/**
* Returns a method spec equivalent to the following:
* <pre>{@code
* public boolean shouldCallMethod(TypedArray attrs) {
* // Some implementation, varies
* }}</pre>
* <p>
* The body is dynamically generated based on the attr checks defined by the supplied attribute.
*
* @param anno
* the annotation to base the method body on, not null
*
* @return the method spec, not null
*
* @throws IllegalArgumentException
* if {@code annotation} is null
*/
public MethodSpec generateShouldCallMethodSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!shouldCallMethodMethodBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a mirror of a call handler annotation.");
}
final CodeBlock methodBody = shouldCallMethodMethodBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("shouldCallMethod")
.addModifiers(PUBLIC)
.returns(boolean.class)
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs", FINAL)
.addCode(methodBody)
.build();
}
public MethodSpec generateValueIsAvailableSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!valueIsAvailableBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a mirror of a value handler annotation.");
}
final CodeBlock methodBody = valueIsAvailableBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("valueIsAvailable")
.addModifiers(PUBLIC)
.returns(boolean.class)
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs")
.addCode(methodBody)
.build();
}
public MethodSpec generateGetValueSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!getValueMethodBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a mirror of a value handler annotation.");
}
final CodeBlock methodBody = getValueMethodBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("getValue")
.addModifiers(PUBLIC)
.returns(Object.class)
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs")
.addCode(methodBody)
.build();
}
public MethodSpec generateGetDefaultValueSpecFor(final AnnotationMirror anno) {
checkNotNull(anno, "Argument \'anno\' cannot be null.");
final String annotationTypeName = anno.getAnnotationType().toString();
if (!getDefaultValueMethodBodySuppliers.containsKey(annotationTypeName)) {
throw new IllegalArgumentException("Argument \'anno\' must be a default annotation.");
}
final CodeBlock methodBody = getDefaultValueMethodBodySuppliers.get(annotationTypeName).supplyFor(anno);
return MethodSpec
.methodBuilder("getDefaultValue")
.addModifiers(PUBLIC)
.returns(Object.class)
.addParameter(AndroidClassNames.CONTEXT, "context")
.addParameter(AndroidClassNames.TYPED_ARRAY, "attrs")
.addCode(methodBody)
.build();
}
@SuppressWarnings("unchecked") // Unchecked exceptions are managed externally
private <T> T getValueFromAnnotationMirror(final AnnotationMirror mirror, final String key) {
final AnnotationValue value = AnnotationMirrorUtil.getAnnotationValueWithDefaults(mirror, key, elementsUtil);
if (value == null) {
return null;
}
return (T) value.getValue();
}
private String getAttributeId(final AnnotationMirror mirror) {
final AnnotationValue value = AnnotationMirrorUtil.getAnnotationValueWithDefaults(
mirror,
"attributeId",
elementsUtil);
return value.toString();
}
} | Deleted erroneous line
| processors/src/main/java/com/matthewtamlin/spyglass/processors/code_generation/CallerComponentGenerator.java | Deleted erroneous line | <ide><path>rocessors/src/main/java/com/matthewtamlin/spyglass/processors/code_generation/CallerComponentGenerator.java
<ide> new ParametrisedSupplier<AnnotationMirror, CodeBlock>() {
<ide> @Override
<ide> public CodeBlock supplyFor(final AnnotationMirror object) {
<del> final int getAttributeId(object) = getValueFromAnnotationMirror(object, "getAttributeId(object)");
<del>
<ide> return CodeBlock
<ide> .builder()
<ide> .addStatement("return attrs.getInt($L, 1)", getAttributeId(object)) |
|
Java | lgpl-2.1 | 8ba2f87fefa01d8560d4daa95be30b726337ecff | 0 | levants/lightmare | package org.lightmare.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.WatchUtils;
/**
* Container class to save {@link MetaData} for bean interface {@link Class} and
* connections ({@link EntityManagerFactory}) for unit names
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
*/
public class MetaContainer {
// Cached instance of MetaCreator
private static MetaCreator creator;
/**
* {@link Configuration} container class for server
*/
public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>();
// Cached bean meta data
private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>();
// Cached bean class name by its URL for undeploy processing
private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>();
private static final Logger LOG = Logger.getLogger(MetaContainer.class);
/**
* Gets cached {@link MetaCreator} object
*
* @return {@link MetaCreator}
*/
public static MetaCreator getCreator() {
synchronized (MetaContainer.class) {
return creator;
}
}
/**
* Caches {@link MetaCreator} object
*
* @param metaCreator
*/
public static void setCreator(MetaCreator metaCreator) {
synchronized (MetaContainer.class) {
creator = metaCreator;
}
}
/**
* Caches {@link Configuration} for specific {@link URL} array
*
* @param archives
* @param config
*/
public static void putConfig(URL[] archives, Configuration config) {
if (CollectionUtils.valid(archives)) {
boolean containsPath;
for (URL archive : archives) {
String path = WatchUtils.clearPath(archive.getFile());
containsPath = CONFIGS.containsKey(path);
if (ObjectUtils.notTrue(containsPath)) {
CONFIGS.put(path, config);
}
}
}
}
/**
* Gets {@link Configuration} from cache for specific {@link URL} array
*
* @param archives
* @param config
*/
public static Configuration getConfig(URL[] archives) {
Configuration config;
URL archive = CollectionUtils.getFirst(archives);
if (ObjectUtils.notNull(archive)) {
String path = WatchUtils.clearPath(archive.getFile());
config = CONFIGS.get(path);
} else {
config = null;
}
return config;
}
/**
* Adds {@link MetaData} to cache on specified bean name if absent and
* returns previous value on this name or null if such value does not exists
*
* @param beanName
* @param metaData
* @return
*/
public static MetaData addMetaData(String beanName, MetaData metaData) {
return EJBS.putIfAbsent(beanName, metaData);
}
/**
* Check if {@link MetaData} is ceched for specified bean name if true
* throws {@link BeanInUseException}
*
* @param beanName
* @param metaData
* @throws BeanInUseException
*/
public static void checkAndAddMetaData(String beanName, MetaData metaData)
throws BeanInUseException {
MetaData tmpMeta = addMetaData(beanName, metaData);
if (ObjectUtils.notNull(tmpMeta)) {
throw BeanInUseException.get(beanName);
}
}
/**
* Checks if bean with associated name deployed and if it is, then checks if
* deployment is in progress
*
* @param beanName
* @return boolean
*/
public static boolean checkMetaData(String beanName) {
boolean check;
MetaData metaData = EJBS.get(beanName);
check = metaData == null;
if (ObjectUtils.notTrue(check)) {
check = metaData.isInProgress();
}
return check;
}
/**
* Checks if bean with associated name is already deployed
*
* @param beanName
* @return boolean
*/
public boolean checkBean(String beanName) {
return EJBS.containsKey(beanName);
}
/**
* Waits while passed {@link MetaData} instance is in progress
*
* @param inProgress
* @param metaData
* @throws IOException
*/
private static void awaitProgress(boolean inProgress, MetaData metaData)
throws IOException {
while (inProgress) {
try {
metaData.wait();
inProgress = metaData.isInProgress();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Waits while {@link MetaData#isInProgress()} is true (and if it is calls
* {@link MetaContainer#awaitProgress(boolean, MetaData)} method)
*
* @param metaData
* @throws IOException
*/
public static void awaitMetaData(MetaData metaData) throws IOException {
boolean inProgress = metaData.isInProgress();
if (inProgress) {
synchronized (metaData) {
awaitProgress(inProgress, metaData);
}
}
}
/**
* Gets deployed bean {@link MetaData} by name without checking deployment
* progress
*
* @param beanName
* @return {@link MetaData}
*/
public static MetaData getMetaData(String beanName) {
return EJBS.get(beanName);
}
/**
* Check if {@link MetaData} with associated name deployed and if it is
* waits while {@link MetaData#isInProgress()} true before return it
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
public static MetaData getSyncMetaData(String beanName) throws IOException {
MetaData metaData = getMetaData(beanName);
if (metaData == null) {
throw new IOException(String.format("Bean %s is not deployed",
beanName));
}
awaitMetaData(metaData);
return metaData;
}
/**
* Gets bean name by containing archive {@link URL} address
*
* @param url
* @return {@link Collection}<code><String></code>
*/
public static Collection<String> getBeanNames(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.get(url);
}
}
/**
* Checks containing archive {@link URL} address
*
* @param url
* @return <code>boolean</code>
*/
public static boolean chackDeployment(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.containsKey(url);
}
}
/**
* Removes cached EJB bean names {@link Collection} by containing file
* {@link URL} as key
*
* @param url
*/
public static void removeBeanNames(URL url) {
synchronized (MetaContainer.class) {
EJB_URLS.remove(url);
}
}
/**
* Caches EJB bean name by {@link URL} of jar ear or any file
*
* @param beanName
*/
public static void addBeanName(URL url, String beanName) {
synchronized (MetaContainer.class) {
Collection<String> beanNames = EJB_URLS.get(url);
if (CollectionUtils.invalid(beanNames)) {
beanNames = new HashSet<String>();
EJB_URLS.put(url, beanNames);
}
beanNames.add(beanName);
}
}
/**
* Lists {@link Set} for deployed application {@link URL}'s
*
* @return {@link Set}<URL>
*/
public static Set<URL> listApplications() {
Set<URL> apps = EJB_URLS.keySet();
return apps;
}
/**
* Clears connection from cache
*
* @param metaData
* @throws IOException
*/
private static void clearConnection(MetaData metaData) throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
// Gets connection to clear
String unitName = connection.getUnitName();
ConnectionSemaphore semaphore = connection.getConnection();
if (semaphore == null) {
semaphore = ConnectionContainer.getConnection(unitName);
}
if (ObjectUtils.notNull(semaphore)
&& semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) {
ConnectionContainer.removeConnection(unitName);
}
}
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by bean class
* name
*
* @param beanName
* @throws IOException
*/
public static void undeployBean(String beanName) throws IOException {
MetaData metaData = null;
try {
metaData = getSyncMetaData(beanName);
} catch (IOException ex) {
LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s",
beanName, ex.getMessage());
}
// Removes MetaData from cache
removeMeta(beanName);
if (ObjectUtils.notNull(metaData)) {
// Removes appropriated resource class from REST service
if (RestContainer.hasRest()) {
RestProvider.remove(metaData.getBeanClass());
}
clearConnection(metaData);
ClassLoader loader = metaData.getLoader();
LibraryLoader.closeClassLoader(loader);
metaData = null;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of
* archive file
*
* @param url
* @throws IOException
*/
public static boolean undeploy(URL url) throws IOException {
boolean valid;
synchronized (MetaContainer.class) {
Collection<String> beanNames = getBeanNames(url);
valid = CollectionUtils.valid(beanNames);
if (valid) {
for (String beanName : beanNames) {
undeployBean(beanName);
}
}
removeBeanNames(url);
}
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* of archive file
*
* @param file
* @throws IOException
*/
public static boolean undeploy(File file) throws IOException {
boolean valid;
URL url = file.toURI().toURL();
valid = undeploy(url);
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* path of archive file
*
* @param path
* @throws IOException
*/
public static boolean undeploy(String path) throws IOException {
boolean valid;
File file = new File(path);
valid = undeploy(file);
return valid;
}
/**
* Removed {@link MetaData} from cache
*
* @param beanName
*/
public static void removeMeta(String beanName) {
EJBS.remove(beanName);
}
/**
* Gets {@link java.util.Iterator}<MetaData> over all cached
* {@link org.lightmare.cache.MetaData}
*
* @return {@link java.util.Iterator}<MetaData>
*/
public static Iterator<MetaData> getBeanClasses() {
return EJBS.values().iterator();
}
/**
* Removes all cached resources
*/
public static void clear() {
if (ObjectUtils.notNull(creator)) {
synchronized (MetaContainer.class) {
if (ObjectUtils.notNull(creator)) {
creator.clear();
creator = null;
}
}
}
CONFIGS.clear();
EJBS.clear();
EJB_URLS.clear();
}
}
| src/main/java/org/lightmare/cache/MetaContainer.java | package org.lightmare.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.WatchUtils;
/**
* Container class to save {@link MetaData} for bean interface {@link Class} and
* connections ({@link EntityManagerFactory}) for unit names
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
*/
public class MetaContainer {
// Cached instance of MetaCreator
private static MetaCreator creator;
/**
* {@link Configuration} container class for server
*/
public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>();
// Cached bean meta data
private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>();
// Cached bean class name by its URL for undeploy processing
private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>();
private static final Logger LOG = Logger.getLogger(MetaContainer.class);
/**
* Gets cached {@link MetaCreator} object
*
* @return {@link MetaCreator}
*/
public static MetaCreator getCreator() {
synchronized (MetaContainer.class) {
return creator;
}
}
/**
* Caches {@link MetaCreator} object
*
* @param metaCreator
*/
public static void setCreator(MetaCreator metaCreator) {
synchronized (MetaContainer.class) {
creator = metaCreator;
}
}
/**
* Caches {@link Configuration} for specific {@link URL} array
*
* @param archives
* @param config
*/
public static void putConfig(URL[] archives, Configuration config) {
if (CollectionUtils.valid(archives)) {
boolean containsPath;
for (URL archive : archives) {
String path = WatchUtils.clearPath(archive.getFile());
containsPath = CONFIGS.containsKey(path);
if (ObjectUtils.notTrue(containsPath)) {
CONFIGS.put(path, config);
}
}
}
}
/**
* Gets {@link Configuration} from cache for specific {@link URL} array
*
* @param archives
* @param config
*/
public static Configuration getConfig(URL[] archives) {
Configuration config;
URL archive = CollectionUtils.getFirst(archives);
if (ObjectUtils.notNull(archive)) {
String path = WatchUtils.clearPath(archive.getFile());
config = CONFIGS.get(path);
} else {
config = null;
}
return config;
}
/**
* Adds {@link MetaData} to cache on specified bean name if absent and
* returns previous value on this name or null if such value does not exists
*
* @param beanName
* @param metaData
* @return
*/
public static MetaData addMetaData(String beanName, MetaData metaData) {
return EJBS.putIfAbsent(beanName, metaData);
}
/**
* Check if {@link MetaData} is ceched for specified bean name if true
* throws {@link BeanInUseException}
*
* @param beanName
* @param metaData
* @throws BeanInUseException
*/
public static void checkAndAddMetaData(String beanName, MetaData metaData)
throws BeanInUseException {
MetaData tmpMeta = addMetaData(beanName, metaData);
if (ObjectUtils.notNull(tmpMeta)) {
throw BeanInUseException.get(beanName);
}
}
/**
* Checks if bean with associated name deployed and if it is, then checks if
* deployment is in progress
*
* @param beanName
* @return boolean
*/
public static boolean checkMetaData(String beanName) {
boolean check;
MetaData metaData = EJBS.get(beanName);
check = metaData == null;
if (ObjectUtils.notTrue(check)) {
check = metaData.isInProgress();
}
return check;
}
/**
* Checks if bean with associated name is already deployed
*
* @param beanName
* @return boolean
*/
public boolean checkBean(String beanName) {
return EJBS.containsKey(beanName);
}
/**
* Waits while passed {@link MetaData} instance is in progress
*
* @param inProgress
* @param metaData
* @throws IOException
*/
private static void awaitProgress(boolean inProgress, MetaData metaData)
throws IOException {
while (inProgress) {
try {
metaData.wait();
inProgress = metaData.isInProgress();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Waits while {@link MetaData#isInProgress()} is true (and if it is calls
* {@link MetaContainer#awaitProgress(boolean, MetaData)} method)
*
* @param metaData
* @throws IOException
*/
public static void awaitMetaData(MetaData metaData) throws IOException {
boolean inProgress = metaData.isInProgress();
if (inProgress) {
synchronized (metaData) {
awaitProgress(inProgress, metaData);
}
}
}
/**
* Gets deployed bean {@link MetaData} by name without checking deployment
* progress
*
* @param beanName
* @return {@link MetaData}
*/
public static MetaData getMetaData(String beanName) {
return EJBS.get(beanName);
}
/**
* Check if {@link MetaData} with associated name deployed and if it is
* waits while {@link MetaData#isInProgress()} true before return it
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
public static MetaData getSyncMetaData(String beanName) throws IOException {
MetaData metaData = getMetaData(beanName);
if (metaData == null) {
throw new IOException(String.format("Bean %s is not deployed",
beanName));
}
awaitMetaData(metaData);
return metaData;
}
/**
* Gets bean name by containing archive {@link URL} address
*
* @param url
* @return {@link Collection}<code><String></code>
*/
public static Collection<String> getBeanNames(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.get(url);
}
}
/**
* Checks containing archive {@link URL} address
*
* @param url
* @return <code>boolean</code>
*/
public static boolean chackDeployment(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.containsKey(url);
}
}
/**
* Removes cached EJB bean names {@link Collection} by containing file
* {@link URL} as key
*
* @param url
*/
public static void removeBeanNames(URL url) {
synchronized (MetaContainer.class) {
EJB_URLS.remove(url);
}
}
/**
* Caches bean name by {@link URL} of jar ear or any file
*
* @param beanName
*/
public static void addBeanName(URL url, String beanName) {
synchronized (MetaContainer.class) {
Collection<String> beanNames = EJB_URLS.get(url);
if (CollectionUtils.invalid(beanNames)) {
beanNames = new HashSet<String>();
EJB_URLS.put(url, beanNames);
}
beanNames.add(beanName);
}
}
/**
* Lists {@link Set} for deployed application {@link URL}'s
*
* @return {@link Set}<URL>
*/
public static Set<URL> listApplications() {
Set<URL> apps = EJB_URLS.keySet();
return apps;
}
/**
* Clears connection from cache
*
* @param metaData
* @throws IOException
*/
private static void clearConnection(MetaData metaData) throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
// Gets connection to clear
String unitName = connection.getUnitName();
ConnectionSemaphore semaphore = connection.getConnection();
if (semaphore == null) {
semaphore = ConnectionContainer.getConnection(unitName);
}
if (ObjectUtils.notNull(semaphore)
&& semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) {
ConnectionContainer.removeConnection(unitName);
}
}
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by bean class
* name
*
* @param beanName
* @throws IOException
*/
public static void undeployBean(String beanName) throws IOException {
MetaData metaData = null;
try {
metaData = getSyncMetaData(beanName);
} catch (IOException ex) {
LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s",
beanName, ex.getMessage());
}
// Removes MetaData from cache
removeMeta(beanName);
if (ObjectUtils.notNull(metaData)) {
// Removes appropriated resource class from REST service
if (RestContainer.hasRest()) {
RestProvider.remove(metaData.getBeanClass());
}
clearConnection(metaData);
ClassLoader loader = metaData.getLoader();
LibraryLoader.closeClassLoader(loader);
metaData = null;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of
* archive file
*
* @param url
* @throws IOException
*/
public static boolean undeploy(URL url) throws IOException {
boolean valid;
synchronized (MetaContainer.class) {
Collection<String> beanNames = getBeanNames(url);
valid = CollectionUtils.valid(beanNames);
if (valid) {
for (String beanName : beanNames) {
undeployBean(beanName);
}
}
removeBeanNames(url);
}
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* of archive file
*
* @param file
* @throws IOException
*/
public static boolean undeploy(File file) throws IOException {
boolean valid;
URL url = file.toURI().toURL();
valid = undeploy(url);
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* path of archive file
*
* @param path
* @throws IOException
*/
public static boolean undeploy(String path) throws IOException {
boolean valid;
File file = new File(path);
valid = undeploy(file);
return valid;
}
/**
* Removed {@link MetaData} from cache
*
* @param beanName
*/
public static void removeMeta(String beanName) {
EJBS.remove(beanName);
}
/**
* Gets {@link java.util.Iterator}<MetaData> over all cached
* {@link org.lightmare.cache.MetaData}
*
* @return {@link java.util.Iterator}<MetaData>
*/
public static Iterator<MetaData> getBeanClasses() {
return EJBS.values().iterator();
}
/**
* Removes all cached resources
*/
public static void clear() {
if (ObjectUtils.notNull(creator)) {
synchronized (MetaContainer.class) {
if (ObjectUtils.notNull(creator)) {
creator.clear();
creator = null;
}
}
}
CONFIGS.clear();
EJBS.clear();
EJB_URLS.clear();
}
}
| improved / commented code in utility classes | src/main/java/org/lightmare/cache/MetaContainer.java | improved / commented code in utility classes | <ide><path>rc/main/java/org/lightmare/cache/MetaContainer.java
<ide> }
<ide>
<ide> /**
<del> * Caches bean name by {@link URL} of jar ear or any file
<add> * Caches EJB bean name by {@link URL} of jar ear or any file
<ide> *
<ide> * @param beanName
<ide> */ |
|
Java | apache-2.0 | d24d8220e3beec2cd6b1e2d362d67b930ccc57f2 | 0 | realityforge/gwt-eventsource,realityforge/gwt-eventsource | package org.realityforge.gwt.eventsource.client;
import com.google.gwt.core.shared.GWT;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import javax.annotation.Nonnull;
import org.realityforge.gwt.eventsource.client.event.CloseEvent;
import org.realityforge.gwt.eventsource.client.event.ErrorEvent;
import org.realityforge.gwt.eventsource.client.event.MessageEvent;
import org.realityforge.gwt.eventsource.client.event.OpenEvent;
import org.realityforge.gwt.eventsource.client.html5.Html5EventSource;
public abstract class EventSource
{
public interface Factory
{
EventSource newEventSource();
}
// ready state
public enum ReadyState
{
CONNECTING, OPEN, CLOSED
}
private static SupportDetector g_supportDetector;
private static Factory g_factory;
private final EventBus _eventBus;
public static EventSource newEventSourceIfSupported()
{
if ( null == g_factory && isSupported() )
{
register( getSupportDetector().newFactory() );
return g_factory.newEventSource();
}
return ( null != g_factory ) ? g_factory.newEventSource() : null;
}
/**
* @return true if newEventSourceIfSupported() will return a non-null value, false otherwise.
*/
public static boolean isSupported()
{
return ( null != g_factory ) || GWT.isClient() && getSupportDetector().isSupported();
}
public static void register( @Nonnull final Factory factory )
{
g_factory = factory;
}
public static boolean deregister( @Nonnull final Factory factory )
{
if ( g_factory != factory )
{
return false;
}
else
{
g_factory = null;
return true;
}
}
public EventSource( final EventBus eventBus )
{
_eventBus = eventBus;
}
public final void open( @Nonnull final String url )
{
open( url, false );
}
public abstract void open( @Nonnull String url, boolean withCredentials );
public abstract void close();
@Nonnull
public abstract String getURL()
throws IllegalStateException;
public abstract boolean getWithCredentials()
throws IllegalStateException;
@Nonnull
public abstract ReadyState getReadyState();
@Nonnull
public final HandlerRegistration addOpenHandler( @Nonnull OpenEvent.Handler handler )
{
return _eventBus.addHandler( OpenEvent.getType(), handler );
}
@Nonnull
public final HandlerRegistration addCloseHandler( @Nonnull CloseEvent.Handler handler )
{
return _eventBus.addHandler( CloseEvent.getType(), handler );
}
@Nonnull
public final HandlerRegistration addMessageHandler( @Nonnull MessageEvent.Handler handler )
{
return _eventBus.addHandler( MessageEvent.getType(), handler );
}
@Nonnull
public final HandlerRegistration addErrorHandler( @Nonnull ErrorEvent.Handler handler )
{
return _eventBus.addHandler( ErrorEvent.getType(), handler );
}
/**
* Fire a Connected event.
*/
protected final void onOpen()
{
_eventBus.fireEventFromSource( new OpenEvent( this ), this );
}
/**
* Fire a Close event.
*/
protected final void onClose()
{
_eventBus.fireEventFromSource( new CloseEvent( this ), this );
}
/**
* Fire a Message event.
*/
protected final void onMessage( final String data )
{
_eventBus.fireEventFromSource( new MessageEvent( this, data ), this );
}
/**
* Fire an Error event.
*/
protected final void onError()
{
_eventBus.fireEventFromSource( new ErrorEvent( this ), this );
}
/**
* Detector for browser support.
*/
private static class SupportDetector
{
public boolean isSupported()
{
return Html5EventSource.isSupported();
}
public Factory newFactory()
{
return new Html5EventSource.Factory();
}
}
/**
* Detector for browsers without EventSource support.
*/
@SuppressWarnings( "unused" )
private static class NoSupportDetector
extends SupportDetector
{
@Override
public boolean isSupported()
{
return false;
}
@Override
public Factory newFactory()
{
return null;
}
}
private static SupportDetector getSupportDetector()
{
if ( null == g_supportDetector )
{
g_supportDetector = com.google.gwt.core.shared.GWT.create( SupportDetector.class );
}
return g_supportDetector;
}
}
| src/main/java/org/realityforge/gwt/eventsource/client/EventSource.java | package org.realityforge.gwt.eventsource.client;
import com.google.gwt.core.shared.GWT;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.gwt.eventsource.client.event.CloseEvent;
import org.realityforge.gwt.eventsource.client.event.ErrorEvent;
import org.realityforge.gwt.eventsource.client.event.MessageEvent;
import org.realityforge.gwt.eventsource.client.event.OpenEvent;
import org.realityforge.gwt.eventsource.client.html5.Html5EventSource;
public abstract class EventSource
{
public interface Factory
{
EventSource newEventSource();
}
// ready state
public enum ReadyState
{
CONNECTING, OPEN, CLOSED
}
private static SupportDetector g_supportDetector;
private static Factory g_factory;
private final EventBus _eventBus;
public static EventSource newEventSourceIfSupported()
{
if ( null == g_factory && isSupported() )
{
register( getSupportDetector().newFactory() );
return g_factory.newEventSource();
}
return ( null != g_factory ) ? g_factory.newEventSource() : null;
}
/**
* @return true if newEventSourceIfSupported() will return a non-null value, false otherwise.
*/
public static boolean isSupported()
{
return ( null != g_factory ) || GWT.isClient() && getSupportDetector().isSupported();
}
public static void register( @Nonnull final Factory factory )
{
g_factory = factory;
}
public static boolean deregister( @Nonnull final Factory factory )
{
if ( g_factory != factory )
{
return false;
}
else
{
g_factory = null;
return true;
}
}
public EventSource( final EventBus eventBus )
{
_eventBus = eventBus;
}
public final void open( @Nonnull final String url )
{
open( url, false );
}
public abstract void open( @Nonnull String url, boolean withCredentials );
public abstract void close();
@Nonnull
public abstract String getURL()
throws IllegalStateException;
public abstract boolean getWithCredentials()
throws IllegalStateException;
@Nonnull
public abstract ReadyState getReadyState();
@Nonnull
public final HandlerRegistration addOpenHandler( @Nonnull OpenEvent.Handler handler )
{
return _eventBus.addHandler( OpenEvent.getType(), handler );
}
@Nonnull
public final HandlerRegistration addCloseHandler( @Nonnull CloseEvent.Handler handler )
{
return _eventBus.addHandler( CloseEvent.getType(), handler );
}
@Nonnull
public final HandlerRegistration addMessageHandler( @Nonnull MessageEvent.Handler handler )
{
return _eventBus.addHandler( MessageEvent.getType(), handler );
}
@Nonnull
public final HandlerRegistration addErrorHandler( @Nonnull ErrorEvent.Handler handler )
{
return _eventBus.addHandler( ErrorEvent.getType(), handler );
}
/**
* Fire a Connected event.
*/
protected final void onOpen()
{
_eventBus.fireEventFromSource( new OpenEvent( this ), this );
}
/**
* Fire a Close event.
*/
protected final void onClose()
{
_eventBus.fireEventFromSource( new CloseEvent( this ), this );
}
/**
* Fire a Message event.
*/
protected final void onMessage( final String data )
{
_eventBus.fireEventFromSource( new MessageEvent( this, data ), this );
}
/**
* Fire an Error event.
*/
protected final void onError()
{
_eventBus.fireEventFromSource( new ErrorEvent( this ), this );
}
/**
* Detector for browser support.
*/
private static class SupportDetector
{
public boolean isSupported()
{
return Html5EventSource.isSupported();
}
public Factory newFactory()
{
return new Html5EventSource.Factory();
}
}
/**
* Detector for browsers without EventSource support.
*/
@SuppressWarnings( "unused" )
private static class NoSupportDetector
extends SupportDetector
{
@Override
public boolean isSupported()
{
return false;
}
@Override
public Factory newFactory()
{
return null;
}
}
private static SupportDetector getSupportDetector()
{
if ( null == g_supportDetector )
{
g_supportDetector = com.google.gwt.core.shared.GWT.create( SupportDetector.class );
}
return g_supportDetector;
}
}
| Optimise imports
| src/main/java/org/realityforge/gwt/eventsource/client/EventSource.java | Optimise imports | <ide><path>rc/main/java/org/realityforge/gwt/eventsource/client/EventSource.java
<ide> import com.google.web.bindery.event.shared.EventBus;
<ide> import com.google.web.bindery.event.shared.HandlerRegistration;
<ide> import javax.annotation.Nonnull;
<del>import javax.annotation.Nullable;
<ide> import org.realityforge.gwt.eventsource.client.event.CloseEvent;
<ide> import org.realityforge.gwt.eventsource.client.event.ErrorEvent;
<ide> import org.realityforge.gwt.eventsource.client.event.MessageEvent; |
|
Java | apache-2.0 | 3dff0ce947bb893ba1c08414dac6f7314d5bf906 | 0 | apache/logging-log4j2,apache/logging-log4j2,apache/logging-log4j2 | /*
* 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.logging.log4j.mongodb2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.categories.Appenders;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.apache.logging.log4j.mongodb2.MongoDbTestRule.LoggingTarget;
import org.apache.logging.log4j.test.AvailablePortSystemPropertyTestRule;
import org.apache.logging.log4j.test.RuleChainFactory;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
/**
*
*/
@Category(Appenders.MongoDb.class)
public class MongoDbTest {
private static LoggerContextRule loggerContextTestRule = new LoggerContextRule("log4j2-mongodb.xml");
private static final AvailablePortSystemPropertyTestRule mongoDbPortTestRule = AvailablePortSystemPropertyTestRule
.create(TestConstants.SYS_PROP_NAME_PORT);
private static final MongoDbTestRule mongoDbTestRule = new MongoDbTestRule(mongoDbPortTestRule.getName(),
LoggingTarget.NULL);
@ClassRule
public static RuleChain ruleChain = RuleChainFactory.create(mongoDbPortTestRule, mongoDbTestRule,
loggerContextTestRule);
@Test
public void test() {
final Logger logger = LogManager.getLogger();
logger.info("Hello log");
final MongoClient mongoClient = mongoDbTestRule.getMongoClient();
try {
final DB database = mongoClient.getDB("test");
Assert.assertNotNull(database);
final DBCollection collection = database.getCollection("applog");
Assert.assertNotNull(collection);
try (DBCursor cursor = collection.find()) {
final DBObject first = cursor.next();
Assert.assertNotNull(first);
Assert.assertEquals(first.toMap().toString(), "Hello log", first.get("message"));
Assert.assertEquals(first.toMap().toString(), "INFO", first.get("level"));
}
} finally {
mongoClient.close();
}
}
}
| log4j-mongodb2/src/test/java/org/apache/logging/log4j/mongodb2/MongoDbTest.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.logging.log4j.mongodb2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.categories.Appenders;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.apache.logging.log4j.mongodb2.MongoDbTestRule.LoggingTarget;
import org.apache.logging.log4j.test.AvailablePortSystemPropertyTestRule;
import org.apache.logging.log4j.test.RuleChainFactory;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
/**
*
*/
@Category(Appenders.MongoDb.class)
public class MongoDbTest {
private static LoggerContextRule loggerContextTestRule = new LoggerContextRule("log4j2-mongodb.xml");
private static final AvailablePortSystemPropertyTestRule mongoDbPortTestRule = AvailablePortSystemPropertyTestRule
.create(TestConstants.SYS_PROP_NAME_PORT);
private static final MongoDbTestRule mongoDbTestRule = new MongoDbTestRule(mongoDbPortTestRule.getName(),
LoggingTarget.NULL);
@ClassRule
public static RuleChain ruleChain = RuleChainFactory.create(mongoDbPortTestRule, mongoDbTestRule,
loggerContextTestRule);
@Test
public void test() {
final Logger logger = LogManager.getLogger();
logger.info("Hello log");
final MongoClient mongoClient = mongoDbTestRule.getMongoClient();
try {
final DB database = mongoClient.getDB("test");
Assert.assertNotNull(database);
final DBCollection collection = database.getCollection("applog");
Assert.assertNotNull(collection);
try (DBCursor cursor = collection.find()) {
final DBObject first = cursor.next();
Assert.assertNotNull(first);
Assert.assertEquals(first.toMap().toString(), "Hello log", first.get("message"));
}
} finally {
mongoClient.close();
}
}
}
| Tests that the level is converted.
| log4j-mongodb2/src/test/java/org/apache/logging/log4j/mongodb2/MongoDbTest.java | Tests that the level is converted. | <ide><path>og4j-mongodb2/src/test/java/org/apache/logging/log4j/mongodb2/MongoDbTest.java
<ide> final DBObject first = cursor.next();
<ide> Assert.assertNotNull(first);
<ide> Assert.assertEquals(first.toMap().toString(), "Hello log", first.get("message"));
<add> Assert.assertEquals(first.toMap().toString(), "INFO", first.get("level"));
<ide> }
<ide> } finally {
<ide> mongoClient.close(); |
|
Java | lgpl-2.1 | 5b55902d9aad9d0f4baea67d954ab7390510d569 | 0 | GateNLP/gateplugin-LearningFramework,GateNLP/gateplugin-LearningFramework,GateNLP/gateplugin-LearningFramework,GateNLP/gateplugin-LearningFramework,GateNLP/gateplugin-LearningFramework | /*
* 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 gate.plugin.learningframework.engines;
import cc.mallet.fst.CRF;
import cc.mallet.fst.CRFOptimizableByLabelLikelihood;
import cc.mallet.fst.CRFTrainerByLabelLikelihood;
import cc.mallet.fst.CRFTrainerByStochasticGradient;
import cc.mallet.fst.CRFTrainerByThreadedLabelLikelihood;
import cc.mallet.fst.CRFTrainerByValueGradients;
import cc.mallet.fst.MEMM;
import cc.mallet.fst.MEMMTrainer;
import cc.mallet.fst.SumLatticeDefault;
import cc.mallet.fst.Transducer;
import cc.mallet.fst.TransducerTrainer;
import cc.mallet.fst.ViterbiWriter;
import cc.mallet.optimize.Optimizable;
import cc.mallet.pipe.Pipe;
import cc.mallet.types.FeatureVectorSequence;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import gate.Annotation;
import gate.AnnotationSet;
import gate.plugin.learningframework.EvaluationMethod;
import gate.plugin.learningframework.GateClassification;
import gate.plugin.learningframework.data.CorpusRepresentationMalletSeq;
import static gate.plugin.learningframework.engines.Engine.FILENAME_MODEL;
import gate.plugin.learningframework.features.TargetType;
import gate.util.GateRuntimeException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.log4j.Logger;
/**
*
* @author Johann Petrak
*/
public class EngineMalletSeq extends EngineMallet {
private static Logger logger = Logger.getLogger(EngineMalletSeq.class);
@Override
public void initializeAlgorithm(Algorithm algorithm, String parms) {
// DOES NOTHINIG?
}
public AlgorithmKind getAlgorithmKind() {
return AlgorithmKind.SEQUENCE_TAGGER;
}
@Override
public void trainModel(File DataDirectory, String instanceType, String options) {
InstanceList trainingData = corpusRepresentationMallet.getRepresentationMallet();
Transducer td = trainModel(trainingData,options);
model = td;
updateInfo();
}
public static TransducerTrainer createTrainer(InstanceList trainingData, Info info, String options) {
TransducerTrainer transtrainer = null;
// NOTE: Training of the CRF is very flexible in Mallet and not everything is clear to me
// yet. Unfortunately, there is practically no documentation available.
// There is some useful example code around:
// http://mallet.cs.umass.edu/fst.php - the only real documentation available
// src/cc/mallet/examples/TrainCRF.java - very basic example
// src/cc/mallet/fst/SimpleTagger.java - more detailled: especially also shows multithreaded training!
// how to use this: http://mallet.cs.umass.edu/sequences.php
// NOTE: the name can come from an algorithm selected for classification OR an algorithm
// selected for actual sequence tagging. This is why we check the literal name here
// instead of something derived from the Algorithm enum class.
// NOTE on supported trainers: we only support trainers here which are not
// too complex to set up and which can be used with the normal succession of
// how training works in the LF.
// Mallet also supports a lot of additional things, e.g. regularization
// on unlabeled data, but this cannot be used here.
//
String alg = info.algorithmName;
System.err.println("DEBUG: our algorithm name is "+alg);
if(alg.startsWith("MALLET_SEQ_CRF")) {
CRF crf = new CRF(trainingData.getPipe(), null);
Parms parms = new Parms(options,
"S:states:s",
"o:orders:s",
"f:ofully:b",
"a:addstart:b",
"v:logViterbiPaths:i",
"t:threads:i",
"sg:stochasticGradient:b",
"wdd:weightDimDensely:b",
"usw:useSparseWeights:b",
"ssut:setSomeUnsupportedTrick:b");
String states = (String)parms.getValueOrElse("states", "fully-connected");
switch (states) {
case "fully-connected":
crf.addFullyConnectedStatesForLabels();
break;
case "as-in":
crf.addStatesForLabelsConnectedAsIn(trainingData);
break;
case "fully-threequarter":
crf.addFullyConnectedStatesForThreeQuarterLabels(trainingData);
break;
case "half":
crf.addStatesForHalfLabelsConnectedAsIn(trainingData);
break;
case "order-n":
int[] orders = new int[]{1};
String ordersparm = (String)parms.getValueOrElse("orders", "0:1");
if(ordersparm.equals("1")) {
orders = new int[]{1};
} else if(ordersparm.equals("0:1")) {
orders = new int[]{0,1};
} else if(ordersparm.equals("0:1:2")) {
orders = new int[]{0,1,2};
} else if(ordersparm.equals("0")) {
orders = new int[]{0};
} else if(ordersparm.equals("1:2")) {
orders = new int[]{1,2};
} else if(ordersparm.equals("2")) {
orders = new int[]{2};
} else {
throw new GateRuntimeException("Invalid value for parameter orders: "+ordersparm);
}
boolean ofully = (Boolean)parms.getValueOrElse("ofully", false);
crf.addOrderNStates(trainingData, orders, null, null, null, null, ofully);
break;
default:
throw new GateRuntimeException("Unknown value for parameter states: "+states);
}
boolean addStart = (boolean) parms.getValueOrElse("addstart", true);
if(addStart) crf.addStartState();
boolean wdd = (boolean) parms.getValueOrElse("weightDimDensely", false);
if(wdd) crf.setWeightsDimensionDensely();
// initialize model's weights
// TODO: make this conditional on a parm, how does this relate to
// weightDimDensely??
// !!! This should probably be the same parameter!!!
// TODO: second parm should depend on the unsupported trick option!
crf.setWeightsDimensionAsIn(trainingData, false);
// now depending on which trainer we want we need to do slightly different
// things
if(alg.equals("MALLET_SEQ_CRF")) { // By[Thread]LabelLikelihood
// if threads parameter is specified and >0, we use ByThreadLabelLikelihood
int threads = (int) parms.getValueOrElse("threads", 0);
boolean usw = (boolean) parms.getValueOrElse("useSparseWeights", false);
boolean ssut = (boolean) parms.getValueOrElse("setSomeUnsupportedTrick", false);
if(threads<=0) {
CRFTrainerByLabelLikelihood tr = new CRFTrainerByLabelLikelihood(crf);
if(usw) tr.setUseSparseWeights(true);
if(ssut) tr.setUseSomeUnsupportedTrick(true);
transtrainer = tr;
} else {
CRFTrainerByThreadedLabelLikelihood tr =
new CRFTrainerByThreadedLabelLikelihood(crf, threads);
if(usw) tr.setUseSparseWeights(true);
if(ssut) tr.setUseSomeUnsupportedTrick(true);
transtrainer = tr;
}
} else if(alg.equals("MALLET_SEQ_CRF_SG")) {
// TODO: instead of all trainingData, use sample?
// TODO: allow to use training rate instead of trainingData?
CRFTrainerByStochasticGradient crft =
new CRFTrainerByStochasticGradient(crf, trainingData);
} else if(alg.equals("MALLET_SEQ_CRF_VG")) {
// CRFOptimizableBy* objects (terms in the objective function)
// objective 1: label likelihood objective
CRFOptimizableByLabelLikelihood optLabel
= new CRFOptimizableByLabelLikelihood(crf, trainingData);
Optimizable.ByGradientValue[] opts
= new Optimizable.ByGradientValue[]{optLabel};
// by default, use L-BFGS as the optimizer
CRFTrainerByValueGradients crfTrainer = new CRFTrainerByValueGradients(crf, opts);
crfTrainer.setMaxResets(0);
transtrainer = crfTrainer;
} else {
throw new GateRuntimeException("Not yet supported: "+alg);
}
// TODO: if we want to output the viterbi paths:
int logVit = (int) parms.getValueOrElse("logViterbiPaths", 0);
if(logVit==0) logVit=Integer.MAX_VALUE;
final int lv = logVit;
ViterbiWriter viterbiWriter = new ViterbiWriter(
"LF_debug", // output file prefix
new InstanceList[] { trainingData },
new String[] { "train" }) {
@Override
public boolean precondition (TransducerTrainer tt) {
return tt.getIteration() % lv == 0;
}
};
transtrainer.addEvaluator(viterbiWriter);
} else if(alg.equals("MALLET_SEQ_MEMM")) {
// TODO:
MEMM memm = new MEMM(trainingData.getDataAlphabet(),trainingData.getTargetAlphabet());
transtrainer = new MEMMTrainer(memm);
} else {
// Nothing else supported!
throw new GateRuntimeException("EngineMalletSeq: unknown/unsupported algorithm: "+alg);
}
return transtrainer;
}
public Transducer trainModel(InstanceList trainingData, String options) {
TransducerTrainer trainer = createTrainer(trainingData, info, options);
Parms parms = new Parms(options,"i:iterations:i","V:verbose:b");
boolean verbose = (boolean)parms.getValueOrElse("verbose", false);
int iters = (int) parms.getValueOrElse("iterations", 0);
if(iters==0) iters = Integer.MAX_VALUE;
trainer.train(trainingData, iters);
if(verbose)
trainer.getTransducer().print();
Transducer td = trainer.getTransducer();
return td;
}
@Override
public List<GateClassification> classify(
AnnotationSet instanceAS, AnnotationSet inputAS, AnnotationSet sequenceAS, String parms) {
// stop growth
CorpusRepresentationMalletSeq data = (CorpusRepresentationMalletSeq)corpusRepresentationMallet;
data.stopGrowth();
List<GateClassification> gcs = new ArrayList<GateClassification>();
Transducer crf = (Transducer)model;
for(Annotation sequenceAnn : sequenceAS) {
int sequenceSpanId = sequenceAnn.getId();
Instance inst = data.getInstanceForSequence(
instanceAS, sequenceAnn, inputAS, null, null, TargetType.NONE, null);
//Always put the instance through the same pipe used for training.
inst = crf.getInputPipe().instanceFrom(inst);
SumLatticeDefault sl = new SumLatticeDefault(crf,
(FeatureVectorSequence) inst.getData());
List<Annotation> instanceAnnotations = gate.Utils.getContainedAnnotations(
instanceAS, sequenceAnn).inDocumentOrder();
//Sanity check that we're mapping the probs back onto the right anns.
//This being wrong might follow from errors reading in the data to mallet inst.
if (instanceAnnotations.size() != ((FeatureVectorSequence) inst.getData()).size()) {
logger.warn("LearningFramework: CRF output length: "
+ ((FeatureVectorSequence) inst.getData()).size()
+ ", GATE instances: " + instanceAnnotations.size()
+ ". Can't assign.");
} else {
int i = 0;
for (Annotation instanceAnn : instanceAnnotations) {
i++;
String bestLabel = null;
double bestProb = 0.0;
//For each label option ..
// NOTE: for CRF we had this code:
//for (int j = 0; j < crf.getOutputAlphabet().size(); j++) {
// String label = crf.getOutputAlphabet().lookupObject(j).toString();
// but for Transducer we do not have the getOutputAlphabet method so we use
// model.getInputPipe().getTargetAlphabet() instead (this seems to be what
// is used inside CRF anyway.)
for (int j = 0; j < crf.getInputPipe().getTargetAlphabet().size(); j++) {
String label = crf.getInputPipe().getTargetAlphabet().lookupObject(j).toString();
//Get the probability of being in state j at position i+1
//Note that the plus one is because the labels are on the
//transitions. Positions are between transitions.
double marg = sl.getGammaProbability(i, crf.getState(j));
if (marg > bestProb) {
bestLabel = label;
bestProb = marg;
}
}
GateClassification gc = new GateClassification(
instanceAnn, bestLabel, bestProb, sequenceSpanId);
gcs.add(gc);
}
}
}
data.startGrowth();
return gcs;
}
@Override
protected void loadMalletCorpusRepresentation(File directory) {
corpusRepresentationMallet = CorpusRepresentationMalletSeq.load(directory);
}
@Override
protected void loadModel(File directory, String parms) {
File modelFile = new File(directory, FILENAME_MODEL);
if (!modelFile.exists()) {
throw new GateRuntimeException("Cannot load model file, does not exist: " + modelFile);
}
Transducer classifier;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(modelFile));
classifier = (CRF) ois.readObject();
model=classifier;
} catch (Exception ex) {
throw new GateRuntimeException("Could not load Mallet model", ex);
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException ex) {
logger.error("Could not close object input stream after loading model", ex);
}
}
}
}
@Override
// NOTE: this evaluates only the classification problem generated from the original chunking problem,
// so as for classification, we get accuracy estimates, not precision/recall/F-measure.
// We do not have anything in the LearningFramework for doing F-measure evaluation, this has to
// be done outside of the LF in some kind of wrapper or script that invokes the proper LF methods.
public EvaluationResult evaluate(String algorithmParameters, EvaluationMethod evaluationMethod, int numberOfFolds, double trainingFraction, int numberOfRepeats) {
EvaluationResult ret = null;
Parms parms = new Parms(algorithmParameters,"s:seed:i");
int seed = (Integer)parms.getValueOrElse("seed", 1);
if(evaluationMethod == EvaluationMethod.CROSSVALIDATION) {
InstanceList.CrossValidationIterator cvi = corpusRepresentationMallet.getRepresentationMallet().crossValidationIterator(numberOfFolds, seed);
if(algorithm instanceof AlgorithmClassification) {
double sumOfAccs = 0.0;
while(cvi.hasNext()) {
InstanceList[] il = cvi.nextSplit();
InstanceList trainSet = il[0];
InstanceList testSet = il[1];
Transducer crf = trainModel(trainSet, algorithmParameters);
sumOfAccs += crf.averageTokenAccuracy(testSet);
}
EvaluationResultClXval e = new EvaluationResultClXval();
e.internalEvaluationResult = null;
e.accuracyEstimate = sumOfAccs/numberOfFolds;
e.nrFolds = numberOfFolds;
ret = e;
} else {
throw new GateRuntimeException("Mallet evaluation: not available for regression!");
}
} else {
if(algorithm instanceof AlgorithmClassification) {
Random rnd = new Random(seed);
double sumOfAccs = 0.0;
for(int i = 0; i<numberOfRepeats; i++) {
InstanceList[] sets = corpusRepresentationMallet.getRepresentationMallet().split(rnd,
new double[]{trainingFraction, 1-trainingFraction});
Transducer crf = trainModel(sets[0], algorithmParameters);
sumOfAccs += crf.averageTokenAccuracy(sets[1]);
}
EvaluationResultClHO e = new EvaluationResultClHO();
e.internalEvaluationResult = null;
e.accuracyEstimate = sumOfAccs/numberOfRepeats;
e.trainingFraction = trainingFraction;
e.nrRepeats = numberOfRepeats;
ret = e;
} else {
throw new GateRuntimeException("Mallet evaluation: not available for regression!");
}
}
return ret;
}
}
| src/gate/plugin/learningframework/engines/EngineMalletSeq.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 gate.plugin.learningframework.engines;
import cc.mallet.fst.CRF;
import cc.mallet.fst.CRFOptimizableByLabelLikelihood;
import cc.mallet.fst.CRFTrainerByLabelLikelihood;
import cc.mallet.fst.CRFTrainerByStochasticGradient;
import cc.mallet.fst.CRFTrainerByThreadedLabelLikelihood;
import cc.mallet.fst.CRFTrainerByValueGradients;
import cc.mallet.fst.MEMM;
import cc.mallet.fst.MEMMTrainer;
import cc.mallet.fst.SumLatticeDefault;
import cc.mallet.fst.Transducer;
import cc.mallet.fst.TransducerTrainer;
import cc.mallet.fst.ViterbiWriter;
import cc.mallet.optimize.Optimizable;
import cc.mallet.pipe.Pipe;
import cc.mallet.types.FeatureVectorSequence;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import gate.Annotation;
import gate.AnnotationSet;
import gate.plugin.learningframework.EvaluationMethod;
import gate.plugin.learningframework.GateClassification;
import gate.plugin.learningframework.data.CorpusRepresentationMalletSeq;
import static gate.plugin.learningframework.engines.Engine.FILENAME_MODEL;
import gate.plugin.learningframework.features.TargetType;
import gate.util.GateRuntimeException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.log4j.Logger;
/**
*
* @author Johann Petrak
*/
public class EngineMalletSeq extends EngineMallet {
private static Logger logger = Logger.getLogger(EngineMalletSeq.class);
@Override
public void initializeAlgorithm(Algorithm algorithm, String parms) {
// DOES NOTHINIG?
}
public AlgorithmKind getAlgorithmKind() {
return AlgorithmKind.SEQUENCE_TAGGER;
}
@Override
public void trainModel(File DataDirectory, String instanceType, String options) {
InstanceList trainingData = corpusRepresentationMallet.getRepresentationMallet();
Transducer td = trainModel(trainingData,options);
model = td;
updateInfo();
}
public static TransducerTrainer createTrainer(InstanceList trainingData, Info info, String options) {
TransducerTrainer transtrainer = null;
// NOTE: Training of the CRF is very flexible in Mallet and not everything is clear to me
// yet. Unfortunately, there is practically no documentation available.
// There is some useful example code around:
// http://mallet.cs.umass.edu/fst.php - the only real documentation available
// src/cc/mallet/examples/TrainCRF.java - very basic example
// src/cc/mallet/fst/SimpleTagger.java - more detailled: especially also shows multithreaded training!
// how to use this: http://mallet.cs.umass.edu/sequences.php
// NOTE: the name can come from an algorithm selected for classification OR an algorithm
// selected for actual sequence tagging. This is why we check the literal name here
// instead of something derived from the Algorithm enum class.
// NOTE on supported trainers: we only support trainers here which are not
// too complex to set up and which can be used with the normal succession of
// how training works in the LF.
// Mallet also supports a lot of additional things, e.g. regularization
// on unlabeled data, but this cannot be used here.
//
String alg = info.algorithmName;
System.err.println("DEBUG: our algorithm name is "+alg);
if(alg.startsWith("MALLET_SEQ_CRF")) {
CRF crf = new CRF(trainingData.getPipe(), null);
Parms parms = new Parms(options,
"S:states:s",
"o:orders:s",
"f:ofully:b",
"a:addstart:b",
"v:logViterbiPaths:i",
"t:threads:i",
"sg:stochasticGradient:b",
"wdd:weightDimDensely:b",
"usw:useSparseWeights:b",
"ssut:setSomeUnsupportedTrick:b");
String states = (String)parms.getValueOrElse("states", "fully-connected");
switch (states) {
case "fully-connected":
crf.addFullyConnectedStatesForLabels();
break;
case "as-in":
crf.addStatesForLabelsConnectedAsIn(trainingData);
break;
case "fully-threequarter":
crf.addFullyConnectedStatesForThreeQuarterLabels(trainingData);
break;
case "half":
crf.addStatesForHalfLabelsConnectedAsIn(trainingData);
break;
case "order-n":
int[] orders = new int[]{1};
String ordersparm = (String)parms.getValueOrElse("orders", "0:1");
if(ordersparm.equals("1")) {
orders = new int[]{1};
} else if(ordersparm.equals("0:1")) {
orders = new int[]{0,1};
} else if(ordersparm.equals("0:1:2")) {
orders = new int[]{0,1,2};
} else if(ordersparm.equals("0")) {
orders = new int[]{0};
} else if(ordersparm.equals("1:2")) {
orders = new int[]{1,2};
} else if(ordersparm.equals("2")) {
orders = new int[]{2};
} else {
throw new GateRuntimeException("Invalid value for parameter orders: "+ordersparm);
}
boolean ofully = (Boolean)parms.getValueOrElse("ofully", false);
crf.addOrderNStates(trainingData, orders, null, null, null, null, ofully);
break;
default:
throw new GateRuntimeException("Unknown value for parameter states: "+states);
}
boolean addStart = (boolean) parms.getValueOrElse("addstart", true);
if(addStart) crf.addStartState();
boolean wdd = (boolean) parms.getValueOrElse("weightDimDensely", false);
if(wdd) crf.setWeightsDimensionDensely();
// initialize model's weights
crf.setWeightsDimensionAsIn(trainingData, false);
// now depending on which trainer we want we need to do slightly different
// things
if(alg.equals("MALLET_SEQ_CRF")) { // By[Thread]LabelLikelihood
// if threads parameter is specified and >0, we use ByThreadLabelLikelihood
int threads = (int) parms.getValueOrElse("threads", 0);
boolean usw = (boolean) parms.getValueOrElse("useSparseWeights", false);
boolean ssut = (boolean) parms.getValueOrElse("setSomeUnsupportedTrick", false);
if(threads<=0) {
CRFTrainerByLabelLikelihood tr = new CRFTrainerByLabelLikelihood(crf);
if(usw) tr.setUseSparseWeights(true);
if(ssut) tr.setUseSomeUnsupportedTrick(true);
transtrainer = tr;
} else {
CRFTrainerByThreadedLabelLikelihood tr =
new CRFTrainerByThreadedLabelLikelihood(crf, threads);
if(usw) tr.setUseSparseWeights(true);
if(ssut) tr.setUseSomeUnsupportedTrick(true);
transtrainer = tr;
}
} else if(alg.equals("MALLET_SEQ_CRF_SG")) {
// TODO: instead of all trainingData, use sample?
// TODO: allow to use training rate instead of trainingData?
CRFTrainerByStochasticGradient crft =
new CRFTrainerByStochasticGradient(crf, trainingData);
} else if(alg.equals("MALLET_SEQ_CRF_VG")) {
// CRFOptimizableBy* objects (terms in the objective function)
// objective 1: label likelihood objective
CRFOptimizableByLabelLikelihood optLabel
= new CRFOptimizableByLabelLikelihood(crf, trainingData);
Optimizable.ByGradientValue[] opts
= new Optimizable.ByGradientValue[]{optLabel};
// by default, use L-BFGS as the optimizer
CRFTrainerByValueGradients crfTrainer = new CRFTrainerByValueGradients(crf, opts);
crfTrainer.setMaxResets(0);
transtrainer = crfTrainer;
} else {
throw new GateRuntimeException("Not yet supported: "+alg);
}
// TODO: if we want to output the viterbi paths:
int logVit = (int) parms.getValueOrElse("logViterbiPaths", 0);
if(logVit==0) logVit=Integer.MAX_VALUE;
final int lv = logVit;
ViterbiWriter viterbiWriter = new ViterbiWriter(
"LF_debug", // output file prefix
new InstanceList[] { trainingData },
new String[] { "train" }) {
@Override
public boolean precondition (TransducerTrainer tt) {
return tt.getIteration() % lv == 0;
}
};
transtrainer.addEvaluator(viterbiWriter);
} else if(alg.equals("MALLET_SEQ_MEMM")) {
// TODO:
MEMM memm = new MEMM(trainingData.getDataAlphabet(),trainingData.getTargetAlphabet());
transtrainer = new MEMMTrainer(memm);
} else {
// Nothing else supported!
throw new GateRuntimeException("EngineMalletSeq: unknown/unsupported algorithm: "+alg);
}
return transtrainer;
}
public Transducer trainModel(InstanceList trainingData, String options) {
TransducerTrainer trainer = createTrainer(trainingData, info, options);
Parms parms = new Parms(options,"i:iterations:i","V:verbose:b");
boolean verbose = (boolean)parms.getValueOrElse("verbose", false);
int iters = (int) parms.getValueOrElse("iterations", 0);
if(iters==0) iters = Integer.MAX_VALUE;
trainer.train(trainingData, iters);
if(verbose)
trainer.getTransducer().print();
Transducer td = trainer.getTransducer();
return td;
}
@Override
public List<GateClassification> classify(
AnnotationSet instanceAS, AnnotationSet inputAS, AnnotationSet sequenceAS, String parms) {
// stop growth
CorpusRepresentationMalletSeq data = (CorpusRepresentationMalletSeq)corpusRepresentationMallet;
data.stopGrowth();
List<GateClassification> gcs = new ArrayList<GateClassification>();
Transducer crf = (Transducer)model;
for(Annotation sequenceAnn : sequenceAS) {
int sequenceSpanId = sequenceAnn.getId();
Instance inst = data.getInstanceForSequence(
instanceAS, sequenceAnn, inputAS, null, null, TargetType.NONE, null);
//Always put the instance through the same pipe used for training.
inst = crf.getInputPipe().instanceFrom(inst);
SumLatticeDefault sl = new SumLatticeDefault(crf,
(FeatureVectorSequence) inst.getData());
List<Annotation> instanceAnnotations = gate.Utils.getContainedAnnotations(
instanceAS, sequenceAnn).inDocumentOrder();
//Sanity check that we're mapping the probs back onto the right anns.
//This being wrong might follow from errors reading in the data to mallet inst.
if (instanceAnnotations.size() != ((FeatureVectorSequence) inst.getData()).size()) {
logger.warn("LearningFramework: CRF output length: "
+ ((FeatureVectorSequence) inst.getData()).size()
+ ", GATE instances: " + instanceAnnotations.size()
+ ". Can't assign.");
} else {
int i = 0;
for (Annotation instanceAnn : instanceAnnotations) {
i++;
String bestLabel = null;
double bestProb = 0.0;
//For each label option ..
// NOTE: for CRF we had this code:
//for (int j = 0; j < crf.getOutputAlphabet().size(); j++) {
// String label = crf.getOutputAlphabet().lookupObject(j).toString();
// but for Transducer we do not have the getOutputAlphabet method so we use
// model.getInputPipe().getTargetAlphabet() instead (this seems to be what
// is used inside CRF anyway.)
for (int j = 0; j < crf.getInputPipe().getTargetAlphabet().size(); j++) {
String label = crf.getInputPipe().getTargetAlphabet().lookupObject(j).toString();
//Get the probability of being in state j at position i+1
//Note that the plus one is because the labels are on the
//transitions. Positions are between transitions.
double marg = sl.getGammaProbability(i, crf.getState(j));
if (marg > bestProb) {
bestLabel = label;
bestProb = marg;
}
}
GateClassification gc = new GateClassification(
instanceAnn, bestLabel, bestProb, sequenceSpanId);
gcs.add(gc);
}
}
}
data.startGrowth();
return gcs;
}
@Override
protected void loadMalletCorpusRepresentation(File directory) {
corpusRepresentationMallet = CorpusRepresentationMalletSeq.load(directory);
}
@Override
protected void loadModel(File directory, String parms) {
File modelFile = new File(directory, FILENAME_MODEL);
if (!modelFile.exists()) {
throw new GateRuntimeException("Cannot load model file, does not exist: " + modelFile);
}
Transducer classifier;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(modelFile));
classifier = (CRF) ois.readObject();
model=classifier;
} catch (Exception ex) {
throw new GateRuntimeException("Could not load Mallet model", ex);
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException ex) {
logger.error("Could not close object input stream after loading model", ex);
}
}
}
}
@Override
// NOTE: this evaluates only the classification problem generated from the original chunking problem,
// so as for classification, we get accuracy estimates, not precision/recall/F-measure.
// We do not have anything in the LearningFramework for doing F-measure evaluation, this has to
// be done outside of the LF in some kind of wrapper or script that invokes the proper LF methods.
public EvaluationResult evaluate(String algorithmParameters, EvaluationMethod evaluationMethod, int numberOfFolds, double trainingFraction, int numberOfRepeats) {
EvaluationResult ret = null;
Parms parms = new Parms(algorithmParameters,"s:seed:i");
int seed = (Integer)parms.getValueOrElse("seed", 1);
if(evaluationMethod == EvaluationMethod.CROSSVALIDATION) {
InstanceList.CrossValidationIterator cvi = corpusRepresentationMallet.getRepresentationMallet().crossValidationIterator(numberOfFolds, seed);
if(algorithm instanceof AlgorithmClassification) {
double sumOfAccs = 0.0;
while(cvi.hasNext()) {
InstanceList[] il = cvi.nextSplit();
InstanceList trainSet = il[0];
InstanceList testSet = il[1];
Transducer crf = trainModel(trainSet, algorithmParameters);
sumOfAccs += crf.averageTokenAccuracy(testSet);
}
EvaluationResultClXval e = new EvaluationResultClXval();
e.internalEvaluationResult = null;
e.accuracyEstimate = sumOfAccs/numberOfFolds;
e.nrFolds = numberOfFolds;
ret = e;
} else {
throw new GateRuntimeException("Mallet evaluation: not available for regression!");
}
} else {
if(algorithm instanceof AlgorithmClassification) {
Random rnd = new Random(seed);
double sumOfAccs = 0.0;
for(int i = 0; i<numberOfRepeats; i++) {
InstanceList[] sets = corpusRepresentationMallet.getRepresentationMallet().split(rnd,
new double[]{trainingFraction, 1-trainingFraction});
Transducer crf = trainModel(sets[0], algorithmParameters);
sumOfAccs += crf.averageTokenAccuracy(sets[1]);
}
EvaluationResultClHO e = new EvaluationResultClHO();
e.internalEvaluationResult = null;
e.accuracyEstimate = sumOfAccs/numberOfRepeats;
e.trainingFraction = trainingFraction;
e.nrRepeats = numberOfRepeats;
ret = e;
} else {
throw new GateRuntimeException("Mallet evaluation: not available for regression!");
}
}
return ret;
}
}
| Add comment about parameter/option.
| src/gate/plugin/learningframework/engines/EngineMalletSeq.java | Add comment about parameter/option. | <ide><path>rc/gate/plugin/learningframework/engines/EngineMalletSeq.java
<ide> if(wdd) crf.setWeightsDimensionDensely();
<ide>
<ide> // initialize model's weights
<add> // TODO: make this conditional on a parm, how does this relate to
<add> // weightDimDensely??
<add> // !!! This should probably be the same parameter!!!
<add> // TODO: second parm should depend on the unsupported trick option!
<ide> crf.setWeightsDimensionAsIn(trainingData, false);
<ide>
<ide> // now depending on which trainer we want we need to do slightly different |
|
Java | apache-2.0 | 5dd17f754d7a0ae1eade7e5a9ea5ec9ca4b67de6 | 0 | NessComputing/components-ness-pg,NessComputing/components-ness-pg | /**
* Copyright (C) 2012 Ness Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nesscomputing.db.postgres.embedded;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.postgresql.jdbc2.optional.SimpleDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmbeddedPostgreSQL implements Closeable
{
private static final Logger LOG = LoggerFactory.getLogger(EmbeddedPostgreSQL.class);
private static final String JDBC_FORMAT = "jdbc:postgresql://localhost:%s/%s?user=%s";
private static final String PG_STOP_MODE = "fast";
private static final String PG_STOP_WAIT_S = "5";
private static final String PG_SUPERUSER = "postgres";
private static final int PG_STARTUP_WAIT_MS = 10 * 1000;
private static final String PG_DIGEST;
private static final String TMP_DIR_LOC = System.getProperty("java.io.tmpdir");
private static final File TMP_DIR = new File(TMP_DIR_LOC, "embedded-pg");
private static final String LOCK_FILE_NAME = "epg-lock";
private static final String UNAME_S, UNAME_M;
private static final File PG_DIR;
private final File dataDirectory, lockFile;
private final UUID instanceId = UUID.randomUUID();
private final int port;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
private final Map<String, String> postgresConfig;
private volatile Process postmaster;
private volatile FileOutputStream lockStream;
private volatile FileLock lock;
private final boolean cleanDataDirectory;
EmbeddedPostgreSQL(File parentDirectory, File dataDirectory, boolean cleanDataDirectory, Map<String, String> postgresConfig) throws IOException
{
this.cleanDataDirectory = cleanDataDirectory;
this.postgresConfig = ImmutableMap.copyOf(postgresConfig);
port = detectPort();
if (parentDirectory != null) {
mkdirs(parentDirectory);
cleanOldDataDirectories(parentDirectory);
this.dataDirectory = Objects.firstNonNull(dataDirectory, new File(parentDirectory, instanceId.toString()));
} else {
this.dataDirectory = dataDirectory;
}
Preconditions.checkArgument(this.dataDirectory != null, "null data directory");
LOG.trace("{} postgres data directory is {}", instanceId, this.dataDirectory);
Preconditions.checkState(this.dataDirectory.exists() || this.dataDirectory.mkdir(), "Failed to mkdir %s", this.dataDirectory);
lockFile = new File(this.dataDirectory, LOCK_FILE_NAME);
if (cleanDataDirectory || !new File(dataDirectory, "postgresql.conf").exists()) {
initdb();
}
lock();
startPostmaster();
}
public DataSource getTemplateDatabase()
{
return getDatabase("postgres", "template1");
}
public DataSource getPostgresDatabase()
{
return getDatabase("postgres", "postgres");
}
public DataSource getDatabase(String userName, String dbName)
{
final SimpleDataSource ds = new SimpleDataSource();
ds.setServerName("localhost");
ds.setPortNumber(port);
ds.setDatabaseName(dbName);
ds.setUser(userName);
return ds;
}
public String getJdbcUrl(String userName, String dbName)
{
return String.format(JDBC_FORMAT, port, dbName, userName);
}
public int getPort()
{
return port;
}
private int detectPort() throws IOException
{
final ServerSocket socket = new ServerSocket(0);
try {
return socket.getLocalPort();
} finally {
socket.close();
}
}
private void lock() throws IOException
{
lockStream = new FileOutputStream(lockFile);
Preconditions.checkState((lock = lockStream.getChannel().tryLock()) != null, "could not lock %s", lockFile);
}
private void initdb()
{
final StopWatch watch = new StopWatch();
watch.start();
system(pgBin("initdb"), "-A", "trust", "-U", PG_SUPERUSER, "-D", dataDirectory.getPath(), "-E", "UTF-8");
LOG.info("{} initdb completed in {}", instanceId, watch);
}
private void startPostmaster() throws IOException
{
final StopWatch watch = new StopWatch();
watch.start();
Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");
final List<String> args = Lists.newArrayList(
pgBin("postgres"),
"-D", dataDirectory.getPath(),
"-p", Integer.toString(port),
"-i",
"-F");
for (final Entry<String, String> config : postgresConfig.entrySet())
{
args.add("-c");
args.add(config.getKey() + "=" + config.getValue());
}
final ProcessBuilder builder = new ProcessBuilder(args);
builder.redirectErrorStream(true);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
postmaster = builder.start();
LOG.info("{} postmaster started as {} on port {}. Waiting up to {}ms for server startup to finish.", instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);
Runtime.getRuntime().addShutdownHook(newCloserThread());
waitForServerStartup(watch);
}
private void waitForServerStartup(StopWatch watch) throws UnknownHostException, IOException
{
Throwable lastCause = null;
final long start = System.nanoTime();
final long maxWaitNs = TimeUnit.NANOSECONDS.convert(PG_STARTUP_WAIT_MS, TimeUnit.MILLISECONDS);
while (System.nanoTime() - start < maxWaitNs) {
try {
checkReady();
LOG.info("{} postmaster startup finished in {}", instanceId, watch);
return;
} catch (final SQLException e) {
lastCause = e;
LOG.trace("While waiting for server startup", e);
}
try {
throw new IOException(String.format("%s postmaster exited with value %d, check standard out for more detail!", instanceId, postmaster.exitValue()));
} catch (final IllegalThreadStateException e) {
// Process is not yet dead, loop and try again
LOG.trace("While waiting for server startup", e);
}
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
throw new IOException("Gave up waiting for server to start after " + PG_STARTUP_WAIT_MS + "ms", lastCause);
}
private void checkReady() throws SQLException
{
try (final Connection c = getPostgresDatabase().getConnection()) {
try (final Statement s = c.createStatement()) {
try (final ResultSet rs = s.executeQuery("SELECT 1")) { // NOPMD
Preconditions.checkState(rs.next() == true, "expecting single row");
Preconditions.checkState(1 == rs.getInt(1), "expecting 1");
Preconditions.checkState(rs.next() == false, "expecting single row");
}
}
}
}
private Thread newCloserThread()
{
final Thread closeThread = new Thread(new Runnable() {
@Override
public void run()
{
try {
Closeables.close(EmbeddedPostgreSQL.this, true);
}
catch (IOException ex) {
LOG.error("Unexpected IOException from Closeables.close", ex);
}
}
});
closeThread.setName("postgres-" + instanceId + "-closer");
return closeThread;
}
@Override
public void close() throws IOException
{
if (closed.getAndSet(true)) {
return;
}
final StopWatch watch = new StopWatch();
watch.start();
try {
pgCtl(dataDirectory, "stop");
LOG.info("{} shut down postmaster in {}", instanceId, watch);
} catch (final Exception e) {
LOG.error("Could not stop postmaster " + instanceId, e);
}
if (lock != null) {
lock.release();
}
Closeables.close(lockStream, true);
if (cleanDataDirectory && System.getProperty("ness.epg.no-cleanup") == null) {
FileUtils.deleteDirectory(dataDirectory);
} else {
LOG.info("Did not clean up directory {}", dataDirectory.getAbsolutePath());
}
}
private void pgCtl(File dir, String action)
{
system(pgBin("pg_ctl"), "-D", dir.getPath(), action, "-m", PG_STOP_MODE, "-t", PG_STOP_WAIT_S, "-w");
}
private void cleanOldDataDirectories(File parentDirectory)
{
for (final File dir : parentDirectory.listFiles())
{
if (!dir.isDirectory()) {
continue;
}
final File lockFile = new File(dir, LOCK_FILE_NAME);
if (!lockFile.exists()) {
continue;
}
try {
final FileOutputStream fos = new FileOutputStream(lockFile);
try {
try (FileLock lock = fos.getChannel().tryLock()) {
if (lock != null) {
LOG.info("Found stale data directory {}", dir);
if (new File(dir, "postmaster.pid").exists()) {
try {
pgCtl(dir, "stop");
LOG.info("Shut down orphaned postmaster!");
} catch (Exception e) {
LOG.warn("Failed to stop postmaster " + dir, e);
}
}
FileUtils.deleteDirectory(dir);
}
}
} finally {
fos.close();
}
} catch (final OverlappingFileLockException e) {
// The directory belongs to another instance in this VM.
LOG.trace("While cleaning old data directories", e);
} catch (final Exception e) {
LOG.warn("While cleaning old data directories", e);
}
}
}
private static String pgBin(String binaryName)
{
return new File(PG_DIR, "bin/" + binaryName).getPath();
}
public static EmbeddedPostgreSQL start() throws IOException
{
return builder().start();
}
public static EmbeddedPostgreSQL.Builder builder()
{
return new Builder();
}
public static class Builder
{
private final File parentDirectory = new File(System.getProperty("ness.embedded-pg.dir", TMP_DIR.getPath()));
private File dataDirectory;
private final Map<String, String> config = Maps.newHashMap();
private boolean cleanDataDirectory = true;
Builder() {
config.put("timezone", "UTC");
config.put("synchronous_commit", "off");
config.put("checkpoint_segments", "64");
config.put("max_connections", "300");
}
public Builder setCleanDataDirectory(boolean cleanDataDirectory)
{
this.cleanDataDirectory = cleanDataDirectory;
return this;
}
public Builder setDataDirectory(File directory)
{
dataDirectory = directory;
return this;
}
public Builder setServerConfig(String key, String value)
{
config.put(key, value);
return this;
}
public EmbeddedPostgreSQL start() throws IOException
{
return new EmbeddedPostgreSQL(parentDirectory, dataDirectory, cleanDataDirectory, config);
}
}
private static List<String> system(String... command)
{
try {
final Process process = new ProcessBuilder(command).start();
Preconditions.checkState(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command), IOUtils.toString(process.getErrorStream()));
try (InputStream stream = process.getInputStream()) {
return IOUtils.readLines(stream);
}
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
private static void mkdirs(File dir)
{
Preconditions.checkState(dir.mkdirs() || (dir.isDirectory() && dir.exists()), // NOPMD
"could not create %s", dir);
}
static {
UNAME_S = system("uname", "-s").get(0);
UNAME_M = system("uname", "-m").get(0);
LOG.info("Detected a {} {} system", UNAME_S, UNAME_M);
File pgTbz;
try {
pgTbz = File.createTempFile("pgpg", "pgpg");
} catch (final IOException e) {
throw new ExceptionInInitializerError(e);
}
try {
final DigestInputStream pgArchiveData = new DigestInputStream(
EmbeddedPostgreSQL.class.getResourceAsStream(String.format("/postgresql-%s-%s.tbz", UNAME_S, UNAME_M)),
MessageDigest.getInstance("MD5"));
final FileOutputStream os = new FileOutputStream(pgTbz);
IOUtils.copy(pgArchiveData, os);
pgArchiveData.close();
os.close();
PG_DIGEST = Hex.encodeHexString(pgArchiveData.getMessageDigest().digest());
PG_DIR = new File(TMP_DIR, String.format("PG-%s", PG_DIGEST));
mkdirs(PG_DIR);
final File unpackLockFile = new File(PG_DIR, LOCK_FILE_NAME);
final File pgDirExists = new File(PG_DIR, ".exists");
if (!pgDirExists.exists()) {
try (final FileOutputStream lockStream = new FileOutputStream(unpackLockFile);
final FileLock unpackLock = lockStream.getChannel().tryLock()) {
if (unpackLock != null) {
try {
Preconditions.checkState(!pgDirExists.exists(), "unpack lock acquired but .exists file is present.");
LOG.info("Extracting Postgres...");
system("tar", "-x", "-f", pgTbz.getPath(), "-C", PG_DIR.getPath());
Files.touch(pgDirExists);
} finally {
Preconditions.checkState(unpackLockFile.delete(), "could not remove lock file %s", unpackLockFile.getAbsolutePath());
}
} else {
// the other guy is unpacking for us.
int maxAttempts = 60;
while (!pgDirExists.exists() && --maxAttempts > 0) {
Thread.sleep(1000L);
}
Preconditions.checkState(pgDirExists.exists(), "Waited 60 seconds for postgres to be unpacked but it never finished!");
}
}
}
} catch (final IOException | NoSuchAlgorithmException e) {
throw new ExceptionInInitializerError(e);
} catch (final InterruptedException ie) {
Thread.currentThread().interrupt();
throw new ExceptionInInitializerError(ie);
} finally {
Preconditions.checkState(pgTbz.delete(), "could not delete %s", pgTbz);
}
LOG.info("Postgres binaries at {}", PG_DIR);
}
@Override
public String toString()
{
return "EmbeddedPG-" + instanceId;
}
}
| src/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQL.java | /**
* Copyright (C) 2012 Ness Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nesscomputing.db.postgres.embedded;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.postgresql.jdbc2.optional.SimpleDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmbeddedPostgreSQL implements Closeable
{
private static final Logger LOG = LoggerFactory.getLogger(EmbeddedPostgreSQL.class);
private static final String JDBC_FORMAT = "jdbc:postgresql://localhost:%s/%s?user=%s";
private static final String PG_STOP_MODE = "fast";
private static final String PG_STOP_WAIT_S = "5";
private static final String PG_SUPERUSER = "postgres";
private static final int PG_STARTUP_WAIT_MS = 10 * 1000;
private static final String PG_DIGEST;
private static final String TMP_DIR_LOC = System.getProperty("java.io.tmpdir");
private static final File TMP_DIR = new File(TMP_DIR_LOC, "embedded-pg");
private static final String LOCK_FILE_NAME = "epg-lock";
private static final String UNAME_S, UNAME_M;
private static final File PG_DIR;
private final File dataDirectory, lockFile;
private final UUID instanceId = UUID.randomUUID();
private final int port;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
private final Map<String, String> postgresConfig;
private volatile Process postmaster;
private volatile FileOutputStream lockStream;
private volatile FileLock lock;
private final boolean cleanDataDirectory;
EmbeddedPostgreSQL(File parentDirectory, File dataDirectory, boolean cleanDataDirectory, Map<String, String> postgresConfig) throws IOException
{
this.cleanDataDirectory = cleanDataDirectory;
this.postgresConfig = ImmutableMap.copyOf(postgresConfig);
port = detectPort();
if (parentDirectory != null) {
mkdirs(parentDirectory);
cleanOldDataDirectories(parentDirectory);
this.dataDirectory = Objects.firstNonNull(dataDirectory, new File(parentDirectory, instanceId.toString()));
} else {
this.dataDirectory = dataDirectory;
}
Preconditions.checkArgument(this.dataDirectory != null, "null data directory");
LOG.trace("{} postgres data directory is {}", instanceId, this.dataDirectory);
Preconditions.checkState(this.dataDirectory.exists() || this.dataDirectory.mkdir(), "Failed to mkdir %s", this.dataDirectory);
lockFile = new File(this.dataDirectory, LOCK_FILE_NAME);
if (cleanDataDirectory || !new File(dataDirectory, "postgresql.conf").exists()) {
initdb();
}
lock();
startPostmaster();
}
public DataSource getTemplateDatabase()
{
return getDatabase("postgres", "template1");
}
public DataSource getPostgresDatabase()
{
return getDatabase("postgres", "postgres");
}
public DataSource getDatabase(String userName, String dbName)
{
final SimpleDataSource ds = new SimpleDataSource();
ds.setServerName("localhost");
ds.setPortNumber(port);
ds.setDatabaseName(dbName);
ds.setUser(userName);
return ds;
}
public String getJdbcUrl(String userName, String dbName)
{
return String.format(JDBC_FORMAT, port, dbName, userName);
}
public int getPort()
{
return port;
}
private int detectPort() throws IOException
{
final ServerSocket socket = new ServerSocket(0);
try {
return socket.getLocalPort();
} finally {
socket.close();
}
}
private void lock() throws IOException
{
lockStream = new FileOutputStream(lockFile);
Preconditions.checkState((lock = lockStream.getChannel().tryLock()) != null, "could not lock %s", lockFile);
}
private void initdb()
{
final StopWatch watch = new StopWatch();
watch.start();
system(pgBin("initdb"), "-A", "trust", "-U", PG_SUPERUSER, "-D", dataDirectory.getPath(), "-E", "UTF-8");
LOG.info("{} initdb completed in {}", instanceId, watch);
}
private void startPostmaster() throws IOException
{
final StopWatch watch = new StopWatch();
watch.start();
Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");
final List<String> args = Lists.newArrayList(
pgBin("postgres"),
"-D", dataDirectory.getPath(),
"-p", Integer.toString(port),
"-i",
"-F");
for (final Entry<String, String> config : postgresConfig.entrySet())
{
args.add("-c");
args.add(config.getKey() + "=" + config.getValue());
}
final ProcessBuilder builder = new ProcessBuilder(args);
builder.redirectErrorStream(true);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
postmaster = builder.start();
LOG.info("{} postmaster started as {} on port {}. Waiting up to {}ms for server startup to finish.", instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);
Runtime.getRuntime().addShutdownHook(newCloserThread());
waitForServerStartup(watch);
}
private void waitForServerStartup(StopWatch watch) throws UnknownHostException, IOException
{
Throwable lastCause = null;
final long start = System.nanoTime();
final long maxWaitNs = TimeUnit.NANOSECONDS.convert(PG_STARTUP_WAIT_MS, TimeUnit.MILLISECONDS);
while (System.nanoTime() - start < maxWaitNs) {
try {
checkReady();
LOG.info("{} postmaster startup finished in {}", instanceId, watch);
return;
} catch (final SQLException e) {
lastCause = e;
LOG.trace("While waiting for server startup", e);
}
try {
throw new IOException(String.format("%s postmaster exited with value %d, check standard out for more detail!", instanceId, postmaster.exitValue()));
} catch (final IllegalThreadStateException e) {
// Process is not yet dead, loop and try again
LOG.trace("While waiting for server startup", e);
}
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
throw new IOException("Gave up waiting for server to start after " + PG_STARTUP_WAIT_MS + "ms", lastCause);
}
private void checkReady() throws SQLException
{
try (final Connection c = getPostgresDatabase().getConnection()) {
try (final Statement s = c.createStatement()) {
try (final ResultSet rs = s.executeQuery("SELECT 1")) { // NOPMD
Preconditions.checkState(rs.next() == true, "expecting single row");
Preconditions.checkState(1 == rs.getInt(1), "expecting 1");
Preconditions.checkState(rs.next() == false, "expecting single row");
}
}
}
}
private Thread newCloserThread()
{
final Thread closeThread = new Thread(new Runnable() {
@Override
public void run()
{
try {
Closeables.close(EmbeddedPostgreSQL.this, true);
}
catch (IOException ex) {
LOG.error("Unexpected IOException from Closeables.close", ex);
}
}
});
closeThread.setName("postgres-" + instanceId + "-closer");
return closeThread;
}
@Override
public void close() throws IOException
{
if (closed.getAndSet(true)) {
return;
}
final StopWatch watch = new StopWatch();
watch.start();
try {
pgCtl(dataDirectory, "stop");
LOG.info("{} shut down postmaster in {}", instanceId, watch);
} catch (final Exception e) {
LOG.error("Could not stop postmaster " + instanceId, e);
}
if (lock != null) {
lock.release();
}
Closeables.close(lockStream, true);
if (cleanDataDirectory && System.getProperty("ness.epg.no-cleanup") == null) {
FileUtils.deleteDirectory(dataDirectory);
} else {
LOG.info("Did not clean up directory {}", dataDirectory.getAbsolutePath());
}
}
private void pgCtl(File dir, String action)
{
system(pgBin("pg_ctl"), "-D", dir.getPath(), action, "-m", PG_STOP_MODE, "-t", PG_STOP_WAIT_S, "-w");
}
private void cleanOldDataDirectories(File parentDirectory)
{
for (final File dir : parentDirectory.listFiles())
{
if (!dir.isDirectory()) {
continue;
}
final File lockFile = new File(dir, LOCK_FILE_NAME);
if (!lockFile.exists()) {
continue;
}
try {
final FileOutputStream fos = new FileOutputStream(lockFile);
try {
try (FileLock lock = fos.getChannel().tryLock()) {
if (lock != null) {
LOG.info("Found stale data directory {}", dir);
if (new File(dir, "postmaster.pid").exists()) {
pgCtl(dir, "stop");
LOG.info("Shut down orphaned postmaster!");
}
FileUtils.deleteDirectory(dir);
}
}
} finally {
fos.close();
}
} catch (final OverlappingFileLockException e) {
// The directory belongs to another instance in this VM.
LOG.trace("While cleaning old data directories", e);
} catch (final Exception e) {
LOG.warn("While cleaning old data directories", e);
}
}
}
private static String pgBin(String binaryName)
{
return new File(PG_DIR, "bin/" + binaryName).getPath();
}
public static EmbeddedPostgreSQL start() throws IOException
{
return builder().start();
}
public static EmbeddedPostgreSQL.Builder builder()
{
return new Builder();
}
public static class Builder
{
private final File parentDirectory = new File(System.getProperty("ness.embedded-pg.dir", TMP_DIR.getPath()));
private File dataDirectory;
private final Map<String, String> config = Maps.newHashMap();
private boolean cleanDataDirectory = true;
Builder() {
config.put("timezone", "UTC");
config.put("synchronous_commit", "off");
config.put("checkpoint_segments", "64");
config.put("max_connections", "300");
}
public Builder setCleanDataDirectory(boolean cleanDataDirectory)
{
this.cleanDataDirectory = cleanDataDirectory;
return this;
}
public Builder setDataDirectory(File directory)
{
dataDirectory = directory;
return this;
}
public Builder setServerConfig(String key, String value)
{
config.put(key, value);
return this;
}
public EmbeddedPostgreSQL start() throws IOException
{
return new EmbeddedPostgreSQL(parentDirectory, dataDirectory, cleanDataDirectory, config);
}
}
private static List<String> system(String... command)
{
try {
final Process process = new ProcessBuilder(command).start();
Preconditions.checkState(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command), IOUtils.toString(process.getErrorStream()));
try (InputStream stream = process.getInputStream()) {
return IOUtils.readLines(stream);
}
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
private static void mkdirs(File dir)
{
Preconditions.checkState(dir.mkdirs() || (dir.isDirectory() && dir.exists()), // NOPMD
"could not create %s", dir);
}
static {
UNAME_S = system("uname", "-s").get(0);
UNAME_M = system("uname", "-m").get(0);
LOG.info("Detected a {} {} system", UNAME_S, UNAME_M);
File pgTbz;
try {
pgTbz = File.createTempFile("pgpg", "pgpg");
} catch (final IOException e) {
throw new ExceptionInInitializerError(e);
}
try {
final DigestInputStream pgArchiveData = new DigestInputStream(
EmbeddedPostgreSQL.class.getResourceAsStream(String.format("/postgresql-%s-%s.tbz", UNAME_S, UNAME_M)),
MessageDigest.getInstance("MD5"));
final FileOutputStream os = new FileOutputStream(pgTbz);
IOUtils.copy(pgArchiveData, os);
pgArchiveData.close();
os.close();
PG_DIGEST = Hex.encodeHexString(pgArchiveData.getMessageDigest().digest());
PG_DIR = new File(TMP_DIR, String.format("PG-%s", PG_DIGEST));
mkdirs(PG_DIR);
final File unpackLockFile = new File(PG_DIR, LOCK_FILE_NAME);
final File pgDirExists = new File(PG_DIR, ".exists");
if (!pgDirExists.exists()) {
try (final FileOutputStream lockStream = new FileOutputStream(unpackLockFile);
final FileLock unpackLock = lockStream.getChannel().tryLock()) {
if (unpackLock != null) {
try {
Preconditions.checkState(!pgDirExists.exists(), "unpack lock acquired but .exists file is present.");
LOG.info("Extracting Postgres...");
system("tar", "-x", "-f", pgTbz.getPath(), "-C", PG_DIR.getPath());
Files.touch(pgDirExists);
} finally {
Preconditions.checkState(unpackLockFile.delete(), "could not remove lock file %s", unpackLockFile.getAbsolutePath());
}
} else {
// the other guy is unpacking for us.
int maxAttempts = 60;
while (!pgDirExists.exists() && --maxAttempts > 0) {
Thread.sleep(1000L);
}
Preconditions.checkState(pgDirExists.exists(), "Waited 60 seconds for postgres to be unpacked but it never finished!");
}
}
}
} catch (final IOException | NoSuchAlgorithmException e) {
throw new ExceptionInInitializerError(e);
} catch (final InterruptedException ie) {
Thread.currentThread().interrupt();
throw new ExceptionInInitializerError(ie);
} finally {
Preconditions.checkState(pgTbz.delete(), "could not delete %s", pgTbz);
}
LOG.info("Postgres binaries at {}", PG_DIR);
}
@Override
public String toString()
{
return "EmbeddedPG-" + instanceId;
}
}
| Don't bail if postmaster cleanup fails
Fixes #16
| src/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQL.java | Don't bail if postmaster cleanup fails Fixes #16 | <ide><path>rc/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQL.java
<ide> if (lock != null) {
<ide> LOG.info("Found stale data directory {}", dir);
<ide> if (new File(dir, "postmaster.pid").exists()) {
<del> pgCtl(dir, "stop");
<del> LOG.info("Shut down orphaned postmaster!");
<add> try {
<add> pgCtl(dir, "stop");
<add> LOG.info("Shut down orphaned postmaster!");
<add> } catch (Exception e) {
<add> LOG.warn("Failed to stop postmaster " + dir, e);
<add> }
<ide> }
<ide> FileUtils.deleteDirectory(dir);
<ide> } |
|
Java | apache-2.0 | fb7dad3c489411354b19daa0e5ebf8aacb37a3e8 | 0 | seema-at-box/box-android-browse-sdk,box/box-android-browse-sdk,seema-at-box/box-android-browse-sdk,box/box-android-browse-sdk | package com.box.androidsdk.browse.fragments;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.box.androidsdk.browse.R;
import com.box.androidsdk.browse.activities.BoxBrowseActivity;
import com.box.androidsdk.browse.uidata.BoxListItem;
import com.box.androidsdk.browse.uidata.ThumbnailManager;
import com.box.androidsdk.content.BoxApiFile;
import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.models.BoxFile;
import com.box.androidsdk.content.models.BoxFolder;
import com.box.androidsdk.content.models.BoxItem;
import com.box.androidsdk.content.models.BoxListItems;
import com.box.androidsdk.content.models.BoxSession;
import com.box.androidsdk.content.requests.BoxRequestsFile;
import com.box.androidsdk.content.utils.SdkUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link BoxBrowseFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
*/
public abstract class BoxBrowseFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public static final String ARG_ID = "argId";
public static final String ARG_USER_ID = "argUserId";
public static final String ARG_NAME = "argName";
public static final String TAG = BoxBrowseFragment.class.getName();
protected static final int DEFAULT_LIMIT = 1000;
protected static final String ACTION_FETCHED_ITEMS = "BoxBrowseFragment_FetchedItems";
protected static final String ACTION_FETCHED_INFO = "BoxBrowseFragment_FetchedInfo";
protected static final String ACTION_DOWNLOADED_FILE_THUMBNAIL = "BoxBrowseFragment_DownloadedFileThumbnail";
protected static final String EXTRA_SUCCESS = "BoxBrowseFragment_ArgSuccess";
protected static final String EXTRA_EXCEPTION = "BoxBrowseFragment_ArgException";
protected static final String EXTRA_ID = "BoxBrowseFragment_FolderId";
protected static final String EXTRA_FILE_ID = "BoxBrowseFragment_FileId";
protected static final String EXTRA_OFFSET = "BoxBrowseFragment_ArgOffset";
protected static final String EXTRA_LIMIT = "BoxBrowseFragment_Limit";
protected static final String EXTRA_FOLDER = "BoxBrowseFragment_Folder";
protected static final String EXTRA_COLLECTION = "BoxBrowseFragment_Collection";
private static List<String> THUMBNAIL_MEDIA_EXTENSIONS = Arrays.asList(new String[] {"gif", "jpeg", "jpg", "bmp", "svg", "png", "tiff"});
protected String mUserId;
protected BoxSession mSession;
private BoxListItems mBoxListItems;
protected OnFragmentInteractionListener mListener;
protected BoxItemAdapter mAdapter;
protected RecyclerView mItemsView;
protected ThumbnailManager mThumbnailManager;
protected SwipeRefreshLayout mSwipeRefresh;
protected LocalBroadcastManager mLocalBroadcastManager;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_DOWNLOADED_FILE_THUMBNAIL)) {
onDownloadedThumbnail(intent);
} else {
// Handle response
if (intent.getAction().equals(ACTION_FETCHED_INFO)) {
onInfoFetched(intent);
} else if (intent.getAction().equals(ACTION_FETCHED_ITEMS)) {
onItemsFetched(intent);
}
// Remove refreshing icon
if (mSwipeRefresh != null) {
mSwipeRefresh.setRefreshing(false);
}
}
}
};
private static ThreadPoolExecutor mApiExecutor;
private static ThreadPoolExecutor mThumbnailExecutor;
protected ThreadPoolExecutor getApiExecutor() {
if (mApiExecutor == null || mApiExecutor.isShutdown()) {
mApiExecutor = new ThreadPoolExecutor(1, 1, 3600, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
return mApiExecutor;
}
/**
* Executor that we will submit thumbnail tasks to.
*
* @return executor
*/
protected ThreadPoolExecutor getThumbnailExecutor() {
if (mThumbnailExecutor == null || mThumbnailExecutor.isShutdown()) {
mThumbnailExecutor = new ThreadPoolExecutor(1, 10, 3600, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
return mThumbnailExecutor;
}
protected IntentFilter initializeIntentFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_FETCHED_INFO);
filter.addAction(ACTION_FETCHED_ITEMS);
filter.addAction(ACTION_DOWNLOADED_FILE_THUMBNAIL);
return filter;
}
public BoxBrowseFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize broadcast managers
mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
if (getArguments() != null) {
mUserId = getArguments().getString(ARG_USER_ID);
mThumbnailManager = initializeThumbnailManager();
mUserId = getArguments().getString(ARG_USER_ID);
mSession = new BoxSession(getActivity(), mUserId);
}
if (savedInstanceState != null) {
setListItem((BoxListItems) savedInstanceState.getSerializable(EXTRA_COLLECTION));
}
}
@Override
public void onResume() {
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, initializeIntentFilters());
super.onResume();
}
@Override
public void onPause() {
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(EXTRA_COLLECTION, mBoxListItems);
super.onSaveInstanceState(outState);
}
private ThumbnailManager initializeThumbnailManager() {
try {
return new ThumbnailManager(getActivity().getCacheDir());
} catch (FileNotFoundException e) {
// TODO: Call error handler
return null;
}
}
protected void setToolbar(String name) {
if (getActivity() != null && getActivity() instanceof AppCompatActivity) {
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (toolbar != null) {
toolbar.setTitle(name);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.box_browsesdk_fragment_browse, container, false);
mSwipeRefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.box_browsesdk_swipe_reresh);
mSwipeRefresh.setOnRefreshListener(this);
mSwipeRefresh.setColorSchemeColors(R.color.box_accent);
// This is a work around to show the loading circle because SwipeRefreshLayout.onMeasure must be called before setRefreshing to show the animation
mSwipeRefresh.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
mItemsView = (RecyclerView) rootView.findViewById(R.id.box_browsesdk_items_recycler_view);
mItemsView.addItemDecoration(new BoxItemDividerDecoration(getResources()));
mItemsView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new BoxItemAdapter();
mItemsView.setAdapter(mAdapter);
if (mBoxListItems == null) {
mAdapter.add(new BoxListItem(fetchInfo(), ACTION_FETCHED_INFO));
} else {
displayBoxList(mBoxListItems);
}
return rootView;
}
protected void setListItem(final BoxListItems items) {
mBoxListItems = items;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
@Override
public void onRefresh() {
mSwipeRefresh.setRefreshing(true);
getApiExecutor().execute(fetchInfo());
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
protected void onInfoFetched(Intent intent) {
onItemsFetched(intent);
}
/**
* Fetch the first information relevant to this fragment or what should be used for refreshing.
*
* @return A FutureTask that is tasked with fetching the first information relevant to this fragment or what should be used for refreshing.
*/
public abstract FutureTask<Intent> fetchInfo();
/**
* Handle showing a collection in the given intent.
*
* @param intent an intent that contains a collection in EXTRA_COLLECTION.
*/
protected void onItemsFetched(Intent intent) {
if (intent.getBooleanExtra(EXTRA_SUCCESS, true)) {
mAdapter.remove(intent.getAction());
} else {
BoxListItem item = mAdapter.get(intent.getAction());
if (item != null) {
item.setIsError(true);
if (intent.getAction().equals(ACTION_FETCHED_INFO)) {
item.setTask(fetchInfo());
} else if (intent.getAction().equals(ACTION_FETCHED_ITEMS)) {
int limit = intent.getIntExtra(EXTRA_LIMIT, DEFAULT_LIMIT);
int offset = intent.getIntExtra(EXTRA_OFFSET, 0);
item.setTask(fetchItems(offset, limit));
}
mAdapter.update(intent.getAction());
}
return;
}
displayBoxList((BoxListItems) intent.getSerializableExtra(EXTRA_COLLECTION));
mSwipeRefresh.setRefreshing(false);
}
/**
* show in this fragment a box list of items.
*/
protected void displayBoxList(final BoxListItems items) {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
// if we are trying to display the original list no need to add.
if (items == mBoxListItems) {
// mBoxListItems.addAll(items);
if (mAdapter.getItemCount() < 1) {
mAdapter.addAll(items);
}
} else {
if (mBoxListItems == null) {
setListItem(items);
}
mBoxListItems.addAll(items);
mAdapter.addAll(items);
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
int limit = DEFAULT_LIMIT;
if (items.limit() != null && items.limit() > 0) {
limit = items.limit().intValue();
}
if (mBoxListItems.size() < items.fullSize()) {
// if not all entries were fetched add a task to fetch more items if user scrolls to last entry.
mAdapter.add(new BoxListItem(fetchItems(mBoxListItems.size(), limit),
ACTION_FETCHED_ITEMS));
}
}
protected abstract FutureTask<Intent> fetchItems(final int offset, final int limit);
/**
* Handles showing new thumbnails after they have been downloaded.
*
* @param intent
*/
protected void onDownloadedThumbnail(final Intent intent) {
if (intent.getBooleanExtra(EXTRA_SUCCESS, false) && mAdapter != null) {
mAdapter.update(intent.getStringExtra(EXTRA_FILE_ID));
}
}
private class BoxItemDividerDecoration extends RecyclerView.ItemDecoration {
Drawable mDivider;
public BoxItemDividerDecoration(Resources resources) {
mDivider = resources.getDrawable(R.drawable.box_browsesdk_item_divider);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
protected class BoxItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
BoxListItem mItem;
View mView;
ImageView mThumbView;
TextView mNameView;
TextView mMetaDescription;
ProgressBar mProgressBar;
public BoxItemViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mView = itemView;
mThumbView = (ImageView) itemView.findViewById(R.id.box_browsesdk_thumb_image);
mNameView = (TextView) itemView.findViewById(R.id.box_browsesdk_name_text);
mMetaDescription = (TextView) itemView.findViewById(R.id.metaline_description);
mProgressBar = (ProgressBar) itemView.findViewById((R.id.spinner));
setAccentColor(getResources(), mProgressBar);
}
public void bindItem(BoxListItem item) {
mItem = item;
onBindBoxItemViewHolder(this);
}
public void setError(BoxListItem item) {
mItem = item;
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
mThumbView.setImageResource(R.drawable.ic_box_browsesdk_refresh_grey_36dp);
mThumbView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mMetaDescription.setVisibility(View.VISIBLE);
mNameView.setText(activity.getResources().getString(R.string.box_browsesdk_error_retrieving_items));
mMetaDescription.setText(activity.getResources().getString(R.string.box_browsesdk_tap_to_retry));
}
public void setLoading() {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
mThumbView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
mMetaDescription.setVisibility(View.GONE);
mNameView.setText(activity.getResources().getString(R.string.boxsdk_Please_wait));
}
public BoxListItem getItem() {
return mItem;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public TextView getMetaDescription() {
return mMetaDescription;
}
public TextView getNameView() {
return mNameView;
}
public ImageView getThumbView() {
return mThumbView;
}
public View getView() {
return mView;
}
@Override
public void onClick(View v) {
if(mSwipeRefresh.isRefreshing()){
return;
}
if (mItem == null) {
return;
}
if (mItem.getIsError()) {
mItem.setIsError(false);
mApiExecutor.execute(mItem.getTask());
setLoading();
}
if (mListener != null) {
if (mListener.handleOnItemClick(mItem.getBoxItem())) {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
if (mItem.getBoxItem() instanceof BoxFolder) {
BoxFolder folder = (BoxFolder) mItem.getBoxItem();
FragmentTransaction trans = activity.getSupportFragmentManager().beginTransaction();
// All fragments will always navigate into folders
BoxBrowseFolderFragment browseFolderFragment = BoxBrowseFolderFragment.newInstance(folder, mSession);
trans.replace(R.id.box_browsesdk_fragment_container, browseFolderFragment)
.addToBackStack(TAG)
.commit();
}
}
}
}
}
protected class BoxItemAdapter extends RecyclerView.Adapter<BoxItemViewHolder> {
protected ArrayList<BoxListItem> mListItems = new ArrayList<BoxListItem>();
protected HashMap<String, BoxListItem> mItemsMap = new HashMap<String, BoxListItem>();
@Override
public BoxItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.box_browsesdk_list_item, viewGroup, false);
return new BoxItemViewHolder(view);
}
@Override
public void onBindViewHolder(BoxItemViewHolder boxItemHolder, int i) {
BoxListItem item = mListItems.get(i);
if (item.getIsError()) {
boxItemHolder.setError(item);
return;
} else if (item.getType() == BoxListItem.TYPE_FUTURE_TASK) {
getApiExecutor().execute(item.getTask());
boxItemHolder.setLoading();
return;
} else {
boxItemHolder.bindItem(item);
// Fetch thumbnails for media file types
if (item.getBoxItem() instanceof BoxFile && isMediaType(item.getBoxItem().getName())) {
if (item.getTask() == null) {
item.setTask(downloadThumbnail(item.getBoxItem().getId(),
mThumbnailManager.getThumbnailForFile(item.getBoxItem().getId()), boxItemHolder));
} else if (item.getTask().isDone()) {
try {
Intent intent = (Intent) item.getTask().get();
if (!intent.getBooleanExtra(EXTRA_SUCCESS, false)) {
// if we were unable to get this thumbnail for any reason besides a 404 try it again.
Object ex = intent.getSerializableExtra(EXTRA_EXCEPTION);
if (ex != null && ex instanceof BoxException && ((BoxException) ex).getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
item.setTask(downloadThumbnail(item.getBoxItem().getId(),
mThumbnailManager.getThumbnailForFile(item.getBoxItem().getId()), boxItemHolder));
}
}
} catch (Exception e) {
// e.printStackTrace();
}
}
}
}
if (item.getTask() != null && !item.getTask().isDone()) {
getThumbnailExecutor().execute(item.getTask());
}
}
private boolean isMediaType(String name) {
if (SdkUtils.isBlank(name)) {
return false;
}
int index = name.lastIndexOf(".");
if (index > 0) {
return THUMBNAIL_MEDIA_EXTENSIONS.contains(name.substring(index + 1).toLowerCase());
}
return false;
}
@Override
public int getItemCount() {
return mListItems.size();
}
public BoxListItem get(String id) {
return mItemsMap.get(id);
}
public synchronized void removeAll() {
mItemsMap.clear();
mListItems.clear();
}
public void remove(BoxListItem listItem) {
remove(listItem.getIdentifier());
}
public synchronized void remove(String key) {
BoxListItem item = mItemsMap.remove(key);
if (item != null) {
boolean success = mListItems.remove(item);
}
}
public void addAll(BoxListItems items) {
for (BoxItem item : items) {
if (!mItemsMap.containsKey(item.getId())) {
add(new BoxListItem(item, item.getId()));
} else {
// update an existing item if it exists.
mItemsMap.get(item.getId()).setBoxItem(item);
}
}
}
public synchronized void add(BoxListItem listItem) {
if (listItem.getBoxItem() != null) {
// If the item should not be visible, skip adding the item
if (!isItemVisible(listItem.getBoxItem())) {
return;
}
listItem.setIsEnabled(isItemEnabled(listItem.getBoxItem()));
}
mListItems.add(listItem);
mItemsMap.put(listItem.getIdentifier(), listItem);
}
public void update(String id) {
BoxListItem item = mItemsMap.get(id);
if (item != null) {
int index = mListItems.indexOf(item);
notifyItemChanged(index);
}
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an item being tapped to be communicated to the activity
*/
public interface OnFragmentInteractionListener {
/**
* Called whenever an item in the RecyclerView is clicked
*
* @param item the item that was clicked
* @return whether the click event should continue to be handled by the fragment
*/
boolean handleOnItemClick(BoxItem item);
}
/**
* Called when a {@link BoxListItem} is bound to a ViewHolder. Customizations of UI elements
* should be done by overriding this method. If extending from a {@link BoxBrowseActivity}
* a custom BoxBrowseFolder fragment can be returned in
* {@link BoxBrowseActivity#createBrowseFolderFragment(BoxItem, BoxSession)}
*
* @param holder the BoxItemHolder
*/
protected void onBindBoxItemViewHolder(BoxItemViewHolder holder) {
if (holder.getItem() == null || holder.getItem().getBoxItem() == null) {
return;
}
final BoxItem item = holder.getItem().getBoxItem();
holder.getNameView().setText(item.getName());
String description = "";
if (item != null) {
String modifiedAt = item.getModifiedAt() != null ?
DateFormat.getDateInstance(DateFormat.MEDIUM).format(item.getModifiedAt()).toUpperCase() :
"";
String size = item.getSize() != null ?
localFileSizeToDisplay(item.getSize()) :
"";
description = String.format(Locale.ENGLISH, "%s • %s", modifiedAt, size);
mThumbnailManager.setThumbnailIntoView(holder.getThumbView(), item);
}
holder.getMetaDescription().setText(description);
holder.getProgressBar().setVisibility(View.GONE);
holder.getMetaDescription().setVisibility(View.VISIBLE);
holder.getThumbView().setVisibility(View.VISIBLE);
if (!holder.getItem().getIsEnabled()) {
holder.getView().setEnabled(false);
holder.getNameView().setTextColor(getResources().getColor(R.color.box_browsesdk_hint));
holder.getMetaDescription().setTextColor(getResources().getColor(R.color.box_browsesdk_disabled_hint));
holder.getThumbView().setAlpha(0.26f);
} else {
holder.getView().setEnabled(true);
holder.getNameView().setTextColor(getResources().getColor(R.color.box_browsesdk_primary_text));
holder.getMetaDescription().setTextColor(getResources().getColor(R.color.box_browsesdk_hint));
holder.getThumbView().setAlpha(1f);
}
}
/**
* Defines the conditions for when a BoxItem should be shown as enabled
*
* @param item the BoxItem that should be enabled or not
* @return whether or not the BoxItem should be enabled
*/
public boolean isItemEnabled(BoxItem item) {
return true;
}
/**
* Defines the conditions for when a BoxItem should be shown in the adapter
*
* @param item the BoxItem that should be visible or not
* @return whether or not the BoxItem should be visible
*/
public boolean isItemVisible(BoxItem item) {
return true;
}
/**
* Download the thumbnail for a given file.
*
* @param fileId file id to download thumbnail for.
* @return A FutureTask that is tasked with fetching information on the given folder.
*/
private FutureTask<Intent> downloadThumbnail(final String fileId, final File downloadLocation, final BoxItemViewHolder holder) {
return new FutureTask<Intent>(new Callable<Intent>() {
@Override
public Intent call() throws Exception {
Intent intent = new Intent();
intent.setAction(ACTION_DOWNLOADED_FILE_THUMBNAIL);
intent.putExtra(EXTRA_FILE_ID, fileId);
intent.putExtra(EXTRA_SUCCESS, false);
try {
// no need to continue downloading thumbnail if we already have a thumbnail
if (downloadLocation.exists() && downloadLocation.length() > 0) {
intent.putExtra(EXTRA_SUCCESS, true);
return intent;
}
// no need to continue downloading thumbnail if we are not viewing this thumbnail.
if (holder.getItem() == null || holder.getItem().getBoxItem() == null || !(holder.getItem().getBoxItem() instanceof BoxFile)
|| !holder.getItem().getBoxItem().getId().equals(fileId)) {
intent.putExtra(EXTRA_SUCCESS, false);
return intent;
}
BoxApiFile api = new BoxApiFile(mSession);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int thumbSize = BoxRequestsFile.DownloadThumbnail.SIZE_128;
if (metrics.density <= DisplayMetrics.DENSITY_MEDIUM) {
thumbSize = BoxRequestsFile.DownloadThumbnail.SIZE_64;
} else if (metrics.density <= DisplayMetrics.DENSITY_HIGH) {
thumbSize = BoxRequestsFile.DownloadThumbnail.SIZE_64;
}
api.getDownloadThumbnailRequest(downloadLocation, fileId)
.setMinHeight(thumbSize)
.setMinWidth(thumbSize)
.send();
if (downloadLocation.exists()) {
intent.putExtra(EXTRA_SUCCESS, true);
}
} catch (BoxException e) {
intent.putExtra(EXTRA_SUCCESS, false);
intent.putExtra(EXTRA_EXCEPTION, e);
} finally {
mLocalBroadcastManager.sendBroadcast(intent);
}
return intent;
}
});
}
/**
* Java version of routine to turn a long into a short user readable string.
* <p/>
* This routine is used if the JNI native C version is not available.
*
* @param numSize the number of bytes in the file.
* @return String Short human readable String e.g. 2.5 MB
*/
private String localFileSizeToDisplay(final double numSize) {
final int constKB = 1024;
final int constMB = constKB * constKB;
final int constGB = constMB * constKB;
final double floatKB = 1024.0f;
final double floatMB = floatKB * floatKB;
final double floatGB = floatMB * floatKB;
final String BYTES = "B";
String textSize = "0 bytes";
String strSize = Double.toString(numSize);
double size;
if (numSize < constKB) {
textSize = strSize + " " + BYTES;
} else if ((numSize >= constKB) && (numSize < constMB)) {
size = numSize / floatKB;
textSize = String.format(Locale.ENGLISH, "%4.1f KB", size);
} else if ((numSize >= constMB) && (numSize < constGB)) {
size = numSize / floatMB;
textSize = String.format(Locale.ENGLISH, "%4.1f MB", size);
} else if (numSize >= constGB) {
size = numSize / floatGB;
textSize = String.format(Locale.ENGLISH, "%4.1f GB", size);
}
return textSize;
}
public static void setAccentColor(Resources res, ProgressBar progressBar) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
int accentColor = res.getColor(R.color.box_accent);
Drawable drawable = progressBar.getIndeterminateDrawable();
if (drawable != null) {
drawable.setColorFilter(accentColor, PorterDuff.Mode.SRC_IN);
drawable.invalidateSelf();
}
}
}
}
| box-browse-sdk/src/main/java/com/box/androidsdk/browse/fragments/BoxBrowseFragment.java | package com.box.androidsdk.browse.fragments;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.box.androidsdk.browse.R;
import com.box.androidsdk.browse.activities.BoxBrowseActivity;
import com.box.androidsdk.browse.uidata.BoxListItem;
import com.box.androidsdk.browse.uidata.ThumbnailManager;
import com.box.androidsdk.content.BoxApiFile;
import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.models.BoxFile;
import com.box.androidsdk.content.models.BoxFolder;
import com.box.androidsdk.content.models.BoxItem;
import com.box.androidsdk.content.models.BoxListItems;
import com.box.androidsdk.content.models.BoxSession;
import com.box.androidsdk.content.requests.BoxRequestsFile;
import com.box.androidsdk.content.utils.SdkUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link BoxBrowseFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
*/
public abstract class BoxBrowseFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public static final String ARG_ID = "argId";
public static final String ARG_USER_ID = "argUserId";
public static final String ARG_NAME = "argName";
public static final String TAG = BoxBrowseFragment.class.getName();
protected static final int DEFAULT_LIMIT = 1000;
protected static final String ACTION_FETCHED_ITEMS = "BoxBrowseFragment_FetchedItems";
protected static final String ACTION_FETCHED_INFO = "BoxBrowseFragment_FetchedInfo";
protected static final String ACTION_DOWNLOADED_FILE_THUMBNAIL = "BoxBrowseFragment_DownloadedFileThumbnail";
protected static final String EXTRA_SUCCESS = "BoxBrowseFragment_ArgSuccess";
protected static final String EXTRA_EXCEPTION = "BoxBrowseFragment_ArgException";
protected static final String EXTRA_ID = "BoxBrowseFragment_FolderId";
protected static final String EXTRA_FILE_ID = "BoxBrowseFragment_FileId";
protected static final String EXTRA_OFFSET = "BoxBrowseFragment_ArgOffset";
protected static final String EXTRA_LIMIT = "BoxBrowseFragment_Limit";
protected static final String EXTRA_FOLDER = "BoxBrowseFragment_Folder";
protected static final String EXTRA_COLLECTION = "BoxBrowseFragment_Collection";
private static List<String> THUMBNAIL_MEDIA_EXTENSIONS = Arrays.asList(new String[] {"gif", "jpeg", "jpg", "bmp", "svg", "png", "tiff"});
protected String mUserId;
protected BoxSession mSession;
private BoxListItems mBoxListItems;
protected OnFragmentInteractionListener mListener;
protected BoxItemAdapter mAdapter;
protected RecyclerView mItemsView;
protected ThumbnailManager mThumbnailManager;
protected SwipeRefreshLayout mSwipeRefresh;
protected LocalBroadcastManager mLocalBroadcastManager;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_DOWNLOADED_FILE_THUMBNAIL)) {
onDownloadedThumbnail(intent);
} else {
// Handle response
if (intent.getAction().equals(ACTION_FETCHED_INFO)) {
onInfoFetched(intent);
} else if (intent.getAction().equals(ACTION_FETCHED_ITEMS)) {
onItemsFetched(intent);
}
// Remove refreshing icon
if (mSwipeRefresh != null) {
mSwipeRefresh.setRefreshing(false);
}
}
}
};
private static ThreadPoolExecutor mApiExecutor;
private static ThreadPoolExecutor mThumbnailExecutor;
protected ThreadPoolExecutor getApiExecutor() {
if (mApiExecutor == null || mApiExecutor.isShutdown()) {
mApiExecutor = new ThreadPoolExecutor(1, 1, 3600, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
return mApiExecutor;
}
/**
* Executor that we will submit thumbnail tasks to.
*
* @return executor
*/
protected ThreadPoolExecutor getThumbnailExecutor() {
if (mThumbnailExecutor == null || mThumbnailExecutor.isShutdown()) {
mThumbnailExecutor = new ThreadPoolExecutor(1, 10, 3600, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
return mThumbnailExecutor;
}
protected IntentFilter initializeIntentFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_FETCHED_INFO);
filter.addAction(ACTION_FETCHED_ITEMS);
filter.addAction(ACTION_DOWNLOADED_FILE_THUMBNAIL);
return filter;
}
public BoxBrowseFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize broadcast managers
mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
if (getArguments() != null) {
mUserId = getArguments().getString(ARG_USER_ID);
mThumbnailManager = initializeThumbnailManager();
mUserId = getArguments().getString(ARG_USER_ID);
mSession = new BoxSession(getActivity(), mUserId);
}
if (savedInstanceState != null) {
setListItem((BoxListItems) savedInstanceState.getSerializable(EXTRA_COLLECTION));
}
}
@Override
public void onResume() {
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, initializeIntentFilters());
super.onResume();
}
@Override
public void onPause() {
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(EXTRA_COLLECTION, mBoxListItems);
super.onSaveInstanceState(outState);
}
private ThumbnailManager initializeThumbnailManager() {
try {
return new ThumbnailManager(getActivity().getCacheDir());
} catch (FileNotFoundException e) {
// TODO: Call error handler
return null;
}
}
protected void setToolbar(String name) {
if (getActivity() != null && getActivity() instanceof AppCompatActivity) {
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (toolbar != null) {
toolbar.setTitle(name);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.box_browsesdk_fragment_browse, container, false);
mSwipeRefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.box_browsesdk_swipe_reresh);
mSwipeRefresh.setOnRefreshListener(this);
mSwipeRefresh.setColorSchemeColors(R.color.box_accent);
// This is a work around to show the loading circle because SwipeRefreshLayout.onMeasure must be called before setRefreshing to show the animation
mSwipeRefresh.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
mItemsView = (RecyclerView) rootView.findViewById(R.id.box_browsesdk_items_recycler_view);
mItemsView.addItemDecoration(new BoxItemDividerDecoration(getResources()));
mItemsView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new BoxItemAdapter();
mItemsView.setAdapter(mAdapter);
if (mBoxListItems == null) {
mAdapter.add(new BoxListItem(fetchInfo(), ACTION_FETCHED_INFO));
} else {
displayBoxList(mBoxListItems);
}
return rootView;
}
protected void setListItem(final BoxListItems items) {
mBoxListItems = items;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
@Override
public void onRefresh() {
mSwipeRefresh.setRefreshing(true);
getApiExecutor().execute(fetchInfo());
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
protected void onInfoFetched(Intent intent) {
onItemsFetched(intent);
}
/**
* Fetch the first information relevant to this fragment or what should be used for refreshing.
*
* @return A FutureTask that is tasked with fetching the first information relevant to this fragment or what should be used for refreshing.
*/
public abstract FutureTask<Intent> fetchInfo();
/**
* Handle showing a collection in the given intent.
*
* @param intent an intent that contains a collection in EXTRA_COLLECTION.
*/
protected void onItemsFetched(Intent intent) {
if (intent.getBooleanExtra(EXTRA_SUCCESS, true)) {
mAdapter.remove(intent.getAction());
} else {
BoxListItem item = mAdapter.get(intent.getAction());
if (item != null) {
item.setIsError(true);
if (intent.getAction().equals(ACTION_FETCHED_INFO)) {
item.setTask(fetchInfo());
} else if (intent.getAction().equals(ACTION_FETCHED_ITEMS)) {
int limit = intent.getIntExtra(EXTRA_LIMIT, DEFAULT_LIMIT);
int offset = intent.getIntExtra(EXTRA_OFFSET, 0);
item.setTask(fetchItems(offset, limit));
}
mAdapter.update(intent.getAction());
}
return;
}
displayBoxList((BoxListItems) intent.getSerializableExtra(EXTRA_COLLECTION));
mSwipeRefresh.setRefreshing(false);
}
/**
* show in this fragment a box list of items.
*/
protected void displayBoxList(final BoxListItems items) {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
// if we are trying to display the original list no need to add.
if (items == mBoxListItems) {
// mBoxListItems.addAll(items);
if (mAdapter.getItemCount() < 1) {
mAdapter.addAll(items);
}
} else {
if (mBoxListItems == null) {
setListItem(items);
}
mBoxListItems.addAll(items);
mAdapter.addAll(items);
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
int limit = DEFAULT_LIMIT;
if (items.limit() != null && items.limit() > 0) {
limit = items.limit().intValue();
}
if (mBoxListItems.size() < items.fullSize()) {
// if not all entries were fetched add a task to fetch more items if user scrolls to last entry.
mAdapter.add(new BoxListItem(fetchItems(mBoxListItems.size(), limit),
ACTION_FETCHED_ITEMS));
}
}
protected abstract FutureTask<Intent> fetchItems(final int offset, final int limit);
/**
* Handles showing new thumbnails after they have been downloaded.
*
* @param intent
*/
protected void onDownloadedThumbnail(final Intent intent) {
if (intent.getBooleanExtra(EXTRA_SUCCESS, false) && mAdapter != null) {
mAdapter.update(intent.getStringExtra(EXTRA_FILE_ID));
}
}
private class BoxItemDividerDecoration extends RecyclerView.ItemDecoration {
Drawable mDivider;
public BoxItemDividerDecoration(Resources resources) {
mDivider = resources.getDrawable(R.drawable.box_browsesdk_item_divider);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
protected class BoxItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
BoxListItem mItem;
View mView;
ImageView mThumbView;
TextView mNameView;
TextView mMetaDescription;
ProgressBar mProgressBar;
public BoxItemViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mView = itemView;
mThumbView = (ImageView) itemView.findViewById(R.id.box_browsesdk_thumb_image);
mNameView = (TextView) itemView.findViewById(R.id.box_browsesdk_name_text);
mMetaDescription = (TextView) itemView.findViewById(R.id.metaline_description);
mProgressBar = (ProgressBar) itemView.findViewById((R.id.spinner));
}
public void bindItem(BoxListItem item) {
mItem = item;
onBindBoxItemViewHolder(this);
}
public void setError(BoxListItem item) {
mItem = item;
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
mThumbView.setImageResource(R.drawable.ic_box_browsesdk_refresh_grey_36dp);
mThumbView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mMetaDescription.setVisibility(View.VISIBLE);
mNameView.setText(activity.getResources().getString(R.string.box_browsesdk_error_retrieving_items));
mMetaDescription.setText(activity.getResources().getString(R.string.box_browsesdk_tap_to_retry));
}
public void setLoading() {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
mThumbView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
mMetaDescription.setVisibility(View.GONE);
mNameView.setText(activity.getResources().getString(R.string.boxsdk_Please_wait));
}
public BoxListItem getItem() {
return mItem;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public TextView getMetaDescription() {
return mMetaDescription;
}
public TextView getNameView() {
return mNameView;
}
public ImageView getThumbView() {
return mThumbView;
}
public View getView() {
return mView;
}
@Override
public void onClick(View v) {
if(mSwipeRefresh.isRefreshing()){
return;
}
if (mItem == null) {
return;
}
if (mItem.getIsError()) {
mItem.setIsError(false);
mApiExecutor.execute(mItem.getTask());
setLoading();
}
if (mListener != null) {
if (mListener.handleOnItemClick(mItem.getBoxItem())) {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
if (mItem.getBoxItem() instanceof BoxFolder) {
BoxFolder folder = (BoxFolder) mItem.getBoxItem();
FragmentTransaction trans = activity.getSupportFragmentManager().beginTransaction();
// All fragments will always navigate into folders
BoxBrowseFolderFragment browseFolderFragment = BoxBrowseFolderFragment.newInstance(folder, mSession);
trans.replace(R.id.box_browsesdk_fragment_container, browseFolderFragment)
.addToBackStack(TAG)
.commit();
}
}
}
}
}
protected class BoxItemAdapter extends RecyclerView.Adapter<BoxItemViewHolder> {
protected ArrayList<BoxListItem> mListItems = new ArrayList<BoxListItem>();
protected HashMap<String, BoxListItem> mItemsMap = new HashMap<String, BoxListItem>();
@Override
public BoxItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.box_browsesdk_list_item, viewGroup, false);
return new BoxItemViewHolder(view);
}
@Override
public void onBindViewHolder(BoxItemViewHolder boxItemHolder, int i) {
BoxListItem item = mListItems.get(i);
if (item.getIsError()) {
boxItemHolder.setError(item);
return;
} else if (item.getType() == BoxListItem.TYPE_FUTURE_TASK) {
getApiExecutor().execute(item.getTask());
boxItemHolder.setLoading();
return;
} else {
boxItemHolder.bindItem(item);
// Fetch thumbnails for media file types
if (item.getBoxItem() instanceof BoxFile && isMediaType(item.getBoxItem().getName())) {
if (item.getTask() == null) {
item.setTask(downloadThumbnail(item.getBoxItem().getId(),
mThumbnailManager.getThumbnailForFile(item.getBoxItem().getId()), boxItemHolder));
} else if (item.getTask().isDone()) {
try {
Intent intent = (Intent) item.getTask().get();
if (!intent.getBooleanExtra(EXTRA_SUCCESS, false)) {
// if we were unable to get this thumbnail for any reason besides a 404 try it again.
Object ex = intent.getSerializableExtra(EXTRA_EXCEPTION);
if (ex != null && ex instanceof BoxException && ((BoxException) ex).getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
item.setTask(downloadThumbnail(item.getBoxItem().getId(),
mThumbnailManager.getThumbnailForFile(item.getBoxItem().getId()), boxItemHolder));
}
}
} catch (Exception e) {
// e.printStackTrace();
}
}
}
}
if (item.getTask() != null && !item.getTask().isDone()) {
getThumbnailExecutor().execute(item.getTask());
}
}
private boolean isMediaType(String name) {
if (SdkUtils.isBlank(name)) {
return false;
}
int index = name.lastIndexOf(".");
if (index > 0) {
return THUMBNAIL_MEDIA_EXTENSIONS.contains(name.substring(index + 1).toLowerCase());
}
return false;
}
@Override
public int getItemCount() {
return mListItems.size();
}
public BoxListItem get(String id) {
return mItemsMap.get(id);
}
public synchronized void removeAll() {
mItemsMap.clear();
mListItems.clear();
}
public void remove(BoxListItem listItem) {
remove(listItem.getIdentifier());
}
public synchronized void remove(String key) {
BoxListItem item = mItemsMap.remove(key);
if (item != null) {
boolean success = mListItems.remove(item);
}
}
public void addAll(BoxListItems items) {
for (BoxItem item : items) {
if (!mItemsMap.containsKey(item.getId())) {
add(new BoxListItem(item, item.getId()));
} else {
// update an existing item if it exists.
mItemsMap.get(item.getId()).setBoxItem(item);
}
}
}
public synchronized void add(BoxListItem listItem) {
if (listItem.getBoxItem() != null) {
// If the item should not be visible, skip adding the item
if (!isItemVisible(listItem.getBoxItem())) {
return;
}
listItem.setIsEnabled(isItemEnabled(listItem.getBoxItem()));
}
mListItems.add(listItem);
mItemsMap.put(listItem.getIdentifier(), listItem);
}
public void update(String id) {
BoxListItem item = mItemsMap.get(id);
if (item != null) {
int index = mListItems.indexOf(item);
notifyItemChanged(index);
}
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an item being tapped to be communicated to the activity
*/
public interface OnFragmentInteractionListener {
/**
* Called whenever an item in the RecyclerView is clicked
*
* @param item the item that was clicked
* @return whether the click event should continue to be handled by the fragment
*/
boolean handleOnItemClick(BoxItem item);
}
/**
* Called when a {@link BoxListItem} is bound to a ViewHolder. Customizations of UI elements
* should be done by overriding this method. If extending from a {@link BoxBrowseActivity}
* a custom BoxBrowseFolder fragment can be returned in
* {@link BoxBrowseActivity#createBrowseFolderFragment(BoxItem, BoxSession)}
*
* @param holder the BoxItemHolder
*/
protected void onBindBoxItemViewHolder(BoxItemViewHolder holder) {
if (holder.getItem() == null || holder.getItem().getBoxItem() == null) {
return;
}
final BoxItem item = holder.getItem().getBoxItem();
holder.getNameView().setText(item.getName());
String description = "";
if (item != null) {
String modifiedAt = item.getModifiedAt() != null ?
DateFormat.getDateInstance(DateFormat.MEDIUM).format(item.getModifiedAt()).toUpperCase() :
"";
String size = item.getSize() != null ?
localFileSizeToDisplay(item.getSize()) :
"";
description = String.format(Locale.ENGLISH, "%s • %s", modifiedAt, size);
mThumbnailManager.setThumbnailIntoView(holder.getThumbView(), item);
}
holder.getMetaDescription().setText(description);
holder.getProgressBar().setVisibility(View.GONE);
holder.getMetaDescription().setVisibility(View.VISIBLE);
holder.getThumbView().setVisibility(View.VISIBLE);
if (!holder.getItem().getIsEnabled()) {
holder.getView().setEnabled(false);
holder.getNameView().setTextColor(getResources().getColor(R.color.box_browsesdk_hint));
holder.getMetaDescription().setTextColor(getResources().getColor(R.color.box_browsesdk_disabled_hint));
holder.getThumbView().setAlpha(0.26f);
} else {
holder.getView().setEnabled(true);
holder.getNameView().setTextColor(getResources().getColor(R.color.box_browsesdk_primary_text));
holder.getMetaDescription().setTextColor(getResources().getColor(R.color.box_browsesdk_hint));
holder.getThumbView().setAlpha(1f);
}
}
/**
* Defines the conditions for when a BoxItem should be shown as enabled
*
* @param item the BoxItem that should be enabled or not
* @return whether or not the BoxItem should be enabled
*/
public boolean isItemEnabled(BoxItem item) {
return true;
}
/**
* Defines the conditions for when a BoxItem should be shown in the adapter
*
* @param item the BoxItem that should be visible or not
* @return whether or not the BoxItem should be visible
*/
public boolean isItemVisible(BoxItem item) {
return true;
}
/**
* Download the thumbnail for a given file.
*
* @param fileId file id to download thumbnail for.
* @return A FutureTask that is tasked with fetching information on the given folder.
*/
private FutureTask<Intent> downloadThumbnail(final String fileId, final File downloadLocation, final BoxItemViewHolder holder) {
return new FutureTask<Intent>(new Callable<Intent>() {
@Override
public Intent call() throws Exception {
Intent intent = new Intent();
intent.setAction(ACTION_DOWNLOADED_FILE_THUMBNAIL);
intent.putExtra(EXTRA_FILE_ID, fileId);
intent.putExtra(EXTRA_SUCCESS, false);
try {
// no need to continue downloading thumbnail if we already have a thumbnail
if (downloadLocation.exists() && downloadLocation.length() > 0) {
intent.putExtra(EXTRA_SUCCESS, true);
return intent;
}
// no need to continue downloading thumbnail if we are not viewing this thumbnail.
if (holder.getItem() == null || holder.getItem().getBoxItem() == null || !(holder.getItem().getBoxItem() instanceof BoxFile)
|| !holder.getItem().getBoxItem().getId().equals(fileId)) {
intent.putExtra(EXTRA_SUCCESS, false);
return intent;
}
BoxApiFile api = new BoxApiFile(mSession);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int thumbSize = BoxRequestsFile.DownloadThumbnail.SIZE_128;
if (metrics.density <= DisplayMetrics.DENSITY_MEDIUM) {
thumbSize = BoxRequestsFile.DownloadThumbnail.SIZE_64;
} else if (metrics.density <= DisplayMetrics.DENSITY_HIGH) {
thumbSize = BoxRequestsFile.DownloadThumbnail.SIZE_64;
}
api.getDownloadThumbnailRequest(downloadLocation, fileId)
.setMinHeight(thumbSize)
.setMinWidth(thumbSize)
.send();
if (downloadLocation.exists()) {
intent.putExtra(EXTRA_SUCCESS, true);
}
} catch (BoxException e) {
intent.putExtra(EXTRA_SUCCESS, false);
intent.putExtra(EXTRA_EXCEPTION, e);
} finally {
mLocalBroadcastManager.sendBroadcast(intent);
}
return intent;
}
});
}
/**
* Java version of routine to turn a long into a short user readable string.
* <p/>
* This routine is used if the JNI native C version is not available.
*
* @param numSize the number of bytes in the file.
* @return String Short human readable String e.g. 2.5 MB
*/
private String localFileSizeToDisplay(final double numSize) {
final int constKB = 1024;
final int constMB = constKB * constKB;
final int constGB = constMB * constKB;
final double floatKB = 1024.0f;
final double floatMB = floatKB * floatKB;
final double floatGB = floatMB * floatKB;
final String BYTES = "B";
String textSize = "0 bytes";
String strSize = Double.toString(numSize);
double size;
if (numSize < constKB) {
textSize = strSize + " " + BYTES;
} else if ((numSize >= constKB) && (numSize < constMB)) {
size = numSize / floatKB;
textSize = String.format(Locale.ENGLISH, "%4.1f KB", size);
} else if ((numSize >= constMB) && (numSize < constGB)) {
size = numSize / floatMB;
textSize = String.format(Locale.ENGLISH, "%4.1f MB", size);
} else if (numSize >= constGB) {
size = numSize / floatGB;
textSize = String.format(Locale.ENGLISH, "%4.1f GB", size);
}
return textSize;
}
}
| Styling progress bar for pre-lollipop releases
| box-browse-sdk/src/main/java/com/box/androidsdk/browse/fragments/BoxBrowseFragment.java | Styling progress bar for pre-lollipop releases | <ide><path>ox-browse-sdk/src/main/java/com/box/androidsdk/browse/fragments/BoxBrowseFragment.java
<ide> import android.content.IntentFilter;
<ide> import android.content.res.Resources;
<ide> import android.graphics.Canvas;
<add>import android.graphics.PorterDuff;
<ide> import android.graphics.drawable.Drawable;
<add>import android.os.Build;
<ide> import android.os.Bundle;
<ide> import android.support.v4.app.Fragment;
<ide> import android.support.v4.app.FragmentActivity;
<ide> mNameView = (TextView) itemView.findViewById(R.id.box_browsesdk_name_text);
<ide> mMetaDescription = (TextView) itemView.findViewById(R.id.metaline_description);
<ide> mProgressBar = (ProgressBar) itemView.findViewById((R.id.spinner));
<add> setAccentColor(getResources(), mProgressBar);
<ide> }
<ide>
<ide> public void bindItem(BoxListItem item) {
<ide> return textSize;
<ide> }
<ide>
<add> public static void setAccentColor(Resources res, ProgressBar progressBar) {
<add> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
<add> int accentColor = res.getColor(R.color.box_accent);
<add> Drawable drawable = progressBar.getIndeterminateDrawable();
<add> if (drawable != null) {
<add> drawable.setColorFilter(accentColor, PorterDuff.Mode.SRC_IN);
<add> drawable.invalidateSelf();
<add> }
<add> }
<add> }
<add>
<add>
<ide> } |
|
Java | apache-2.0 | ed8484937fe944fcc4b30a797f7bc70076a428f4 | 0 | AlienQueen/wicket,mosoft521/wicket,dashorst/wicket,martin-g/wicket-osgi,freiheit-com/wicket,mosoft521/wicket,Servoy/wicket,freiheit-com/wicket,mosoft521/wicket,astrapi69/wicket,bitstorm/wicket,klopfdreh/wicket,mafulafunk/wicket,klopfdreh/wicket,martin-g/wicket-osgi,selckin/wicket,Servoy/wicket,topicusonderwijs/wicket,freiheit-com/wicket,klopfdreh/wicket,aldaris/wicket,Servoy/wicket,klopfdreh/wicket,dashorst/wicket,dashorst/wicket,aldaris/wicket,Servoy/wicket,AlienQueen/wicket,mafulafunk/wicket,aldaris/wicket,martin-g/wicket-osgi,mosoft521/wicket,aldaris/wicket,apache/wicket,dashorst/wicket,topicusonderwijs/wicket,bitstorm/wicket,apache/wicket,astrapi69/wicket,dashorst/wicket,zwsong/wicket,AlienQueen/wicket,astrapi69/wicket,AlienQueen/wicket,freiheit-com/wicket,mafulafunk/wicket,Servoy/wicket,selckin/wicket,bitstorm/wicket,selckin/wicket,topicusonderwijs/wicket,AlienQueen/wicket,bitstorm/wicket,selckin/wicket,topicusonderwijs/wicket,apache/wicket,apache/wicket,klopfdreh/wicket,apache/wicket,astrapi69/wicket,selckin/wicket,aldaris/wicket,zwsong/wicket,zwsong/wicket,mosoft521/wicket,zwsong/wicket,freiheit-com/wicket,bitstorm/wicket,topicusonderwijs/wicket | /*
* $Id$
* $Revision$
* $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.markup.html.link;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.Serializable;
import wicket.markup.ComponentTag;
import wicket.markup.MarkupStream;
import wicket.markup.html.HtmlComponent;
/**
* An image map holds links with different hot-area shapes.
*
* @author Jonathan Locke
*/
public final class ImageMap extends HtmlComponent
{
/** Serial Version ID. */
private static final long serialVersionUID = 209001445308790198L;
/** list of shape links. */
private final List shapeLinks = new ArrayList();
/**
* Constructor.
* @param name component name
*/
public ImageMap(final String name)
{
super(name);
}
/**
* Renders this component.
* @see wicket.Component#handleRender()
*/
protected void handleRender()
{
// Get markup stream
final MarkupStream markupStream = findMarkupStream();
// Get mutable copy of next tag
final ComponentTag tag = markupStream.getTag().mutable();
// Must be an img tag
checkComponentTag(tag, "img");
// Set map name to path
tag.put("usemap", "#" + getPath());
// Write out the tag
renderComponentTag(tag);
markupStream.next();
// Write out the image map
final StringBuffer imageMap = new StringBuffer();
imageMap.append("\n<map name=\"" + getPath() + "\"> ");
for (Iterator iterator = shapeLinks.iterator(); iterator.hasNext();)
{
final ShapeLink shapeLink = (ShapeLink) iterator.next();
imageMap.append('\n');
imageMap.append(shapeLink.toString());
}
imageMap.append("\n</map>");
getResponse().write(imageMap.toString());
}
/**
* Adds a polygon link.
* @param coordinates the coordinates for the polygon
* @param link the link
* @return This
*/
public ImageMap addPolygonLink(final int[] coordinates, final Link link)
{
shapeLinks.add(new PolygonLink(coordinates, link));
return this;
}
/**
* Adds a rectangular link.
* @param x1 top left x
* @param y1 top left y
* @param x2 bottom right x
* @param y2 bottom right y
* @param link
* @return This
*/
public ImageMap addRectangleLink(final int x1, final int y1, final int x2, final int y2,
final Link link)
{
shapeLinks.add(new RectangleLink(x1, y1, x2, y2, link));
return this;
}
/**
* Adds a circle link.
* @param x1 top left x
* @param y1 top left y
* @param radius the radius
* @param link the link
* @return This
*/
public ImageMap addCircleLink(final int x1, final int y1, final int radius, final Link link)
{
shapeLinks.add(new CircleLink(x1, y1, radius, link));
return this;
}
/**
* Base class for shaped links.
*/
private static abstract class ShapeLink implements Serializable
{
/** the link. */
private final Link link;
/**
* Constructor.
* @param link the link
*/
public ShapeLink(final Link link)
{
this.link = link;
}
/**
* Gets the shape type.
* @return the shape type
*/
abstract String getType();
/**
* Gets the coordinates of the shape.
* @return the coordinates of the shape
*/
abstract String getCoordinates();
/**
* The shape as a string using the given request cycle; will be used
* for rendering.
* @return The shape as a string
*/
public String toString()
{
// Add any popup script
final String popupJavaScript;
if (link.getPopupSettings() != null)
{
popupJavaScript = link.getPopupSettings().getPopupJavaScript();
}
else
{
popupJavaScript = null;
}
return "<area shape=\""
+ getType() + "\"" + " coords=\"" + getCoordinates() + "\"" + " href=\""
+ link.getURL() + "\""
+ ((popupJavaScript == null) ? "" : (" onClick = \"" + popupJavaScript + "\""))
+ ">";
}
}
/**
* A shape that has a free (polygon) form.
*/
private static final class PolygonLink extends ShapeLink
{
/** Its coordinates. */
private final int[] coordinates;
/**
* Construct.
* @param coordinates the polygon coordinates
* @param link the link
*/
public PolygonLink(final int[] coordinates, final Link link)
{
super(link);
this.coordinates = coordinates;
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
*/
String getType()
{
return "polygon";
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
*/
String getCoordinates()
{
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i < coordinates.length; i++)
{
buffer.append(coordinates[i]);
if (i < (coordinates.length - 1))
{
buffer.append(',');
}
}
return buffer.toString();
}
}
/**
* A shape that has a rectangular form.
*/
private static final class RectangleLink extends ShapeLink
{
/** left upper x. */
private final int x1;
/** left upper y. */
private final int y1;
/** right bottom x. */
private final int x2;
/** right bottom y. */
private final int y2;
/**
* Construct.
* @param x1 left upper x
* @param y1 left upper y
* @param x2 right bottom x
* @param y2 right bottom y
* @param link the link
*/
public RectangleLink(final int x1, final int y1, final int x2, final int y2, final Link link)
{
super(link);
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
*/
String getType()
{
return "rectangle";
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
*/
String getCoordinates()
{
return x1 + "," + y1 + "," + x2 + "," + y2;
}
}
/**
* A shape that has a circle form.
*/
private static final class CircleLink extends ShapeLink
{
/** left upper x. */
private final int x1;
/** left upper y. */
private final int y1;
/** the circles' radius. */
private final int radius;
/**
* Construct.
* @param x1 left upper x
* @param y1 left upper y
* @param radius the circles' radius
* @param link the link
*/
public CircleLink(final int x1, final int y1, final int radius, final Link link)
{
super(link);
this.x1 = x1;
this.y1 = y1;
this.radius = radius;
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
*/
String getType()
{
return "circle";
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
*/
String getCoordinates()
{
return x1 + "," + y1 + "," + radius;
}
}
} | wicket/src/java/wicket/markup/html/link/ImageMap.java | /*
* $Id$
* $Revision$
* $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.markup.html.link;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import wicket.markup.ComponentTag;
import wicket.markup.MarkupStream;
import wicket.markup.html.HtmlComponent;
/**
* An image map holds links with different hot-area shapes.
*
* @author Jonathan Locke
*/
public final class ImageMap extends HtmlComponent
{
/** Serial Version ID. */
private static final long serialVersionUID = 209001445308790198L;
/** list of shape links. */
private final List shapeLinks = new ArrayList();
/**
* Constructor.
* @param name component name
*/
public ImageMap(final String name)
{
super(name);
}
/**
* Renders this component.
* @see wicket.Component#handleRender()
*/
protected void handleRender()
{
// Get markup stream
final MarkupStream markupStream = findMarkupStream();
// Get mutable copy of next tag
final ComponentTag tag = markupStream.getTag().mutable();
// Must be an img tag
checkComponentTag(tag, "img");
// Set map name to path
tag.put("usemap", "#" + getPath());
// Write out the tag
renderComponentTag(tag);
markupStream.next();
// Write out the image map
final StringBuffer imageMap = new StringBuffer();
imageMap.append("\n<map name=\"" + getPath() + "\"> ");
for (Iterator iterator = shapeLinks.iterator(); iterator.hasNext();)
{
final ShapeLink shapeLink = (ShapeLink) iterator.next();
imageMap.append('\n');
imageMap.append(shapeLink.toString());
}
imageMap.append("\n</map>");
getResponse().write(imageMap.toString());
}
/**
* Adds a polygon link.
* @param coordinates the coordinates for the polygon
* @param link the link
* @return This
*/
public ImageMap addPolygonLink(final int[] coordinates, final Link link)
{
shapeLinks.add(new PolygonLink(coordinates, link));
return this;
}
/**
* Adds a rectangular link.
* @param x1 top left x
* @param y1 top left y
* @param x2 bottom right x
* @param y2 bottom right y
* @param link
* @return This
*/
public ImageMap addRectangleLink(final int x1, final int y1, final int x2, final int y2,
final Link link)
{
shapeLinks.add(new RectangleLink(x1, y1, x2, y2, link));
return this;
}
/**
* Adds a circle link.
* @param x1 top left x
* @param y1 top left y
* @param radius the radius
* @param link the link
* @return This
*/
public ImageMap addCircleLink(final int x1, final int y1, final int radius, final Link link)
{
shapeLinks.add(new CircleLink(x1, y1, radius, link));
return this;
}
/**
* Base class for shaped links.
*/
private static abstract class ShapeLink
{
/** the link. */
private final Link link;
/**
* Constructor.
* @param link the link
*/
public ShapeLink(final Link link)
{
this.link = link;
}
/**
* Gets the shape type.
* @return the shape type
*/
abstract String getType();
/**
* Gets the coordinates of the shape.
* @return the coordinates of the shape
*/
abstract String getCoordinates();
/**
* The shape as a string using the given request cycle; will be used
* for rendering.
* @return The shape as a string
*/
public String toString()
{
// Add any popup script
final String popupJavaScript;
if (link.getPopupSettings() != null)
{
popupJavaScript = link.getPopupSettings().getPopupJavaScript();
}
else
{
popupJavaScript = null;
}
return "<area shape=\""
+ getType() + "\"" + " coords=\"" + getCoordinates() + "\"" + " href=\""
+ link.getURL() + "\""
+ ((popupJavaScript == null) ? "" : (" onClick = \"" + popupJavaScript + "\""))
+ ">";
}
}
/**
* A shape that has a free (polygon) form.
*/
private static final class PolygonLink extends ShapeLink
{
/** Its coordinates. */
private final int[] coordinates;
/**
* Construct.
* @param coordinates the polygon coordinates
* @param link the link
*/
public PolygonLink(final int[] coordinates, final Link link)
{
super(link);
this.coordinates = coordinates;
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
*/
String getType()
{
return "polygon";
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
*/
String getCoordinates()
{
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i < coordinates.length; i++)
{
buffer.append(coordinates[i]);
if (i < (coordinates.length - 1))
{
buffer.append(',');
}
}
return buffer.toString();
}
}
/**
* A shape that has a rectangular form.
*/
private static final class RectangleLink extends ShapeLink
{
/** left upper x. */
private final int x1;
/** left upper y. */
private final int y1;
/** right bottom x. */
private final int x2;
/** right bottom y. */
private final int y2;
/**
* Construct.
* @param x1 left upper x
* @param y1 left upper y
* @param x2 right bottom x
* @param y2 right bottom y
* @param link the link
*/
public RectangleLink(final int x1, final int y1, final int x2, final int y2, final Link link)
{
super(link);
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
*/
String getType()
{
return "rectangle";
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
*/
String getCoordinates()
{
return x1 + "," + y1 + "," + x2 + "," + y2;
}
}
/**
* A shape that has a circle form.
*/
private static final class CircleLink extends ShapeLink
{
/** left upper x. */
private final int x1;
/** left upper y. */
private final int y1;
/** the circles' radius. */
private final int radius;
/**
* Construct.
* @param x1 left upper x
* @param y1 left upper y
* @param radius the circles' radius
* @param link the link
*/
public CircleLink(final int x1, final int y1, final int radius, final Link link)
{
super(link);
this.x1 = x1;
this.y1 = y1;
this.radius = radius;
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
*/
String getType()
{
return "circle";
}
/**
* @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
*/
String getCoordinates()
{
return x1 + "," + y1 + "," + radius;
}
}
} | Made shapelink class Serializable so that image maps can be clustered
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@455776 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/java/wicket/markup/html/link/ImageMap.java | Made shapelink class Serializable so that image maps can be clustered | <ide><path>icket/src/java/wicket/markup/html/link/ImageMap.java
<ide> import java.util.ArrayList;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<add>import java.io.Serializable;
<ide>
<ide> import wicket.markup.ComponentTag;
<ide> import wicket.markup.MarkupStream;
<ide> */
<ide> public final class ImageMap extends HtmlComponent
<ide> {
<del> /** Serial Version ID. */
<add> /** Serial Version ID. */
<ide> private static final long serialVersionUID = 209001445308790198L;
<ide>
<ide> /** list of shape links. */
<ide> private final List shapeLinks = new ArrayList();
<ide>
<del> /**
<del> * Constructor.
<del> * @param name component name
<del> */
<del> public ImageMap(final String name)
<del> {
<del> super(name);
<del> }
<del>
<del> /**
<del> * Renders this component.
<del> * @see wicket.Component#handleRender()
<del> */
<del> protected void handleRender()
<del> {
<del> // Get markup stream
<del> final MarkupStream markupStream = findMarkupStream();
<del>
<del> // Get mutable copy of next tag
<del> final ComponentTag tag = markupStream.getTag().mutable();
<del>
<del> // Must be an img tag
<del> checkComponentTag(tag, "img");
<del>
<del> // Set map name to path
<del> tag.put("usemap", "#" + getPath());
<del>
<del> // Write out the tag
<del> renderComponentTag(tag);
<del> markupStream.next();
<del>
<del> // Write out the image map
<del> final StringBuffer imageMap = new StringBuffer();
<del>
<del> imageMap.append("\n<map name=\"" + getPath() + "\"> ");
<del>
<del> for (Iterator iterator = shapeLinks.iterator(); iterator.hasNext();)
<del> {
<del> final ShapeLink shapeLink = (ShapeLink) iterator.next();
<del>
<del> imageMap.append('\n');
<del> imageMap.append(shapeLink.toString());
<del> }
<del>
<del> imageMap.append("\n</map>");
<del> getResponse().write(imageMap.toString());
<del> }
<del>
<del> /**
<del> * Adds a polygon link.
<del> * @param coordinates the coordinates for the polygon
<del> * @param link the link
<del> * @return This
<del> */
<del> public ImageMap addPolygonLink(final int[] coordinates, final Link link)
<del> {
<del> shapeLinks.add(new PolygonLink(coordinates, link));
<del>
<del> return this;
<del> }
<del>
<del> /**
<del> * Adds a rectangular link.
<del> * @param x1 top left x
<del> * @param y1 top left y
<del> * @param x2 bottom right x
<del> * @param y2 bottom right y
<del> * @param link
<del> * @return This
<del> */
<del> public ImageMap addRectangleLink(final int x1, final int y1, final int x2, final int y2,
<del> final Link link)
<del> {
<del> shapeLinks.add(new RectangleLink(x1, y1, x2, y2, link));
<del>
<del> return this;
<del> }
<del>
<del> /**
<del> * Adds a circle link.
<del> * @param x1 top left x
<del> * @param y1 top left y
<del> * @param radius the radius
<del> * @param link the link
<del> * @return This
<del> */
<del> public ImageMap addCircleLink(final int x1, final int y1, final int radius, final Link link)
<del> {
<del> shapeLinks.add(new CircleLink(x1, y1, radius, link));
<del>
<del> return this;
<del> }
<del>
<del> /**
<del> * Base class for shaped links.
<del> */
<del> private static abstract class ShapeLink
<del> {
<del> /** the link. */
<del> private final Link link;
<del>
<del> /**
<del> * Constructor.
<del> * @param link the link
<del> */
<del> public ShapeLink(final Link link)
<del> {
<del> this.link = link;
<del> }
<del>
<del> /**
<del> * Gets the shape type.
<del> * @return the shape type
<del> */
<del> abstract String getType();
<del>
<del> /**
<del> * Gets the coordinates of the shape.
<del> * @return the coordinates of the shape
<del> */
<del> abstract String getCoordinates();
<del>
<del> /**
<del> * The shape as a string using the given request cycle; will be used
<del> * for rendering.
<del> * @return The shape as a string
<del> */
<del> public String toString()
<del> {
<del> // Add any popup script
<del> final String popupJavaScript;
<del>
<del> if (link.getPopupSettings() != null)
<del> {
<del> popupJavaScript = link.getPopupSettings().getPopupJavaScript();
<del> }
<del> else
<del> {
<del> popupJavaScript = null;
<del> }
<del>
<del> return "<area shape=\""
<del> + getType() + "\"" + " coords=\"" + getCoordinates() + "\"" + " href=\""
<del> + link.getURL() + "\""
<del> + ((popupJavaScript == null) ? "" : (" onClick = \"" + popupJavaScript + "\""))
<del> + ">";
<del> }
<del> }
<del>
<del> /**
<del> * A shape that has a free (polygon) form.
<del> */
<del> private static final class PolygonLink extends ShapeLink
<del> {
<del> /** Its coordinates. */
<del> private final int[] coordinates;
<del>
<del> /**
<del> * Construct.
<del> * @param coordinates the polygon coordinates
<del> * @param link the link
<del> */
<del> public PolygonLink(final int[] coordinates, final Link link)
<del> {
<del> super(link);
<del> this.coordinates = coordinates;
<del> }
<del>
<del> /**
<del> * @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
<del> */
<del> String getType()
<del> {
<del> return "polygon";
<del> }
<del>
<del> /**
<del> * @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
<del> */
<del> String getCoordinates()
<del> {
<del> final StringBuffer buffer = new StringBuffer();
<del> for (int i = 0; i < coordinates.length; i++)
<del> {
<del> buffer.append(coordinates[i]);
<del>
<del> if (i < (coordinates.length - 1))
<del> {
<del> buffer.append(',');
<del> }
<del> }
<del> return buffer.toString();
<del> }
<del> }
<del>
<del> /**
<del> * A shape that has a rectangular form.
<del> */
<del> private static final class RectangleLink extends ShapeLink
<del> {
<del> /** left upper x. */
<del> private final int x1;
<del>
<del> /** left upper y. */
<del> private final int y1;
<del>
<del> /** right bottom x. */
<del> private final int x2;
<del>
<del> /** right bottom y. */
<del> private final int y2;
<del>
<del> /**
<del> * Construct.
<del> * @param x1 left upper x
<del> * @param y1 left upper y
<del> * @param x2 right bottom x
<del> * @param y2 right bottom y
<del> * @param link the link
<del> */
<del> public RectangleLink(final int x1, final int y1, final int x2, final int y2, final Link link)
<del> {
<del> super(link);
<del> this.x1 = x1;
<del> this.y1 = y1;
<del> this.x2 = x2;
<del> this.y2 = y2;
<del> }
<del>
<del> /**
<del> * @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
<del> */
<del> String getType()
<del> {
<del> return "rectangle";
<del> }
<del>
<del> /**
<del> * @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
<del> */
<del> String getCoordinates()
<del> {
<del> return x1 + "," + y1 + "," + x2 + "," + y2;
<del> }
<del> }
<del>
<del> /**
<del> * A shape that has a circle form.
<del> */
<del> private static final class CircleLink extends ShapeLink
<del> {
<del> /** left upper x. */
<del> private final int x1;
<del>
<del> /** left upper y. */
<del> private final int y1;
<del>
<del> /** the circles' radius. */
<del> private final int radius;
<del>
<del> /**
<del> * Construct.
<del> * @param x1 left upper x
<del> * @param y1 left upper y
<del> * @param radius the circles' radius
<del> * @param link the link
<del> */
<del> public CircleLink(final int x1, final int y1, final int radius, final Link link)
<del> {
<del> super(link);
<del> this.x1 = x1;
<del> this.y1 = y1;
<del> this.radius = radius;
<del> }
<del>
<del> /**
<del> * @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
<del> */
<del> String getType()
<del> {
<del> return "circle";
<del> }
<del>
<del> /**
<del> * @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
<del> */
<del> String getCoordinates()
<del> {
<del> return x1 + "," + y1 + "," + radius;
<del> }
<del> }
<add> /**
<add> * Constructor.
<add> * @param name component name
<add> */
<add> public ImageMap(final String name)
<add> {
<add> super(name);
<add> }
<add>
<add> /**
<add> * Renders this component.
<add> * @see wicket.Component#handleRender()
<add> */
<add> protected void handleRender()
<add> {
<add> // Get markup stream
<add> final MarkupStream markupStream = findMarkupStream();
<add>
<add> // Get mutable copy of next tag
<add> final ComponentTag tag = markupStream.getTag().mutable();
<add>
<add> // Must be an img tag
<add> checkComponentTag(tag, "img");
<add>
<add> // Set map name to path
<add> tag.put("usemap", "#" + getPath());
<add>
<add> // Write out the tag
<add> renderComponentTag(tag);
<add> markupStream.next();
<add>
<add> // Write out the image map
<add> final StringBuffer imageMap = new StringBuffer();
<add>
<add> imageMap.append("\n<map name=\"" + getPath() + "\"> ");
<add>
<add> for (Iterator iterator = shapeLinks.iterator(); iterator.hasNext();)
<add> {
<add> final ShapeLink shapeLink = (ShapeLink) iterator.next();
<add>
<add> imageMap.append('\n');
<add> imageMap.append(shapeLink.toString());
<add> }
<add>
<add> imageMap.append("\n</map>");
<add> getResponse().write(imageMap.toString());
<add> }
<add>
<add> /**
<add> * Adds a polygon link.
<add> * @param coordinates the coordinates for the polygon
<add> * @param link the link
<add> * @return This
<add> */
<add> public ImageMap addPolygonLink(final int[] coordinates, final Link link)
<add> {
<add> shapeLinks.add(new PolygonLink(coordinates, link));
<add>
<add> return this;
<add> }
<add>
<add> /**
<add> * Adds a rectangular link.
<add> * @param x1 top left x
<add> * @param y1 top left y
<add> * @param x2 bottom right x
<add> * @param y2 bottom right y
<add> * @param link
<add> * @return This
<add> */
<add> public ImageMap addRectangleLink(final int x1, final int y1, final int x2, final int y2,
<add> final Link link)
<add> {
<add> shapeLinks.add(new RectangleLink(x1, y1, x2, y2, link));
<add>
<add> return this;
<add> }
<add>
<add> /**
<add> * Adds a circle link.
<add> * @param x1 top left x
<add> * @param y1 top left y
<add> * @param radius the radius
<add> * @param link the link
<add> * @return This
<add> */
<add> public ImageMap addCircleLink(final int x1, final int y1, final int radius, final Link link)
<add> {
<add> shapeLinks.add(new CircleLink(x1, y1, radius, link));
<add>
<add> return this;
<add> }
<add>
<add> /**
<add> * Base class for shaped links.
<add> */
<add> private static abstract class ShapeLink implements Serializable
<add> {
<add> /** the link. */
<add> private final Link link;
<add>
<add> /**
<add> * Constructor.
<add> * @param link the link
<add> */
<add> public ShapeLink(final Link link)
<add> {
<add> this.link = link;
<add> }
<add>
<add> /**
<add> * Gets the shape type.
<add> * @return the shape type
<add> */
<add> abstract String getType();
<add>
<add> /**
<add> * Gets the coordinates of the shape.
<add> * @return the coordinates of the shape
<add> */
<add> abstract String getCoordinates();
<add>
<add> /**
<add> * The shape as a string using the given request cycle; will be used
<add> * for rendering.
<add> * @return The shape as a string
<add> */
<add> public String toString()
<add> {
<add> // Add any popup script
<add> final String popupJavaScript;
<add>
<add> if (link.getPopupSettings() != null)
<add> {
<add> popupJavaScript = link.getPopupSettings().getPopupJavaScript();
<add> }
<add> else
<add> {
<add> popupJavaScript = null;
<add> }
<add>
<add> return "<area shape=\""
<add> + getType() + "\"" + " coords=\"" + getCoordinates() + "\"" + " href=\""
<add> + link.getURL() + "\""
<add> + ((popupJavaScript == null) ? "" : (" onClick = \"" + popupJavaScript + "\""))
<add> + ">";
<add> }
<add> }
<add>
<add> /**
<add> * A shape that has a free (polygon) form.
<add> */
<add> private static final class PolygonLink extends ShapeLink
<add> {
<add> /** Its coordinates. */
<add> private final int[] coordinates;
<add>
<add> /**
<add> * Construct.
<add> * @param coordinates the polygon coordinates
<add> * @param link the link
<add> */
<add> public PolygonLink(final int[] coordinates, final Link link)
<add> {
<add> super(link);
<add> this.coordinates = coordinates;
<add> }
<add>
<add> /**
<add> * @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
<add> */
<add> String getType()
<add> {
<add> return "polygon";
<add> }
<add>
<add> /**
<add> * @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
<add> */
<add> String getCoordinates()
<add> {
<add> final StringBuffer buffer = new StringBuffer();
<add> for (int i = 0; i < coordinates.length; i++)
<add> {
<add> buffer.append(coordinates[i]);
<add>
<add> if (i < (coordinates.length - 1))
<add> {
<add> buffer.append(',');
<add> }
<add> }
<add> return buffer.toString();
<add> }
<add> }
<add>
<add> /**
<add> * A shape that has a rectangular form.
<add> */
<add> private static final class RectangleLink extends ShapeLink
<add> {
<add> /** left upper x. */
<add> private final int x1;
<add>
<add> /** left upper y. */
<add> private final int y1;
<add>
<add> /** right bottom x. */
<add> private final int x2;
<add>
<add> /** right bottom y. */
<add> private final int y2;
<add>
<add> /**
<add> * Construct.
<add> * @param x1 left upper x
<add> * @param y1 left upper y
<add> * @param x2 right bottom x
<add> * @param y2 right bottom y
<add> * @param link the link
<add> */
<add> public RectangleLink(final int x1, final int y1, final int x2, final int y2, final Link link)
<add> {
<add> super(link);
<add> this.x1 = x1;
<add> this.y1 = y1;
<add> this.x2 = x2;
<add> this.y2 = y2;
<add> }
<add>
<add> /**
<add> * @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
<add> */
<add> String getType()
<add> {
<add> return "rectangle";
<add> }
<add>
<add> /**
<add> * @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
<add> */
<add> String getCoordinates()
<add> {
<add> return x1 + "," + y1 + "," + x2 + "," + y2;
<add> }
<add> }
<add>
<add> /**
<add> * A shape that has a circle form.
<add> */
<add> private static final class CircleLink extends ShapeLink
<add> {
<add> /** left upper x. */
<add> private final int x1;
<add>
<add> /** left upper y. */
<add> private final int y1;
<add>
<add> /** the circles' radius. */
<add> private final int radius;
<add>
<add> /**
<add> * Construct.
<add> * @param x1 left upper x
<add> * @param y1 left upper y
<add> * @param radius the circles' radius
<add> * @param link the link
<add> */
<add> public CircleLink(final int x1, final int y1, final int radius, final Link link)
<add> {
<add> super(link);
<add> this.x1 = x1;
<add> this.y1 = y1;
<add> this.radius = radius;
<add> }
<add>
<add> /**
<add> * @see wicket.markup.html.link.ImageMap.ShapeLink#getType()
<add> */
<add> String getType()
<add> {
<add> return "circle";
<add> }
<add>
<add> /**
<add> * @see wicket.markup.html.link.ImageMap.ShapeLink#getCoordinates()
<add> */
<add> String getCoordinates()
<add> {
<add> return x1 + "," + y1 + "," + radius;
<add> }
<add> }
<ide> } |
|
Java | epl-1.0 | 9ea9616a56f69ba2ca77e644944cc48359df2348 | 0 | codenvy/plugin-editor-codemirror,codenvy/plugin-editor-codemirror | /*******************************************************************************
* Copyright (c) 2014 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.ide.editor.codemirror.client.jso;
import com.codenvy.ide.editor.codemirror.client.jso.hints.CMHintFunctionOverlay;
import com.codenvy.ide.editor.codemirror.client.jso.options.CMEditorOptionsOverlay;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Element;
/**
* Overlay on the CodeMirror javascript object.
*/
public class CodeMirrorOverlay extends JavaScriptObject {
protected CodeMirrorOverlay() {}
/**
* Creates an editor instance using the global CodeMirror object.
* @param element the element backing the editor
* @return an editor instance
*/
public final static native CMEditorOverlay createEditorGlobal(final Element element) /*-{
return $wnd.CodeMirror(element, {});
}-*/;
/**
* Creates an editor instance using the global CodeMirror object.
* @param element the element backing the editor
* @param options the editor options
* @return an editor instance
*/
public final static native CMEditorOverlay createEditorGlobal(Element element,
JavaScriptObject options) /*-{
return $wnd.CodeMirror(element, options);
}-*/;
/**
* Creates an editor instance.
* @param element the element backing the editor
* @return an editor instance
*/
public final native CMEditorOverlay createEditor(Element element) /*-{
return this(element, options);
}-*/;
/**
* Creates an editor instance using the given CodeMirror object.
* @param element the element backing the editor
* @param options the editor options
* @return an editor instance
*/
public final native CMEditorOverlay createEditor(Element element,
JavaScriptObject options) /*-{
return this(element, options);
}-*/;
/**
* Version of codemirror.
*
* @return the version, major.minor.patch (all three are integers)
*/
public final static native String version() /*-{
return this.version();
}-*/;
/**
* Returns the default configuration object for new codemirror editors.<br>
* This object properties can be modified to change the default options for new editors (but will not change existing ones).
*
* @return the default configuration
*/
public final native CMEditorOptionsOverlay defaults() /*-{
return this.defaults;
}-*/;
/**
* CodeMirror modes by name.
*
* @return a javascript object such that modes[modeName] is the mode object
*/
public final native JavaScriptObject modes() /*-{
return this.modes;
}-*/;
/**
* Names of the modes loaded in codemirror.
*
* @return an array of names of modes
*/
public final native JsArrayString modeNames() /*-{
return Object.getOwnPropertyNames(this.modes).sort();
}-*/;
/**
* Codemirror modes by mime-types.
*
* @return a javascript object such that mimeModes[mimeType] is the matching mode object
*/
public final native JavaScriptObject mimeModes() /*-{
return this.mimeModes;
}-*/;
/**
* Names of the mime-types known in codemirror.
*
* @return an array of names of mime-types
*/
public final native JsArrayString mimeModeNames() /*-{
return Object.getOwnPropertyNames(this.mimeModes).sort();
}-*/;
/**
* Return the registered keymaps.
* @return the keymaps
*/
public final native CMKeymapSetOverlay keyMap() /*-{
return this.keyMap;
}-*/;
/**
* Returns the list of key names by code.
* @return the key names
*/
public final native JsArrayString keyNames() /*-{
return this.keyNames;
}-*/;
/**
* Tells in the showHint method is available on the CodeMirror object.
* @param module the CodeMirror object
* @return true iff CodeMirror.showHint is defined
*/
public static final native boolean hasShowHint(JavaScriptObject module) /*-{
return (("showHint" in module) && !(typeof(module[showHint]) === 'undefined'));
}-*/;
/**
* Returns the hint function matching the given name.
* @param name the name of the function
* @return the hint function
*/
public final static native CMHintFunctionOverlay getHintFunction(String name) /*-{
return this.hint[name];
}-*/;
}
| src/main/java/com/codenvy/ide/editor/codemirror/client/jso/CodeMirrorOverlay.java | /*******************************************************************************
* Copyright (c) 2014 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.ide.editor.codemirror.client.jso;
import com.codenvy.ide.editor.codemirror.client.jso.hints.CMHintFunctionOverlay;
import com.codenvy.ide.editor.codemirror.client.jso.options.CMEditorOptionsOverlay;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Element;
/**
* Overlay on the CodeMirror javascript object.
*/
public class CodeMirrorOverlay extends JavaScriptObject {
/**
* Creates an editor instance using the global CodeMirror object.
* @param element the element backing the editor
* @return an editor instance
*/
public final static native CMEditorOverlay createEditorGlobal(final Element element) /*-{
return $wnd.CodeMirror(element, {});
}-*/;
/**
* Creates an editor instance using the global CodeMirror object.
* @param element the element backing the editor
* @param options the editor options
* @return an editor instance
*/
public final static native CMEditorOverlay createEditorGlobal(Element element,
JavaScriptObject options) /*-{
return $wnd.CodeMirror(element, options);
}-*/;
/**
* Creates an editor instance.
* @param element the element backing the editor
* @return an editor instance
*/
public final native CMEditorOverlay createEditor(Element element) /*-{
return this(element, options);
}-*/;
/**
* Creates an editor instance using the given CodeMirror object.
* @param element the element backing the editor
* @param options the editor options
* @return an editor instance
*/
public final native CMEditorOverlay createEditor(Element element,
JavaScriptObject options) /*-{
return this(element, options);
}-*/;
/**
* Version of codemirror.
*
* @return the version, major.minor.patch (all three are integers)
*/
public final static native String version() /*-{
return this.version();
}-*/;
/**
* Returns the default configuration object for new codemirror editors.<br>
* This object properties can be modified to change the default options for new editors (but will not change existing ones).
*
* @return the default configuration
*/
public final native CMEditorOptionsOverlay defaults() /*-{
return this.defaults;
}-*/;
/**
* CodeMirror modes by name.
*
* @return a javascript object such that modes[modeName] is the mode object
*/
public final native JavaScriptObject modes() /*-{
return this.modes;
}-*/;
/**
* Names of the modes loaded in codemirror.
*
* @return an array of names of modes
*/
public final native JsArrayString modeNames() /*-{
return Object.getOwnPropertyNames(this.modes).sort();
}-*/;
/**
* Codemirror modes by mime-types.
*
* @return a javascript object such that mimeModes[mimeType] is the matching mode object
*/
public final native JavaScriptObject mimeModes() /*-{
return this.mimeModes;
}-*/;
/**
* Names of the mime-types known in codemirror.
*
* @return an array of names of mime-types
*/
public final native JsArrayString mimeModeNames() /*-{
return Object.getOwnPropertyNames(this.mimeModes).sort();
}-*/;
/**
* Return the registered keymaps.
* @return the keymaps
*/
public final native CMKeymapSetOverlay keyMap() /*-{
return this.keyMap;
}-*/;
/**
* Returns the list of key names by code.
* @return the key names
*/
public final native JsArrayString keyNames() /*-{
return this.keyNames;
}-*/;
/**
* Tells in the showHint method is available on the CodeMirror object.
* @param module the CodeMirror object
* @return true iff CodeMirror.showHint is defined
*/
public static final native boolean hasShowHint(JavaScriptObject module) /*-{
return (("showHint" in module) && !(typeof(module[showHint]) === 'undefined'));
}-*/;
/**
* Returns the hint function matching the given name.
* @param name the name of the function
* @return the hint function
*/
public final static native CMHintFunctionOverlay getHintFunction(String name) /*-{
return this.hint[name];
}-*/;
}
| Add missing protected constructor | src/main/java/com/codenvy/ide/editor/codemirror/client/jso/CodeMirrorOverlay.java | Add missing protected constructor | <ide><path>rc/main/java/com/codenvy/ide/editor/codemirror/client/jso/CodeMirrorOverlay.java
<ide> * Overlay on the CodeMirror javascript object.
<ide> */
<ide> public class CodeMirrorOverlay extends JavaScriptObject {
<add>
<add> protected CodeMirrorOverlay() {}
<ide>
<ide> /**
<ide> * Creates an editor instance using the global CodeMirror object. |
|
Java | mit | e446cc4604a0a89c8d742a0ca29772853641136a | 0 | przodownikR1/springJpaCamp,przodownikR1/springJpaCamp | package pl.java.scalatech.exercise.creating;
import org.junit.Test;
public class CreateUsingStandardServiceRegistryBuilderTest {
//AnnotationConfiguration, ServiceRegistryBuilder deprecated from hibernate 4
@Test
public void shouldCreateSession(){
}
}
| src/test/java/pl/java/scalatech/exercise/creating/CreateUsingStandardServiceRegistryBuilderTest.java | package pl.java.scalatech.exercise.creating;
import org.junit.Test;
public class CreateUsingStandardServiceRegistryBuilderTest {
@Test
public void shouldCreateSession(){
}
}
| session builder test
| src/test/java/pl/java/scalatech/exercise/creating/CreateUsingStandardServiceRegistryBuilderTest.java | session builder test | <ide><path>rc/test/java/pl/java/scalatech/exercise/creating/CreateUsingStandardServiceRegistryBuilderTest.java
<ide> package pl.java.scalatech.exercise.creating;
<add>
<ide>
<ide> import org.junit.Test;
<ide>
<ide> public class CreateUsingStandardServiceRegistryBuilderTest {
<del>
<add>
<add> //AnnotationConfiguration, ServiceRegistryBuilder deprecated from hibernate 4
<add>
<ide> @Test
<ide> public void shouldCreateSession(){
<ide> |
|
Java | apache-2.0 | d153a0e89a246d7d25e5a3b76804f2678bf1caa5 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.fileTypes.impl;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.diagnostic.PluginException;
import com.intellij.ide.highlighter.custom.SyntaxTable;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.plugins.StartupAbortedException;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.fileTypes.ex.ExternalizableFileType;
import com.intellij.openapi.fileTypes.ex.FileTypeChooser;
import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.openapi.options.NonLazySchemeProcessor;
import com.intellij.openapi.options.SchemeManager;
import com.intellij.openapi.options.SchemeManagerFactory;
import com.intellij.openapi.options.SchemeState;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.ByteArraySequence;
import com.intellij.openapi.util.io.ByteSequence;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.FileAttribute;
import com.intellij.openapi.vfs.newvfs.FileSystemInterface;
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.ui.GuiUtils;
import com.intellij.util.*;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.concurrency.BoundedTaskExecutor;
import com.intellij.util.containers.ConcurrentPackedBitsArray;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSetQueue;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.ide.PooledThreadExecutor;
import org.jetbrains.jps.model.fileTypes.FileNameMatcherFactory;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
@State(name = "FileTypeManager", storages = @Storage("filetypes.xml"), additionalExportFile = FileTypeManagerImpl.FILE_SPEC )
public class FileTypeManagerImpl extends FileTypeManagerEx implements PersistentStateComponent<Element>, Disposable {
private static final ExtensionPointName<FileTypeBean> EP_NAME = ExtensionPointName.create("com.intellij.fileType");
private static final Logger LOG = Logger.getInstance(FileTypeManagerImpl.class);
// You must update all existing default configurations accordingly
private static final int VERSION = 17;
private static final ThreadLocal<Pair<VirtualFile, FileType>> FILE_TYPE_FIXED_TEMPORARILY = new ThreadLocal<>();
// cached auto-detected file type. If the file was auto-detected as plain text or binary
// then the value is null and AUTO_DETECTED_* flags stored in packedFlags are used instead.
static final Key<FileType> DETECTED_FROM_CONTENT_FILE_TYPE_KEY = Key.create("DETECTED_FROM_CONTENT_FILE_TYPE_KEY");
// must be sorted
@SuppressWarnings("SpellCheckingInspection")
static final String DEFAULT_IGNORED = "*.hprof;*.pyc;*.pyo;*.rbc;*.yarb;*~;.DS_Store;.git;.hg;.svn;CVS;__pycache__;_svn;vssver.scc;vssver2.scc;";
private static boolean RE_DETECT_ASYNC = !ApplicationManager.getApplication().isUnitTestMode();
private final Set<FileType> myDefaultTypes = new THashSet<>();
private FileTypeIdentifiableByVirtualFile[] mySpecialFileTypes = FileTypeIdentifiableByVirtualFile.EMPTY_ARRAY;
private FileTypeAssocTable<FileType> myPatternsTable = new FileTypeAssocTable<>();
private final IgnoredPatternSet myIgnoredPatterns = new IgnoredPatternSet();
private final IgnoredFileCache myIgnoredFileCache = new IgnoredFileCache(myIgnoredPatterns);
private final FileTypeAssocTable<FileType> myInitialAssociations = new FileTypeAssocTable<>();
private final Map<FileNameMatcher, String> myUnresolvedMappings = new THashMap<>();
private final RemovedMappingTracker myRemovedMappingTracker = new RemovedMappingTracker();
private final Map<String, FileTypeBean> myPendingFileTypes = new HashMap<>();
private final FileTypeAssocTable<FileTypeBean> myPendingAssociations = new FileTypeAssocTable<>();
@NonNls private static final String ELEMENT_FILETYPE = "filetype";
@NonNls private static final String ELEMENT_IGNORE_FILES = "ignoreFiles";
@NonNls private static final String ATTRIBUTE_LIST = "list";
@NonNls private static final String ATTRIBUTE_VERSION = "version";
@NonNls private static final String ATTRIBUTE_NAME = "name";
@NonNls private static final String ATTRIBUTE_DESCRIPTION = "description";
private static class StandardFileType {
@NotNull private final FileType fileType;
@NotNull private final List<FileNameMatcher> matchers;
private StandardFileType(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers) {
this.fileType = fileType;
this.matchers = matchers;
}
}
private final MessageBus myMessageBus;
private final Map<String, StandardFileType> myStandardFileTypes = new LinkedHashMap<>();
@NonNls
private static final String[] FILE_TYPES_WITH_PREDEFINED_EXTENSIONS = {"JSP", "JSPX", "DTD", "HTML", "Properties", "XHTML"};
private final SchemeManager<FileType> mySchemeManager;
@NonNls
static final String FILE_SPEC = "filetypes";
// these flags are stored in 'packedFlags' as chunks of four bits
private static final byte AUTO_DETECTED_AS_TEXT_MASK = 1; // set if the file was auto-detected as text
private static final byte AUTO_DETECTED_AS_BINARY_MASK = 1<<1; // set if the file was auto-detected as binary
// set if auto-detection was performed for this file.
// if some detector returned some custom file type, it's stored in DETECTED_FROM_CONTENT_FILE_TYPE_KEY file key.
// otherwise if auto-detected as text or binary, the result is stored in AUTO_DETECTED_AS_TEXT_MASK|AUTO_DETECTED_AS_BINARY_MASK bits
private static final byte AUTO_DETECT_WAS_RUN_MASK = 1<<2;
private static final byte ATTRIBUTES_WERE_LOADED_MASK = 1<<3; // set if AUTO_* bits above were loaded from the file persistent attributes and saved to packedFlags
private final ConcurrentPackedBitsArray packedFlags = new ConcurrentPackedBitsArray(4);
private final AtomicInteger counterAutoDetect = new AtomicInteger();
private final AtomicLong elapsedAutoDetect = new AtomicLong();
private final Object PENDING_INIT_LOCK = new Object();
public FileTypeManagerImpl() {
int fileTypeChangedCounter = PropertiesComponent.getInstance().getInt("fileTypeChangedCounter", 0);
fileTypeChangedCount = new AtomicInteger(fileTypeChangedCounter);
autoDetectedAttribute = new FileAttribute("AUTO_DETECTION_CACHE_ATTRIBUTE", fileTypeChangedCounter, true);
myMessageBus = ApplicationManager.getApplication().getMessageBus();
mySchemeManager = SchemeManagerFactory.getInstance().create(FILE_SPEC, new NonLazySchemeProcessor<FileType, AbstractFileType>() {
@NotNull
@Override
public AbstractFileType readScheme(@NotNull Element element, boolean duringLoad) {
if (!duringLoad) {
fireBeforeFileTypesChanged();
}
AbstractFileType type = (AbstractFileType)loadFileType(element, false);
if (!duringLoad) {
fireFileTypesChanged(type, null);
}
return type;
}
@NotNull
@Override
public SchemeState getState(@NotNull FileType fileType) {
if (!(fileType instanceof AbstractFileType) || !shouldSave(fileType)) {
return SchemeState.NON_PERSISTENT;
}
if (!myDefaultTypes.contains(fileType)) {
return SchemeState.POSSIBLY_CHANGED;
}
return ((AbstractFileType)fileType).isModified() ? SchemeState.POSSIBLY_CHANGED : SchemeState.NON_PERSISTENT;
}
@NotNull
@Override
public Element writeScheme(@NotNull AbstractFileType fileType) {
Element root = new Element(ELEMENT_FILETYPE);
root.setAttribute("binary", String.valueOf(fileType.isBinary()));
if (!StringUtil.isEmpty(fileType.getDefaultExtension())) {
root.setAttribute("default_extension", fileType.getDefaultExtension());
}
root.setAttribute(ATTRIBUTE_DESCRIPTION, fileType.getDescription());
root.setAttribute(ATTRIBUTE_NAME, fileType.getName());
fileType.writeExternal(root);
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
writeExtensionsMap(map, fileType, false);
if (!map.getChildren().isEmpty()) {
root.addContent(map);
}
return root;
}
@Override
public void onSchemeDeleted(@NotNull AbstractFileType scheme) {
GuiUtils.invokeLaterIfNeeded(() -> {
Application app = ApplicationManager.getApplication();
app.runWriteAction(() -> fireBeforeFileTypesChanged());
myPatternsTable.removeAllAssociations(scheme);
app.runWriteAction(() -> fireFileTypesChanged(null, scheme));
}, ModalityState.NON_MODAL);
}
});
// this should be done BEFORE reading state
initStandardFileTypes();
myMessageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
Collection<VirtualFile> files = ContainerUtil.map2Set(events, (Function<VFileEvent, VirtualFile>)event -> {
VirtualFile file = event instanceof VFileCreateEvent ? /* avoid expensive find child here */ null : event.getFile();
VirtualFile filtered = file != null && wasAutoDetectedBefore(file) && isDetectable(file) ? file : null;
if (toLog()) {
log("F: after() VFS event " + event +
"; filtered file: " + filtered +
" (file: " + file +
"; wasAutoDetectedBefore(file): " + (file == null ? null : wasAutoDetectedBefore(file)) +
"; isDetectable(file): " + (file == null ? null : isDetectable(file)) +
"; file.getLength(): " + (file == null ? null : file.getLength()) +
"; file.isValid(): " + (file == null ? null : file.isValid()) +
"; file.is(VFileProperty.SPECIAL): " + (file == null ? null : file.is(VFileProperty.SPECIAL)) +
"; packedFlags.get(id): " + (file instanceof VirtualFileWithId ? readableFlags(packedFlags.get(((VirtualFileWithId)file).getId())) : null) +
"; file.getFileSystem():" + (file == null ? null : file.getFileSystem()) + ")");
}
return filtered;
});
files.remove(null);
if (toLog()) {
log("F: after() VFS events: " + events+"; files: "+files);
}
if (!files.isEmpty() && RE_DETECT_ASYNC) {
if (toLog()) {
log("F: after() queued to redetect: " + files);
}
synchronized (filesToRedetect) {
if (filesToRedetect.addAll(files)) {
awakeReDetectExecutor();
}
}
}
}
});
myIgnoredPatterns.setIgnoreMasks(DEFAULT_IGNORED);
EP_NAME.addExtensionPointListener(new ExtensionPointListener<FileTypeBean>() {
@Override
public void extensionAdded(@NotNull FileTypeBean extension, @NotNull PluginDescriptor pluginDescriptor) {
fireBeforeFileTypesChanged();
initializeMatchers(extension);
FileType fileType = instantiateFileTypeBean(extension);
fireFileTypesChanged(fileType, null);
}
@Override
public void extensionRemoved(@NotNull FileTypeBean extension, @NotNull PluginDescriptor pluginDescriptor) {
final FileType fileType = findFileTypeByName(extension.name);
unregisterFileType(fileType);
if (fileType instanceof LanguageFileType) {
final LanguageFileType languageFileType = (LanguageFileType)fileType;
if (!languageFileType.isSecondary()) {
Language.unregisterLanguage(languageFileType.getLanguage());
}
}
}
}, this);
}
@VisibleForTesting
void initStandardFileTypes() {
loadFileTypeBeans();
FileTypeConsumer consumer = new FileTypeConsumer() {
@Override
public void consume(@NotNull FileType fileType) {
register(fileType, parse(fileType.getDefaultExtension()));
}
@Override
public void consume(@NotNull final FileType fileType, String extensions) {
register(fileType, parse(extensions));
}
@Override
public void consume(@NotNull final FileType fileType, @NotNull final FileNameMatcher... matchers) {
register(fileType, new ArrayList<>(Arrays.asList(matchers)));
}
@Override
public FileType getStandardFileTypeByName(@NotNull final String name) {
final StandardFileType type = myStandardFileTypes.get(name);
return type != null ? type.fileType : null;
}
private void register(@NotNull FileType fileType, @NotNull List<FileNameMatcher> fileNameMatchers) {
instantiatePendingFileTypeByName(fileType.getName());
for (FileNameMatcher matcher : fileNameMatchers) {
FileTypeBean pendingTypeByMatcher = myPendingAssociations.findAssociatedFileType(matcher);
if (pendingTypeByMatcher != null) {
PluginId id = pendingTypeByMatcher.getPluginId();
if (id == null || PluginManagerCore.CORE_ID == id) {
instantiateFileTypeBean(pendingTypeByMatcher);
}
}
}
final StandardFileType type = myStandardFileTypes.get(fileType.getName());
if (type != null) {
type.matchers.addAll(fileNameMatchers);
}
else {
myStandardFileTypes.put(fileType.getName(), new StandardFileType(fileType, fileNameMatchers));
}
}
};
//noinspection deprecation
FileTypeFactory.FILE_TYPE_FACTORY_EP.processWithPluginDescriptor((factory, pluginDescriptor) -> {
try {
factory.createFileTypes(consumer);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (StartupAbortedException e) {
throw e;
}
catch (Throwable e) {
throw new StartupAbortedException("Cannot create file types", new PluginException(e, pluginDescriptor.getPluginId()));
}
});
for (StandardFileType pair : myStandardFileTypes.values()) {
registerFileTypeWithoutNotification(pair.fileType, pair.matchers, true);
}
try {
URL defaultFileTypesUrl = FileTypeManagerImpl.class.getResource("/defaultFileTypes.xml");
if (defaultFileTypesUrl != null) {
Element defaultFileTypesElement = JDOMUtil.load(URLUtil.openStream(defaultFileTypesUrl));
for (Element e : defaultFileTypesElement.getChildren()) {
if ("filetypes".equals(e.getName())) {
for (Element element : e.getChildren(ELEMENT_FILETYPE)) {
String fileTypeName = element.getAttributeValue(ATTRIBUTE_NAME);
if (myPendingFileTypes.get(fileTypeName) != null) continue;
loadFileType(element, true);
}
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(e.getName())) {
readGlobalMappings(e, true);
}
}
if (PlatformUtils.isIdeaCommunity()) {
Element extensionMap = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
extensionMap.addContent(new Element(AbstractFileType.ELEMENT_MAPPING)
.setAttribute(AbstractFileType.ATTRIBUTE_EXT, "jspx")
.setAttribute(AbstractFileType.ATTRIBUTE_TYPE, "XML"));
//noinspection SpellCheckingInspection
extensionMap.addContent(new Element(AbstractFileType.ELEMENT_MAPPING)
.setAttribute(AbstractFileType.ATTRIBUTE_EXT, "tagx")
.setAttribute(AbstractFileType.ATTRIBUTE_TYPE, "XML"));
readGlobalMappings(extensionMap, true);
}
}
}
catch (Exception e) {
LOG.error(e);
}
}
private void loadFileTypeBeans() {
final List<FileTypeBean> fileTypeBeans = EP_NAME.getExtensionList();
for (FileTypeBean bean : fileTypeBeans) {
initializeMatchers(bean);
}
for (FileTypeBean bean : fileTypeBeans) {
if (bean.implementationClass == null) continue;
if (myPendingFileTypes.containsKey(bean.name)) {
LOG.error(new PluginException("Trying to override already registered file type " + bean.name, bean.getPluginId()));
continue;
}
myPendingFileTypes.put(bean.name, bean);
for (FileNameMatcher matcher : bean.getMatchers()) {
myPendingAssociations.addAssociation(matcher, bean);
}
}
// Register additional extensions for file types
for (FileTypeBean bean : fileTypeBeans) {
if (bean.implementationClass != null) continue;
FileTypeBean oldBean = myPendingFileTypes.get(bean.name);
if (oldBean == null) {
LOG.error(new PluginException("Trying to add extensions to non-registered file type " + bean.name, bean.getPluginId()));
continue;
}
oldBean.addMatchers(bean.getMatchers());
for (FileNameMatcher matcher : bean.getMatchers()) {
myPendingAssociations.addAssociation(matcher, oldBean);
}
}
}
private static void initializeMatchers(FileTypeBean bean) {
bean.addMatchers(ContainerUtil.concat(
parse(bean.extensions),
parse(bean.fileNames, token -> new ExactFileNameMatcher(token)),
parse(bean.fileNamesCaseInsensitive, token -> new ExactFileNameMatcher(token, true)),
parse(bean.patterns, token -> FileNameMatcherFactory.getInstance().createMatcher(token))));
}
private void instantiatePendingFileTypes() {
final Collection<FileTypeBean> fileTypes = new ArrayList<>(myPendingFileTypes.values());
for (FileTypeBean fileTypeBean : fileTypes) {
final StandardFileType type = myStandardFileTypes.get(fileTypeBean.name);
if (type != null) {
type.matchers.addAll(fileTypeBean.getMatchers());
}
else {
instantiateFileTypeBean(fileTypeBean);
}
}
}
private FileType instantiateFileTypeBean(@NotNull FileTypeBean fileTypeBean) {
FileType fileType;
PluginId pluginId = fileTypeBean.getPluginDescriptor().getPluginId();
try {
@SuppressWarnings("unchecked")
Class<FileType> beanClass = (Class<FileType>)Class.forName(fileTypeBean.implementationClass, true, fileTypeBean.getPluginDescriptor().getPluginClassLoader());
if (fileTypeBean.fieldName != null) {
Field field = beanClass.getDeclaredField(fileTypeBean.fieldName);
field.setAccessible(true);
fileType = (FileType)field.get(null);
}
else {
// uncached - cached by FileTypeManagerImpl and not by bean
fileType = ReflectionUtil.newInstance(beanClass, false);
}
}
catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
LOG.error(new PluginException(e, pluginId));
return null;
}
if (!fileType.getName().equals(fileTypeBean.name)) {
LOG.error(new PluginException("Incorrect name specified in <fileType>, should be " + fileType.getName() + ", actual " + fileTypeBean.name, pluginId));
}
if (fileType instanceof LanguageFileType) {
final LanguageFileType languageFileType = (LanguageFileType)fileType;
String expectedLanguage = languageFileType.isSecondary() ? null : languageFileType.getLanguage().getID();
if (!Comparing.equal(fileTypeBean.language, expectedLanguage)) {
LOG.error(new PluginException("Incorrect language specified in <fileType> for " + fileType.getName() + ", should be " + expectedLanguage + ", actual " + fileTypeBean.language, pluginId));
}
}
final StandardFileType standardFileType = new StandardFileType(fileType, fileTypeBean.getMatchers());
myStandardFileTypes.put(fileTypeBean.name, standardFileType);
registerFileTypeWithoutNotification(standardFileType.fileType, standardFileType.matchers, true);
myPendingAssociations.removeAllAssociations(fileTypeBean);
myPendingFileTypes.remove(fileTypeBean.name);
return fileType;
}
@TestOnly
boolean toLog;
private boolean toLog() {
return toLog;
}
private static void log(String message) {
LOG.debug(message + " - "+Thread.currentThread());
}
private final Executor
reDetectExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("FileTypeManager Redetect Pool", PooledThreadExecutor.INSTANCE, 1, this);
private final HashSetQueue<VirtualFile> filesToRedetect = new HashSetQueue<>();
private static final int CHUNK_SIZE = 10;
private void awakeReDetectExecutor() {
reDetectExecutor.execute(() -> {
List<VirtualFile> files = new ArrayList<>(CHUNK_SIZE);
synchronized (filesToRedetect) {
for (int i = 0; i < CHUNK_SIZE; i++) {
VirtualFile file = filesToRedetect.poll();
if (file == null) break;
files.add(file);
}
}
if (files.size() == CHUNK_SIZE) {
awakeReDetectExecutor();
}
reDetect(files);
});
}
@TestOnly
public void drainReDetectQueue() {
try {
((BoundedTaskExecutor)reDetectExecutor).waitAllTasksExecuted(1, TimeUnit.MINUTES);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@TestOnly
@NotNull
Collection<VirtualFile> dumpReDetectQueue() {
synchronized (filesToRedetect) {
return new ArrayList<>(filesToRedetect);
}
}
@TestOnly
static void reDetectAsync(boolean enable) {
RE_DETECT_ASYNC = enable;
}
private void reDetect(@NotNull Collection<? extends VirtualFile> files) {
List<VirtualFile> changed = new ArrayList<>();
List<VirtualFile> crashed = new ArrayList<>();
for (VirtualFile file : files) {
boolean shouldRedetect = wasAutoDetectedBefore(file) && isDetectable(file);
if (toLog()) {
log("F: reDetect("+file.getName()+") " + file.getName() + "; shouldRedetect: " + shouldRedetect);
}
if (shouldRedetect) {
int id = ((VirtualFileWithId)file).getId();
long flags = packedFlags.get(id);
FileType before = ObjectUtils.notNull(textOrBinaryFromCachedFlags(flags),
ObjectUtils.notNull(file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY),
PlainTextFileType.INSTANCE));
FileType after = getByFile(file);
if (toLog()) {
log("F: reDetect(" + file.getName() + ") prepare to redetect. flags: " + readableFlags(flags) +
"; beforeType: " + before.getName() + "; afterByFileType: " + (after == null ? null : after.getName()));
}
if (after == null || mightBeReplacedByDetectedFileType(after)) {
try {
after = detectFromContentAndCache(file, null);
}
catch (IOException e) {
crashed.add(file);
if (toLog()) {
log("F: reDetect(" + file.getName() + ") " + "before: " + before.getName() + "; after: crashed with " + e.getMessage() +
"; now getFileType()=" + file.getFileType().getName() +
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
continue;
}
}
else {
// back to standard file type
// detected by conventional methods, no need to run detect-from-content
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
flags = 0;
packedFlags.set(id, flags);
}
if (toLog()) {
log("F: reDetect(" + file.getName() + ") " + "before: " + before.getName() + "; after: " + after.getName() +
"; now getFileType()=" + file.getFileType().getName() +
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
if (before != after) {
changed.add(file);
}
}
}
if (!changed.isEmpty()) {
reparseLater(changed);
}
if (!crashed.isEmpty()) {
// do not re-scan locked or invalid files too often to avoid constant disk thrashing if that condition is permanent
AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> reparseLater(crashed), 10, TimeUnit.SECONDS);
}
}
private static void reparseLater(@NotNull List<? extends VirtualFile> changed) {
ApplicationManager.getApplication().invokeLater(() -> FileContentUtilCore.reparseFiles(changed), ApplicationManager.getApplication().getDisposed());
}
private boolean wasAutoDetectedBefore(@NotNull VirtualFile file) {
if (file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) != null) {
return true;
}
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
// do not re-detect binary files
return (packedFlags.get(id) & (AUTO_DETECT_WAS_RUN_MASK | AUTO_DETECTED_AS_BINARY_MASK)) == AUTO_DETECT_WAS_RUN_MASK;
}
return false;
}
@Override
@NotNull
public FileType getStdFileType(@NotNull @NonNls String name) {
StandardFileType stdFileType;
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(name);
stdFileType = myStandardFileTypes.get(name);
}
return stdFileType != null ? stdFileType.fileType : PlainTextFileType.INSTANCE;
}
private void instantiatePendingFileTypeByName(@NonNls @NotNull String name) {
final FileTypeBean bean = myPendingFileTypes.get(name);
if (bean != null) {
instantiateFileTypeBean(bean);
}
}
@Override
public void initializeComponent() {
if (!myUnresolvedMappings.isEmpty()) {
instantiatePendingFileTypes();
}
if (!myUnresolvedMappings.isEmpty()) {
for (StandardFileType pair : myStandardFileTypes.values()) {
registerReDetectedMappings(pair);
}
}
// resolve unresolved mappings initialized before certain plugin initialized
if (!myUnresolvedMappings.isEmpty()) {
for (StandardFileType pair : myStandardFileTypes.values()) {
bindUnresolvedMappings(pair.fileType);
}
}
boolean isAtLeastOneStandardFileTypeHasBeenRead = false;
for (FileType fileType : mySchemeManager.loadSchemes()) {
isAtLeastOneStandardFileTypeHasBeenRead |= myInitialAssociations.hasAssociationsFor(fileType);
}
if (isAtLeastOneStandardFileTypeHasBeenRead) {
restoreStandardFileExtensions();
}
}
@Override
@NotNull
public FileType getFileTypeByFileName(@NotNull String fileName) {
return getFileTypeByFileName((CharSequence)fileName);
}
@Override
@NotNull
public FileType getFileTypeByFileName(@NotNull CharSequence fileName) {
synchronized (PENDING_INIT_LOCK) {
final FileTypeBean pendingFileType = myPendingAssociations.findAssociatedFileType(fileName);
if (pendingFileType != null) {
return ObjectUtils.notNull(instantiateFileTypeBean(pendingFileType), UnknownFileType.INSTANCE);
}
FileType type = myPatternsTable.findAssociatedFileType(fileName);
return ObjectUtils.notNull(type, UnknownFileType.INSTANCE);
}
}
public void freezeFileTypeTemporarilyIn(@NotNull VirtualFile file, @NotNull Runnable runnable) {
FileType fileType = file.getFileType();
Pair<VirtualFile, FileType> old = FILE_TYPE_FIXED_TEMPORARILY.get();
FILE_TYPE_FIXED_TEMPORARILY.set(Pair.create(file, fileType));
if (toLog()) {
log("F: freezeFileTypeTemporarilyIn(" + file.getName() + ") to " + fileType.getName()+" in "+Thread.currentThread());
}
try {
runnable.run();
}
finally {
if (old == null) {
FILE_TYPE_FIXED_TEMPORARILY.remove();
}
else {
FILE_TYPE_FIXED_TEMPORARILY.set(old);
}
if (toLog()) {
log("F: unfreezeFileType(" + file.getName() + ") in "+Thread.currentThread());
}
}
}
@Override
@NotNull
public FileType getFileTypeByFile(@NotNull VirtualFile file) {
return getFileTypeByFile(file, null);
}
@Override
@NotNull
public FileType getFileTypeByFile(@NotNull VirtualFile file, @Nullable byte[] content) {
FileType overriddenFileType = FileTypeOverrider.EP_NAME.computeSafeIfAny((overrider) -> overrider.getOverriddenFileType(file));
if (overriddenFileType != null) {
return overriddenFileType;
}
FileType fileType = getByFile(file);
if (!(file instanceof StubVirtualFile)) {
if (fileType == null) {
return getOrDetectFromContent(file, content);
}
if (mightBeReplacedByDetectedFileType(fileType) && isDetectable(file)) {
FileType detectedFromContent = getOrDetectFromContent(file, content);
// unknown file type means that it was detected as binary, it's better to keep it binary
if (detectedFromContent != PlainTextFileType.INSTANCE) {
return detectedFromContent;
}
}
}
return ObjectUtils.notNull(fileType, UnknownFileType.INSTANCE);
}
private static boolean mightBeReplacedByDetectedFileType(FileType fileType) {
return fileType instanceof PlainTextLikeFileType && fileType.isReadOnly();
}
@Nullable // null means all conventional detect methods returned UnknownFileType.INSTANCE, have to detect from content
public FileType getByFile(@NotNull VirtualFile file) {
Pair<VirtualFile, FileType> fixedType = FILE_TYPE_FIXED_TEMPORARILY.get();
if (fixedType != null && fixedType.getFirst().equals(file)) {
FileType fileType = fixedType.getSecond();
if (toLog()) {
log("F: getByFile(" + file.getName() + ") was frozen to " + fileType.getName()+" in "+Thread.currentThread());
}
return fileType;
}
if (file instanceof LightVirtualFile) {
FileType fileType = ((LightVirtualFile)file).getAssignedFileType();
if (fileType != null) {
return fileType;
}
}
for (FileTypeIdentifiableByVirtualFile type : mySpecialFileTypes) {
if (type.isMyFileType(file)) {
if (toLog()) {
log("F: getByFile(" + file.getName() + "): Special file type: " + type.getName());
}
return type;
}
}
FileType fileType = getFileTypeByFileName(file.getNameSequence());
if (fileType == UnknownFileType.INSTANCE) {
fileType = null;
}
if (toLog()) {
log("F: getByFile(" + file.getName() + ") By name file type: "+(fileType == null ? null : fileType.getName()));
}
return fileType;
}
@NotNull
private FileType getOrDetectFromContent(@NotNull VirtualFile file, @Nullable byte[] content) {
if (!isDetectable(file)) return UnknownFileType.INSTANCE;
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
long flags = packedFlags.get(id);
if (!BitUtil.isSet(flags, ATTRIBUTES_WERE_LOADED_MASK)) {
flags = readFlagsFromCache(file);
flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true);
packedFlags.set(id, flags);
if (toLog()) {
log("F: getOrDetectFromContent(" + file.getName() + "): readFlagsFromCache() = " + readableFlags(flags));
}
}
boolean autoDetectWasRun = BitUtil.isSet(flags, AUTO_DETECT_WAS_RUN_MASK);
if (autoDetectWasRun) {
FileType type = textOrBinaryFromCachedFlags(flags);
if (toLog()) {
log("F: getOrDetectFromContent("+file.getName()+"):" +
" cached type = "+(type==null?null:type.getName())+
"; packedFlags.get(id):"+ readableFlags(flags)+
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
if (type != null) {
return type;
}
}
}
FileType fileType = file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY);
if (toLog()) {
log("F: getOrDetectFromContent("+file.getName()+"): " +
"getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) = "+(fileType == null ? null : fileType.getName()));
}
if (fileType == null) {
// run autodetection
try {
fileType = detectFromContentAndCache(file, content);
}
catch (IOException e) {
fileType = UnknownFileType.INSTANCE;
}
}
if (toLog()) {
log("F: getOrDetectFromContent("+file.getName()+"): getFileType after detect run = "+fileType.getName());
}
return fileType;
}
@NotNull
private static String readableFlags(long flags) {
String result = "";
if (BitUtil.isSet(flags, ATTRIBUTES_WERE_LOADED_MASK)) result += "ATTRIBUTES_WERE_LOADED_MASK";
if (BitUtil.isSet(flags, AUTO_DETECT_WAS_RUN_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECT_WAS_RUN_MASK";
if (BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECTED_AS_BINARY_MASK";
if (BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECTED_AS_TEXT_MASK";
return result;
}
private volatile FileAttribute autoDetectedAttribute;
// read auto-detection flags from the persistent FS file attributes. If file attributes are absent, return 0 for flags
// returns three bits value for AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK and AUTO_DETECT_WAS_RUN_MASK bits
protected byte readFlagsFromCache(@NotNull VirtualFile file) {
boolean wasAutoDetectRun = false;
byte status = 0;
try (DataInputStream stream = autoDetectedAttribute.readAttribute(file)) {
status = stream == null ? 0 : stream.readByte();
wasAutoDetectRun = stream != null;
}
catch (IOException ignored) {
}
status = BitUtil.set(status, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun);
return (byte)(status & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK | AUTO_DETECT_WAS_RUN_MASK));
}
// store auto-detection flags to the persistent FS file attributes
// writes AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK bits only
protected void writeFlagsToCache(@NotNull VirtualFile file, int flags) {
try (DataOutputStream stream = autoDetectedAttribute.writeAttribute(file)) {
stream.writeByte(flags & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK));
}
catch (IOException e) {
LOG.error(e);
}
}
void clearCaches() {
packedFlags.clear();
if (toLog()) {
log("F: clearCaches()");
}
}
private void clearPersistentAttributes() {
int count = fileTypeChangedCount.incrementAndGet();
autoDetectedAttribute = autoDetectedAttribute.newVersion(count);
PropertiesComponent.getInstance().setValue("fileTypeChangedCounter", Integer.toString(count));
if (toLog()) {
log("F: clearPersistentAttributes()");
}
}
@Nullable //null means the file was not auto-detected as text/binary
private static FileType textOrBinaryFromCachedFlags(long flags) {
return BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK) ? PlainTextFileType.INSTANCE :
BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK) ? UnknownFileType.INSTANCE :
null;
}
private void cacheAutoDetectedFileType(@NotNull VirtualFile file, @NotNull FileType fileType) {
boolean wasAutodetectedAsText = fileType == PlainTextFileType.INSTANCE;
boolean wasAutodetectedAsBinary = fileType == UnknownFileType.INSTANCE;
int flags = BitUtil.set(0, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
writeFlagsToCache(file, flags);
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
flags = BitUtil.set(flags, AUTO_DETECT_WAS_RUN_MASK, true);
flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true);
packedFlags.set(id, flags);
if (wasAutodetectedAsText || wasAutodetectedAsBinary) {
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
if (toLog()) {
log("F: cacheAutoDetectedFileType("+file.getName()+") " +
"cached to " + fileType.getName() +
" flags = "+ readableFlags(flags)+
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
return;
}
}
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, fileType);
if (toLog()) {
log("F: cacheAutoDetectedFileType("+file.getName()+") " +
"cached to " + fileType.getName() +
" flags = "+ readableFlags(flags)+
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
}
@Override
public FileType findFileTypeByName(@NotNull String fileTypeName) {
FileType type = getStdFileType(fileTypeName);
// TODO: Abstract file types are not std one, so need to be restored specially,
// currently there are 6 of them and restoration does not happen very often so just iteration is enough
if (type != PlainTextFileType.INSTANCE || fileTypeName.equals(type.getName())) {
return type;
}
for (FileType fileType: mySchemeManager.getAllSchemes()) {
if (fileTypeName.equals(fileType.getName())) {
return fileType;
}
}
return null;
}
private static boolean isDetectable(@NotNull final VirtualFile file) {
if (file.isDirectory() || !file.isValid() || file.is(VFileProperty.SPECIAL) || file.getLength() == 0) {
// for empty file there is still hope its type will change
return false;
}
return file.getFileSystem() instanceof FileSystemInterface;
}
private int readSafely(@NotNull InputStream stream, @NotNull byte[] buffer, int offset, int length) throws IOException {
int n = stream.read(buffer, offset, length);
if (n <= 0) {
// maybe locked because someone else is writing to it
// repeat inside read action to guarantee all writes are finished
if (toLog()) {
log("F: processFirstBytes(): inputStream.read() returned "+n+"; retrying with read action. stream="+ streamInfo(stream));
}
n = ReadAction.compute(() -> stream.read(buffer, offset, length));
if (toLog()) {
log("F: processFirstBytes(): under read action inputStream.read() returned "+n+"; stream="+ streamInfo(stream));
}
}
return n;
}
@NotNull
private FileType detectFromContentAndCache(@NotNull final VirtualFile file, @Nullable byte[] content) throws IOException {
long start = System.currentTimeMillis();
FileType fileType = detectFromContent(file, content, FileTypeDetector.EP_NAME.getExtensionList());
cacheAutoDetectedFileType(file, fileType);
counterAutoDetect.incrementAndGet();
long elapsed = System.currentTimeMillis() - start;
elapsedAutoDetect.addAndGet(elapsed);
return fileType;
}
@NotNull
private FileType detectFromContent(@NotNull VirtualFile file, @Nullable byte[] content, @NotNull Iterable<? extends FileTypeDetector> detectors) throws IOException {
FileType fileType;
if (content != null) {
fileType = detect(file, content, content.length, detectors);
}
else {
try (InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
if (toLog()) {
log("F: detectFromContentAndCache(" + file.getName() + "):" + " inputStream=" + streamInfo(inputStream));
}
int fileLength = (int)file.getLength();
int bufferLength = StreamSupport.stream(detectors.spliterator(), false)
.map(FileTypeDetector::getDesiredContentPrefixLength)
.max(Comparator.naturalOrder())
.orElse(FileUtilRt.getUserContentLoadLimit());
byte[] buffer = fileLength <= FileUtilRt.THREAD_LOCAL_BUFFER_LENGTH
? FileUtilRt.getThreadLocalBuffer()
: new byte[Math.min(fileLength, bufferLength)];
int n = readSafely(inputStream, buffer, 0, buffer.length);
fileType = detect(file, buffer, n, detectors);
if (toLog()) {
try (InputStream newStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
byte[] buffer2 = new byte[50];
int n2 = newStream.read(buffer2, 0, buffer2.length);
log("F: detectFromContentAndCache(" + file.getName() + "): result: " + fileType.getName() +
"; stream: " + streamInfo(inputStream) +
"; newStream: " + streamInfo(newStream) +
"; read: " + n2 +
"; buffer: " + Arrays.toString(buffer2));
}
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect);
}
return fileType;
}
@NotNull
private FileType detect(@NotNull VirtualFile file, @NotNull byte[] bytes, int length, @NotNull Iterable<? extends FileTypeDetector> detectors) {
if (length <= 0) return UnknownFileType.INSTANCE;
// use PlainTextFileType because it doesn't supply its own charset detector
// help set charset in the process to avoid double charset detection from content
return LoadTextUtil.processTextFromBinaryPresentationOrNull(bytes, length,
file, true, true,
PlainTextFileType.INSTANCE, (@Nullable CharSequence text) -> {
if (toLog()) {
log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): bytes length=" + length +
"; isText=" + (text != null) + "; text='" + (text == null ? null : StringUtil.first(text, 100, true)) + "'" +
", detectors=" + detectors);
}
FileType detected = null;
ByteSequence firstBytes = new ByteArraySequence(bytes, 0, length);
for (FileTypeDetector detector : detectors) {
try {
detected = detector.detect(file, firstBytes, text);
}
catch (ProcessCanceledException e) {
LOG.error("Detector " + detector + " (" + detector.getClass() + ") threw PCE. Bad detector, bad!", new RuntimeException(e));
}
catch (Exception e) {
LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e);
}
if (detected != null) {
if (toLog()) {
log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): detector " + detector + " type as " + detected.getName());
}
break;
}
}
if (detected == null) {
detected = text == null ? UnknownFileType.INSTANCE : PlainTextFileType.INSTANCE;
if (toLog()) {
log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): " +
"no detector was able to detect. assigned " + detected.getName());
}
}
return detected;
});
}
// for diagnostics
@SuppressWarnings("ConstantConditions")
private static Object streamInfo(@NotNull InputStream stream) throws IOException {
if (stream instanceof BufferedInputStream) {
InputStream in = ReflectionUtil.getField(stream.getClass(), stream, InputStream.class, "in");
byte[] buf = ReflectionUtil.getField(stream.getClass(), stream, byte[].class, "buf");
int count = ReflectionUtil.getField(stream.getClass(), stream, int.class, "count");
int pos = ReflectionUtil.getField(stream.getClass(), stream, int.class, "pos");
return "BufferedInputStream(buf=" + (buf == null ? null : Arrays.toString(Arrays.copyOf(buf, count))) +
", count=" + count + ", pos=" + pos + ", in=" + streamInfo(in) + ")";
}
if (stream instanceof FileInputStream) {
String path = ReflectionUtil.getField(stream.getClass(), stream, String.class, "path");
FileChannel channel = ReflectionUtil.getField(stream.getClass(), stream, FileChannel.class, "channel");
boolean closed = ReflectionUtil.getField(stream.getClass(), stream, boolean.class, "closed");
int available = stream.available();
File file = new File(path);
return "FileInputStream(path=" + path + ", available=" + available + ", closed=" + closed +
", channel=" + channel + ", channel.size=" + (channel == null ? null : channel.size()) +
", file.exists=" + file.exists() + ", file.content='" + FileUtil.loadFile(file) + "')";
}
return stream;
}
@Override
public LanguageFileType findFileTypeByLanguage(@NotNull Language language) {
synchronized (PENDING_INIT_LOCK) {
for (FileTypeBean bean : myPendingFileTypes.values()) {
if (language.getID().equals(bean.language)) {
return (LanguageFileType)instantiateFileTypeBean(bean);
}
}
}
// Do not use getRegisteredFileTypes() to avoid instantiating all pending file types
return language.findMyFileType(mySchemeManager.getAllSchemes().toArray(FileType.EMPTY_ARRAY));
}
@Override
@NotNull
public FileType getFileTypeByExtension(@NotNull String extension) {
synchronized (PENDING_INIT_LOCK) {
final FileTypeBean pendingFileType = myPendingAssociations.findByExtension(extension);
if (pendingFileType != null) {
return ObjectUtils.notNull(instantiateFileTypeBean(pendingFileType), UnknownFileType.INSTANCE);
}
FileType type = myPatternsTable.findByExtension(extension);
return ObjectUtils.notNull(type, UnknownFileType.INSTANCE);
}
}
@Override
@Deprecated
public void registerFileType(@NotNull FileType fileType) {
registerFileType(fileType, ArrayUtilRt.EMPTY_STRING_ARRAY);
}
@Override
public void registerFileType(@NotNull final FileType type, @NotNull final List<? extends FileNameMatcher> defaultAssociations) {
DeprecatedMethodException.report("Use fileType extension instead.");
ApplicationManager.getApplication().runWriteAction(() -> {
fireBeforeFileTypesChanged();
registerFileTypeWithoutNotification(type, defaultAssociations, true);
fireFileTypesChanged(type, null);
});
}
@Override
public void unregisterFileType(@NotNull final FileType fileType) {
ApplicationManager.getApplication().runWriteAction(() -> {
fireBeforeFileTypesChanged();
unregisterFileTypeWithoutNotification(fileType);
myStandardFileTypes.remove(fileType.getName());
fireFileTypesChanged(null, fileType);
});
}
private void unregisterFileTypeWithoutNotification(@NotNull FileType fileType) {
myPatternsTable.removeAllAssociations(fileType);
myInitialAssociations.removeAllAssociations(fileType);
mySchemeManager.removeScheme(fileType);
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
final FileTypeIdentifiableByVirtualFile fakeFileType = (FileTypeIdentifiableByVirtualFile)fileType;
mySpecialFileTypes = ArrayUtil.remove(mySpecialFileTypes, fakeFileType, FileTypeIdentifiableByVirtualFile.ARRAY_FACTORY);
}
}
@Override
@NotNull
public FileType[] getRegisteredFileTypes() {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypes();
}
Collection<FileType> fileTypes = mySchemeManager.getAllSchemes();
return fileTypes.toArray(FileType.EMPTY_ARRAY);
}
@Override
@NotNull
public String getExtension(@NotNull String fileName) {
return FileUtilRt.getExtension(fileName);
}
@Override
@NotNull
public String getIgnoredFilesList() {
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
return masks.isEmpty() ? "" : StringUtil.join(masks, ";") + ";";
}
@Override
public void setIgnoredFilesList(@NotNull String list) {
fireBeforeFileTypesChanged();
myIgnoredFileCache.clearCache();
myIgnoredPatterns.setIgnoreMasks(list);
fireFileTypesChanged();
}
@Override
public boolean isIgnoredFilesListEqualToCurrent(@NotNull String list) {
Set<String> tempSet = new THashSet<>();
StringTokenizer tokenizer = new StringTokenizer(list, ";");
while (tokenizer.hasMoreTokens()) {
tempSet.add(tokenizer.nextToken());
}
return tempSet.equals(myIgnoredPatterns.getIgnoreMasks());
}
@Override
public boolean isFileIgnored(@NotNull String name) {
return myIgnoredPatterns.isIgnored(name);
}
@Override
public boolean isFileIgnored(@NotNull VirtualFile file) {
return myIgnoredFileCache.isFileIgnored(file);
}
@Override
@NotNull
public String[] getAssociatedExtensions(@NotNull FileType type) {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(type.getName());
//noinspection deprecation
return myPatternsTable.getAssociatedExtensions(type);
}
}
@Override
@NotNull
public List<FileNameMatcher> getAssociations(@NotNull FileType type) {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(type.getName());
return myPatternsTable.getAssociations(type);
}
}
@Override
public void associate(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
associate(type, matcher, true);
}
@Override
public void removeAssociation(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
removeAssociation(type, matcher, true);
}
@Override
public void fireBeforeFileTypesChanged() {
FileTypeEvent event = new FileTypeEvent(this, null, null);
myMessageBus.syncPublisher(TOPIC).beforeFileTypesChanged(event);
}
private final AtomicInteger fileTypeChangedCount;
@Override
public void fireFileTypesChanged() {
fireFileTypesChanged(null, null);
}
public void fireFileTypesChanged(@Nullable FileType addedFileType, @Nullable FileType removedFileType) {
clearCaches();
clearPersistentAttributes();
myMessageBus.syncPublisher(TOPIC).fileTypesChanged(new FileTypeEvent(this, addedFileType, removedFileType));
}
private final Map<FileTypeListener, MessageBusConnection> myAdapters = new HashMap<>();
@Override
public void addFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myMessageBus.connect();
connection.subscribe(TOPIC, listener);
myAdapters.put(listener, connection);
}
@Override
public void removeFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myAdapters.remove(listener);
if (connection != null) {
connection.disconnect();
}
}
@Override
public void loadState(@NotNull Element state) {
int savedVersion = StringUtilRt.parseInt(state.getAttributeValue(ATTRIBUTE_VERSION), 0);
for (Element element : state.getChildren()) {
if (element.getName().equals(ELEMENT_IGNORE_FILES)) {
myIgnoredPatterns.setIgnoreMasks(element.getAttributeValue(ATTRIBUTE_LIST));
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(element.getName())) {
readGlobalMappings(element, false);
}
}
if (savedVersion < 4) {
if (savedVersion == 0) {
addIgnore(".svn");
}
if (savedVersion < 2) {
restoreStandardFileExtensions();
}
addIgnore("*.pyc");
addIgnore("*.pyo");
addIgnore(".git");
}
if (savedVersion < 5) {
addIgnore("*.hprof");
}
if (savedVersion < 6) {
addIgnore("_svn");
}
if (savedVersion < 7) {
addIgnore(".hg");
}
if (savedVersion < 8) {
addIgnore("*~");
}
if (savedVersion < 9) {
addIgnore("__pycache__");
}
if (savedVersion < 11) {
addIgnore("*.rbc");
}
if (savedVersion < 13) {
// we want *.lib back since it's an important user artifact for CLion, also for IDEA project itself, since we have some libs.
unignoreMask("*.lib");
}
if (savedVersion < 15) {
// we want .bundle back, bundler keeps useful data there
unignoreMask(".bundle");
}
if (savedVersion < 16) {
// we want .tox back to allow users selecting interpreters from it
unignoreMask(".tox");
}
if (savedVersion < 17) {
addIgnore("*.rbc");
}
myIgnoredFileCache.clearCache();
String counter = JDOMExternalizer.readString(state, "fileTypeChangedCounter");
if (counter != null) {
fileTypeChangedCount.set(StringUtilRt.parseInt(counter, 0));
autoDetectedAttribute = autoDetectedAttribute.newVersion(fileTypeChangedCount.get());
}
}
private void unignoreMask(@NotNull final String maskToRemove) {
final Set<String> masks = new LinkedHashSet<>(myIgnoredPatterns.getIgnoreMasks());
masks.remove(maskToRemove);
myIgnoredPatterns.clearPatterns();
for (final String each : masks) {
myIgnoredPatterns.addIgnoreMask(each);
}
}
private void readGlobalMappings(@NotNull Element e, boolean isAddToInit) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(e)) {
FileType type = getFileTypeByName(association.getSecond());
FileNameMatcher matcher = association.getFirst();
final FileTypeBean pendingFileTypeBean = myPendingAssociations.findAssociatedFileType(matcher);
if (pendingFileTypeBean != null) {
instantiateFileTypeBean(pendingFileTypeBean);
}
if (type != null) {
if (PlainTextFileType.INSTANCE == type) {
FileType newFileType = myPatternsTable.findAssociatedFileType(matcher);
if (newFileType != null && newFileType != PlainTextFileType.INSTANCE && newFileType != UnknownFileType.INSTANCE) {
myRemovedMappingTracker.add(matcher, newFileType.getName(), false);
}
}
associate(type, matcher, false);
if (isAddToInit) {
myInitialAssociations.addAssociation(matcher, type);
}
}
else {
myUnresolvedMappings.put(matcher, association.getSecond());
}
}
myRemovedMappingTracker.load(e);
for (RemovedMappingTracker.RemovedMapping mapping : myRemovedMappingTracker.getRemovedMappings()) {
FileType fileType = getFileTypeByName(mapping.getFileTypeName());
if (fileType != null) {
removeAssociation(fileType, mapping.getFileNameMatcher(), false);
}
}
}
private void addIgnore(@NonNls @NotNull String ignoreMask) {
myIgnoredPatterns.addIgnoreMask(ignoreMask);
}
private void restoreStandardFileExtensions() {
for (final String name : FILE_TYPES_WITH_PREDEFINED_EXTENSIONS) {
final StandardFileType stdFileType = myStandardFileTypes.get(name);
if (stdFileType != null) {
FileType fileType = stdFileType.fileType;
for (FileNameMatcher matcher : myPatternsTable.getAssociations(fileType)) {
FileType defaultFileType = myInitialAssociations.findAssociatedFileType(matcher);
if (defaultFileType != null && defaultFileType != fileType) {
removeAssociation(fileType, matcher, false);
associate(defaultFileType, matcher, false);
}
}
for (FileNameMatcher matcher : myInitialAssociations.getAssociations(fileType)) {
associate(fileType, matcher, false);
}
}
}
}
@NotNull
@Override
public Element getState() {
Element state = new Element("state");
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
String ignoreFiles;
if (masks.isEmpty()) {
ignoreFiles = "";
}
else {
String[] strings = ArrayUtilRt.toStringArray(masks);
Arrays.sort(strings);
ignoreFiles = StringUtil.join(strings, ";") + ";";
}
if (!ignoreFiles.equalsIgnoreCase(DEFAULT_IGNORED)) {
// empty means empty list - we need to distinguish null and empty to apply or not to apply default value
state.addContent(new Element(ELEMENT_IGNORE_FILES).setAttribute(ATTRIBUTE_LIST, ignoreFiles));
}
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
List<FileType> notExternalizableFileTypes = new ArrayList<>();
for (FileType type : mySchemeManager.getAllSchemes()) {
if (!(type instanceof AbstractFileType) || myDefaultTypes.contains(type)) {
notExternalizableFileTypes.add(type);
}
}
if (!notExternalizableFileTypes.isEmpty()) {
Collections.sort(notExternalizableFileTypes, Comparator.comparing(FileType::getName));
for (FileType type : notExternalizableFileTypes) {
writeExtensionsMap(map, type, true);
}
}
// https://youtrack.jetbrains.com/issue/IDEA-138366
myRemovedMappingTracker.save(map);
if (!myUnresolvedMappings.isEmpty()) {
FileNameMatcher[] unresolvedMappingKeys = myUnresolvedMappings.keySet().toArray(new FileNameMatcher[0]);
Arrays.sort(unresolvedMappingKeys, Comparator.comparing(FileNameMatcher::getPresentableString));
for (FileNameMatcher fileNameMatcher : unresolvedMappingKeys) {
Element content = AbstractFileType.writeMapping(myUnresolvedMappings.get(fileNameMatcher), fileNameMatcher, true);
if (content != null) {
map.addContent(content);
}
}
}
if (!map.getChildren().isEmpty()) {
state.addContent(map);
}
if (!state.getChildren().isEmpty()) {
state.setAttribute(ATTRIBUTE_VERSION, String.valueOf(VERSION));
}
return state;
}
private void writeExtensionsMap(@NotNull Element map, @NotNull FileType type, boolean specifyTypeName) {
List<FileNameMatcher> associations = myPatternsTable.getAssociations(type);
Set<FileNameMatcher> defaultAssociations = new THashSet<>(myInitialAssociations.getAssociations(type));
for (FileNameMatcher matcher : associations) {
boolean isDefaultAssociationContains = defaultAssociations.remove(matcher);
if (!isDefaultAssociationContains && shouldSave(type)) {
Element content = AbstractFileType.writeMapping(type.getName(), matcher, specifyTypeName);
if (content != null) {
map.addContent(content);
}
}
}
myRemovedMappingTracker.saveRemovedMappingsForFileType(map, type.getName(), defaultAssociations, specifyTypeName);
}
// -------------------------------------------------------------------------
// Helper methods
// -------------------------------------------------------------------------
@Nullable
private FileType getFileTypeByName(@NotNull String name) {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(name);
return mySchemeManager.findSchemeByName(name);
}
}
@NotNull
private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited) {
return parse(semicolonDelimited, token -> new ExtensionFileNameMatcher(token));
}
@NotNull
private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited, Function<? super String, ? extends FileNameMatcher> matcherFactory) {
if (semicolonDelimited == null) {
return Collections.emptyList();
}
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
ArrayList<FileNameMatcher> list = new ArrayList<>(semicolonDelimited.length() / "py;".length());
while (tokenizer.hasMoreTokens()) {
list.add(matcherFactory.fun(tokenizer.nextToken().trim()));
}
return list;
}
/**
* Registers a standard file type. Doesn't notifyListeners any change events.
*/
private void registerFileTypeWithoutNotification(@NotNull FileType fileType, @NotNull List<? extends FileNameMatcher> matchers, boolean addScheme) {
if (addScheme) {
mySchemeManager.addScheme(fileType);
}
for (FileNameMatcher matcher : matchers) {
myPatternsTable.addAssociation(matcher, fileType);
myInitialAssociations.addAssociation(matcher, fileType);
}
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
mySpecialFileTypes = ArrayUtil.append(mySpecialFileTypes, (FileTypeIdentifiableByVirtualFile)fileType, FileTypeIdentifiableByVirtualFile.ARRAY_FACTORY);
}
}
private void bindUnresolvedMappings(@NotNull FileType fileType) {
for (FileNameMatcher matcher : new THashSet<>(myUnresolvedMappings.keySet())) {
String name = myUnresolvedMappings.get(matcher);
if (Comparing.equal(name, fileType.getName())) {
myPatternsTable.addAssociation(matcher, fileType);
myUnresolvedMappings.remove(matcher);
}
}
for (FileNameMatcher matcher : myRemovedMappingTracker.getMappingsForFileType(fileType.getName())) {
removeAssociation(fileType, matcher, false);
}
}
@NotNull
private FileType loadFileType(@NotNull Element typeElement, boolean isDefault) {
String fileTypeName = typeElement.getAttributeValue(ATTRIBUTE_NAME);
String fileTypeDescr = typeElement.getAttributeValue(ATTRIBUTE_DESCRIPTION);
String iconPath = typeElement.getAttributeValue("icon");
String extensionsStr = StringUtil.nullize(typeElement.getAttributeValue("extensions"));
if (isDefault && extensionsStr != null) {
// todo support wildcards
extensionsStr = filterAlreadyRegisteredExtensions(extensionsStr);
}
FileType type = isDefault ? getFileTypeByName(fileTypeName) : null;
if (type != null) {
return type;
}
Element element = typeElement.getChild(AbstractFileType.ELEMENT_HIGHLIGHTING);
if (element == null) {
type = new UserBinaryFileType();
}
else {
SyntaxTable table = AbstractFileType.readSyntaxTable(element);
type = new AbstractFileType(table);
((AbstractFileType)type).initSupport();
}
setFileTypeAttributes((UserFileType)type, fileTypeName, fileTypeDescr, iconPath);
registerFileTypeWithoutNotification(type, parse(extensionsStr), isDefault);
if (isDefault) {
myDefaultTypes.add(type);
if (type instanceof ExternalizableFileType) {
((ExternalizableFileType)type).markDefaultSettings();
}
}
else {
Element extensions = typeElement.getChild(AbstractFileType.ELEMENT_EXTENSION_MAP);
if (extensions != null) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(extensions)) {
associate(type, association.getFirst(), false);
}
for (RemovedMappingTracker.RemovedMapping removedAssociation : RemovedMappingTracker.readRemovedMappings(extensions)) {
removeAssociation(type, removedAssociation.getFileNameMatcher(), false);
}
}
}
return type;
}
@Nullable
private String filterAlreadyRegisteredExtensions(@NotNull String semicolonDelimited) {
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
StringBuilder builder = null;
while (tokenizer.hasMoreTokens()) {
String extension = tokenizer.nextToken().trim();
if (myPendingAssociations.findByExtension(extension) == null && getFileTypeByExtension(extension) == UnknownFileType.INSTANCE) {
if (builder == null) {
builder = new StringBuilder();
}
else if (builder.length() > 0) {
builder.append(FileTypeConsumer.EXTENSION_DELIMITER);
}
builder.append(extension);
}
}
return builder == null ? null : builder.toString();
}
private static void setFileTypeAttributes(@NotNull UserFileType fileType, @Nullable String name, @Nullable String description, @Nullable String iconPath) {
if (!StringUtil.isEmptyOrSpaces(iconPath)) {
fileType.setIconPath(iconPath);
}
if (description != null) {
fileType.setDescription(description);
}
if (name != null) {
fileType.setName(name);
}
}
private static boolean shouldSave(@NotNull FileType fileType) {
return fileType != UnknownFileType.INSTANCE && !fileType.isReadOnly();
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
@NotNull
FileTypeAssocTable<FileType> getExtensionMap() {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypes();
}
return myPatternsTable;
}
void setPatternsTable(@NotNull Set<? extends FileType> fileTypes, @NotNull FileTypeAssocTable<FileType> assocTable) {
Map<FileNameMatcher, FileType> removedMappings = getExtensionMap().getRemovedMappings(assocTable, fileTypes);
fireBeforeFileTypesChanged();
for (FileType existing : getRegisteredFileTypes()) {
if (!fileTypes.contains(existing)) {
mySchemeManager.removeScheme(existing);
}
}
for (FileType fileType : fileTypes) {
mySchemeManager.addScheme(fileType);
if (fileType instanceof AbstractFileType) {
((AbstractFileType)fileType).initSupport();
}
}
myPatternsTable = assocTable.copy();
fireFileTypesChanged();
myRemovedMappingTracker.removeMatching((matcher, fileTypeName) -> {
FileType fileType = getFileTypeByName(fileTypeName);
return fileType != null && assocTable.isAssociatedWith(fileType, matcher);
});
for (Map.Entry<FileNameMatcher, FileType> entry : removedMappings.entrySet()) {
myRemovedMappingTracker.add(entry.getKey(), entry.getValue().getName(), true);
}
}
public void associate(@NotNull FileType fileType, @NotNull FileNameMatcher matcher, boolean fireChange) {
if (!myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.addAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
public void removeAssociation(@NotNull FileType fileType, @NotNull FileNameMatcher matcher, boolean fireChange) {
if (myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.removeAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
@Override
@Nullable
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file) {
FileType type = file.getFileType();
if (type == UnknownFileType.INSTANCE) {
type = FileTypeChooser.associateFileType(file.getName());
}
return type;
}
@Override
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @NotNull Project project) {
return FileTypeChooser.getKnownFileTypeOrAssociate(file, project);
}
private void registerReDetectedMappings(@NotNull StandardFileType pair) {
FileType fileType = pair.fileType;
if (fileType == PlainTextFileType.INSTANCE) return;
for (FileNameMatcher matcher : pair.matchers) {
registerReDetectedMapping(fileType.getName(), matcher);
if (matcher instanceof ExtensionFileNameMatcher) {
// also check exact file name matcher
ExtensionFileNameMatcher extMatcher = (ExtensionFileNameMatcher)matcher;
registerReDetectedMapping(fileType.getName(), new ExactFileNameMatcher("." + extMatcher.getExtension()));
}
}
}
private void registerReDetectedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher) {
String typeName = myUnresolvedMappings.get(matcher);
if (typeName != null && !typeName.equals(fileTypeName)) {
if (!myRemovedMappingTracker.hasRemovedMapping(matcher)) {
myRemovedMappingTracker.add(matcher, fileTypeName, false);
}
myUnresolvedMappings.remove(matcher);
}
}
@NotNull
RemovedMappingTracker getRemovedMappingTracker() {
return myRemovedMappingTracker;
}
@TestOnly
void clearForTests() {
for (StandardFileType fileType : myStandardFileTypes.values()) {
myPatternsTable.removeAllAssociations(fileType.fileType);
}
for (FileType type : myDefaultTypes) {
myPatternsTable.removeAllAssociations(type);
}
myStandardFileTypes.clear();
myDefaultTypes.clear();
myUnresolvedMappings.clear();
myRemovedMappingTracker.clear();
for (FileTypeBean bean : myPendingFileTypes.values()) {
myPendingAssociations.removeAllAssociations(bean);
}
myPendingFileTypes.clear();
mySchemeManager.setSchemes(Collections.emptyList());
}
@Override
public void dispose() {
LOG.info(String.format("%s auto-detected files. Detection took %s ms", counterAutoDetect, elapsedAutoDetect));
}
}
| platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.fileTypes.impl;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.diagnostic.PluginException;
import com.intellij.ide.highlighter.custom.SyntaxTable;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.plugins.StartupAbortedException;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.fileTypes.ex.ExternalizableFileType;
import com.intellij.openapi.fileTypes.ex.FileTypeChooser;
import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.openapi.options.NonLazySchemeProcessor;
import com.intellij.openapi.options.SchemeManager;
import com.intellij.openapi.options.SchemeManagerFactory;
import com.intellij.openapi.options.SchemeState;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.ByteArraySequence;
import com.intellij.openapi.util.io.ByteSequence;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.FileAttribute;
import com.intellij.openapi.vfs.newvfs.FileSystemInterface;
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.ui.GuiUtils;
import com.intellij.util.*;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.concurrency.BoundedTaskExecutor;
import com.intellij.util.containers.ConcurrentPackedBitsArray;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSetQueue;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.ide.PooledThreadExecutor;
import org.jetbrains.jps.model.fileTypes.FileNameMatcherFactory;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
@State(name = "FileTypeManager", storages = @Storage("filetypes.xml"), additionalExportFile = FileTypeManagerImpl.FILE_SPEC )
public class FileTypeManagerImpl extends FileTypeManagerEx implements PersistentStateComponent<Element>, Disposable {
private static final ExtensionPointName<FileTypeBean> EP_NAME = ExtensionPointName.create("com.intellij.fileType");
private static final Logger LOG = Logger.getInstance(FileTypeManagerImpl.class);
// You must update all existing default configurations accordingly
private static final int VERSION = 17;
private static final ThreadLocal<Pair<VirtualFile, FileType>> FILE_TYPE_FIXED_TEMPORARILY = new ThreadLocal<>();
// cached auto-detected file type. If the file was auto-detected as plain text or binary
// then the value is null and AUTO_DETECTED_* flags stored in packedFlags are used instead.
static final Key<FileType> DETECTED_FROM_CONTENT_FILE_TYPE_KEY = Key.create("DETECTED_FROM_CONTENT_FILE_TYPE_KEY");
// must be sorted
@SuppressWarnings("SpellCheckingInspection")
static final String DEFAULT_IGNORED = "*.hprof;*.pyc;*.pyo;*.rbc;*.yarb;*~;.DS_Store;.git;.hg;.svn;CVS;__pycache__;_svn;vssver.scc;vssver2.scc;";
private static boolean RE_DETECT_ASYNC = !ApplicationManager.getApplication().isUnitTestMode();
private final Set<FileType> myDefaultTypes = new THashSet<>();
private FileTypeIdentifiableByVirtualFile[] mySpecialFileTypes = FileTypeIdentifiableByVirtualFile.EMPTY_ARRAY;
private FileTypeAssocTable<FileType> myPatternsTable = new FileTypeAssocTable<>();
private final IgnoredPatternSet myIgnoredPatterns = new IgnoredPatternSet();
private final IgnoredFileCache myIgnoredFileCache = new IgnoredFileCache(myIgnoredPatterns);
private final FileTypeAssocTable<FileType> myInitialAssociations = new FileTypeAssocTable<>();
private final Map<FileNameMatcher, String> myUnresolvedMappings = new THashMap<>();
private final RemovedMappingTracker myRemovedMappingTracker = new RemovedMappingTracker();
private final Map<String, FileTypeBean> myPendingFileTypes = new HashMap<>();
private final FileTypeAssocTable<FileTypeBean> myPendingAssociations = new FileTypeAssocTable<>();
@NonNls private static final String ELEMENT_FILETYPE = "filetype";
@NonNls private static final String ELEMENT_IGNORE_FILES = "ignoreFiles";
@NonNls private static final String ATTRIBUTE_LIST = "list";
@NonNls private static final String ATTRIBUTE_VERSION = "version";
@NonNls private static final String ATTRIBUTE_NAME = "name";
@NonNls private static final String ATTRIBUTE_DESCRIPTION = "description";
private static class StandardFileType {
@NotNull private final FileType fileType;
@NotNull private final List<FileNameMatcher> matchers;
private StandardFileType(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers) {
this.fileType = fileType;
this.matchers = matchers;
}
}
private final MessageBus myMessageBus;
private final Map<String, StandardFileType> myStandardFileTypes = new LinkedHashMap<>();
@NonNls
private static final String[] FILE_TYPES_WITH_PREDEFINED_EXTENSIONS = {"JSP", "JSPX", "DTD", "HTML", "Properties", "XHTML"};
private final SchemeManager<FileType> mySchemeManager;
@NonNls
static final String FILE_SPEC = "filetypes";
// these flags are stored in 'packedFlags' as chunks of four bits
private static final byte AUTO_DETECTED_AS_TEXT_MASK = 1; // set if the file was auto-detected as text
private static final byte AUTO_DETECTED_AS_BINARY_MASK = 1<<1; // set if the file was auto-detected as binary
// set if auto-detection was performed for this file.
// if some detector returned some custom file type, it's stored in DETECTED_FROM_CONTENT_FILE_TYPE_KEY file key.
// otherwise if auto-detected as text or binary, the result is stored in AUTO_DETECTED_AS_TEXT_MASK|AUTO_DETECTED_AS_BINARY_MASK bits
private static final byte AUTO_DETECT_WAS_RUN_MASK = 1<<2;
private static final byte ATTRIBUTES_WERE_LOADED_MASK = 1<<3; // set if AUTO_* bits above were loaded from the file persistent attributes and saved to packedFlags
private final ConcurrentPackedBitsArray packedFlags = new ConcurrentPackedBitsArray(4);
private final AtomicInteger counterAutoDetect = new AtomicInteger();
private final AtomicLong elapsedAutoDetect = new AtomicLong();
private final Object PENDING_INIT_LOCK = new Object();
public FileTypeManagerImpl() {
int fileTypeChangedCounter = PropertiesComponent.getInstance().getInt("fileTypeChangedCounter", 0);
fileTypeChangedCount = new AtomicInteger(fileTypeChangedCounter);
autoDetectedAttribute = new FileAttribute("AUTO_DETECTION_CACHE_ATTRIBUTE", fileTypeChangedCounter, true);
myMessageBus = ApplicationManager.getApplication().getMessageBus();
mySchemeManager = SchemeManagerFactory.getInstance().create(FILE_SPEC, new NonLazySchemeProcessor<FileType, AbstractFileType>() {
@NotNull
@Override
public AbstractFileType readScheme(@NotNull Element element, boolean duringLoad) {
if (!duringLoad) {
fireBeforeFileTypesChanged();
}
AbstractFileType type = (AbstractFileType)loadFileType(element, false);
if (!duringLoad) {
fireFileTypesChanged(type, null);
}
return type;
}
@NotNull
@Override
public SchemeState getState(@NotNull FileType fileType) {
if (!(fileType instanceof AbstractFileType) || !shouldSave(fileType)) {
return SchemeState.NON_PERSISTENT;
}
if (!myDefaultTypes.contains(fileType)) {
return SchemeState.POSSIBLY_CHANGED;
}
return ((AbstractFileType)fileType).isModified() ? SchemeState.POSSIBLY_CHANGED : SchemeState.NON_PERSISTENT;
}
@NotNull
@Override
public Element writeScheme(@NotNull AbstractFileType fileType) {
Element root = new Element(ELEMENT_FILETYPE);
root.setAttribute("binary", String.valueOf(fileType.isBinary()));
if (!StringUtil.isEmpty(fileType.getDefaultExtension())) {
root.setAttribute("default_extension", fileType.getDefaultExtension());
}
root.setAttribute(ATTRIBUTE_DESCRIPTION, fileType.getDescription());
root.setAttribute(ATTRIBUTE_NAME, fileType.getName());
fileType.writeExternal(root);
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
writeExtensionsMap(map, fileType, false);
if (!map.getChildren().isEmpty()) {
root.addContent(map);
}
return root;
}
@Override
public void onSchemeDeleted(@NotNull AbstractFileType scheme) {
GuiUtils.invokeLaterIfNeeded(() -> {
Application app = ApplicationManager.getApplication();
app.runWriteAction(() -> fireBeforeFileTypesChanged());
myPatternsTable.removeAllAssociations(scheme);
app.runWriteAction(() -> fireFileTypesChanged(null, scheme));
}, ModalityState.NON_MODAL);
}
});
// this should be done BEFORE reading state
initStandardFileTypes();
myMessageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
Collection<VirtualFile> files = ContainerUtil.map2Set(events, (Function<VFileEvent, VirtualFile>)event -> {
VirtualFile file = event instanceof VFileCreateEvent ? /* avoid expensive find child here */ null : event.getFile();
VirtualFile filtered = file != null && wasAutoDetectedBefore(file) && isDetectable(file) ? file : null;
if (toLog()) {
log("F: after() VFS event " + event +
"; filtered file: " + filtered +
" (file: " + file +
"; wasAutoDetectedBefore(file): " + (file == null ? null : wasAutoDetectedBefore(file)) +
"; isDetectable(file): " + (file == null ? null : isDetectable(file)) +
"; file.getLength(): " + (file == null ? null : file.getLength()) +
"; file.isValid(): " + (file == null ? null : file.isValid()) +
"; file.is(VFileProperty.SPECIAL): " + (file == null ? null : file.is(VFileProperty.SPECIAL)) +
"; packedFlags.get(id): " + (file instanceof VirtualFileWithId ? readableFlags(packedFlags.get(((VirtualFileWithId)file).getId())) : null) +
"; file.getFileSystem():" + (file == null ? null : file.getFileSystem()) + ")");
}
return filtered;
});
files.remove(null);
if (toLog()) {
log("F: after() VFS events: " + events+"; files: "+files);
}
if (!files.isEmpty() && RE_DETECT_ASYNC) {
if (toLog()) {
log("F: after() queued to redetect: " + files);
}
synchronized (filesToRedetect) {
if (filesToRedetect.addAll(files)) {
awakeReDetectExecutor();
}
}
}
}
});
myIgnoredPatterns.setIgnoreMasks(DEFAULT_IGNORED);
EP_NAME.addExtensionPointListener(new ExtensionPointListener<FileTypeBean>() {
@Override
public void extensionAdded(@NotNull FileTypeBean extension, @NotNull PluginDescriptor pluginDescriptor) {
fireBeforeFileTypesChanged();
initializeMatchers(extension);
FileType fileType = instantiateFileTypeBean(extension);
fireFileTypesChanged(fileType, null);
}
@Override
public void extensionRemoved(@NotNull FileTypeBean extension, @NotNull PluginDescriptor pluginDescriptor) {
final FileType fileType = findFileTypeByName(extension.name);
unregisterFileType(fileType);
if (fileType instanceof LanguageFileType) {
final LanguageFileType languageFileType = (LanguageFileType)fileType;
if (!languageFileType.isSecondary()) {
Language.unregisterLanguage(languageFileType.getLanguage());
}
}
}
}, this);
}
@VisibleForTesting
void initStandardFileTypes() {
loadFileTypeBeans();
FileTypeConsumer consumer = new FileTypeConsumer() {
@Override
public void consume(@NotNull FileType fileType) {
register(fileType, parse(fileType.getDefaultExtension()));
}
@Override
public void consume(@NotNull final FileType fileType, String extensions) {
register(fileType, parse(extensions));
}
@Override
public void consume(@NotNull final FileType fileType, @NotNull final FileNameMatcher... matchers) {
register(fileType, new ArrayList<>(Arrays.asList(matchers)));
}
@Override
public FileType getStandardFileTypeByName(@NotNull final String name) {
final StandardFileType type = myStandardFileTypes.get(name);
return type != null ? type.fileType : null;
}
private void register(@NotNull FileType fileType, @NotNull List<FileNameMatcher> fileNameMatchers) {
instantiatePendingFileTypeByName(fileType.getName());
for (FileNameMatcher matcher : fileNameMatchers) {
FileTypeBean pendingTypeByMatcher = myPendingAssociations.findAssociatedFileType(matcher);
if (pendingTypeByMatcher != null) {
PluginId id = pendingTypeByMatcher.getPluginId();
if (id == null || PluginManagerCore.CORE_ID == id) {
instantiateFileTypeBean(pendingTypeByMatcher);
}
}
}
final StandardFileType type = myStandardFileTypes.get(fileType.getName());
if (type != null) {
type.matchers.addAll(fileNameMatchers);
}
else {
myStandardFileTypes.put(fileType.getName(), new StandardFileType(fileType, fileNameMatchers));
}
}
};
//noinspection deprecation
FileTypeFactory.FILE_TYPE_FACTORY_EP.processWithPluginDescriptor((factory, pluginDescriptor) -> {
try {
factory.createFileTypes(consumer);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (StartupAbortedException e) {
throw e;
}
catch (Throwable e) {
throw new StartupAbortedException("Cannot create file types", new PluginException(e, pluginDescriptor.getPluginId()));
}
});
for (StandardFileType pair : myStandardFileTypes.values()) {
registerFileTypeWithoutNotification(pair.fileType, pair.matchers, true);
}
try {
URL defaultFileTypesUrl = FileTypeManagerImpl.class.getResource("/defaultFileTypes.xml");
if (defaultFileTypesUrl != null) {
Element defaultFileTypesElement = JDOMUtil.load(URLUtil.openStream(defaultFileTypesUrl));
for (Element e : defaultFileTypesElement.getChildren()) {
if ("filetypes".equals(e.getName())) {
for (Element element : e.getChildren(ELEMENT_FILETYPE)) {
String fileTypeName = element.getAttributeValue(ATTRIBUTE_NAME);
if (myPendingFileTypes.get(fileTypeName) != null) continue;
loadFileType(element, true);
}
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(e.getName())) {
readGlobalMappings(e, true);
}
}
if (PlatformUtils.isIdeaCommunity()) {
Element extensionMap = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
extensionMap.addContent(new Element(AbstractFileType.ELEMENT_MAPPING)
.setAttribute(AbstractFileType.ATTRIBUTE_EXT, "jspx")
.setAttribute(AbstractFileType.ATTRIBUTE_TYPE, "XML"));
//noinspection SpellCheckingInspection
extensionMap.addContent(new Element(AbstractFileType.ELEMENT_MAPPING)
.setAttribute(AbstractFileType.ATTRIBUTE_EXT, "tagx")
.setAttribute(AbstractFileType.ATTRIBUTE_TYPE, "XML"));
readGlobalMappings(extensionMap, true);
}
}
}
catch (Exception e) {
LOG.error(e);
}
}
private void loadFileTypeBeans() {
final List<FileTypeBean> fileTypeBeans = EP_NAME.getExtensionList();
for (FileTypeBean bean : fileTypeBeans) {
initializeMatchers(bean);
}
for (FileTypeBean bean : fileTypeBeans) {
if (bean.implementationClass == null) continue;
if (myPendingFileTypes.containsKey(bean.name)) {
LOG.error(new PluginException("Trying to override already registered file type " + bean.name, bean.getPluginId()));
continue;
}
myPendingFileTypes.put(bean.name, bean);
for (FileNameMatcher matcher : bean.getMatchers()) {
myPendingAssociations.addAssociation(matcher, bean);
}
}
// Register additional extensions for file types
for (FileTypeBean bean : fileTypeBeans) {
if (bean.implementationClass != null) continue;
FileTypeBean oldBean = myPendingFileTypes.get(bean.name);
if (oldBean == null) {
LOG.error(new PluginException("Trying to add extensions to non-registered file type " + bean.name, bean.getPluginId()));
continue;
}
oldBean.addMatchers(bean.getMatchers());
for (FileNameMatcher matcher : bean.getMatchers()) {
myPendingAssociations.addAssociation(matcher, oldBean);
}
}
}
private static void initializeMatchers(FileTypeBean bean) {
bean.addMatchers(ContainerUtil.concat(
parse(bean.extensions),
parse(bean.fileNames, token -> new ExactFileNameMatcher(token)),
parse(bean.fileNamesCaseInsensitive, token -> new ExactFileNameMatcher(token, true)),
parse(bean.patterns, token -> FileNameMatcherFactory.getInstance().createMatcher(token))));
}
private void instantiatePendingFileTypes() {
final Collection<FileTypeBean> fileTypes = new ArrayList<>(myPendingFileTypes.values());
for (FileTypeBean fileTypeBean : fileTypes) {
final StandardFileType type = myStandardFileTypes.get(fileTypeBean.name);
if (type != null) {
type.matchers.addAll(fileTypeBean.getMatchers());
}
else {
instantiateFileTypeBean(fileTypeBean);
}
}
}
private FileType instantiateFileTypeBean(@NotNull FileTypeBean fileTypeBean) {
FileType fileType;
PluginId pluginId = fileTypeBean.getPluginDescriptor().getPluginId();
try {
@SuppressWarnings("unchecked")
Class<FileType> beanClass = (Class<FileType>)Class.forName(fileTypeBean.implementationClass, true, fileTypeBean.getPluginDescriptor().getPluginClassLoader());
if (fileTypeBean.fieldName != null) {
Field field = beanClass.getDeclaredField(fileTypeBean.fieldName);
field.setAccessible(true);
fileType = (FileType)field.get(null);
}
else {
// uncached - cached by FileTypeManagerImpl and not by bean
fileType = ReflectionUtil.newInstance(beanClass, false);
}
}
catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
LOG.error(new PluginException(e, pluginId));
return null;
}
if (!fileType.getName().equals(fileTypeBean.name)) {
LOG.error(new PluginException("Incorrect name specified in <fileType>, should be " + fileType.getName() + ", actual " + fileTypeBean.name, pluginId));
}
if (fileType instanceof LanguageFileType) {
final LanguageFileType languageFileType = (LanguageFileType)fileType;
String expectedLanguage = languageFileType.isSecondary() ? null : languageFileType.getLanguage().getID();
if (!Comparing.equal(fileTypeBean.language, expectedLanguage)) {
LOG.error(new PluginException("Incorrect language specified in <fileType> for " + fileType.getName() + ", should be " + expectedLanguage + ", actual " + fileTypeBean.language, pluginId));
}
}
final StandardFileType standardFileType = new StandardFileType(fileType, fileTypeBean.getMatchers());
myStandardFileTypes.put(fileTypeBean.name, standardFileType);
registerFileTypeWithoutNotification(standardFileType.fileType, standardFileType.matchers, true);
myPendingAssociations.removeAllAssociations(fileTypeBean);
myPendingFileTypes.remove(fileTypeBean.name);
return fileType;
}
@TestOnly
boolean toLog;
private boolean toLog() {
return toLog;
}
private static void log(String message) {
LOG.debug(message + " - "+Thread.currentThread());
}
private final Executor
reDetectExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("FileTypeManager Redetect Pool", PooledThreadExecutor.INSTANCE, 1, this);
private final HashSetQueue<VirtualFile> filesToRedetect = new HashSetQueue<>();
private static final int CHUNK_SIZE = 10;
private void awakeReDetectExecutor() {
reDetectExecutor.execute(() -> {
List<VirtualFile> files = new ArrayList<>(CHUNK_SIZE);
synchronized (filesToRedetect) {
for (int i = 0; i < CHUNK_SIZE; i++) {
VirtualFile file = filesToRedetect.poll();
if (file == null) break;
files.add(file);
}
}
if (files.size() == CHUNK_SIZE) {
awakeReDetectExecutor();
}
reDetect(files);
});
}
@TestOnly
public void drainReDetectQueue() {
try {
((BoundedTaskExecutor)reDetectExecutor).waitAllTasksExecuted(1, TimeUnit.MINUTES);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@TestOnly
@NotNull
Collection<VirtualFile> dumpReDetectQueue() {
synchronized (filesToRedetect) {
return new ArrayList<>(filesToRedetect);
}
}
@TestOnly
static void reDetectAsync(boolean enable) {
RE_DETECT_ASYNC = enable;
}
private void reDetect(@NotNull Collection<? extends VirtualFile> files) {
List<VirtualFile> changed = new ArrayList<>();
List<VirtualFile> crashed = new ArrayList<>();
for (VirtualFile file : files) {
boolean shouldRedetect = wasAutoDetectedBefore(file) && isDetectable(file);
if (toLog()) {
log("F: reDetect("+file.getName()+") " + file.getName() + "; shouldRedetect: " + shouldRedetect);
}
if (shouldRedetect) {
int id = ((VirtualFileWithId)file).getId();
long flags = packedFlags.get(id);
FileType before = ObjectUtils.notNull(textOrBinaryFromCachedFlags(flags),
ObjectUtils.notNull(file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY),
PlainTextFileType.INSTANCE));
FileType after = getByFile(file);
if (toLog()) {
log("F: reDetect(" + file.getName() + ") prepare to redetect. flags: " + readableFlags(flags) +
"; beforeType: " + before.getName() + "; afterByFileType: " + (after == null ? null : after.getName()));
}
if (after == null || mightBeReplacedByDetectedFileType(after)) {
try {
after = detectFromContentAndCache(file, null);
}
catch (IOException e) {
crashed.add(file);
if (toLog()) {
log("F: reDetect(" + file.getName() + ") " + "before: " + before.getName() + "; after: crashed with " + e.getMessage() +
"; now getFileType()=" + file.getFileType().getName() +
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
continue;
}
}
else {
// back to standard file type
// detected by conventional methods, no need to run detect-from-content
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
flags = 0;
packedFlags.set(id, flags);
}
if (toLog()) {
log("F: reDetect(" + file.getName() + ") " + "before: " + before.getName() + "; after: " + after.getName() +
"; now getFileType()=" + file.getFileType().getName() +
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
if (before != after) {
changed.add(file);
}
}
}
if (!changed.isEmpty()) {
reparseLater(changed);
}
if (!crashed.isEmpty()) {
// do not re-scan locked or invalid files too often to avoid constant disk thrashing if that condition is permanent
AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> reparseLater(crashed), 10, TimeUnit.SECONDS);
}
}
private static void reparseLater(@NotNull List<? extends VirtualFile> changed) {
ApplicationManager.getApplication().invokeLater(() -> FileContentUtilCore.reparseFiles(changed), ApplicationManager.getApplication().getDisposed());
}
private boolean wasAutoDetectedBefore(@NotNull VirtualFile file) {
if (file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) != null) {
return true;
}
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
// do not re-detect binary files
return (packedFlags.get(id) & (AUTO_DETECT_WAS_RUN_MASK | AUTO_DETECTED_AS_BINARY_MASK)) == AUTO_DETECT_WAS_RUN_MASK;
}
return false;
}
@Override
@NotNull
public FileType getStdFileType(@NotNull @NonNls String name) {
StandardFileType stdFileType;
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(name);
stdFileType = myStandardFileTypes.get(name);
}
return stdFileType != null ? stdFileType.fileType : PlainTextFileType.INSTANCE;
}
private void instantiatePendingFileTypeByName(@NonNls @NotNull String name) {
final FileTypeBean bean = myPendingFileTypes.get(name);
if (bean != null) {
instantiateFileTypeBean(bean);
}
}
@Override
public void initializeComponent() {
if (!myUnresolvedMappings.isEmpty()) {
instantiatePendingFileTypes();
}
if (!myUnresolvedMappings.isEmpty()) {
for (StandardFileType pair : myStandardFileTypes.values()) {
registerReDetectedMappings(pair);
}
}
// resolve unresolved mappings initialized before certain plugin initialized
if (!myUnresolvedMappings.isEmpty()) {
for (StandardFileType pair : myStandardFileTypes.values()) {
bindUnresolvedMappings(pair.fileType);
}
}
boolean isAtLeastOneStandardFileTypeHasBeenRead = false;
for (FileType fileType : mySchemeManager.loadSchemes()) {
isAtLeastOneStandardFileTypeHasBeenRead |= myInitialAssociations.hasAssociationsFor(fileType);
}
if (isAtLeastOneStandardFileTypeHasBeenRead) {
restoreStandardFileExtensions();
}
}
@Override
@NotNull
public FileType getFileTypeByFileName(@NotNull String fileName) {
return getFileTypeByFileName((CharSequence)fileName);
}
@Override
@NotNull
public FileType getFileTypeByFileName(@NotNull CharSequence fileName) {
synchronized (PENDING_INIT_LOCK) {
final FileTypeBean pendingFileType = myPendingAssociations.findAssociatedFileType(fileName);
if (pendingFileType != null) {
return ObjectUtils.notNull(instantiateFileTypeBean(pendingFileType), UnknownFileType.INSTANCE);
}
FileType type = myPatternsTable.findAssociatedFileType(fileName);
return ObjectUtils.notNull(type, UnknownFileType.INSTANCE);
}
}
public void freezeFileTypeTemporarilyIn(@NotNull VirtualFile file, @NotNull Runnable runnable) {
FileType fileType = file.getFileType();
Pair<VirtualFile, FileType> old = FILE_TYPE_FIXED_TEMPORARILY.get();
FILE_TYPE_FIXED_TEMPORARILY.set(Pair.create(file, fileType));
if (toLog()) {
log("F: freezeFileTypeTemporarilyIn(" + file.getName() + ") to " + fileType.getName()+" in "+Thread.currentThread());
}
try {
runnable.run();
}
finally {
if (old == null) {
FILE_TYPE_FIXED_TEMPORARILY.remove();
}
else {
FILE_TYPE_FIXED_TEMPORARILY.set(old);
}
if (toLog()) {
log("F: unfreezeFileType(" + file.getName() + ") in "+Thread.currentThread());
}
}
}
@Override
@NotNull
public FileType getFileTypeByFile(@NotNull VirtualFile file) {
return getFileTypeByFile(file, null);
}
@Override
@NotNull
public FileType getFileTypeByFile(@NotNull VirtualFile file, @Nullable byte[] content) {
FileType overriddenFileType = FileTypeOverrider.EP_NAME.computeSafeIfAny((overrider) -> overrider.getOverriddenFileType(file));
if (overriddenFileType != null) {
return overriddenFileType;
}
FileType fileType = getByFile(file);
if (!(file instanceof StubVirtualFile)) {
if (fileType == null) {
return getOrDetectFromContent(file, content);
}
if (mightBeReplacedByDetectedFileType(fileType) && isDetectable(file)) {
FileType detectedFromContent = getOrDetectFromContent(file, content);
// unknown file type means that it was detected as binary, it's better to keep it binary
if (detectedFromContent != PlainTextFileType.INSTANCE) {
return detectedFromContent;
}
}
}
return ObjectUtils.notNull(fileType, UnknownFileType.INSTANCE);
}
private static boolean mightBeReplacedByDetectedFileType(FileType fileType) {
return fileType instanceof PlainTextLikeFileType && fileType.isReadOnly();
}
@Nullable // null means all conventional detect methods returned UnknownFileType.INSTANCE, have to detect from content
public FileType getByFile(@NotNull VirtualFile file) {
Pair<VirtualFile, FileType> fixedType = FILE_TYPE_FIXED_TEMPORARILY.get();
if (fixedType != null && fixedType.getFirst().equals(file)) {
FileType fileType = fixedType.getSecond();
if (toLog()) {
log("F: getByFile(" + file.getName() + ") was frozen to " + fileType.getName()+" in "+Thread.currentThread());
}
return fileType;
}
if (file instanceof LightVirtualFile) {
FileType fileType = ((LightVirtualFile)file).getAssignedFileType();
if (fileType != null) {
return fileType;
}
}
for (FileTypeIdentifiableByVirtualFile type : mySpecialFileTypes) {
if (type.isMyFileType(file)) {
if (toLog()) {
log("F: getByFile(" + file.getName() + "): Special file type: " + type.getName());
}
return type;
}
}
FileType fileType = getFileTypeByFileName(file.getNameSequence());
if (fileType == UnknownFileType.INSTANCE) {
fileType = null;
}
if (toLog()) {
log("F: getByFile(" + file.getName() + ") By name file type: "+(fileType == null ? null : fileType.getName()));
}
return fileType;
}
@NotNull
private FileType getOrDetectFromContent(@NotNull VirtualFile file, @Nullable byte[] content) {
if (!isDetectable(file)) return UnknownFileType.INSTANCE;
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
long flags = packedFlags.get(id);
if (!BitUtil.isSet(flags, ATTRIBUTES_WERE_LOADED_MASK)) {
flags = readFlagsFromCache(file);
flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true);
packedFlags.set(id, flags);
if (toLog()) {
log("F: getOrDetectFromContent(" + file.getName() + "): readFlagsFromCache() = " + readableFlags(flags));
}
}
boolean autoDetectWasRun = BitUtil.isSet(flags, AUTO_DETECT_WAS_RUN_MASK);
if (autoDetectWasRun) {
FileType type = textOrBinaryFromCachedFlags(flags);
if (toLog()) {
log("F: getOrDetectFromContent("+file.getName()+"):" +
" cached type = "+(type==null?null:type.getName())+
"; packedFlags.get(id):"+ readableFlags(flags)+
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
if (type != null) {
return type;
}
}
}
FileType fileType = file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY);
if (toLog()) {
log("F: getOrDetectFromContent("+file.getName()+"): " +
"getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) = "+(fileType == null ? null : fileType.getName()));
}
if (fileType == null) {
// run autodetection
try {
fileType = detectFromContentAndCache(file, content);
}
catch (IOException e) {
fileType = UnknownFileType.INSTANCE;
}
}
if (toLog()) {
log("F: getOrDetectFromContent("+file.getName()+"): getFileType after detect run = "+fileType.getName());
}
return fileType;
}
@NotNull
private static String readableFlags(long flags) {
String result = "";
if (BitUtil.isSet(flags, ATTRIBUTES_WERE_LOADED_MASK)) result += "ATTRIBUTES_WERE_LOADED_MASK";
if (BitUtil.isSet(flags, AUTO_DETECT_WAS_RUN_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECT_WAS_RUN_MASK";
if (BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECTED_AS_BINARY_MASK";
if (BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK)) result += (result.isEmpty() ? "" :" | ") + "AUTO_DETECTED_AS_TEXT_MASK";
return result;
}
private volatile FileAttribute autoDetectedAttribute;
// read auto-detection flags from the persistent FS file attributes. If file attributes are absent, return 0 for flags
// returns three bits value for AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK and AUTO_DETECT_WAS_RUN_MASK bits
protected byte readFlagsFromCache(@NotNull VirtualFile file) {
boolean wasAutoDetectRun = false;
byte status = 0;
try (DataInputStream stream = autoDetectedAttribute.readAttribute(file)) {
status = stream == null ? 0 : stream.readByte();
wasAutoDetectRun = stream != null;
}
catch (IOException ignored) {
}
status = BitUtil.set(status, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun);
return (byte)(status & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK | AUTO_DETECT_WAS_RUN_MASK));
}
// store auto-detection flags to the persistent FS file attributes
// writes AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK bits only
protected void writeFlagsToCache(@NotNull VirtualFile file, int flags) {
try (DataOutputStream stream = autoDetectedAttribute.writeAttribute(file)) {
stream.writeByte(flags & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK));
}
catch (IOException e) {
LOG.error(e);
}
}
void clearCaches() {
packedFlags.clear();
if (toLog()) {
log("F: clearCaches()");
}
}
private void clearPersistentAttributes() {
int count = fileTypeChangedCount.incrementAndGet();
autoDetectedAttribute = autoDetectedAttribute.newVersion(count);
PropertiesComponent.getInstance().setValue("fileTypeChangedCounter", Integer.toString(count));
if (toLog()) {
log("F: clearPersistentAttributes()");
}
}
@Nullable //null means the file was not auto-detected as text/binary
private static FileType textOrBinaryFromCachedFlags(long flags) {
return BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK) ? PlainTextFileType.INSTANCE :
BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK) ? UnknownFileType.INSTANCE :
null;
}
private void cacheAutoDetectedFileType(@NotNull VirtualFile file, @NotNull FileType fileType) {
boolean wasAutodetectedAsText = fileType == PlainTextFileType.INSTANCE;
boolean wasAutodetectedAsBinary = fileType == UnknownFileType.INSTANCE;
int flags = BitUtil.set(0, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
writeFlagsToCache(file, flags);
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
flags = BitUtil.set(flags, AUTO_DETECT_WAS_RUN_MASK, true);
flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true);
packedFlags.set(id, flags);
if (wasAutodetectedAsText || wasAutodetectedAsBinary) {
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
if (toLog()) {
log("F: cacheAutoDetectedFileType("+file.getName()+") " +
"cached to " + fileType.getName() +
" flags = "+ readableFlags(flags)+
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
return;
}
}
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, fileType);
if (toLog()) {
log("F: cacheAutoDetectedFileType("+file.getName()+") " +
"cached to " + fileType.getName() +
" flags = "+ readableFlags(flags)+
"; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): "+file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
}
}
@Override
public FileType findFileTypeByName(@NotNull String fileTypeName) {
FileType type = getStdFileType(fileTypeName);
// TODO: Abstract file types are not std one, so need to be restored specially,
// currently there are 6 of them and restoration does not happen very often so just iteration is enough
if (type == PlainTextFileType.INSTANCE && !fileTypeName.equals(type.getName())) {
for (FileType fileType: mySchemeManager.getAllSchemes()) {
if (fileTypeName.equals(fileType.getName())) {
return fileType;
}
}
}
return type;
}
private static boolean isDetectable(@NotNull final VirtualFile file) {
if (file.isDirectory() || !file.isValid() || file.is(VFileProperty.SPECIAL) || file.getLength() == 0) {
// for empty file there is still hope its type will change
return false;
}
return file.getFileSystem() instanceof FileSystemInterface;
}
private int readSafely(@NotNull InputStream stream, @NotNull byte[] buffer, int offset, int length) throws IOException {
int n = stream.read(buffer, offset, length);
if (n <= 0) {
// maybe locked because someone else is writing to it
// repeat inside read action to guarantee all writes are finished
if (toLog()) {
log("F: processFirstBytes(): inputStream.read() returned "+n+"; retrying with read action. stream="+ streamInfo(stream));
}
n = ReadAction.compute(() -> stream.read(buffer, offset, length));
if (toLog()) {
log("F: processFirstBytes(): under read action inputStream.read() returned "+n+"; stream="+ streamInfo(stream));
}
}
return n;
}
@NotNull
private FileType detectFromContentAndCache(@NotNull final VirtualFile file, @Nullable byte[] content) throws IOException {
long start = System.currentTimeMillis();
FileType fileType = detectFromContent(file, content, FileTypeDetector.EP_NAME.getExtensionList());
cacheAutoDetectedFileType(file, fileType);
counterAutoDetect.incrementAndGet();
long elapsed = System.currentTimeMillis() - start;
elapsedAutoDetect.addAndGet(elapsed);
return fileType;
}
@NotNull
private FileType detectFromContent(@NotNull VirtualFile file, @Nullable byte[] content, @NotNull Iterable<? extends FileTypeDetector> detectors) throws IOException {
FileType fileType;
if (content != null) {
fileType = detect(file, content, content.length, detectors);
}
else {
try (InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
if (toLog()) {
log("F: detectFromContentAndCache(" + file.getName() + "):" + " inputStream=" + streamInfo(inputStream));
}
int fileLength = (int)file.getLength();
int bufferLength = StreamSupport.stream(detectors.spliterator(), false)
.map(FileTypeDetector::getDesiredContentPrefixLength)
.max(Comparator.naturalOrder())
.orElse(FileUtilRt.getUserContentLoadLimit());
byte[] buffer = fileLength <= FileUtilRt.THREAD_LOCAL_BUFFER_LENGTH
? FileUtilRt.getThreadLocalBuffer()
: new byte[Math.min(fileLength, bufferLength)];
int n = readSafely(inputStream, buffer, 0, buffer.length);
fileType = detect(file, buffer, n, detectors);
if (toLog()) {
try (InputStream newStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
byte[] buffer2 = new byte[50];
int n2 = newStream.read(buffer2, 0, buffer2.length);
log("F: detectFromContentAndCache(" + file.getName() + "): result: " + fileType.getName() +
"; stream: " + streamInfo(inputStream) +
"; newStream: " + streamInfo(newStream) +
"; read: " + n2 +
"; buffer: " + Arrays.toString(buffer2));
}
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect);
}
return fileType;
}
@NotNull
private FileType detect(@NotNull VirtualFile file, @NotNull byte[] bytes, int length, @NotNull Iterable<? extends FileTypeDetector> detectors) {
if (length <= 0) return UnknownFileType.INSTANCE;
// use PlainTextFileType because it doesn't supply its own charset detector
// help set charset in the process to avoid double charset detection from content
return LoadTextUtil.processTextFromBinaryPresentationOrNull(bytes, length,
file, true, true,
PlainTextFileType.INSTANCE, (@Nullable CharSequence text) -> {
if (toLog()) {
log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): bytes length=" + length +
"; isText=" + (text != null) + "; text='" + (text == null ? null : StringUtil.first(text, 100, true)) + "'" +
", detectors=" + detectors);
}
FileType detected = null;
ByteSequence firstBytes = new ByteArraySequence(bytes, 0, length);
for (FileTypeDetector detector : detectors) {
try {
detected = detector.detect(file, firstBytes, text);
}
catch (ProcessCanceledException e) {
LOG.error("Detector " + detector + " (" + detector.getClass() + ") threw PCE. Bad detector, bad!", new RuntimeException(e));
}
catch (Exception e) {
LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e);
}
if (detected != null) {
if (toLog()) {
log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): detector " + detector + " type as " + detected.getName());
}
break;
}
}
if (detected == null) {
detected = text == null ? UnknownFileType.INSTANCE : PlainTextFileType.INSTANCE;
if (toLog()) {
log("F: detectFromContentAndCache.processFirstBytes(" + file.getName() + "): " +
"no detector was able to detect. assigned " + detected.getName());
}
}
return detected;
});
}
// for diagnostics
@SuppressWarnings("ConstantConditions")
private static Object streamInfo(@NotNull InputStream stream) throws IOException {
if (stream instanceof BufferedInputStream) {
InputStream in = ReflectionUtil.getField(stream.getClass(), stream, InputStream.class, "in");
byte[] buf = ReflectionUtil.getField(stream.getClass(), stream, byte[].class, "buf");
int count = ReflectionUtil.getField(stream.getClass(), stream, int.class, "count");
int pos = ReflectionUtil.getField(stream.getClass(), stream, int.class, "pos");
return "BufferedInputStream(buf=" + (buf == null ? null : Arrays.toString(Arrays.copyOf(buf, count))) +
", count=" + count + ", pos=" + pos + ", in=" + streamInfo(in) + ")";
}
if (stream instanceof FileInputStream) {
String path = ReflectionUtil.getField(stream.getClass(), stream, String.class, "path");
FileChannel channel = ReflectionUtil.getField(stream.getClass(), stream, FileChannel.class, "channel");
boolean closed = ReflectionUtil.getField(stream.getClass(), stream, boolean.class, "closed");
int available = stream.available();
File file = new File(path);
return "FileInputStream(path=" + path + ", available=" + available + ", closed=" + closed +
", channel=" + channel + ", channel.size=" + (channel == null ? null : channel.size()) +
", file.exists=" + file.exists() + ", file.content='" + FileUtil.loadFile(file) + "')";
}
return stream;
}
@Override
public LanguageFileType findFileTypeByLanguage(@NotNull Language language) {
synchronized (PENDING_INIT_LOCK) {
for (FileTypeBean bean : myPendingFileTypes.values()) {
if (language.getID().equals(bean.language)) {
return (LanguageFileType)instantiateFileTypeBean(bean);
}
}
}
// Do not use getRegisteredFileTypes() to avoid instantiating all pending file types
return language.findMyFileType(mySchemeManager.getAllSchemes().toArray(FileType.EMPTY_ARRAY));
}
@Override
@NotNull
public FileType getFileTypeByExtension(@NotNull String extension) {
synchronized (PENDING_INIT_LOCK) {
final FileTypeBean pendingFileType = myPendingAssociations.findByExtension(extension);
if (pendingFileType != null) {
return ObjectUtils.notNull(instantiateFileTypeBean(pendingFileType), UnknownFileType.INSTANCE);
}
FileType type = myPatternsTable.findByExtension(extension);
return ObjectUtils.notNull(type, UnknownFileType.INSTANCE);
}
}
@Override
@Deprecated
public void registerFileType(@NotNull FileType fileType) {
registerFileType(fileType, ArrayUtilRt.EMPTY_STRING_ARRAY);
}
@Override
public void registerFileType(@NotNull final FileType type, @NotNull final List<? extends FileNameMatcher> defaultAssociations) {
DeprecatedMethodException.report("Use fileType extension instead.");
ApplicationManager.getApplication().runWriteAction(() -> {
fireBeforeFileTypesChanged();
registerFileTypeWithoutNotification(type, defaultAssociations, true);
fireFileTypesChanged(type, null);
});
}
@Override
public void unregisterFileType(@NotNull final FileType fileType) {
ApplicationManager.getApplication().runWriteAction(() -> {
fireBeforeFileTypesChanged();
unregisterFileTypeWithoutNotification(fileType);
myStandardFileTypes.remove(fileType.getName());
fireFileTypesChanged(null, fileType);
});
}
private void unregisterFileTypeWithoutNotification(@NotNull FileType fileType) {
myPatternsTable.removeAllAssociations(fileType);
myInitialAssociations.removeAllAssociations(fileType);
mySchemeManager.removeScheme(fileType);
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
final FileTypeIdentifiableByVirtualFile fakeFileType = (FileTypeIdentifiableByVirtualFile)fileType;
mySpecialFileTypes = ArrayUtil.remove(mySpecialFileTypes, fakeFileType, FileTypeIdentifiableByVirtualFile.ARRAY_FACTORY);
}
}
@Override
@NotNull
public FileType[] getRegisteredFileTypes() {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypes();
}
Collection<FileType> fileTypes = mySchemeManager.getAllSchemes();
return fileTypes.toArray(FileType.EMPTY_ARRAY);
}
@Override
@NotNull
public String getExtension(@NotNull String fileName) {
return FileUtilRt.getExtension(fileName);
}
@Override
@NotNull
public String getIgnoredFilesList() {
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
return masks.isEmpty() ? "" : StringUtil.join(masks, ";") + ";";
}
@Override
public void setIgnoredFilesList(@NotNull String list) {
fireBeforeFileTypesChanged();
myIgnoredFileCache.clearCache();
myIgnoredPatterns.setIgnoreMasks(list);
fireFileTypesChanged();
}
@Override
public boolean isIgnoredFilesListEqualToCurrent(@NotNull String list) {
Set<String> tempSet = new THashSet<>();
StringTokenizer tokenizer = new StringTokenizer(list, ";");
while (tokenizer.hasMoreTokens()) {
tempSet.add(tokenizer.nextToken());
}
return tempSet.equals(myIgnoredPatterns.getIgnoreMasks());
}
@Override
public boolean isFileIgnored(@NotNull String name) {
return myIgnoredPatterns.isIgnored(name);
}
@Override
public boolean isFileIgnored(@NotNull VirtualFile file) {
return myIgnoredFileCache.isFileIgnored(file);
}
@Override
@NotNull
public String[] getAssociatedExtensions(@NotNull FileType type) {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(type.getName());
//noinspection deprecation
return myPatternsTable.getAssociatedExtensions(type);
}
}
@Override
@NotNull
public List<FileNameMatcher> getAssociations(@NotNull FileType type) {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(type.getName());
return myPatternsTable.getAssociations(type);
}
}
@Override
public void associate(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
associate(type, matcher, true);
}
@Override
public void removeAssociation(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
removeAssociation(type, matcher, true);
}
@Override
public void fireBeforeFileTypesChanged() {
FileTypeEvent event = new FileTypeEvent(this, null, null);
myMessageBus.syncPublisher(TOPIC).beforeFileTypesChanged(event);
}
private final AtomicInteger fileTypeChangedCount;
@Override
public void fireFileTypesChanged() {
fireFileTypesChanged(null, null);
}
public void fireFileTypesChanged(@Nullable FileType addedFileType, @Nullable FileType removedFileType) {
clearCaches();
clearPersistentAttributes();
myMessageBus.syncPublisher(TOPIC).fileTypesChanged(new FileTypeEvent(this, addedFileType, removedFileType));
}
private final Map<FileTypeListener, MessageBusConnection> myAdapters = new HashMap<>();
@Override
public void addFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myMessageBus.connect();
connection.subscribe(TOPIC, listener);
myAdapters.put(listener, connection);
}
@Override
public void removeFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myAdapters.remove(listener);
if (connection != null) {
connection.disconnect();
}
}
@Override
public void loadState(@NotNull Element state) {
int savedVersion = StringUtilRt.parseInt(state.getAttributeValue(ATTRIBUTE_VERSION), 0);
for (Element element : state.getChildren()) {
if (element.getName().equals(ELEMENT_IGNORE_FILES)) {
myIgnoredPatterns.setIgnoreMasks(element.getAttributeValue(ATTRIBUTE_LIST));
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(element.getName())) {
readGlobalMappings(element, false);
}
}
if (savedVersion < 4) {
if (savedVersion == 0) {
addIgnore(".svn");
}
if (savedVersion < 2) {
restoreStandardFileExtensions();
}
addIgnore("*.pyc");
addIgnore("*.pyo");
addIgnore(".git");
}
if (savedVersion < 5) {
addIgnore("*.hprof");
}
if (savedVersion < 6) {
addIgnore("_svn");
}
if (savedVersion < 7) {
addIgnore(".hg");
}
if (savedVersion < 8) {
addIgnore("*~");
}
if (savedVersion < 9) {
addIgnore("__pycache__");
}
if (savedVersion < 11) {
addIgnore("*.rbc");
}
if (savedVersion < 13) {
// we want *.lib back since it's an important user artifact for CLion, also for IDEA project itself, since we have some libs.
unignoreMask("*.lib");
}
if (savedVersion < 15) {
// we want .bundle back, bundler keeps useful data there
unignoreMask(".bundle");
}
if (savedVersion < 16) {
// we want .tox back to allow users selecting interpreters from it
unignoreMask(".tox");
}
if (savedVersion < 17) {
addIgnore("*.rbc");
}
myIgnoredFileCache.clearCache();
String counter = JDOMExternalizer.readString(state, "fileTypeChangedCounter");
if (counter != null) {
fileTypeChangedCount.set(StringUtilRt.parseInt(counter, 0));
autoDetectedAttribute = autoDetectedAttribute.newVersion(fileTypeChangedCount.get());
}
}
private void unignoreMask(@NotNull final String maskToRemove) {
final Set<String> masks = new LinkedHashSet<>(myIgnoredPatterns.getIgnoreMasks());
masks.remove(maskToRemove);
myIgnoredPatterns.clearPatterns();
for (final String each : masks) {
myIgnoredPatterns.addIgnoreMask(each);
}
}
private void readGlobalMappings(@NotNull Element e, boolean isAddToInit) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(e)) {
FileType type = getFileTypeByName(association.getSecond());
FileNameMatcher matcher = association.getFirst();
final FileTypeBean pendingFileTypeBean = myPendingAssociations.findAssociatedFileType(matcher);
if (pendingFileTypeBean != null) {
instantiateFileTypeBean(pendingFileTypeBean);
}
if (type != null) {
if (PlainTextFileType.INSTANCE == type) {
FileType newFileType = myPatternsTable.findAssociatedFileType(matcher);
if (newFileType != null && newFileType != PlainTextFileType.INSTANCE && newFileType != UnknownFileType.INSTANCE) {
myRemovedMappingTracker.add(matcher, newFileType.getName(), false);
}
}
associate(type, matcher, false);
if (isAddToInit) {
myInitialAssociations.addAssociation(matcher, type);
}
}
else {
myUnresolvedMappings.put(matcher, association.getSecond());
}
}
myRemovedMappingTracker.load(e);
for (RemovedMappingTracker.RemovedMapping mapping : myRemovedMappingTracker.getRemovedMappings()) {
FileType fileType = getFileTypeByName(mapping.getFileTypeName());
if (fileType != null) {
removeAssociation(fileType, mapping.getFileNameMatcher(), false);
}
}
}
private void addIgnore(@NonNls @NotNull String ignoreMask) {
myIgnoredPatterns.addIgnoreMask(ignoreMask);
}
private void restoreStandardFileExtensions() {
for (final String name : FILE_TYPES_WITH_PREDEFINED_EXTENSIONS) {
final StandardFileType stdFileType = myStandardFileTypes.get(name);
if (stdFileType != null) {
FileType fileType = stdFileType.fileType;
for (FileNameMatcher matcher : myPatternsTable.getAssociations(fileType)) {
FileType defaultFileType = myInitialAssociations.findAssociatedFileType(matcher);
if (defaultFileType != null && defaultFileType != fileType) {
removeAssociation(fileType, matcher, false);
associate(defaultFileType, matcher, false);
}
}
for (FileNameMatcher matcher : myInitialAssociations.getAssociations(fileType)) {
associate(fileType, matcher, false);
}
}
}
}
@NotNull
@Override
public Element getState() {
Element state = new Element("state");
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
String ignoreFiles;
if (masks.isEmpty()) {
ignoreFiles = "";
}
else {
String[] strings = ArrayUtilRt.toStringArray(masks);
Arrays.sort(strings);
ignoreFiles = StringUtil.join(strings, ";") + ";";
}
if (!ignoreFiles.equalsIgnoreCase(DEFAULT_IGNORED)) {
// empty means empty list - we need to distinguish null and empty to apply or not to apply default value
state.addContent(new Element(ELEMENT_IGNORE_FILES).setAttribute(ATTRIBUTE_LIST, ignoreFiles));
}
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
List<FileType> notExternalizableFileTypes = new ArrayList<>();
for (FileType type : mySchemeManager.getAllSchemes()) {
if (!(type instanceof AbstractFileType) || myDefaultTypes.contains(type)) {
notExternalizableFileTypes.add(type);
}
}
if (!notExternalizableFileTypes.isEmpty()) {
Collections.sort(notExternalizableFileTypes, Comparator.comparing(FileType::getName));
for (FileType type : notExternalizableFileTypes) {
writeExtensionsMap(map, type, true);
}
}
// https://youtrack.jetbrains.com/issue/IDEA-138366
myRemovedMappingTracker.save(map);
if (!myUnresolvedMappings.isEmpty()) {
FileNameMatcher[] unresolvedMappingKeys = myUnresolvedMappings.keySet().toArray(new FileNameMatcher[0]);
Arrays.sort(unresolvedMappingKeys, Comparator.comparing(FileNameMatcher::getPresentableString));
for (FileNameMatcher fileNameMatcher : unresolvedMappingKeys) {
Element content = AbstractFileType.writeMapping(myUnresolvedMappings.get(fileNameMatcher), fileNameMatcher, true);
if (content != null) {
map.addContent(content);
}
}
}
if (!map.getChildren().isEmpty()) {
state.addContent(map);
}
if (!state.getChildren().isEmpty()) {
state.setAttribute(ATTRIBUTE_VERSION, String.valueOf(VERSION));
}
return state;
}
private void writeExtensionsMap(@NotNull Element map, @NotNull FileType type, boolean specifyTypeName) {
List<FileNameMatcher> associations = myPatternsTable.getAssociations(type);
Set<FileNameMatcher> defaultAssociations = new THashSet<>(myInitialAssociations.getAssociations(type));
for (FileNameMatcher matcher : associations) {
boolean isDefaultAssociationContains = defaultAssociations.remove(matcher);
if (!isDefaultAssociationContains && shouldSave(type)) {
Element content = AbstractFileType.writeMapping(type.getName(), matcher, specifyTypeName);
if (content != null) {
map.addContent(content);
}
}
}
myRemovedMappingTracker.saveRemovedMappingsForFileType(map, type.getName(), defaultAssociations, specifyTypeName);
}
// -------------------------------------------------------------------------
// Helper methods
// -------------------------------------------------------------------------
@Nullable
private FileType getFileTypeByName(@NotNull String name) {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypeByName(name);
return mySchemeManager.findSchemeByName(name);
}
}
@NotNull
private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited) {
return parse(semicolonDelimited, token -> new ExtensionFileNameMatcher(token));
}
@NotNull
private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited, Function<? super String, ? extends FileNameMatcher> matcherFactory) {
if (semicolonDelimited == null) {
return Collections.emptyList();
}
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
ArrayList<FileNameMatcher> list = new ArrayList<>(semicolonDelimited.length() / "py;".length());
while (tokenizer.hasMoreTokens()) {
list.add(matcherFactory.fun(tokenizer.nextToken().trim()));
}
return list;
}
/**
* Registers a standard file type. Doesn't notifyListeners any change events.
*/
private void registerFileTypeWithoutNotification(@NotNull FileType fileType, @NotNull List<? extends FileNameMatcher> matchers, boolean addScheme) {
if (addScheme) {
mySchemeManager.addScheme(fileType);
}
for (FileNameMatcher matcher : matchers) {
myPatternsTable.addAssociation(matcher, fileType);
myInitialAssociations.addAssociation(matcher, fileType);
}
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
mySpecialFileTypes = ArrayUtil.append(mySpecialFileTypes, (FileTypeIdentifiableByVirtualFile)fileType, FileTypeIdentifiableByVirtualFile.ARRAY_FACTORY);
}
}
private void bindUnresolvedMappings(@NotNull FileType fileType) {
for (FileNameMatcher matcher : new THashSet<>(myUnresolvedMappings.keySet())) {
String name = myUnresolvedMappings.get(matcher);
if (Comparing.equal(name, fileType.getName())) {
myPatternsTable.addAssociation(matcher, fileType);
myUnresolvedMappings.remove(matcher);
}
}
for (FileNameMatcher matcher : myRemovedMappingTracker.getMappingsForFileType(fileType.getName())) {
removeAssociation(fileType, matcher, false);
}
}
@NotNull
private FileType loadFileType(@NotNull Element typeElement, boolean isDefault) {
String fileTypeName = typeElement.getAttributeValue(ATTRIBUTE_NAME);
String fileTypeDescr = typeElement.getAttributeValue(ATTRIBUTE_DESCRIPTION);
String iconPath = typeElement.getAttributeValue("icon");
String extensionsStr = StringUtil.nullize(typeElement.getAttributeValue("extensions"));
if (isDefault && extensionsStr != null) {
// todo support wildcards
extensionsStr = filterAlreadyRegisteredExtensions(extensionsStr);
}
FileType type = isDefault ? getFileTypeByName(fileTypeName) : null;
if (type != null) {
return type;
}
Element element = typeElement.getChild(AbstractFileType.ELEMENT_HIGHLIGHTING);
if (element == null) {
type = new UserBinaryFileType();
}
else {
SyntaxTable table = AbstractFileType.readSyntaxTable(element);
type = new AbstractFileType(table);
((AbstractFileType)type).initSupport();
}
setFileTypeAttributes((UserFileType)type, fileTypeName, fileTypeDescr, iconPath);
registerFileTypeWithoutNotification(type, parse(extensionsStr), isDefault);
if (isDefault) {
myDefaultTypes.add(type);
if (type instanceof ExternalizableFileType) {
((ExternalizableFileType)type).markDefaultSettings();
}
}
else {
Element extensions = typeElement.getChild(AbstractFileType.ELEMENT_EXTENSION_MAP);
if (extensions != null) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(extensions)) {
associate(type, association.getFirst(), false);
}
for (RemovedMappingTracker.RemovedMapping removedAssociation : RemovedMappingTracker.readRemovedMappings(extensions)) {
removeAssociation(type, removedAssociation.getFileNameMatcher(), false);
}
}
}
return type;
}
@Nullable
private String filterAlreadyRegisteredExtensions(@NotNull String semicolonDelimited) {
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
StringBuilder builder = null;
while (tokenizer.hasMoreTokens()) {
String extension = tokenizer.nextToken().trim();
if (myPendingAssociations.findByExtension(extension) == null && getFileTypeByExtension(extension) == UnknownFileType.INSTANCE) {
if (builder == null) {
builder = new StringBuilder();
}
else if (builder.length() > 0) {
builder.append(FileTypeConsumer.EXTENSION_DELIMITER);
}
builder.append(extension);
}
}
return builder == null ? null : builder.toString();
}
private static void setFileTypeAttributes(@NotNull UserFileType fileType, @Nullable String name, @Nullable String description, @Nullable String iconPath) {
if (!StringUtil.isEmptyOrSpaces(iconPath)) {
fileType.setIconPath(iconPath);
}
if (description != null) {
fileType.setDescription(description);
}
if (name != null) {
fileType.setName(name);
}
}
private static boolean shouldSave(@NotNull FileType fileType) {
return fileType != UnknownFileType.INSTANCE && !fileType.isReadOnly();
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
@NotNull
FileTypeAssocTable<FileType> getExtensionMap() {
synchronized (PENDING_INIT_LOCK) {
instantiatePendingFileTypes();
}
return myPatternsTable;
}
void setPatternsTable(@NotNull Set<? extends FileType> fileTypes, @NotNull FileTypeAssocTable<FileType> assocTable) {
Map<FileNameMatcher, FileType> removedMappings = getExtensionMap().getRemovedMappings(assocTable, fileTypes);
fireBeforeFileTypesChanged();
for (FileType existing : getRegisteredFileTypes()) {
if (!fileTypes.contains(existing)) {
mySchemeManager.removeScheme(existing);
}
}
for (FileType fileType : fileTypes) {
mySchemeManager.addScheme(fileType);
if (fileType instanceof AbstractFileType) {
((AbstractFileType)fileType).initSupport();
}
}
myPatternsTable = assocTable.copy();
fireFileTypesChanged();
myRemovedMappingTracker.removeMatching((matcher, fileTypeName) -> {
FileType fileType = getFileTypeByName(fileTypeName);
return fileType != null && assocTable.isAssociatedWith(fileType, matcher);
});
for (Map.Entry<FileNameMatcher, FileType> entry : removedMappings.entrySet()) {
myRemovedMappingTracker.add(entry.getKey(), entry.getValue().getName(), true);
}
}
public void associate(@NotNull FileType fileType, @NotNull FileNameMatcher matcher, boolean fireChange) {
if (!myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.addAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
public void removeAssociation(@NotNull FileType fileType, @NotNull FileNameMatcher matcher, boolean fireChange) {
if (myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.removeAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
@Override
@Nullable
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file) {
FileType type = file.getFileType();
if (type == UnknownFileType.INSTANCE) {
type = FileTypeChooser.associateFileType(file.getName());
}
return type;
}
@Override
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @NotNull Project project) {
return FileTypeChooser.getKnownFileTypeOrAssociate(file, project);
}
private void registerReDetectedMappings(@NotNull StandardFileType pair) {
FileType fileType = pair.fileType;
if (fileType == PlainTextFileType.INSTANCE) return;
for (FileNameMatcher matcher : pair.matchers) {
registerReDetectedMapping(fileType.getName(), matcher);
if (matcher instanceof ExtensionFileNameMatcher) {
// also check exact file name matcher
ExtensionFileNameMatcher extMatcher = (ExtensionFileNameMatcher)matcher;
registerReDetectedMapping(fileType.getName(), new ExactFileNameMatcher("." + extMatcher.getExtension()));
}
}
}
private void registerReDetectedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher) {
String typeName = myUnresolvedMappings.get(matcher);
if (typeName != null && !typeName.equals(fileTypeName)) {
if (!myRemovedMappingTracker.hasRemovedMapping(matcher)) {
myRemovedMappingTracker.add(matcher, fileTypeName, false);
}
myUnresolvedMappings.remove(matcher);
}
}
@NotNull
RemovedMappingTracker getRemovedMappingTracker() {
return myRemovedMappingTracker;
}
@TestOnly
void clearForTests() {
for (StandardFileType fileType : myStandardFileTypes.values()) {
myPatternsTable.removeAllAssociations(fileType.fileType);
}
for (FileType type : myDefaultTypes) {
myPatternsTable.removeAllAssociations(type);
}
myStandardFileTypes.clear();
myDefaultTypes.clear();
myUnresolvedMappings.clear();
myRemovedMappingTracker.clear();
for (FileTypeBean bean : myPendingFileTypes.values()) {
myPendingAssociations.removeAllAssociations(bean);
}
myPendingFileTypes.clear();
mySchemeManager.setSchemes(Collections.emptyList());
}
@Override
public void dispose() {
LOG.info(String.format("%s auto-detected files. Detection took %s ms", counterAutoDetect, elapsedAutoDetect));
}
}
| FileTypeManagerImpl return null if file type is not found by name
GitOrigin-RevId: b51e76fa0245de79c0c10dfea807d8b66991f3c4 | platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java | FileTypeManagerImpl return null if file type is not found by name | <ide><path>latform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java
<ide> FileType type = getStdFileType(fileTypeName);
<ide> // TODO: Abstract file types are not std one, so need to be restored specially,
<ide> // currently there are 6 of them and restoration does not happen very often so just iteration is enough
<del> if (type == PlainTextFileType.INSTANCE && !fileTypeName.equals(type.getName())) {
<del> for (FileType fileType: mySchemeManager.getAllSchemes()) {
<del> if (fileTypeName.equals(fileType.getName())) {
<del> return fileType;
<del> }
<del> }
<del> }
<del> return type;
<add> if (type != PlainTextFileType.INSTANCE || fileTypeName.equals(type.getName())) {
<add> return type;
<add> }
<add> for (FileType fileType: mySchemeManager.getAllSchemes()) {
<add> if (fileTypeName.equals(fileType.getName())) {
<add> return fileType;
<add> }
<add> }
<add> return null;
<ide> }
<ide>
<ide> private static boolean isDetectable(@NotNull final VirtualFile file) { |
|
Java | apache-2.0 | a3927664dddb21b7e67306a31f9acdf60dfd4f20 | 0 | asterisk-java/asterisk-java,asterisk-java/asterisk-java | package org.asteriskjava.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Locker
{
private static final Log logger = LogFactory.getLog(Locker.class);
private static volatile boolean diags = false;
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private static final Map<Integer, LockStats> lockObjectMap = new WeakHashMap<>();
private static final Object mapSync = new Object();
// keep references to LockStats so the WeakHashMap won't remove them between
// reporting intervals
private static final List<LockStats> keepList = new LinkedList<>();
public static LockCloser lock(final Object sync)
{
LockStats finalStats;
synchronized (mapSync)
{
// find or create the semaphore for locking
LockStats stats = lockObjectMap.get(System.identityHashCode(sync));
if (stats == null)
{
String name = getCaller(sync);
stats = new LockStats(sync, name);
lockObjectMap.put(System.identityHashCode(sync), stats);
if (diags)
{
keepList.add(stats);
}
}
finalStats = stats;
}
try
{
if (diags)
{
return lockWithDiags(finalStats);
}
return simpleLock(finalStats);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* determine the caller to Locker
*
* @param object
* @return
*/
private static String getCaller(Object object)
{
Exception ex = new Exception();
StackTraceElement[] trace = ex.getStackTrace();
String name = object.getClass().getCanonicalName();
for (StackTraceElement element : trace)
{
if (element.getFileName() != null && !element.getFileName().contains(Locker.class.getSimpleName()))
{
name = element.getFileName() + " " + element.getMethodName() + " " + element.getLineNumber() + " "
+ element.getClassName();
break;
}
}
return name;
}
public interface LockCloser extends AutoCloseable
{
public void close();
}
private static LockCloser simpleLock(LockStats stats) throws InterruptedException
{
Semaphore lock = stats.semaphore;
lock.acquire();
return new LockCloser()
{
@Override
public void close()
{
lock.release();
}
};
}
private static LockCloser lockWithDiags(LockStats stats) throws InterruptedException
{
int offset = stats.requested.incrementAndGet();
long waitStart = System.currentTimeMillis();
Semaphore lock = stats.semaphore;
lock.acquire();
stats.acquired.getAndIncrement();
long acquiredAt = System.currentTimeMillis();
return new LockCloser()
{
@Override
public void close()
{
// ignore any wait that may have been caused by Locker code, so
// count the waiters before we release the lock
long waiters = stats.requested.get() - offset;
stats.waited.addAndGet((int) waiters);
// release the lock
lock.release();
// count the time waiting and holding the lock
int holdTime = (int) (System.currentTimeMillis() - acquiredAt);
int waitTime = (int) (acquiredAt - waitStart);
stats.totalWaitTime.addAndGet(waitTime);
stats.totalHoldTime.addAndGet(holdTime);
long averageHoldTime = stats.getAverageHoldTime();
if (waiters > 0 && holdTime > averageHoldTime * 2)
{
// some threads waited
String message = "Lock held for (" + holdTime + "MS), " + waiters
+ " threads waited for some of that time! " + getCaller(stats.object);
logger.warn(message);
if (holdTime > averageHoldTime * 10.0)
{
Exception trace = new Exception(message);
logger.error(trace, trace);
}
}
if (holdTime > averageHoldTime * 5.0)
{
// long hold!
String message = "Lock hold of lock (" + holdTime + "MS), average is " + stats.getAverageHoldTime() + " "
+ getCaller(stats.object);
logger.warn(message);
if (holdTime > averageHoldTime * 10.0)
{
Exception trace = new Exception(message);
logger.error(trace, trace);
}
}
}
};
}
/**
* start dumping lock stats once per minute, can't be stopped once started.
*/
public static void enable()
{
if (!diags)
{
diags = true;
executor.scheduleWithFixedDelay(() -> {
dumpStats();
}, 1, 1, TimeUnit.MINUTES);
}
else
{
logger.warn("Already enabled");
}
}
private static void dumpStats()
{
List<LockStats> stats = new LinkedList<>();
synchronized (mapSync)
{
stats.addAll(lockObjectMap.values());
keepList.clear();
}
for (LockStats stat : stats)
{
if (stat.waited.get() > 0)
{
logger.warn(stat);
}
}
logger.warn("Dump Lock Stats finished.");
}
static class LockStats
{
@Override
public String toString()
{
return "LockStats [totalWaitTime=" + totalWaitTime + ", totalHoldTime=" + totalHoldTime + ", waited=" + waited
+ ", acquired=" + acquired + ", object=" + name + "]";
}
final Semaphore semaphore = new Semaphore(1, true);
// this reference to object stops the WeakRefHashMap removing this
// LockStats from
// the map
final Object object;
final String name;
final AtomicInteger totalWaitTime = new AtomicInteger();
final AtomicInteger totalHoldTime = new AtomicInteger();
final AtomicInteger requested = new AtomicInteger();
final AtomicInteger waited = new AtomicInteger();
final AtomicInteger acquired = new AtomicInteger();
LockStats(Object object, String name)
{
this.object = object;
this.name = name;
}
long getAverageHoldTime()
{
long hold = totalHoldTime.get();
long count = acquired.get();
if (count < 10)
{
return 250;
}
return Math.max(hold / count, 50);
}
}
}
| src/main/java/org/asteriskjava/util/Locker.java | package org.asteriskjava.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Locker
{
private static final Log logger = LogFactory.getLog(Locker.class);
private static volatile boolean diags = false;
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private static final Map<Integer, LockStats> lockObjectMap = new WeakHashMap<>();
private static final Object mapSync = new Object();
// keep references to LockStats so the WeakHashMap won't remove them between
// reporting intervals
private static final List<LockStats> keepList = new LinkedList<>();
public static LockCloser lock(final Object sync)
{
LockStats finalStats;
synchronized (mapSync)
{
// find or create the semaphore for locking
LockStats stats = lockObjectMap.get(System.identityHashCode(sync));
if (stats == null)
{
String name = getCaller(sync);
stats = new LockStats(sync, name);
lockObjectMap.put(System.identityHashCode(sync), stats);
if (diags)
{
keepList.add(stats);
}
}
finalStats = stats;
}
try
{
if (diags)
{
return lockWithDiags(finalStats);
}
return simpleLock(finalStats);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* determine the caller to Locker
*
* @param object
* @return
*/
private static String getCaller(Object object)
{
Exception ex = new Exception();
StackTraceElement[] trace = ex.getStackTrace();
String name = object.getClass().getCanonicalName();
for (StackTraceElement element : trace)
{
if (element.getFileName() != null && !element.getFileName().contains(Locker.class.getSimpleName()))
{
name = element.getFileName() + " " + element.getMethodName() + " " + element.getLineNumber() + " "
+ element.getClassName();
break;
}
}
return name;
}
public interface LockCloser extends AutoCloseable
{
public void close();
}
private static LockCloser simpleLock(LockStats stats) throws InterruptedException
{
Semaphore lock = stats.semaphore;
lock.acquire();
return new LockCloser()
{
@Override
public void close()
{
lock.release();
}
};
}
private static LockCloser lockWithDiags(LockStats stats) throws InterruptedException
{
int offset = stats.requested.incrementAndGet();
long waitStart = System.currentTimeMillis();
Semaphore lock = stats.semaphore;
lock.acquire();
stats.acquired.getAndIncrement();
long acquiredAt = System.currentTimeMillis();
return new LockCloser()
{
@Override
public void close()
{
// ignore any wait that may have been caused by Locker code, so
// count the waiters before we release the lock
long waiters = stats.requested.get() - offset;
stats.waited.addAndGet((int) waiters);
// release the lock
lock.release();
// count the time waiting and holding the lock
int holdTime = (int) (System.currentTimeMillis() - acquiredAt);
int waitTime = (int) (acquiredAt - waitStart);
stats.totalWaitTime.addAndGet(waitTime);
stats.totalHoldTime.addAndGet(holdTime);
if (waiters > 0 && holdTime > 1)
{
// some threads waited
String message = "Lock held for (" + holdTime + "MS), " + waiters
+ " threads waited for some of that time! " + getCaller(stats.object);
logger.warn(message);
if (holdTime > stats.getAverageHoldTime() * 10.0)
{
Exception trace = new Exception(message);
logger.error(trace, trace);
}
}
if (holdTime > stats.getAverageHoldTime() * 5.0)
{
// long hold!
String message = "Lock hold of lock (" + holdTime + "MS), average is " + stats.getAverageHoldTime() + " "
+ getCaller(stats.object);
logger.warn(message);
if (holdTime > stats.getAverageHoldTime() * 10.0)
{
Exception trace = new Exception(message);
logger.error(trace, trace);
}
}
}
};
}
/**
* start dumping lock stats once per minute, can't be stopped once started.
*/
public static void enable()
{
if (!diags)
{
diags = true;
executor.scheduleWithFixedDelay(() -> {
dumpStats();
}, 1, 1, TimeUnit.MINUTES);
}
else
{
logger.warn("Already enabled");
}
}
private static void dumpStats()
{
List<LockStats> stats = new LinkedList<>();
synchronized (mapSync)
{
stats.addAll(lockObjectMap.values());
keepList.clear();
}
for (LockStats stat : stats)
{
if (stat.waited.get() > 0)
{
logger.warn(stat);
}
}
logger.warn("Dump Lock Stats finished.");
}
static class LockStats
{
@Override
public String toString()
{
return "LockStats [totalWaitTime=" + totalWaitTime + ", totalHoldTime=" + totalHoldTime + ", waited=" + waited
+ ", acquired=" + acquired + ", object=" + name + "]";
}
final Semaphore semaphore = new Semaphore(1, true);
// this reference to object stops the WeakRefHashMap removing this
// LockStats from
// the map
final Object object;
final String name;
final AtomicInteger totalWaitTime = new AtomicInteger();
final AtomicInteger totalHoldTime = new AtomicInteger();
final AtomicInteger requested = new AtomicInteger();
final AtomicInteger waited = new AtomicInteger();
final AtomicInteger acquired = new AtomicInteger();
LockStats(Object object, String name)
{
this.object = object;
this.name = name;
}
double getAverageHoldTime()
{
long hold = totalHoldTime.get();
long count = acquired.get();
if (count < 10)
{
return 250.0;
}
return Math.max(hold / count, 50);
}
}
}
| reduce logging
| src/main/java/org/asteriskjava/util/Locker.java | reduce logging | <ide><path>rc/main/java/org/asteriskjava/util/Locker.java
<ide> stats.totalWaitTime.addAndGet(waitTime);
<ide> stats.totalHoldTime.addAndGet(holdTime);
<ide>
<del> if (waiters > 0 && holdTime > 1)
<add> long averageHoldTime = stats.getAverageHoldTime();
<add> if (waiters > 0 && holdTime > averageHoldTime * 2)
<ide> {
<ide> // some threads waited
<ide> String message = "Lock held for (" + holdTime + "MS), " + waiters
<ide> + " threads waited for some of that time! " + getCaller(stats.object);
<ide> logger.warn(message);
<del> if (holdTime > stats.getAverageHoldTime() * 10.0)
<add> if (holdTime > averageHoldTime * 10.0)
<ide> {
<ide> Exception trace = new Exception(message);
<ide> logger.error(trace, trace);
<ide> }
<ide> }
<ide>
<del> if (holdTime > stats.getAverageHoldTime() * 5.0)
<add> if (holdTime > averageHoldTime * 5.0)
<ide> {
<ide> // long hold!
<ide> String message = "Lock hold of lock (" + holdTime + "MS), average is " + stats.getAverageHoldTime() + " "
<ide> + getCaller(stats.object);
<ide>
<ide> logger.warn(message);
<del> if (holdTime > stats.getAverageHoldTime() * 10.0)
<add> if (holdTime > averageHoldTime * 10.0)
<ide> {
<ide> Exception trace = new Exception(message);
<ide> logger.error(trace, trace);
<ide> this.name = name;
<ide> }
<ide>
<del> double getAverageHoldTime()
<add> long getAverageHoldTime()
<ide> {
<ide> long hold = totalHoldTime.get();
<ide> long count = acquired.get();
<ide> if (count < 10)
<ide> {
<del> return 250.0;
<add> return 250;
<ide> }
<ide> return Math.max(hold / count, 50);
<ide> } |
|
Java | apache-2.0 | 47bb175bd4b443f992d8ecc55f0bc795693ba016 | 0 | wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,jcshen007/cloudstack,wido/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,resmo/cloudstack | //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.utils.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.security.KeyStore;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.log4j.Logger;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.db.DbProperties;
/**
*/
public class Link {
private static final Logger s_logger = Logger.getLogger(Link.class);
private final InetSocketAddress _addr;
private final NioConnection _connection;
private SelectionKey _key;
private final ConcurrentLinkedQueue<ByteBuffer[]> _writeQueue;
private ByteBuffer _readBuffer;
private ByteBuffer _plaintextBuffer;
private Object _attach;
private boolean _readHeader;
private boolean _gotFollowingPacket;
private SSLEngine _sslEngine;
public static String keystoreFile = "/cloud.keystore";
public Link(InetSocketAddress addr, NioConnection connection) {
_addr = addr;
_connection = connection;
_readBuffer = ByteBuffer.allocate(2048);
_attach = null;
_key = null;
_writeQueue = new ConcurrentLinkedQueue<ByteBuffer[]>();
_readHeader = true;
_gotFollowingPacket = false;
}
public Link(Link link) {
this(link._addr, link._connection);
}
public Object attachment() {
return _attach;
}
public void attach(Object attach) {
_attach = attach;
}
public void setKey(SelectionKey key) {
_key = key;
}
public void setSSLEngine(SSLEngine sslEngine) {
_sslEngine = sslEngine;
}
/**
* No user, so comment it out.
*
* Static methods for reading from a channel in case
* you need to add a client that doesn't require nio.
* @param ch channel to read from.
* @param bytebuffer to use.
* @return bytes read
* @throws IOException if not read to completion.
public static byte[] read(SocketChannel ch, ByteBuffer buff) throws IOException {
synchronized(buff) {
buff.clear();
buff.limit(4);
while (buff.hasRemaining()) {
if (ch.read(buff) == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
}
buff.flip();
int length = buff.getInt();
ByteArrayOutputStream output = new ByteArrayOutputStream(length);
WritableByteChannel outCh = Channels.newChannel(output);
int count = 0;
while (count < length) {
buff.clear();
int read = ch.read(buff);
if (read < 0) {
throw new IOException("Connection closed with -1 on reading data.");
}
count += read;
buff.flip();
outCh.write(buff);
}
return output.toByteArray();
}
}
*/
private static void doWrite(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
SSLSession sslSession = sslEngine.getSession();
ByteBuffer pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
SSLEngineResult engResult;
ByteBuffer headBuf = ByteBuffer.allocate(4);
int totalLen = 0;
for (ByteBuffer buffer : buffers) {
totalLen += buffer.limit();
}
int processedLen = 0;
while (processedLen < totalLen) {
headBuf.clear();
pkgBuf.clear();
engResult = sslEngine.wrap(buffers, pkgBuf);
if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("SSL: SSLEngine return bad result! " + engResult);
}
processedLen = 0;
for (ByteBuffer buffer : buffers) {
processedLen += buffer.position();
}
int dataRemaining = pkgBuf.position();
int header = dataRemaining;
int headRemaining = 4;
pkgBuf.flip();
if (processedLen < totalLen) {
header = header | HEADER_FLAG_FOLLOWING;
}
headBuf.putInt(header);
headBuf.flip();
while (headRemaining > 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Writing Header " + headRemaining);
}
long count = ch.write(headBuf);
headRemaining -= count;
}
while (dataRemaining > 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Writing Data " + dataRemaining);
}
long count = ch.write(pkgBuf);
dataRemaining -= count;
}
}
}
/**
* write method to write to a socket. This method writes to completion so
* it doesn't follow the nio standard. We use this to make sure we write
* our own protocol.
*
* @param ch channel to write to.
* @param buffers buffers to write.
* @throws IOException if unable to write to completion.
*/
public static void write(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
synchronized (ch) {
doWrite(ch, buffers, sslEngine);
}
}
/* SSL has limitation of 16k, we may need to split packets. 18000 is 16k + some extra SSL informations */
protected static final int MAX_SIZE_PER_PACKET = 18000;
protected static final int HEADER_FLAG_FOLLOWING = 0x10000;
public byte[] read(SocketChannel ch) throws IOException {
if (_readHeader) { // Start of a packet
if (_readBuffer.position() == 0) {
_readBuffer.limit(4);
}
if (ch.read(_readBuffer) == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
if (_readBuffer.hasRemaining()) {
s_logger.trace("Need to read the rest of the packet length");
return null;
}
_readBuffer.flip();
int header = _readBuffer.getInt();
int readSize = (short)header;
if (s_logger.isTraceEnabled()) {
s_logger.trace("Packet length is " + readSize);
}
if (readSize > MAX_SIZE_PER_PACKET) {
throw new IOException("Wrong packet size: " + readSize);
}
if (!_gotFollowingPacket) {
_plaintextBuffer = ByteBuffer.allocate(2000);
}
if ((header & HEADER_FLAG_FOLLOWING) != 0) {
_gotFollowingPacket = true;
} else {
_gotFollowingPacket = false;
}
_readBuffer.clear();
_readHeader = false;
if (_readBuffer.capacity() < readSize) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity());
}
_readBuffer = ByteBuffer.allocate(readSize);
}
_readBuffer.limit(readSize);
}
if (ch.read(_readBuffer) == -1) {
throw new IOException("Connection closed with -1 on read.");
}
if (_readBuffer.hasRemaining()) { // We're not done yet.
if (s_logger.isTraceEnabled()) {
s_logger.trace("Still has " + _readBuffer.remaining());
}
return null;
}
_readBuffer.flip();
ByteBuffer appBuf;
SSLSession sslSession = _sslEngine.getSession();
SSLEngineResult engResult;
int remaining = 0;
while (_readBuffer.hasRemaining()) {
remaining = _readBuffer.remaining();
appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
engResult = _sslEngine.unwrap(_readBuffer, appBuf);
if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("SSL: SSLEngine return bad result! " + engResult);
}
if (remaining == _readBuffer.remaining()) {
throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!");
}
appBuf.flip();
if (_plaintextBuffer.remaining() < appBuf.limit()) {
// We need to expand _plaintextBuffer for more data
ByteBuffer newBuffer = ByteBuffer.allocate(_plaintextBuffer.capacity() + appBuf.limit() * 5);
_plaintextBuffer.flip();
newBuffer.put(_plaintextBuffer);
_plaintextBuffer = newBuffer;
}
_plaintextBuffer.put(appBuf);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Done with packet: " + appBuf.limit());
}
}
_readBuffer.clear();
_readHeader = true;
if (!_gotFollowingPacket) {
_plaintextBuffer.flip();
byte[] result = new byte[_plaintextBuffer.limit()];
_plaintextBuffer.get(result);
return result;
} else {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Waiting for more packets");
}
return null;
}
}
public void send(byte[] data) throws ClosedChannelException {
send(data, false);
}
public void send(byte[] data, boolean close) throws ClosedChannelException {
send(new ByteBuffer[] {ByteBuffer.wrap(data)}, close);
}
public void send(ByteBuffer[] data, boolean close) throws ClosedChannelException {
ByteBuffer[] item = new ByteBuffer[data.length + 1];
int remaining = 0;
for (int i = 0; i < data.length; i++) {
remaining += data[i].remaining();
item[i + 1] = data[i];
}
item[0] = ByteBuffer.allocate(4);
item[0].putInt(remaining);
item[0].flip();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending packet of length " + remaining);
}
_writeQueue.add(item);
if (close) {
_writeQueue.add(new ByteBuffer[0]);
}
synchronized (this) {
if (_key == null) {
throw new ClosedChannelException();
}
_connection.change(SelectionKey.OP_WRITE, _key, null);
}
}
public void send(ByteBuffer[] data) throws ClosedChannelException {
send(data, false);
}
public synchronized void close() {
if (_key != null) {
_connection.close(_key);
}
}
public boolean write(SocketChannel ch) throws IOException {
ByteBuffer[] data = null;
while ((data = _writeQueue.poll()) != null) {
if (data.length == 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Closing connection requested");
}
return true;
}
ByteBuffer[] raw_data = new ByteBuffer[data.length - 1];
System.arraycopy(data, 1, raw_data, 0, data.length - 1);
doWrite(ch, raw_data, _sslEngine);
}
return false;
}
public InetSocketAddress getSocketAddress() {
return _addr;
}
public String getIpAddress() {
return _addr.getAddress().toString();
}
public synchronized void terminated() {
_key = null;
}
public synchronized void schedule(Task task) throws ClosedChannelException {
if (_key == null) {
throw new ClosedChannelException();
}
_connection.scheduleTask(task);
}
public static SSLContext initSSLContext(boolean isClient) throws Exception {
InputStream stream;
SSLContext sslContext = null;
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
TrustManager[] tms;
File confFile = PropertiesUtil.findConfigFile("db.properties");
if (null != confFile && !isClient) {
final Properties dbProps = DbProperties.getDbProperties();
char[] passphrase = dbProps.getProperty("db.cloud.keyStorePassphrase").toCharArray();
String confPath = confFile.getParent();
String keystorePath = confPath + keystoreFile;
if (new File(keystorePath).exists()) {
stream = new FileInputStream(keystorePath);
} else {
s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue.");
stream = NioConnection.class.getResourceAsStream("/cloud.keystore");
}
ks.load(stream, passphrase);
stream.close();
kmf.init(ks, passphrase);
tmf.init(ks);
tms = tmf.getTrustManagers();
} else {
ks.load(null, null);
kmf.init(ks, null);
tms = new TrustManager[1];
tms[0] = new TrustAllManager();
}
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tms, null);
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: SSLcontext has been initialized");
}
return sslContext;
}
public static void doHandshake(SocketChannel ch, SSLEngine sslEngine, boolean isClient) throws IOException {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: begin Handshake, isClient: " + isClient);
}
SSLEngineResult engResult;
SSLSession sslSession = sslEngine.getSession();
HandshakeStatus hsStatus;
ByteBuffer in_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
ByteBuffer in_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
ByteBuffer out_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
ByteBuffer out_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
int count;
ch.socket().setSoTimeout(10 * 1000);
InputStream inStream = ch.socket().getInputStream();
// Use readCh to make sure the timeout on reading is working
ReadableByteChannel readCh = Channels.newChannel(inStream);
if (isClient) {
hsStatus = SSLEngineResult.HandshakeStatus.NEED_WRAP;
} else {
hsStatus = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
}
while (hsStatus != SSLEngineResult.HandshakeStatus.FINISHED) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: Handshake status " + hsStatus);
}
engResult = null;
if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
out_pkgBuf.clear();
out_appBuf.clear();
out_appBuf.put("Hello".getBytes());
engResult = sslEngine.wrap(out_appBuf, out_pkgBuf);
out_pkgBuf.flip();
int remain = out_pkgBuf.limit();
while (remain != 0) {
remain -= ch.write(out_pkgBuf);
if (remain < 0) {
throw new IOException("Too much bytes sent?");
}
}
} else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
in_appBuf.clear();
// One packet may contained multiply operation
if (in_pkgBuf.position() == 0 || !in_pkgBuf.hasRemaining()) {
in_pkgBuf.clear();
count = 0;
try {
count = readCh.read(in_pkgBuf);
} catch (SocketTimeoutException ex) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Handshake reading time out! Cut the connection");
}
count = -1;
}
if (count == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
in_pkgBuf.flip();
}
engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
ByteBuffer tmp_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
int loop_count = 0;
while (engResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
// The client is too slow? Cut it and let it reconnect
if (loop_count > 10) {
throw new IOException("Too many times in SSL BUFFER_UNDERFLOW, disconnect guest.");
}
// We need more packets to complete this operation
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: Buffer underflowed, getting more packets");
}
tmp_pkgBuf.clear();
count = ch.read(tmp_pkgBuf);
if (count == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
tmp_pkgBuf.flip();
in_pkgBuf.mark();
in_pkgBuf.position(in_pkgBuf.limit());
in_pkgBuf.limit(in_pkgBuf.limit() + tmp_pkgBuf.limit());
in_pkgBuf.put(tmp_pkgBuf);
in_pkgBuf.reset();
in_appBuf.clear();
engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
loop_count++;
}
} else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
Runnable run;
while ((run = sslEngine.getDelegatedTask()) != null) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: Running delegated task!");
}
run.run();
}
} else if (hsStatus == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
throw new IOException("NOT a handshaking!");
}
if (engResult != null && engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("Fail to handshake! " + engResult.getStatus());
}
if (engResult != null)
hsStatus = engResult.getHandshakeStatus();
else
hsStatus = sslEngine.getHandshakeStatus();
}
}
}
| utils/src/com/cloud/utils/nio/Link.java | //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.utils.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.security.KeyStore;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.log4j.Logger;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.db.DbProperties;
/**
*/
public class Link {
private static final Logger s_logger = Logger.getLogger(Link.class);
private final InetSocketAddress _addr;
private final NioConnection _connection;
private SelectionKey _key;
private final ConcurrentLinkedQueue<ByteBuffer[]> _writeQueue;
private ByteBuffer _readBuffer;
private ByteBuffer _plaintextBuffer;
private Object _attach;
private boolean _readHeader;
private boolean _gotFollowingPacket;
private SSLEngine _sslEngine;
public static String keystoreFile = "/cloudmanagementserver.keystore";
public Link(InetSocketAddress addr, NioConnection connection) {
_addr = addr;
_connection = connection;
_readBuffer = ByteBuffer.allocate(2048);
_attach = null;
_key = null;
_writeQueue = new ConcurrentLinkedQueue<ByteBuffer[]>();
_readHeader = true;
_gotFollowingPacket = false;
}
public Link(Link link) {
this(link._addr, link._connection);
}
public Object attachment() {
return _attach;
}
public void attach(Object attach) {
_attach = attach;
}
public void setKey(SelectionKey key) {
_key = key;
}
public void setSSLEngine(SSLEngine sslEngine) {
_sslEngine = sslEngine;
}
/**
* No user, so comment it out.
*
* Static methods for reading from a channel in case
* you need to add a client that doesn't require nio.
* @param ch channel to read from.
* @param bytebuffer to use.
* @return bytes read
* @throws IOException if not read to completion.
public static byte[] read(SocketChannel ch, ByteBuffer buff) throws IOException {
synchronized(buff) {
buff.clear();
buff.limit(4);
while (buff.hasRemaining()) {
if (ch.read(buff) == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
}
buff.flip();
int length = buff.getInt();
ByteArrayOutputStream output = new ByteArrayOutputStream(length);
WritableByteChannel outCh = Channels.newChannel(output);
int count = 0;
while (count < length) {
buff.clear();
int read = ch.read(buff);
if (read < 0) {
throw new IOException("Connection closed with -1 on reading data.");
}
count += read;
buff.flip();
outCh.write(buff);
}
return output.toByteArray();
}
}
*/
private static void doWrite(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
SSLSession sslSession = sslEngine.getSession();
ByteBuffer pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
SSLEngineResult engResult;
ByteBuffer headBuf = ByteBuffer.allocate(4);
int totalLen = 0;
for (ByteBuffer buffer : buffers) {
totalLen += buffer.limit();
}
int processedLen = 0;
while (processedLen < totalLen) {
headBuf.clear();
pkgBuf.clear();
engResult = sslEngine.wrap(buffers, pkgBuf);
if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("SSL: SSLEngine return bad result! " + engResult);
}
processedLen = 0;
for (ByteBuffer buffer : buffers) {
processedLen += buffer.position();
}
int dataRemaining = pkgBuf.position();
int header = dataRemaining;
int headRemaining = 4;
pkgBuf.flip();
if (processedLen < totalLen) {
header = header | HEADER_FLAG_FOLLOWING;
}
headBuf.putInt(header);
headBuf.flip();
while (headRemaining > 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Writing Header " + headRemaining);
}
long count = ch.write(headBuf);
headRemaining -= count;
}
while (dataRemaining > 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Writing Data " + dataRemaining);
}
long count = ch.write(pkgBuf);
dataRemaining -= count;
}
}
}
/**
* write method to write to a socket. This method writes to completion so
* it doesn't follow the nio standard. We use this to make sure we write
* our own protocol.
*
* @param ch channel to write to.
* @param buffers buffers to write.
* @throws IOException if unable to write to completion.
*/
public static void write(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
synchronized (ch) {
doWrite(ch, buffers, sslEngine);
}
}
/* SSL has limitation of 16k, we may need to split packets. 18000 is 16k + some extra SSL informations */
protected static final int MAX_SIZE_PER_PACKET = 18000;
protected static final int HEADER_FLAG_FOLLOWING = 0x10000;
public byte[] read(SocketChannel ch) throws IOException {
if (_readHeader) { // Start of a packet
if (_readBuffer.position() == 0) {
_readBuffer.limit(4);
}
if (ch.read(_readBuffer) == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
if (_readBuffer.hasRemaining()) {
s_logger.trace("Need to read the rest of the packet length");
return null;
}
_readBuffer.flip();
int header = _readBuffer.getInt();
int readSize = (short)header;
if (s_logger.isTraceEnabled()) {
s_logger.trace("Packet length is " + readSize);
}
if (readSize > MAX_SIZE_PER_PACKET) {
throw new IOException("Wrong packet size: " + readSize);
}
if (!_gotFollowingPacket) {
_plaintextBuffer = ByteBuffer.allocate(2000);
}
if ((header & HEADER_FLAG_FOLLOWING) != 0) {
_gotFollowingPacket = true;
} else {
_gotFollowingPacket = false;
}
_readBuffer.clear();
_readHeader = false;
if (_readBuffer.capacity() < readSize) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity());
}
_readBuffer = ByteBuffer.allocate(readSize);
}
_readBuffer.limit(readSize);
}
if (ch.read(_readBuffer) == -1) {
throw new IOException("Connection closed with -1 on read.");
}
if (_readBuffer.hasRemaining()) { // We're not done yet.
if (s_logger.isTraceEnabled()) {
s_logger.trace("Still has " + _readBuffer.remaining());
}
return null;
}
_readBuffer.flip();
ByteBuffer appBuf;
SSLSession sslSession = _sslEngine.getSession();
SSLEngineResult engResult;
int remaining = 0;
while (_readBuffer.hasRemaining()) {
remaining = _readBuffer.remaining();
appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
engResult = _sslEngine.unwrap(_readBuffer, appBuf);
if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING &&
engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("SSL: SSLEngine return bad result! " + engResult);
}
if (remaining == _readBuffer.remaining()) {
throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!");
}
appBuf.flip();
if (_plaintextBuffer.remaining() < appBuf.limit()) {
// We need to expand _plaintextBuffer for more data
ByteBuffer newBuffer = ByteBuffer.allocate(_plaintextBuffer.capacity() + appBuf.limit() * 5);
_plaintextBuffer.flip();
newBuffer.put(_plaintextBuffer);
_plaintextBuffer = newBuffer;
}
_plaintextBuffer.put(appBuf);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Done with packet: " + appBuf.limit());
}
}
_readBuffer.clear();
_readHeader = true;
if (!_gotFollowingPacket) {
_plaintextBuffer.flip();
byte[] result = new byte[_plaintextBuffer.limit()];
_plaintextBuffer.get(result);
return result;
} else {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Waiting for more packets");
}
return null;
}
}
public void send(byte[] data) throws ClosedChannelException {
send(data, false);
}
public void send(byte[] data, boolean close) throws ClosedChannelException {
send(new ByteBuffer[] {ByteBuffer.wrap(data)}, close);
}
public void send(ByteBuffer[] data, boolean close) throws ClosedChannelException {
ByteBuffer[] item = new ByteBuffer[data.length + 1];
int remaining = 0;
for (int i = 0; i < data.length; i++) {
remaining += data[i].remaining();
item[i + 1] = data[i];
}
item[0] = ByteBuffer.allocate(4);
item[0].putInt(remaining);
item[0].flip();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending packet of length " + remaining);
}
_writeQueue.add(item);
if (close) {
_writeQueue.add(new ByteBuffer[0]);
}
synchronized (this) {
if (_key == null) {
throw new ClosedChannelException();
}
_connection.change(SelectionKey.OP_WRITE, _key, null);
}
}
public void send(ByteBuffer[] data) throws ClosedChannelException {
send(data, false);
}
public synchronized void close() {
if (_key != null) {
_connection.close(_key);
}
}
public boolean write(SocketChannel ch) throws IOException {
ByteBuffer[] data = null;
while ((data = _writeQueue.poll()) != null) {
if (data.length == 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Closing connection requested");
}
return true;
}
ByteBuffer[] raw_data = new ByteBuffer[data.length - 1];
System.arraycopy(data, 1, raw_data, 0, data.length - 1);
doWrite(ch, raw_data, _sslEngine);
}
return false;
}
public InetSocketAddress getSocketAddress() {
return _addr;
}
public String getIpAddress() {
return _addr.getAddress().toString();
}
public synchronized void terminated() {
_key = null;
}
public synchronized void schedule(Task task) throws ClosedChannelException {
if (_key == null) {
throw new ClosedChannelException();
}
_connection.scheduleTask(task);
}
public static SSLContext initSSLContext(boolean isClient) throws Exception {
InputStream stream;
SSLContext sslContext = null;
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
TrustManager[] tms;
File confFile = PropertiesUtil.findConfigFile("db.properties");
if (null != confFile && !isClient) {
final Properties dbProps = DbProperties.getDbProperties();
char[] passphrase = dbProps.getProperty("db.cloud.keyStorePassphrase").toCharArray();
String confPath = confFile.getParent();
String keystorePath = confPath + keystoreFile;
if (new File(keystorePath).exists()) {
stream = new FileInputStream(keystorePath);
} else {
s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue.");
stream = NioConnection.class.getResourceAsStream("/cloud.keystore");
}
ks.load(stream, passphrase);
stream.close();
kmf.init(ks, passphrase);
tmf.init(ks);
tms = tmf.getTrustManagers();
} else {
ks.load(null, null);
kmf.init(ks, null);
tms = new TrustManager[1];
tms[0] = new TrustAllManager();
}
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tms, null);
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: SSLcontext has been initialized");
}
return sslContext;
}
public static void doHandshake(SocketChannel ch, SSLEngine sslEngine, boolean isClient) throws IOException {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: begin Handshake, isClient: " + isClient);
}
SSLEngineResult engResult;
SSLSession sslSession = sslEngine.getSession();
HandshakeStatus hsStatus;
ByteBuffer in_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
ByteBuffer in_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
ByteBuffer out_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
ByteBuffer out_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
int count;
ch.socket().setSoTimeout(10 * 1000);
InputStream inStream = ch.socket().getInputStream();
// Use readCh to make sure the timeout on reading is working
ReadableByteChannel readCh = Channels.newChannel(inStream);
if (isClient) {
hsStatus = SSLEngineResult.HandshakeStatus.NEED_WRAP;
} else {
hsStatus = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
}
while (hsStatus != SSLEngineResult.HandshakeStatus.FINISHED) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: Handshake status " + hsStatus);
}
engResult = null;
if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
out_pkgBuf.clear();
out_appBuf.clear();
out_appBuf.put("Hello".getBytes());
engResult = sslEngine.wrap(out_appBuf, out_pkgBuf);
out_pkgBuf.flip();
int remain = out_pkgBuf.limit();
while (remain != 0) {
remain -= ch.write(out_pkgBuf);
if (remain < 0) {
throw new IOException("Too much bytes sent?");
}
}
} else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
in_appBuf.clear();
// One packet may contained multiply operation
if (in_pkgBuf.position() == 0 || !in_pkgBuf.hasRemaining()) {
in_pkgBuf.clear();
count = 0;
try {
count = readCh.read(in_pkgBuf);
} catch (SocketTimeoutException ex) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Handshake reading time out! Cut the connection");
}
count = -1;
}
if (count == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
in_pkgBuf.flip();
}
engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
ByteBuffer tmp_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
int loop_count = 0;
while (engResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
// The client is too slow? Cut it and let it reconnect
if (loop_count > 10) {
throw new IOException("Too many times in SSL BUFFER_UNDERFLOW, disconnect guest.");
}
// We need more packets to complete this operation
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: Buffer underflowed, getting more packets");
}
tmp_pkgBuf.clear();
count = ch.read(tmp_pkgBuf);
if (count == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
tmp_pkgBuf.flip();
in_pkgBuf.mark();
in_pkgBuf.position(in_pkgBuf.limit());
in_pkgBuf.limit(in_pkgBuf.limit() + tmp_pkgBuf.limit());
in_pkgBuf.put(tmp_pkgBuf);
in_pkgBuf.reset();
in_appBuf.clear();
engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
loop_count++;
}
} else if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
Runnable run;
while ((run = sslEngine.getDelegatedTask()) != null) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: Running delegated task!");
}
run.run();
}
} else if (hsStatus == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
throw new IOException("NOT a handshaking!");
}
if (engResult != null && engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("Fail to handshake! " + engResult.getStatus());
}
if (engResult != null)
hsStatus = engResult.getHandshakeStatus();
else
hsStatus = sslEngine.getHandshakeStatus();
}
}
}
| Partially reverting c61c636ce8a1d74fd22d89026d40ba904fff6cf8. Changing the name if cloud.keystore has bigger impact than just changing the name.
| utils/src/com/cloud/utils/nio/Link.java | Partially reverting c61c636ce8a1d74fd22d89026d40ba904fff6cf8. Changing the name if cloud.keystore has bigger impact than just changing the name. | <ide><path>tils/src/com/cloud/utils/nio/Link.java
<ide> private boolean _gotFollowingPacket;
<ide>
<ide> private SSLEngine _sslEngine;
<del> public static String keystoreFile = "/cloudmanagementserver.keystore";
<add> public static String keystoreFile = "/cloud.keystore";
<ide>
<ide> public Link(InetSocketAddress addr, NioConnection connection) {
<ide> _addr = addr; |
|
JavaScript | mit | 24c942a45d087621bd125e3b5495a17c67dd3ee3 | 0 | phetsims/axon,phetsims/axon,phetsims/axon | // Copyright 2013-2016, University of Colorado Boulder
/**
* An observable array of items.
*
* Because the array is observable, we must be careful about the possibility of concurrent-modification errors.
* Any time we iterate over the array, we must iterate over a copy, because callback may be modifying the array.
*
* @author Sam Reid (PhET Interactive Simulations)
* @author Chris Malley (PixelZoom, Inc.)
*/
define( function( require ) {
'use strict';
// modules
var Property = require( 'AXON/Property' );
var axon = require( 'AXON/axon' );
var inherit = require( 'PHET_CORE/inherit' );
var Emitter = require( 'AXON/Emitter' );
var TObservableArray = require( 'AXON/TObservableArray' );
var Tandem = require( 'TANDEM/Tandem' );
// phet-io modules
var TNumber = require( 'ifphetio!PHET_IO/types/TNumber' );
/**
* @param {Object[]} [array]
* @param {Object} [options]
* @constructor
*/
function ObservableArray( array, options ) {
var self = this;
// Special case that the user supplied options but no array
if ( array instanceof Object && !(array instanceof Array) ) {
options = array;
array = null;
}
options = _.extend( {
allowDuplicates: false, // are duplicate items allowed in the array?
tandem: Tandem.tandemOptional(),
phetioValueType: null,
phetioIncludeInState: false // keep ObservableArray out of the state unless they opt in.
}, options );
// TODO: Should we require tandems for all ObservableArrays?
this.allowDuplicates = options.allowDuplicates; // @private
this._array = array || []; // @private internal, do not access directly
this._addedListeners = []; // @private listeners called when an item is added
this._removedListeners = []; // @private listeners called when an item is removed
// @public (read-only) observe this, but don't set it
this.lengthProperty = new Property( this._array.length, {
tandem: options.tandem && options.tandem.createTandem( 'lengthProperty' ),
phetioValueType: TNumber( { type: 'Integer' } )
} );
// @private Store the initial array, if any, for resetting, see #4
this.initialArray = array ? array.slice() : [];
// @private Event stream for signifying begin/end of callbacks
this.startedCallbacksForItemAddedEmitter = new Emitter( { indicateCallbacks: false } );
this.endedCallbacksForItemAddedEmitter = new Emitter( { indicateCallbacks: false } );
this.startedCallbacksForItemRemovedEmitter = new Emitter( { indicateCallbacks: false } );
this.endedCallbacksForItemRemovedEmitter = new Emitter( { indicateCallbacks: false } );
// public (phet-io) (read-only)
this.phetioIncludeInState = options.phetioIncludeInState;
options.tandem.supplied && options.tandem.addInstance( this, TObservableArray( options.phetioValueType ) );
this.disposeObservableArray = function() {
options.tandem.supplied && options.tandem.removeInstance( self );
};
}
axon.register( 'ObservableArray', ObservableArray );
return inherit( Object, ObservableArray, {
// @public
dispose: function() {
this.disposeObservableArray();
},
/**
* Restore the array back to its initial state
* Note: if an item is in the current array and original array, it is removed and added back
* This may or may not change in the future, see #4
* @public
*/
reset: function() {
for ( var i = 0; i < this._array.length; i++ ) {
this._fireItemRemoved( this._array[ i ] );
}
this._array = this.initialArray.slice();
for ( i = 0; i < this._array.length; i++ ) {
this._fireItemAdded( this._array[ i ] );
}
},
// @public
get length() { return this._array.length; },
/**
* Adds a listener that will be notified when an item is added to the list.
* @param listener function( item, observableArray )
* @public
*/
addItemAddedListener: function( listener ) {
assert && assert( this._addedListeners.indexOf( listener ) === -1 ); // listener is not already registered
this._addedListeners.push( listener );
},
/**
* Removes a listener that was added via addItemAddedListener.
* @param listener
* @public
*/
removeItemAddedListener: function( listener ) {
var index = this._addedListeners.indexOf( listener );
assert && assert( index !== -1 ); // listener is registered
this._addedListeners.splice( index, 1 );
},
/**
* Adds a listener that will be notified when an item is removed from the list.
* @param listener function( item, observableArray )
* @public
*/
addItemRemovedListener: function( listener ) {
assert && assert( this._removedListeners.indexOf( listener ) === -1, 'Listener was already registered' ); // listener is not already registered
this._removedListeners.push( listener );
},
/**
* Removes a listener that was added via addItemRemovedListener.
* @param listener
* @public
*/
removeItemRemovedListener: function( listener ) {
var index = this._removedListeners.indexOf( listener );
assert && assert( index !== -1, 'Listener is still registered after removal' ); // listener is registered
this._removedListeners.splice( index, 1 );
},
// @private called when an item is added.
_fireItemAdded: function( item ) {
this.startedCallbacksForItemAddedEmitter.emit1( item );
//Signify that an item was added to the list
var copy = this._addedListeners.slice( 0 ); // operate on a copy, firing could result in the listeners changing
for ( var i = 0; i < copy.length; i++ ) {
copy[ i ]( item, this );
}
this.endedCallbacksForItemAddedEmitter.emit();
},
// @private called when an item is removed.
_fireItemRemoved: function( item ) {
this.startedCallbacksForItemRemovedEmitter.emit1( item );
//Signify that an item was removed from the list
var copy = this._removedListeners.slice( 0 ); // operate on a copy, firing could result in the listeners changing
for ( var i = 0; i < copy.length; i++ ) {
copy[ i ]( item, this );
}
this.endedCallbacksForItemRemovedEmitter.emit();
},
/**
* Adds an item to the end of the array.
* This is a convenience function, and is the same as push.
* @param item
* @public
*/
add: function( item ) {
this.push( item );
},
/**
* Add items to the end of the array.
* This is a convenience function, and is the same as push.
* @param {Array} items
* @public
*/
addAll: function( items ) {
for ( var i = 0; i < items.length; i++ ) {
this.add( items[ i ] );
}
},
/**
* Removes the first occurrence of an item from the array.
* If duplicates are allowed (see options.allowDuplicates) you may need to call this multiple
* times to totally purge item from the array.
* @param item
* @public
*/
remove: function( item ) {
var index = this._array.indexOf( item );
if ( index !== -1 ) {
this._array.splice( index, 1 );
this.lengthProperty.set( this._array.length );
this._fireItemRemoved( item );
}
},
/**
* Removes the first occurrence of each item in the specified array.
* @param {Array} array a list of items to remove
* @see ObservableArray.remove
* @public
*/
removeAll: function( array ) {
assert && assert( _.isArray( array ), 'array should be an array' );
for ( var i = 0; i < array.length; i++ ) {
this.remove( array[ i ] );
}
},
/**
* Pushes an item onto the end of the array.
* @param item
* @throws Error if duplicates are not allowed (see options.allowDuplicates) and item is already in the array
* @public
*/
push: function( item ) {
if ( !this.allowDuplicates && this.contains( item ) ) {
throw new Error( 'duplicates are not allowed' );
}
this._array.push( item );
this.lengthProperty.set( this._array.length );
this._fireItemAdded( item );
},
/**
* Removes an item from the end of the array and returns it.
* @returns {*}
* @public
*/
pop: function() {
var item = this._array.pop();
if ( item !== undefined ) {
this.lengthProperty.set( this._array.length );
this._fireItemRemoved( item );
}
return item;
},
/**
* Removes an item from the beginning of the array and returns it.
* @returns {*}
* @public
*/
shift: function() {
var item = this._array.shift();
if ( item !== undefined ) {
this.lengthProperty.set( this._array.length );
this._fireItemRemoved( item );
}
return item;
},
/**
* Does the array contain the specified item?
* @param item
* @returns {boolean}
* @public
*/
contains: function( item ) {
return this.indexOf( item ) !== -1;
},
/**
* Gets an item at the specified index.
* @param index
* @returns {*} the item, or undefined if there is no item at the specified index
* @public
*/
get: function( index ) {
return this._array[ index ];
},
/**
* Gets the index of a specified item.
* @param item
* @returns {*} -1 if item is not in the array
* @public
*/
indexOf: function( item ) {
return this._array.indexOf( item );
},
/**
* Removes all items from the array.
* @public
*/
clear: function() {
while ( this.length > 0 ) {
this.pop();
}
},
/**
* Applies a callback function to each item in the array
* @param callback function(item)
* @public
*/
forEach: function( callback ) {
this._array.slice().forEach( callback ); // do this on a copy of the array, in case callbacks involve array modification
},
/**
* Maps the values in this ObservableArray using the specified function, and returns a new ObservableArray for chaining.
* @param mapFunction
* @returns {ObservableArray}
* @public
*/
map: function( mapFunction ) {
return new ObservableArray( this._array.map( mapFunction ) );
},
/**
* Filters the values in this ObservableArray using the predicate function, and returns a new ObservableArray for chaining.
* @param predicate
* @returns {ObservableArray}
* @public
*/
filter: function( predicate ) {
return new ObservableArray( this._array.filter( predicate ) );
},
/**
* Count the number of items in this ObservableArray that satisfy the given Predicate.
* @param {function} predicate
* @returns {number}
* @public
*/
count: function( predicate ) {
var count = 0;
for ( var i = 0; i < this._array.length; i++ ) {
if ( predicate( this._array[ i ] ) ) {
count++;
}
}
return count;
},
/**
* Find the first element that matches the given predicate.
* @param {function} predicate
* @param {number} [fromIndex] - optional start index for the search
*/
find: function( predicate, fromIndex ) {
return _.find( this._array, predicate, fromIndex );
},
/**
* Starting with the initial value, combine values from this ObservableArray to come up with a composite result.
* Same as foldLeft. In underscore this is called _.reduce aka _.fold or _.inject
* @param value
* @param combiner
* @returns {*}
* @public
*/
reduce: function( value, combiner ) {
for ( var i = 0; i < this._array.length; i++ ) {
value = combiner( value, this._array[ i ] );
}
return value;
},
/**
* Return the underlying array
* @returns {Array}
* @public
*/
getArray: function() {
return this._array;
},
/**
* Add/remove elements from any point in the array
* @param {number} start - the index to start adding/removing items
* @param {number} deleteCount - the number of items to delete
* @param {Object} [item1] - an item to add
* @param {Object} [item2] - an item to add
* @param {Object} [etc] - varargs items to add etc.
* @returns {Object[]} the items that were deleted.
* @public
*/
splice: function( start, deleteCount, item1, item2, etc ) {
var deleted = this._array.splice.apply( this._array, arguments );
var args = Array.prototype.slice.call( arguments );
for ( var i = 0; i < deleted.length; i++ ) {
this._fireItemRemoved( deleted[ i ] );
}
for ( var k = 2; k < args.length; k++ ) {
this._fireItemAdded( args[ k ] );
}
return deleted;
},
/**
* Changes the ordering of elements in the array. Requires a Random source so that shuffles can be reproducible.
* No items are added or removed, and this method does not send out any notifications.
* @param {Random} random - from dot
*/
shuffle: function( random ) {
assert && assert( random, 'random must be supplied' );
// preserve the same _array reference in case any clients got a reference to it with getArray()
var shuffled = random.shuffle( this._array );
this._array.length = 0;
Array.prototype.push.apply( this._array, shuffled );
}
} );
} ); | js/ObservableArray.js | // Copyright 2013-2016, University of Colorado Boulder
/**
* An observable array of items.
*
* Because the array is observable, we must be careful about the possibility of concurrent-modification errors.
* Any time we iterate over the array, we must iterate over a copy, because callback may be modifying the array.
*
* @author Sam Reid (PhET Interactive Simulations)
* @author Chris Malley (PixelZoom, Inc.)
*/
define( function( require ) {
'use strict';
// modules
var Property = require( 'AXON/Property' );
var axon = require( 'AXON/axon' );
var inherit = require( 'PHET_CORE/inherit' );
var Emitter = require( 'AXON/Emitter' );
var TObservableArray = require( 'AXON/TObservableArray' );
var Tandem = require( 'TANDEM/Tandem' );
/**
* @param {Object[]} [array]
* @param {Object} [options]
* @constructor
*/
function ObservableArray( array, options ) {
var self = this;
// Special case that the user supplied options but no array
if ( array instanceof Object && !(array instanceof Array) ) {
options = array;
array = null;
}
options = _.extend( {
allowDuplicates: false, // are duplicate items allowed in the array?
tandem: Tandem.tandemOptional(),
phetioValueType: null,
phetioIncludeInState: false // keep ObservableArray out of the state unless they opt in.
}, options );
// TODO: Should we require tandems for all ObservableArrays?
this.allowDuplicates = options.allowDuplicates; // @private
this._array = array || []; // @private internal, do not access directly
this._addedListeners = []; // @private listeners called when an item is added
this._removedListeners = []; // @private listeners called when an item is removed
this.lengthProperty = new Property( this._array.length ); // @public (read-only) observe this, but don't set it
// @private Store the initial array, if any, for resetting, see #4
this.initialArray = array ? array.slice() : [];
// @private Event stream for signifying begin/end of callbacks
this.startedCallbacksForItemAddedEmitter = new Emitter( { indicateCallbacks: false } );
this.endedCallbacksForItemAddedEmitter = new Emitter( { indicateCallbacks: false } );
this.startedCallbacksForItemRemovedEmitter = new Emitter( { indicateCallbacks: false } );
this.endedCallbacksForItemRemovedEmitter = new Emitter( { indicateCallbacks: false } );
// public (phet-io) (read-only)
this.phetioIncludeInState = options.phetioIncludeInState;
options.tandem.supplied && options.tandem.addInstance( this, TObservableArray( options.phetioValueType ) );
this.disposeObservableArray = function() {
options.tandem.supplied && options.tandem.removeInstance( self );
};
}
axon.register( 'ObservableArray', ObservableArray );
return inherit( Object, ObservableArray, {
// @public
dispose: function() {
this.disposeObservableArray();
},
/**
* Restore the array back to its initial state
* Note: if an item is in the current array and original array, it is removed and added back
* This may or may not change in the future, see #4
* @public
*/
reset: function() {
for ( var i = 0; i < this._array.length; i++ ) {
this._fireItemRemoved( this._array[ i ] );
}
this._array = this.initialArray.slice();
for ( i = 0; i < this._array.length; i++ ) {
this._fireItemAdded( this._array[ i ] );
}
},
// @public
get length() { return this._array.length; },
/**
* Adds a listener that will be notified when an item is added to the list.
* @param listener function( item, observableArray )
* @public
*/
addItemAddedListener: function( listener ) {
assert && assert( this._addedListeners.indexOf( listener ) === -1 ); // listener is not already registered
this._addedListeners.push( listener );
},
/**
* Removes a listener that was added via addItemAddedListener.
* @param listener
* @public
*/
removeItemAddedListener: function( listener ) {
var index = this._addedListeners.indexOf( listener );
assert && assert( index !== -1 ); // listener is registered
this._addedListeners.splice( index, 1 );
},
/**
* Adds a listener that will be notified when an item is removed from the list.
* @param listener function( item, observableArray )
* @public
*/
addItemRemovedListener: function( listener ) {
assert && assert( this._removedListeners.indexOf( listener ) === -1, 'Listener was already registered' ); // listener is not already registered
this._removedListeners.push( listener );
},
/**
* Removes a listener that was added via addItemRemovedListener.
* @param listener
* @public
*/
removeItemRemovedListener: function( listener ) {
var index = this._removedListeners.indexOf( listener );
assert && assert( index !== -1, 'Listener is still registered after removal' ); // listener is registered
this._removedListeners.splice( index, 1 );
},
// @private called when an item is added.
_fireItemAdded: function( item ) {
this.startedCallbacksForItemAddedEmitter.emit1( item );
//Signify that an item was added to the list
var copy = this._addedListeners.slice( 0 ); // operate on a copy, firing could result in the listeners changing
for ( var i = 0; i < copy.length; i++ ) {
copy[ i ]( item, this );
}
this.endedCallbacksForItemAddedEmitter.emit();
},
// @private called when an item is removed.
_fireItemRemoved: function( item ) {
this.startedCallbacksForItemRemovedEmitter.emit1( item );
//Signify that an item was removed from the list
var copy = this._removedListeners.slice( 0 ); // operate on a copy, firing could result in the listeners changing
for ( var i = 0; i < copy.length; i++ ) {
copy[ i ]( item, this );
}
this.endedCallbacksForItemRemovedEmitter.emit();
},
/**
* Adds an item to the end of the array.
* This is a convenience function, and is the same as push.
* @param item
* @public
*/
add: function( item ) {
this.push( item );
},
/**
* Add items to the end of the array.
* This is a convenience function, and is the same as push.
* @param {Array} items
* @public
*/
addAll: function( items ) {
for ( var i = 0; i < items.length; i++ ) {
this.add( items[ i ] );
}
},
/**
* Removes the first occurrence of an item from the array.
* If duplicates are allowed (see options.allowDuplicates) you may need to call this multiple
* times to totally purge item from the array.
* @param item
* @public
*/
remove: function( item ) {
var index = this._array.indexOf( item );
if ( index !== -1 ) {
this._array.splice( index, 1 );
this.lengthProperty.set( this._array.length );
this._fireItemRemoved( item );
}
},
/**
* Removes the first occurrence of each item in the specified array.
* @param {Array} array a list of items to remove
* @see ObservableArray.remove
* @public
*/
removeAll: function( array ) {
assert && assert( _.isArray( array ), 'array should be an array' );
for ( var i = 0; i < array.length; i++ ) {
this.remove( array[ i ] );
}
},
/**
* Pushes an item onto the end of the array.
* @param item
* @throws Error if duplicates are not allowed (see options.allowDuplicates) and item is already in the array
* @public
*/
push: function( item ) {
if ( !this.allowDuplicates && this.contains( item ) ) {
throw new Error( 'duplicates are not allowed' );
}
this._array.push( item );
this.lengthProperty.set( this._array.length );
this._fireItemAdded( item );
},
/**
* Removes an item from the end of the array and returns it.
* @returns {*}
* @public
*/
pop: function() {
var item = this._array.pop();
if ( item !== undefined ) {
this.lengthProperty.set( this._array.length );
this._fireItemRemoved( item );
}
return item;
},
/**
* Removes an item from the beginning of the array and returns it.
* @returns {*}
* @public
*/
shift: function() {
var item = this._array.shift();
if ( item !== undefined ) {
this.lengthProperty.set( this._array.length );
this._fireItemRemoved( item );
}
return item;
},
/**
* Does the array contain the specified item?
* @param item
* @returns {boolean}
* @public
*/
contains: function( item ) {
return this.indexOf( item ) !== -1;
},
/**
* Gets an item at the specified index.
* @param index
* @returns {*} the item, or undefined if there is no item at the specified index
* @public
*/
get: function( index ) {
return this._array[ index ];
},
/**
* Gets the index of a specified item.
* @param item
* @returns {*} -1 if item is not in the array
* @public
*/
indexOf: function( item ) {
return this._array.indexOf( item );
},
/**
* Removes all items from the array.
* @public
*/
clear: function() {
while ( this.length > 0 ) {
this.pop();
}
},
/**
* Applies a callback function to each item in the array
* @param callback function(item)
* @public
*/
forEach: function( callback ) {
this._array.slice().forEach( callback ); // do this on a copy of the array, in case callbacks involve array modification
},
/**
* Maps the values in this ObservableArray using the specified function, and returns a new ObservableArray for chaining.
* @param mapFunction
* @returns {ObservableArray}
* @public
*/
map: function( mapFunction ) {
return new ObservableArray( this._array.map( mapFunction ) );
},
/**
* Filters the values in this ObservableArray using the predicate function, and returns a new ObservableArray for chaining.
* @param predicate
* @returns {ObservableArray}
* @public
*/
filter: function( predicate ) {
return new ObservableArray( this._array.filter( predicate ) );
},
/**
* Count the number of items in this ObservableArray that satisfy the given Predicate.
* @param {function} predicate
* @returns {number}
* @public
*/
count: function( predicate ) {
var count = 0;
for ( var i = 0; i < this._array.length; i++ ) {
if ( predicate( this._array[ i ] ) ) {
count++;
}
}
return count;
},
/**
* Find the first element that matches the given predicate.
* @param {function} predicate
* @param {number} [fromIndex] - optional start index for the search
*/
find: function( predicate, fromIndex ) {
return _.find( this._array, predicate, fromIndex );
},
/**
* Starting with the initial value, combine values from this ObservableArray to come up with a composite result.
* Same as foldLeft. In underscore this is called _.reduce aka _.fold or _.inject
* @param value
* @param combiner
* @returns {*}
* @public
*/
reduce: function( value, combiner ) {
for ( var i = 0; i < this._array.length; i++ ) {
value = combiner( value, this._array[ i ] );
}
return value;
},
/**
* Return the underlying array
* @returns {Array}
* @public
*/
getArray: function() {
return this._array;
},
/**
* Add/remove elements from any point in the array
* @param {number} start - the index to start adding/removing items
* @param {number} deleteCount - the number of items to delete
* @param {Object} [item1] - an item to add
* @param {Object} [item2] - an item to add
* @param {Object} [etc] - varargs items to add etc.
* @returns {Object[]} the items that were deleted.
* @public
*/
splice: function( start, deleteCount, item1, item2, etc ) {
var deleted = this._array.splice.apply( this._array, arguments );
var args = Array.prototype.slice.call( arguments );
for ( var i = 0; i < deleted.length; i++ ) {
this._fireItemRemoved( deleted[ i ] );
}
for ( var k = 2; k < args.length; k++ ) {
this._fireItemAdded( args[ k ] );
}
return deleted;
},
/**
* Changes the ordering of elements in the array. Requires a Random source so that shuffles can be reproducible.
* No items are added or removed, and this method does not send out any notifications.
* @param {Random} random - from dot
*/
shuffle: function( random ) {
assert && assert( random, 'random must be supplied' );
// preserve the same _array reference in case any clients got a reference to it with getArray()
var shuffled = random.shuffle( this._array );
this._array.length = 0;
Array.prototype.push.apply( this._array, shuffled );
}
} );
} ); | instrument lengthProperty, see #135
| js/ObservableArray.js | instrument lengthProperty, see #135 | <ide><path>s/ObservableArray.js
<ide> var TObservableArray = require( 'AXON/TObservableArray' );
<ide> var Tandem = require( 'TANDEM/Tandem' );
<ide>
<add> // phet-io modules
<add> var TNumber = require( 'ifphetio!PHET_IO/types/TNumber' );
<add>
<ide> /**
<ide> * @param {Object[]} [array]
<ide> * @param {Object} [options]
<ide> this._addedListeners = []; // @private listeners called when an item is added
<ide> this._removedListeners = []; // @private listeners called when an item is removed
<ide>
<del> this.lengthProperty = new Property( this._array.length ); // @public (read-only) observe this, but don't set it
<add> // @public (read-only) observe this, but don't set it
<add> this.lengthProperty = new Property( this._array.length, {
<add> tandem: options.tandem && options.tandem.createTandem( 'lengthProperty' ),
<add> phetioValueType: TNumber( { type: 'Integer' } )
<add> } );
<ide>
<ide> // @private Store the initial array, if any, for resetting, see #4
<ide> this.initialArray = array ? array.slice() : []; |
|
Java | mit | 202018ce1e4c4b87e763a26cd17b103fbfb2c101 | 0 | openforis/collect,openforis/collect,openforis/collect,openforis/collect | package org.openforis.collect.persistence.jooq;
import static org.jooq.impl.DSL.name;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Date;
import org.jooq.CollectCreateIndexStep;
import org.jooq.Configuration;
import org.jooq.DataType;
import org.jooq.Name;
import org.jooq.SQLDialect;
import org.jooq.Schema;
import org.jooq.Sequence;
import org.jooq.TableField;
import org.jooq.impl.CollectCreateIndexImpl;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultDSLContext;
import org.jooq.impl.DefaultDataType;
import org.jooq.impl.DialectAwareJooqConfiguration;
/**
*
* @author S. Ricci
*
*/
public class CollectDSLContext extends DefaultDSLContext {
private static final long serialVersionUID = 1L;
public CollectDSLContext(Configuration config) {
super(config);
}
public CollectDSLContext(Connection connection) {
super(new DialectAwareJooqConfiguration(connection));
}
@Override
public CollectCreateIndexStep createIndex(String index) {
return createIndex(name(index));
}
@Override
public CollectCreateIndexStep createIndex(Name index) {
return new CollectCreateIndexImpl(configuration(), index);
}
public int nextId(TableField<?, Integer> idField, Sequence<? extends Number> idSequence) {
if (isSQLite()){
Integer id = (Integer) select(DSL.max(idField))
.from(idField.getTable())
.fetchOne(0);
if ( id == null ) {
return 1;
} else {
return id + 1;
}
} else {
return nextval(idSequence).intValue();
}
}
public void restartSequence(Sequence<?> sequence, Number restartValue) {
if (isSequenceSupported()) {
String name = sequence.getName();
String qualifiedName;
if ( sequence.getSchema() != null && configuration().settings().isRenderSchema() ) {
Schema schema = sequence.getSchema();
String schemaName = schema.getName();
qualifiedName = schemaName + "." + name;
} else {
qualifiedName = name;
}
execute("ALTER SEQUENCE " + qualifiedName + " RESTART WITH " + restartValue);
}
}
public DataType<?> getDataType(Class<?> type) {
Class<?> jooqType;
if (type == Date.class) {
jooqType = java.sql.Date.class;
} else if (type == Double.class) {
if (dialect() == SQLDialect.SQLITE) {
jooqType = Float.class; //it will be translated into an SQL REAL data type
} else {
jooqType = BigDecimal.class;
}
} else {
jooqType = type;
}
return DefaultDataType.getDataType(dialect(), jooqType);
}
private boolean isSequenceSupported() {
switch (configuration().dialect()) {
case SQLITE:
return false;
default:
return true;
}
}
public boolean isSchemaLess() {
return ! configuration().settings().isRenderSchema();
}
public boolean isForeignKeySupported() {
return ! isSQLite();
}
public boolean isSQLite() {
return getDialect() == SQLDialect.SQLITE;
}
public SQLDialect getDialect() {
return configuration().dialect();
}
}
| collect-core/src/main/java/org/openforis/collect/persistence/jooq/CollectDSLContext.java | package org.openforis.collect.persistence.jooq;
import static org.jooq.impl.DSL.name;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Date;
import org.jooq.CollectCreateIndexStep;
import org.jooq.Configuration;
import org.jooq.DataType;
import org.jooq.Name;
import org.jooq.SQLDialect;
import org.jooq.Schema;
import org.jooq.Sequence;
import org.jooq.TableField;
import org.jooq.impl.CollectCreateIndexImpl;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultDSLContext;
import org.jooq.impl.DefaultDataType;
import org.jooq.impl.DialectAwareJooqConfiguration;
/**
*
* @author S. Ricci
*
*/
public class CollectDSLContext extends DefaultDSLContext {
private static final long serialVersionUID = 1L;
public CollectDSLContext(Configuration config) {
super(config);
}
public CollectDSLContext(Connection connection) {
super(new DialectAwareJooqConfiguration(connection));
}
@Override
public CollectCreateIndexStep createIndex(String index) {
return createIndex(name(index));
}
@Override
public CollectCreateIndexStep createIndex(Name index) {
return new CollectCreateIndexImpl(configuration(), index);
}
public int nextId(TableField<?, Integer> idField, Sequence<? extends Number> idSequence) {
if (isSQLite()){
Integer id = (Integer) select(DSL.max(idField))
.from(idField.getTable())
.fetchOne(0);
if ( id == null ) {
return 1;
} else {
return id + 1;
}
} else {
return nextval(idSequence).intValue();
}
}
public void restartSequence(Sequence<?> sequence, Number restartValue) {
if (isSequenceSupported()) {
String name = sequence.getName();
String qualifiedName;
if ( sequence.getSchema() != null && configuration().settings().isRenderSchema() ) {
Schema schema = sequence.getSchema();
String schemaName = schema.getName();
qualifiedName = schemaName + "." + name;
} else {
qualifiedName = name;
}
execute("ALTER SEQUENCE " + qualifiedName + " RESTART WITH " + restartValue);
}
}
public DataType<?> getDataType(Class<?> type) {
Class<?> jooqType;
if (type == Date.class) {
jooqType = java.sql.Date.class;
} else if (type == Double.class) {
jooqType = BigDecimal.class;
} else {
jooqType = type;
}
return DefaultDataType.getDataType(dialect(), jooqType);
}
private boolean isSequenceSupported() {
switch (configuration().dialect()) {
case SQLITE:
return false;
default:
return true;
}
}
public boolean isSchemaLess() {
return ! configuration().settings().isRenderSchema();
}
public boolean isForeignKeySupported() {
return ! isSQLite();
}
public boolean isSQLite() {
return getDialect() == SQLDialect.SQLITE;
}
public SQLDialect getDialect() {
return configuration().dialect();
}
}
| Use SQL REAL data type in SQLite DB for numeric columns (otherwise Saiku
rounds all numbers) | collect-core/src/main/java/org/openforis/collect/persistence/jooq/CollectDSLContext.java | Use SQL REAL data type in SQLite DB for numeric columns (otherwise Saiku rounds all numbers) | <ide><path>ollect-core/src/main/java/org/openforis/collect/persistence/jooq/CollectDSLContext.java
<ide> if (type == Date.class) {
<ide> jooqType = java.sql.Date.class;
<ide> } else if (type == Double.class) {
<del> jooqType = BigDecimal.class;
<add> if (dialect() == SQLDialect.SQLITE) {
<add> jooqType = Float.class; //it will be translated into an SQL REAL data type
<add> } else {
<add> jooqType = BigDecimal.class;
<add> }
<ide> } else {
<ide> jooqType = type;
<ide> } |
|
Java | apache-2.0 | ce9c8c001effe91f1184009f38eb61ae1434bf11 | 0 | yunarta/works-codex-android | package com.mobilesolutionworks.codex.internal;
import com.jamesmurty.utils.XMLBuilder2;
import com.mobilesolutionworks.codex.Action;
import com.mobilesolutionworks.codex.ActionHook;
import com.mobilesolutionworks.codex.ActionInfo;
import com.mobilesolutionworks.codex.Property;
import com.mobilesolutionworks.codex.PropertySubscriber;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
/**
* Created by yunarta on 18/8/15.
*/
public class AnnotationProcessor extends AbstractProcessor {
class ActionInfoDoc {
String owner;
String name;
String[] args;
public String key() {
return name + args.length;
}
public String method() {
if (args.length > 0) {
StringBuilder sb = new StringBuilder();
for (String arg : args) {
sb.append(", ").append(arg);
}
sb.delete(0, 2);
return name + "(" + sb.toString() + ")";
} else {
return name + "()";
}
}
}
class PropertyDoc {
String owner;
String name;
String type;
String method;
}
class EmitterDoc {
Map<String, ActionInfoDoc> declaredActions = new TreeMap<>();
Map<String, PropertyDoc> declaredProperties = new TreeMap<>();
}
class ActionHookInfoDoc implements Comparable<ActionHookInfoDoc> {
String name;
String method;
String owner;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActionHookInfoDoc doc = (ActionHookInfoDoc) o;
if (!name.equals(doc.name)) return false;
if (!method.equals(doc.method)) return false;
return owner.equals(doc.owner);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + method.hashCode();
result = 31 * result + owner.hashCode();
return result;
}
@Override
public int compareTo(ActionHookInfoDoc o) {
return name.compareTo(o.name);
}
}
class PropertySubscriberInfoDoc implements Comparable<PropertySubscriberInfoDoc> {
String name;
String method;
String owner;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PropertySubscriberInfoDoc doc = (PropertySubscriberInfoDoc) o;
if (!name.equals(doc.name)) return false;
if (!method.equals(doc.method)) return false;
return owner.equals(doc.owner);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + method.hashCode();
result = 31 * result + owner.hashCode();
return result;
}
@Override
public int compareTo(PropertySubscriberInfoDoc o) {
return name.compareTo(o.name);
}
}
class ReceiverDoc {
Map<String, Set<ActionHookInfoDoc>> declaredActionHooks = new TreeMap<>();
Map<String, Set<PropertySubscriberInfoDoc>> declaredPropertySubscribers = new TreeMap<>();
}
Map<String, EmitterDoc> mEmitterDocMap = new TreeMap<>();
Map<String, ReceiverDoc> mReceiverMap = new TreeMap<>();
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
if (env.processingOver()) return true;
Map<String, String> options = processingEnv.getOptions();
String outputDir = options.get("codexOutput");
if (annotations.isEmpty()) return true;
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
writer = createCodexWriter(outputDir, writer);
Set<? extends Element> elements;
elements = env.getElementsAnnotatedWith(Action.class);
for (Element element : elements) {
Action annotation = element.getAnnotation(Action.class);
TypeElement typeElement = (TypeElement) element;
String key = typeElement.getQualifiedName().toString();
EmitterDoc ci = mEmitterDocMap.getOrDefault(key, new EmitterDoc());
mEmitterDocMap.put(key, ci);
ActionInfo[] infos = annotation.actions();
for (ActionInfo info : infos) {
ActionInfoDoc doc = new ActionInfoDoc();
doc.owner = key;
doc.name = info.name();
doc.args = info.args();
String actionKey = doc.key();
if (ci.declaredActions.containsKey(actionKey)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, key + " has duplicate decration of action " + doc.name);
}
ci.declaredActions.put(actionKey, doc);
}
}
elements = env.getElementsAnnotatedWith(ActionHook.class);
for (Element element : elements) {
ActionHook annotation = element.getAnnotation(ActionHook.class);
TypeElement typeElement = (TypeElement) element.getEnclosingElement();
ExecutableElement variable = (ExecutableElement) element;
List<? extends VariableElement> parameters = variable.getParameters();
int argc = parameters.size();
StringBuffer sb = new StringBuffer();
for (VariableElement param : parameters) {
sb.append(", ").append(param.getSimpleName());
}
if (sb.length() > 0) {
sb.delete(0, 2);
}
String methodName = element.getSimpleName().toString() + "(" + sb.toString() + ")";
String key = typeElement.getQualifiedName().toString();
String hookKey = annotation.name() + argc;
ReceiverDoc info = mReceiverMap.getOrDefault(key, new ReceiverDoc());
mReceiverMap.put(key, info);
Set<ActionHookInfoDoc> set = info.declaredActionHooks.getOrDefault(hookKey, new TreeSet<ActionHookInfoDoc>());
info.declaredActionHooks.put(hookKey, set);
ActionHookInfoDoc doc = new ActionHookInfoDoc();
doc.name = annotation.name();
doc.method = methodName;
doc.owner = key;
set.add(doc);
}
elements = env.getElementsAnnotatedWith(Property.class);
for (Element element : elements) {
Property annotation = element.getAnnotation(Property.class);
TypeElement typeElement = (TypeElement) element.getEnclosingElement();
String key = typeElement.getQualifiedName().toString();
EmitterDoc info = mEmitterDocMap.getOrDefault(key, new EmitterDoc());
mEmitterDocMap.put(key, info);
if (info.declaredProperties.containsKey(annotation.name())) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, key + " have duplicate declaration for property " + annotation.name());
}
ExecutableElement variable = (ExecutableElement) element;
TypeMirror type = variable.getReturnType();
PropertyDoc doc = new PropertyDoc();
doc.name = annotation.name();
doc.method = element.getSimpleName().toString();
doc.owner = key;
doc.type = type.toString();
info.declaredProperties.put(annotation.name(), doc);
}
elements = env.getElementsAnnotatedWith(PropertySubscriber.class);
for (Element element : elements) {
PropertySubscriber annotation = element.getAnnotation(PropertySubscriber.class);
TypeElement typeElement = (TypeElement) element.getEnclosingElement();
String key = typeElement.getQualifiedName().toString();
String subscriberKey = annotation.name();
ReceiverDoc info = mReceiverMap.getOrDefault(key, new ReceiverDoc());
mReceiverMap.put(key, info);
Set<PropertySubscriberInfoDoc> set = info.declaredPropertySubscribers.getOrDefault(subscriberKey, new TreeSet<PropertySubscriberInfoDoc>());
info.declaredPropertySubscribers.put(subscriberKey, set);
PropertySubscriberInfoDoc doc = new PropertySubscriberInfoDoc();
doc.name = annotation.name();
doc.method = element.getSimpleName().toString();
doc.owner = key;
set.add(doc);
}
XMLBuilder2 codex = XMLBuilder2.create("codex");
XMLBuilder2 emitters = codex.e("emitters");
XMLBuilder2 receivers = codex.e("receivers");
XMLBuilder2 actions = codex.e("actions");
XMLBuilder2 properties = codex.e("properties");
Map<String, ActionInfoDoc> allActions = new TreeMap<>();
Map<String, PropertyDoc> allProperties = new TreeMap<>();
Map<String, List<ActionHookInfoDoc>> allActionHooks = new TreeMap<>();
Map<String, List<PropertySubscriberInfoDoc>> allPropertySubscribers = new TreeMap<>();
for (Map.Entry<String, EmitterDoc> entry : mEmitterDocMap.entrySet()) {
String name = entry.getKey();
EmitterDoc value = entry.getValue();
XMLBuilder2 entity = emitters.e("entity").a("type", name);
XMLBuilder2 iterator = entity.e("actions");
for (Map.Entry<String, ActionInfoDoc> action : value.declaredActions.entrySet()) {
String key = action.getKey();
ActionInfoDoc doc = action.getValue();
boolean conflict = allActions.containsKey(key);
if (conflict) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, doc.method() + " had been declared in " + allActions.get(key).owner);
}
allActions.put(key, doc);
XMLBuilder2 actionTag = iterator.e("action");
actionTag.a("name", doc.method());
iterator = actionTag.up();
}
iterator = entity.e("properties");
for (Map.Entry<String, PropertyDoc> property : value.declaredProperties.entrySet()) {
String key = property.getKey();
boolean conflict = allProperties.containsKey(key);
if (conflict) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, property + " had been declared in " + allProperties.get(key));
}
PropertyDoc doc = property.getValue();
allProperties.put(key, doc);
XMLBuilder2 propertyTag = iterator.e("property");
propertyTag.a("name", doc.name);
propertyTag.a("method", doc.method);
propertyTag.a("type", doc.type);
iterator = propertyTag.up();
}
iterator.up();
entity.up();
}
emitters.up();
for (Map.Entry<String, ReceiverDoc> entry : mReceiverMap.entrySet()) {
String name = entry.getKey();
ReceiverDoc value = entry.getValue();
XMLBuilder2 entity = receivers.e("receiver").a("type", name);
XMLBuilder2 iterator = entity.e("actionHooks");
for (Map.Entry<String, Set<ActionHookInfoDoc>> docs : value.declaredActionHooks.entrySet()) {
String hookKey = docs.getKey();
Set<ActionHookInfoDoc> set = docs.getValue();
for (ActionHookInfoDoc doc : set) {
XMLBuilder2 actionTag = iterator.e("actionHook");
actionTag.a("name", doc.name);
actionTag.a("method", doc.method);
iterator = actionTag.up();
List<ActionHookInfoDoc> list = allActionHooks.getOrDefault(hookKey, new ArrayList<ActionHookInfoDoc>());
allActionHooks.put(hookKey, list);
list.add(doc);
}
}
iterator = entity.e("propertySubscribers");
for (Map.Entry<String, Set<PropertySubscriberInfoDoc>> eSubscriber : value.declaredPropertySubscribers.entrySet()) {
String hookKey = eSubscriber.getKey();
Set<PropertySubscriberInfoDoc> set = eSubscriber.getValue();
for (PropertySubscriberInfoDoc doc : set) {
XMLBuilder2 actionTag = iterator.e("propertySubscriber");
actionTag.a("name", doc.name);
actionTag.a("method", doc.method);
iterator = actionTag.up();
List<PropertySubscriberInfoDoc> list = allPropertySubscribers.getOrDefault(hookKey, new ArrayList<PropertySubscriberInfoDoc>());
allPropertySubscribers.put(hookKey, list);
list.add(doc);
}
}
iterator.up();
entity.up();
}
receivers.up();
for (Map.Entry<String, ActionInfoDoc> entry : allActions.entrySet()) {
XMLBuilder2 actionTag = actions.e("action");
ActionInfoDoc actionInfo = entry.getValue();
actionTag.a("name", actionInfo.method());
actionTag.a("owner", actionInfo.owner);
List<ActionHookInfoDoc> actionHookInfo = allActionHooks.remove(actionInfo.key());
if (actionHookInfo != null) {
for (ActionHookInfoDoc hook : actionHookInfo) {
XMLBuilder2 hookTag = actionTag.e("hook");
hookTag.a("name", hook.name);
hookTag.a("method", hook.method);
hookTag.a("owner", hook.owner);
hookTag.up();
}
}
actionTag.up();
}
actions.up();
for (Map.Entry<String, PropertyDoc> entry : allProperties.entrySet()) {
XMLBuilder2 propertyTag = properties.e("property");
PropertyDoc doc = entry.getValue();
propertyTag.a("name", doc.name);
propertyTag.a("method", doc.method);
propertyTag.a("type", doc.type);
propertyTag.a("owner", doc.owner);
List<PropertySubscriberInfoDoc> subscriberInfoDocs = allPropertySubscribers.remove(doc.name);
if (subscriberInfoDocs != null) {
for (PropertySubscriberInfoDoc subscriber : subscriberInfoDocs) {
XMLBuilder2 hookTag = propertyTag.e("subscriber");
hookTag.a("name", subscriber.name);
hookTag.a("method", subscriber.method);
hookTag.a("owner", subscriber.owner);
hookTag.up();
}
}
propertyTag.up();
}
properties.up();
XMLBuilder2 orphanHooks = codex.e("orphan-actionHooks");
for (Map.Entry<String, List<ActionHookInfoDoc>> entry : allActionHooks.entrySet()) {
List<ActionHookInfoDoc> actionHookInfo = entry.getValue();
if (actionHookInfo != null) {
for (ActionHookInfoDoc hook : actionHookInfo) {
XMLBuilder2 hookTag = orphanHooks.e("hook");
hookTag.a("name", hook.name);
hookTag.a("method", hook.method);
hookTag.a("owner", hook.owner);
hookTag.up();
}
}
}
orphanHooks.up();
XMLBuilder2 orphanSubscriber = codex.e("orphan-subscriber");
for (Map.Entry<String, List<PropertySubscriberInfoDoc>> entry : allPropertySubscribers.entrySet()) {
List<PropertySubscriberInfoDoc> subscriberInfoDocs = entry.getValue();
if (subscriberInfoDocs != null) {
for (PropertySubscriberInfoDoc subscriber : subscriberInfoDocs) {
XMLBuilder2 hookTag = orphanSubscriber.e("subscriber");
hookTag.a("name", subscriber.name);
hookTag.a("method", subscriber.method);
hookTag.a("owner", subscriber.owner);
hookTag.up();
}
}
}
orphanSubscriber.up();
codex.up();
codex.toWriter(true, writer, null);
writer.flush();
writer.close();
return true;
}
private PrintWriter createCodexWriter(String outputDir, PrintWriter writer) {
try {
if (outputDir != null) {
writer = new PrintWriter(new FileOutputStream(new File(outputDir, "codex.xml")));
}
} catch (FileNotFoundException e) {
// e.printStackTrace();
e.printStackTrace();
}
return writer;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
HashSet<String> supportedAnnotationTypes = new HashSet<>();
supportedAnnotationTypes.add(Action.class.getCanonicalName());
supportedAnnotationTypes.add(ActionHook.class.getCanonicalName());
supportedAnnotationTypes.add(Property.class.getCanonicalName());
supportedAnnotationTypes.add(PropertySubscriber.class.getCanonicalName());
return supportedAnnotationTypes;
}
@Override
public Set<String> getSupportedOptions() {
HashSet<String> supportedOptions = new HashSet<>();
supportedOptions.add("codexOutput");
return supportedOptions;
}
}
| processor/src/main/java/com/mobilesolutionworks/codex/internal/AnnotationProcessor.java | package com.mobilesolutionworks.codex.internal;
import com.jamesmurty.utils.XMLBuilder2;
import com.mobilesolutionworks.codex.Action;
import com.mobilesolutionworks.codex.ActionHook;
import com.mobilesolutionworks.codex.ActionInfo;
import com.mobilesolutionworks.codex.Property;
import com.mobilesolutionworks.codex.PropertySubscriber;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
/**
* Created by yunarta on 18/8/15.
*/
public class AnnotationProcessor extends AbstractProcessor {
class ActionInfoDoc {
String owner;
String name;
String[] args;
public String key() {
return name + args.length;
}
public String method() {
if (args.length > 0) {
StringBuilder sb = new StringBuilder();
for (String arg : args) {
sb.append(", ").append(arg);
}
sb.delete(0, 2);
return name + "(" + sb.toString() + ")";
} else {
return name + "()";
}
}
}
class PropertyDoc {
String owner;
String name;
String type;
String method;
}
class EmitterDoc {
Map<String, ActionInfoDoc> declaredActions = new TreeMap<>();
Map<String, PropertyDoc> declaredProperties = new TreeMap<>();
}
class ActionHookInfoDoc implements Comparable<ActionHookInfoDoc> {
String name;
String method;
String owner;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActionHookInfoDoc doc = (ActionHookInfoDoc) o;
if (!name.equals(doc.name)) return false;
if (!method.equals(doc.method)) return false;
return owner.equals(doc.owner);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + method.hashCode();
result = 31 * result + owner.hashCode();
return result;
}
@Override
public int compareTo(ActionHookInfoDoc o) {
return name.compareTo(o.name);
}
}
class PropertySubscriberInfoDoc implements Comparable<PropertySubscriberInfoDoc> {
String name;
String method;
String owner;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PropertySubscriberInfoDoc doc = (PropertySubscriberInfoDoc) o;
if (!name.equals(doc.name)) return false;
if (!method.equals(doc.method)) return false;
return owner.equals(doc.owner);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + method.hashCode();
result = 31 * result + owner.hashCode();
return result;
}
@Override
public int compareTo(PropertySubscriberInfoDoc o) {
return name.compareTo(o.name);
}
}
class ReceiverDoc {
Map<String, Set<ActionHookInfoDoc>> declaredActionHooks = new TreeMap<>();
Map<String, Set<PropertySubscriberInfoDoc>> declaredPropertySubscribers = new TreeMap<>();
}
Map<String, EmitterDoc> mEmitterDocMap = new TreeMap<>();
Map<String, ReceiverDoc> mReceiverMap = new TreeMap<>();
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
if (env.processingOver()) return true;
Map<String, String> options = processingEnv.getOptions();
String outputDir = options.get("codexOutput");
if (annotations.isEmpty()) return true;
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
writer = createCodexWriter(outputDir, writer);
Set<? extends Element> elements;
elements = env.getElementsAnnotatedWith(Action.class);
for (Element element : elements) {
Action annotation = element.getAnnotation(Action.class);
TypeElement typeElement = (TypeElement) element;
String key = typeElement.getQualifiedName().toString();
EmitterDoc ci = mEmitterDocMap.getOrDefault(key, new EmitterDoc());
mEmitterDocMap.put(key, ci);
ActionInfo[] infos = annotation.actions();
for (ActionInfo info : infos) {
ActionInfoDoc doc = new ActionInfoDoc();
doc.owner = key;
doc.name = info.name();
doc.args = info.args();
String actionKey = doc.key();
if (ci.declaredActions.containsKey(actionKey)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, key + " has duplicate decration of action " + doc.name);
}
ci.declaredActions.put(actionKey, doc);
}
}
elements = env.getElementsAnnotatedWith(ActionHook.class);
for (Element element : elements) {
ActionHook annotation = element.getAnnotation(ActionHook.class);
TypeElement typeElement = (TypeElement) element.getEnclosingElement();
ExecutableElement variable = (ExecutableElement) element;
List<? extends VariableElement> parameters = variable.getParameters();
int argc = parameters.size();
StringBuffer sb = new StringBuffer();
for (VariableElement param : parameters) {
sb.append(", ").append(param.getSimpleName());
}
if (sb.length() > 0) {
sb.delete(0, 2);
}
String methodName = element.getSimpleName().toString() + "(" + sb.toString() + ")";
String key = typeElement.getQualifiedName().toString();
String hookKey = annotation.name() + argc;
ReceiverDoc info = mReceiverMap.getOrDefault(key, new ReceiverDoc());
mReceiverMap.put(key, info);
Set<ActionHookInfoDoc> set = info.declaredActionHooks.getOrDefault(hookKey, new TreeSet<ActionHookInfoDoc>());
info.declaredActionHooks.put(hookKey, set);
ActionHookInfoDoc doc = new ActionHookInfoDoc();
doc.name = annotation.name();
doc.method = methodName;
doc.owner = key;
set.add(doc);
}
elements = env.getElementsAnnotatedWith(Property.class);
for (Element element : elements) {
Property annotation = element.getAnnotation(Property.class);
TypeElement typeElement = (TypeElement) element.getEnclosingElement();
String key = typeElement.getQualifiedName().toString();
EmitterDoc info = mEmitterDocMap.getOrDefault(key, new EmitterDoc());
mEmitterDocMap.put(key, info);
if (info.declaredProperties.containsKey(annotation.name())) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, key + " have duplicate declaration for property " + annotation.name());
}
ExecutableElement variable = (ExecutableElement) element;
TypeMirror type = variable.getReturnType();
PropertyDoc doc = new PropertyDoc();
doc.name = annotation.name();
doc.method = element.getSimpleName().toString();
doc.owner = key;
doc.type = type.toString();
info.declaredProperties.put(annotation.name(), doc);
}
elements = env.getElementsAnnotatedWith(PropertySubscriber.class);
for (Element element : elements) {
PropertySubscriber annotation = element.getAnnotation(PropertySubscriber.class);
TypeElement typeElement = (TypeElement) element.getEnclosingElement();
String key = typeElement.getQualifiedName().toString();
String subscriberKey = annotation.name();
ReceiverDoc info = mReceiverMap.getOrDefault(key, new ReceiverDoc());
mReceiverMap.put(key, info);
Set<PropertySubscriberInfoDoc> set = info.declaredPropertySubscribers.getOrDefault(subscriberKey, new TreeSet<PropertySubscriberInfoDoc>());
info.declaredPropertySubscribers.put(subscriberKey, set);
PropertySubscriberInfoDoc doc = new PropertySubscriberInfoDoc();
doc.name = annotation.name();
doc.method = element.getSimpleName().toString();
doc.owner = key;
set.add(doc);
}
XMLBuilder2 codex = XMLBuilder2.create("codex");
XMLBuilder2 emitters = codex.e("emitters");
XMLBuilder2 receivers = codex.e("receivers");
XMLBuilder2 actions = codex.e("actions");
XMLBuilder2 properties = codex.e("properties");
Map<String, ActionInfoDoc> allActions = new TreeMap<>();
Map<String, PropertyDoc> allProperties = new TreeMap<>();
Map<String, List<ActionHookInfoDoc>> allActionHooks = new TreeMap<>();
Map<String, List<PropertySubscriberInfoDoc>> allPropertySubscribers = new TreeMap<>();
for (Map.Entry<String, EmitterDoc> entry : mEmitterDocMap.entrySet()) {
String name = entry.getKey();
EmitterDoc value = entry.getValue();
XMLBuilder2 entity = emitters.e("entity").a("type", name);
XMLBuilder2 iterator = entity.e("actions");
for (Map.Entry<String, ActionInfoDoc> action : value.declaredActions.entrySet()) {
String key = action.getKey();
ActionInfoDoc doc = action.getValue();
boolean conflict = allActions.containsKey(key);
if (conflict) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, doc.method() + " had been declared in " + allActions.get(key).owner);
}
allActions.put(key, doc);
XMLBuilder2 actionTag = iterator.e("action");
actionTag.a("name", doc.method());
iterator = actionTag.up();
}
iterator = entity.e("properties");
for (Map.Entry<String, PropertyDoc> property : value.declaredProperties.entrySet()) {
String key = property.getKey();
boolean conflict = allProperties.containsKey(key);
if (conflict) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, property + " had been declared in " + allProperties.get(key));
}
PropertyDoc doc = property.getValue();
allProperties.put(key, doc);
XMLBuilder2 propertyTag = iterator.e("property");
propertyTag.a("name", doc.name);
propertyTag.a("method", doc.method);
propertyTag.a("type", doc.type);
iterator = propertyTag.up();
}
iterator.up();
entity.up();
}
emitters.up();
for (Map.Entry<String, ReceiverDoc> entry : mReceiverMap.entrySet()) {
String name = entry.getKey();
ReceiverDoc value = entry.getValue();
XMLBuilder2 entity = receivers.e("receiver").a("type", name);
XMLBuilder2 iterator = entity.e("actionHooks");
for (Map.Entry<String, Set<ActionHookInfoDoc>> docs : value.declaredActionHooks.entrySet()) {
String hookKey = docs.getKey();
Set<ActionHookInfoDoc> set = docs.getValue();
for (ActionHookInfoDoc doc : set) {
XMLBuilder2 actionTag = iterator.e("actionHook");
actionTag.a("name", doc.name);
actionTag.a("method", doc.method);
iterator = actionTag.up();
List<ActionHookInfoDoc> list = allActionHooks.getOrDefault(hookKey, new ArrayList<ActionHookInfoDoc>());
allActionHooks.put(hookKey, list);
list.add(doc);
}
}
iterator = entity.e("propertySubscribers");
for (Map.Entry<String, Set<PropertySubscriberInfoDoc>> eSubscriber : value.declaredPropertySubscribers.entrySet()) {
String hookKey = eSubscriber.getKey();
Set<PropertySubscriberInfoDoc> set = eSubscriber.getValue();
for (PropertySubscriberInfoDoc doc : set) {
XMLBuilder2 actionTag = iterator.e("propertySubscriber");
actionTag.a("name", doc.name);
actionTag.a("method", doc.method);
iterator = actionTag.up();
List<PropertySubscriberInfoDoc> list = allPropertySubscribers.getOrDefault(hookKey, new ArrayList<PropertySubscriberInfoDoc>());
allPropertySubscribers.put(hookKey, list);
list.add(doc);
}
}
iterator.up();
entity.up();
}
receivers.up();
for (Map.Entry<String, ActionInfoDoc> entry : allActions.entrySet()) {
XMLBuilder2 actionTag = actions.e("action");
ActionInfoDoc actionInfo = entry.getValue();
actionTag.a("name", actionInfo.method());
actionTag.a("owner", actionInfo.owner);
List<ActionHookInfoDoc> actionHookInfo = allActionHooks.remove(actionInfo.key());
if (actionHookInfo != null) {
for (ActionHookInfoDoc hook : actionHookInfo) {
XMLBuilder2 hookTag = actionTag.e("hook");
hookTag.a("name", hook.name);
hookTag.a("method", hook.method);
hookTag.a("owner", hook.owner);
hookTag.up();
}
}
actionTag.up();
}
actions.up();
for (Map.Entry<String, PropertyDoc> entry : allProperties.entrySet()) {
XMLBuilder2 propertyTag = properties.e("property");
PropertyDoc doc = entry.getValue();
propertyTag.a("name", doc.name);
propertyTag.a("method", doc.method);
propertyTag.a("type", doc.type);
propertyTag.a("owner", doc.owner);
List<PropertySubscriberInfoDoc> subscriberInfoDocs = allPropertySubscribers.remove(doc.name);
if (subscriberInfoDocs != null) {
for (PropertySubscriberInfoDoc subscriber : subscriberInfoDocs) {
XMLBuilder2 hookTag = propertyTag.e("subscriber");
hookTag.a("name", subscriber.name);
hookTag.a("method", subscriber.method);
hookTag.a("owner", subscriber.owner);
hookTag.up();
}
}
propertyTag.up();
}
properties.up();
codex.up();
codex.toWriter(true, writer, null);
writer.flush();
writer.close();
return true;
}
private PrintWriter createCodexWriter(String outputDir, PrintWriter writer) {
try {
if (outputDir != null) {
writer = new PrintWriter(new FileOutputStream(new File(outputDir, "codex.xml")));
}
} catch (FileNotFoundException e) {
// e.printStackTrace();
e.printStackTrace();
}
return writer;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
HashSet<String> supportedAnnotationTypes = new HashSet<>();
supportedAnnotationTypes.add(Action.class.getCanonicalName());
supportedAnnotationTypes.add(ActionHook.class.getCanonicalName());
supportedAnnotationTypes.add(Property.class.getCanonicalName());
supportedAnnotationTypes.add(PropertySubscriber.class.getCanonicalName());
return supportedAnnotationTypes;
}
@Override
public Set<String> getSupportedOptions() {
HashSet<String> supportedOptions = new HashSet<>();
supportedOptions.add("codexOutput");
return supportedOptions;
}
}
| added method to documents oprhan hooks and subscribers
| processor/src/main/java/com/mobilesolutionworks/codex/internal/AnnotationProcessor.java | added method to documents oprhan hooks and subscribers | <ide><path>rocessor/src/main/java/com/mobilesolutionworks/codex/internal/AnnotationProcessor.java
<ide> }
<ide> properties.up();
<ide>
<add> XMLBuilder2 orphanHooks = codex.e("orphan-actionHooks");
<add>
<add> for (Map.Entry<String, List<ActionHookInfoDoc>> entry : allActionHooks.entrySet()) {
<add> List<ActionHookInfoDoc> actionHookInfo = entry.getValue();
<add> if (actionHookInfo != null) {
<add> for (ActionHookInfoDoc hook : actionHookInfo) {
<add> XMLBuilder2 hookTag = orphanHooks.e("hook");
<add> hookTag.a("name", hook.name);
<add> hookTag.a("method", hook.method);
<add> hookTag.a("owner", hook.owner);
<add> hookTag.up();
<add> }
<add> }
<add> }
<add> orphanHooks.up();
<add>
<add> XMLBuilder2 orphanSubscriber = codex.e("orphan-subscriber");
<add>
<add> for (Map.Entry<String, List<PropertySubscriberInfoDoc>> entry : allPropertySubscribers.entrySet()) {
<add> List<PropertySubscriberInfoDoc> subscriberInfoDocs = entry.getValue();
<add> if (subscriberInfoDocs != null) {
<add> for (PropertySubscriberInfoDoc subscriber : subscriberInfoDocs) {
<add> XMLBuilder2 hookTag = orphanSubscriber.e("subscriber");
<add> hookTag.a("name", subscriber.name);
<add> hookTag.a("method", subscriber.method);
<add> hookTag.a("owner", subscriber.owner);
<add> hookTag.up();
<add> }
<add> }
<add>
<add> }
<add> orphanSubscriber.up();
<add>
<add>
<ide> codex.up();
<ide> codex.toWriter(true, writer, null);
<ide> writer.flush(); |
|
JavaScript | mit | 88eea458763b7c4da6860ff3f186f91dd067b824 | 0 | keskiju/autocomplete-java | 'use babel';
import { _ } from 'lodash';
import { TextEditor } from 'atom';
import { CompositeDisposable } from 'atom';
import { AtomAutocompleteProvider } from './AtomAutocompleteProvider';
import { JavaClassLoader } from './JavaClassLoader';
import atomJavaUtil from './atomJavaUtil';
class AtomAutocompletePackage {
constructor() {
this.config = require('./config.json');
this.subscriptions = undefined;
this.provider = undefined;
this.classLoader = undefined;
this.classpath = null;
this.initialized = false;
}
activate() {
this.classLoader = new JavaClassLoader(
atom.config.get('autocomplete-java.javaHome'));
this.provider = new AtomAutocompleteProvider(this.classLoader);
this.subscriptions = new CompositeDisposable();
// Listen for commands
this.subscriptions.add(
atom.commands.add('atom-workspace', 'autocomplete-java:organize-imports',
() => {
this._organizeImports();
})
);
this.subscriptions.add(
atom.commands.add('atom-workspace', 'autocomplete-java:refresh-project',
() => {
if (this.initialized) {
this._refresh(false);
}
})
);
this.subscriptions.add(
atom.commands.add('atom-workspace', 'autocomplete-java:full-refresh',
() => {
if (this.initialized) {
this._refresh(true);
}
})
);
// Listen for config changes
// TODO refactor: bypasses provider.configure()
this.subscriptions.add(
atom.config.observe('autocomplete-java.inclusionPriority', (val) => {
this.provider.inclusionPriority = val;
})
);
this.subscriptions.add(
atom.config.observe('autocomplete-java.excludeLowerPriority', (val) => {
this.provider.excludeLowerPriority = val;
})
);
this.subscriptions.add(
atom.config.observe('autocomplete-java.foldImports', (val) => {
this.provider.foldImports = val;
})
);
// Listen for buffer change
this.subscriptions.add(
atom.workspace.onDidStopChangingActivePaneItem((paneItem) => {
this._onChange(paneItem);
})
);
// Listen for file save
atom.workspace.observeTextEditors(editor => {
if (this.subscriptions) {
this.subscriptions.add(editor.getBuffer().onWillSave(() => {
this._onSave(editor);
}));
}
});
// Start full refresh
setTimeout(() => {
// Refresh all classes
this.initialized = true;
this._refresh(true);
}, 300);
}
deactivate() {
this.subscriptions.dispose();
this.provider = null;
this.classLoader = null;
this.subscriptions = null;
this.classpath = null;
this.initialized = false;
}
getProvider() {
return this.provider;
}
// Commands
async _refresh(fullRefresh) {
// Refresh provider settings
// TODO observe config changes
this.provider.configure(atom.config.get('autocomplete-java'));
this.classLoader.setJavaHome(atom.config.get('autocomplete-java.javaHome'));
// Load classes using classpath
const classpath = await this._loadClasspath();
if (classpath) {
this.classLoader.loadClasses(classpath,
atom.config.get('autocomplete-java.loadClassMembers'), fullRefresh);
}
}
_refreshClass(className, delayMillis) {
setTimeout(() => {
if (this.classpath) {
this.classLoader.loadClass(className, this.classpath,
atom.config.get('autocomplete-java.loadClassMembers'));
} else {
console.warn('autocomplete-java: classpath not set.');
}
}, delayMillis);
}
_organizeImports() {
const editor = atom.workspace.getActiveTextEditor();
if (this._isJavaFile(editor)) {
atomJavaUtil.organizeImports(editor, null,
atom.config.get('autocomplete-java.foldImports'));
}
}
_onChange(paneItem) {
if (this._isJavaFile(paneItem)) {
// Active file has changed -> fold imports
if (atom.config.get('autocomplete-java.foldImports')) {
atomJavaUtil.foldImports(paneItem);
}
// Active file has changed -> touch every imported class
_.each(atomJavaUtil.getImports(paneItem), imp => {
try {
this.classLoader.touchClass(imp.match(/import\s*(\S*);/)[1]);
} catch (err) {
// console.warn(err);
}
});
}
}
_onSave(editor) {
// TODO use onDidSave for refreshing and onWillSave for organizing imports
if (this._isJavaFile(editor)) {
// Refresh saved class after it has been compiled
if (atom.config.get('autocomplete-java.refreshClassOnSave')) {
const fileMatch = editor.getPath().match(/\/([^\/]*)\.java/);
const packageMatch = editor.getText().match(/package\s(.*);/);
if (fileMatch && packageMatch) {
// TODO use file watcher instead of hardcoded timeout
const className = packageMatch[1] + '.' + fileMatch[1];
this._refreshClass(className, 3000);
}
}
}
}
// Util methods
_isJavaFile(editor) {
return editor instanceof TextEditor && editor.getPath() &&
editor.getPath().match(/\.java$/);
}
// TODO: this is a quick hack for loading classpath. replace with
// atom-javaenv once it has been implemented
async _loadClasspath() {
let separator = null;
const classpathSet = new Set();
const classpathFileName =
atom.config.get('autocomplete-java.classpathFilePath');
await atom.workspace.scan(/^.+$/, { paths: ['*' + classpathFileName] },
file => {
separator = file.filePath.indexOf(':') !== -1 ? ';' : ':';
_.each(file.matches, match => {
// NOTE: The :\ replace is a quick hack for supporting Windows
// absolute paths e.g E:\myProject\lib
_.each(match.matchText.replace(':\\', '+\\').split(/[\:\;]+/), path => {
classpathSet.add(this._asAbsolutePath(file.filePath,
path.replace('+\\', ':\\')));
});
});
});
let classpath = '';
_.each([...classpathSet], path => {
classpath = classpath + path + separator;
});
this.classpath = classpath;
return classpath;
}
// TODO: this is a quick hack for loading path. replace with atom-javaenv
// once it has been implemented
_asAbsolutePath(currentFilePath, path) {
let p = path;
let dirPath = currentFilePath.match(/(.*)[\\\/]/)[1];
let addBaseDir = false;
// Remove ../ or ..\ from beginning
while (/^\.\.[\\\/]/.test(p)) {
addBaseDir = true;
dirPath = dirPath.match(/(.*)[\\\/]/)[1];
p = p.substring(3);
}
// Remove ./ or .\ from beginning
while (/^\.[\\\/]/.test(p)) {
addBaseDir = true;
p = p.substring(2);
}
return addBaseDir ? dirPath + '/' + p : p;
}
}
export default new AtomAutocompletePackage();
| lib/atomAutocompletePackage.js | 'use babel';
import { _ } from 'lodash';
import { TextEditor } from 'atom';
import { CompositeDisposable } from 'atom';
import { AtomAutocompleteProvider } from './AtomAutocompleteProvider';
import { JavaClassLoader } from './JavaClassLoader';
import atomJavaUtil from './atomJavaUtil';
class AtomAutocompletePackage {
constructor() {
this.config = require('./config.json');
this.subscriptions = undefined;
this.provider = undefined;
this.classLoader = undefined;
this.classpath = null;
this.initialized = false;
}
activate() {
this.classLoader = new JavaClassLoader(
atom.config.get('autocomplete-java.javaHome'));
this.provider = new AtomAutocompleteProvider(this.classLoader);
this.subscriptions = new CompositeDisposable();
// Listen for commands
this.subscriptions.add(
atom.commands.add('atom-workspace', 'autocomplete-java:organize-imports',
() => {
this._organizeImports();
})
);
this.subscriptions.add(
atom.commands.add('atom-workspace', 'autocomplete-java:refresh-project',
() => {
if (this.initialized) {
this._refresh(false);
}
})
);
this.subscriptions.add(
atom.commands.add('atom-workspace', 'autocomplete-java:full-refresh',
() => {
if (this.initialized) {
this._refresh(true);
}
})
);
// Listen for config changes
// TODO refactor: bypasses provider.configure()
this.subscriptions.add(
atom.config.observe('autocomplete-java.inclusionPriority', (val) => {
this.provider.inclusionPriority = val;
})
);
this.subscriptions.add(
atom.config.observe('autocomplete-java.excludeLowerPriority', (val) => {
this.provider.excludeLowerPriority = val;
})
);
this.subscriptions.add(
atom.config.observe('autocomplete-java.foldImports', (val) => {
this.provider.foldImports = val;
})
);
// Listen for buffer change
this.subscriptions.add(
atom.workspace.onDidStopChangingActivePaneItem((paneItem) => {
this._onChange(paneItem);
}));
// Listen for file save
atom.workspace.observeTextEditors(editor => {
this.subscriptions.add(editor.getBuffer().onWillSave(() => {
this._onSave(editor);
}));
});
// Start full refresh
setTimeout(() => {
// Refresh all classes
this.initialized = true;
this._refresh(true);
}, 300);
}
deactivate() {
this.subscriptions.dispose();
this.provider = null;
this.classLoader = null;
this.subscriptions = null;
this.classpath = null;
this.initialized = false;
}
getProvider() {
return this.provider;
}
// Commands
async _refresh(fullRefresh) {
// Refresh provider settings
// TODO observe config changes
this.provider.configure(atom.config.get('autocomplete-java'));
this.classLoader.setJavaHome(atom.config.get('autocomplete-java.javaHome'));
// Load classes using classpath
const classpath = await this._loadClasspath();
if (classpath) {
this.classLoader.loadClasses(classpath,
atom.config.get('autocomplete-java.loadClassMembers'), fullRefresh);
}
}
_refreshClass(className, delayMillis) {
setTimeout(() => {
if (this.classpath) {
this.classLoader.loadClass(className, this.classpath,
atom.config.get('autocomplete-java.loadClassMembers'));
} else {
console.warn('autocomplete-java: classpath not set.');
}
}, delayMillis);
}
_organizeImports() {
const editor = atom.workspace.getActiveTextEditor();
if (this._isJavaFile(editor)) {
atomJavaUtil.organizeImports(editor, null,
atom.config.get('autocomplete-java.foldImports'));
}
}
_onChange(paneItem) {
if (this._isJavaFile(paneItem)) {
// Active file has changed -> fold imports
if (atom.config.get('autocomplete-java.foldImports')) {
atomJavaUtil.foldImports(paneItem);
}
// Active file has changed -> touch every imported class
_.each(atomJavaUtil.getImports(paneItem), imp => {
try {
this.classLoader.touchClass(imp.match(/import\s*(\S*);/)[1]);
} catch (err) {
// console.warn(err);
}
});
}
}
_onSave(editor) {
// TODO use onDidSave for refreshing and onWillSave for organizing imports
if (this._isJavaFile(editor)) {
// Refresh saved class after it has been compiled
if (atom.config.get('autocomplete-java.refreshClassOnSave')) {
const fileMatch = editor.getPath().match(/\/([^\/]*)\.java/);
const packageMatch = editor.getText().match(/package\s(.*);/);
if (fileMatch && packageMatch) {
// TODO use file watcher instead of hardcoded timeout
const className = packageMatch[1] + '.' + fileMatch[1];
this._refreshClass(className, 3000);
}
}
}
}
// Util methods
_isJavaFile(editor) {
return editor instanceof TextEditor && editor.getPath() &&
editor.getPath().match(/\.java$/);
}
// TODO: this is a quick hack for loading classpath. replace with
// atom-javaenv once it has been implemented
async _loadClasspath() {
let separator = null;
const classpathSet = new Set();
const classpathFileName =
atom.config.get('autocomplete-java.classpathFilePath');
await atom.workspace.scan(/^.+$/, { paths: ['*' + classpathFileName] },
file => {
separator = file.filePath.indexOf(':') !== -1 ? ';' : ':';
_.each(file.matches, match => {
// NOTE: The :\ replace is a quick hack for supporting Windows
// absolute paths e.g E:\myProject\lib
_.each(match.matchText.replace(':\\', '+\\').split(/[\:\;]+/), path => {
classpathSet.add(this._asAbsolutePath(file.filePath,
path.replace('+\\', ':\\')));
});
});
});
let classpath = '';
_.each([...classpathSet], path => {
classpath = classpath + path + separator;
});
this.classpath = classpath;
return classpath;
}
// TODO: this is a quick hack for loading path. replace with atom-javaenv
// once it has been implemented
_asAbsolutePath(currentFilePath, path) {
let p = path;
let dirPath = currentFilePath.match(/(.*)[\\\/]/)[1];
let addBaseDir = false;
// Remove ../ or ..\ from beginning
while (/^\.\.[\\\/]/.test(p)) {
addBaseDir = true;
dirPath = dirPath.match(/(.*)[\\\/]/)[1];
p = p.substring(3);
}
// Remove ./ or .\ from beginning
while (/^\.[\\\/]/.test(p)) {
addBaseDir = true;
p = p.substring(2);
}
return addBaseDir ? dirPath + '/' + p : p;
}
}
export default new AtomAutocompletePackage();
| issue #38
| lib/atomAutocompletePackage.js | issue #38 | <ide><path>ib/atomAutocompletePackage.js
<ide>
<ide> // Listen for buffer change
<ide> this.subscriptions.add(
<del> atom.workspace.onDidStopChangingActivePaneItem((paneItem) => {
<del> this._onChange(paneItem);
<del> }));
<add> atom.workspace.onDidStopChangingActivePaneItem((paneItem) => {
<add> this._onChange(paneItem);
<add> })
<add> );
<ide>
<ide> // Listen for file save
<ide> atom.workspace.observeTextEditors(editor => {
<del> this.subscriptions.add(editor.getBuffer().onWillSave(() => {
<del> this._onSave(editor);
<del> }));
<add> if (this.subscriptions) {
<add> this.subscriptions.add(editor.getBuffer().onWillSave(() => {
<add> this._onSave(editor);
<add> }));
<add> }
<ide> });
<ide>
<ide> // Start full refresh |
|
Java | apache-2.0 | 38a178ff7979a4ff7d703861bade92fb5377e60a | 0 | cunningt/camel,tdiesler/camel,christophd/camel,DariusX/camel,tdiesler/camel,apache/camel,adessaigne/camel,nikhilvibhav/camel,nicolaferraro/camel,DariusX/camel,pmoerenhout/camel,nikhilvibhav/camel,pax95/camel,cunningt/camel,pmoerenhout/camel,adessaigne/camel,gnodet/camel,gnodet/camel,ullgren/camel,adessaigne/camel,alvinkwekel/camel,zregvart/camel,pax95/camel,apache/camel,gnodet/camel,apache/camel,CodeSmell/camel,pmoerenhout/camel,cunningt/camel,nicolaferraro/camel,tdiesler/camel,christophd/camel,tadayosi/camel,alvinkwekel/camel,ullgren/camel,nikhilvibhav/camel,mcollovati/camel,tadayosi/camel,CodeSmell/camel,pmoerenhout/camel,christophd/camel,cunningt/camel,alvinkwekel/camel,mcollovati/camel,apache/camel,alvinkwekel/camel,pmoerenhout/camel,christophd/camel,tadayosi/camel,cunningt/camel,ullgren/camel,pax95/camel,ullgren/camel,zregvart/camel,tdiesler/camel,DariusX/camel,christophd/camel,apache/camel,tadayosi/camel,tadayosi/camel,christophd/camel,CodeSmell/camel,apache/camel,cunningt/camel,nicolaferraro/camel,zregvart/camel,zregvart/camel,CodeSmell/camel,adessaigne/camel,DariusX/camel,nikhilvibhav/camel,tadayosi/camel,tdiesler/camel,mcollovati/camel,pax95/camel,adessaigne/camel,pax95/camel,pax95/camel,tdiesler/camel,mcollovati/camel,gnodet/camel,gnodet/camel,pmoerenhout/camel,adessaigne/camel,nicolaferraro/camel | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
/**
* Working with Apache Avro for data serialization.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface AvroEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the Avro component.
*/
public interface AvroEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedAvroEndpointConsumerBuilder advanced() {
return (AdvancedAvroEndpointConsumerBuilder) this;
}
/**
* Avro protocol to use.
*
* The option is a: <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocol(Object protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use.
*
* The option will be converted to a
* <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocol(String protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use defined by the FQN class name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocolClassName(
String protocolClassName) {
doSetProperty("protocolClassName", protocolClassName);
return this;
}
/**
* Avro protocol location.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocolLocation(
String protocolLocation) {
doSetProperty("protocolLocation", protocolLocation);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointConsumerBuilder reflectionProtocol(
boolean reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointConsumerBuilder reflectionProtocol(
String reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointConsumerBuilder singleParameter(
boolean singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointConsumerBuilder singleParameter(
String singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* Authority to use (username and password).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder uriAuthority(String uriAuthority) {
doSetProperty("uriAuthority", uriAuthority);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default AvroEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default AvroEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Avro component.
*/
public interface AdvancedAvroEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AvroEndpointConsumerBuilder basic() {
return (AvroEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint producers for the Avro component.
*/
public interface AvroEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedAvroEndpointProducerBuilder advanced() {
return (AdvancedAvroEndpointProducerBuilder) this;
}
/**
* Avro protocol to use.
*
* The option is a: <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocol(Object protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use.
*
* The option will be converted to a
* <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocol(String protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use defined by the FQN class name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocolClassName(
String protocolClassName) {
doSetProperty("protocolClassName", protocolClassName);
return this;
}
/**
* Avro protocol location.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocolLocation(
String protocolLocation) {
doSetProperty("protocolLocation", protocolLocation);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointProducerBuilder reflectionProtocol(
boolean reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointProducerBuilder reflectionProtocol(
String reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointProducerBuilder singleParameter(
boolean singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointProducerBuilder singleParameter(
String singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* Authority to use (username and password).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder uriAuthority(String uriAuthority) {
doSetProperty("uriAuthority", uriAuthority);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default AvroEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default AvroEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Avro component.
*/
public interface AdvancedAvroEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AvroEndpointProducerBuilder basic() {
return (AvroEndpointProducerBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint for the Avro component.
*/
public interface AvroEndpointBuilder
extends
AvroEndpointConsumerBuilder, AvroEndpointProducerBuilder {
default AdvancedAvroEndpointBuilder advanced() {
return (AdvancedAvroEndpointBuilder) this;
}
/**
* Avro protocol to use.
*
* The option is a: <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocol(Object protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use.
*
* The option will be converted to a
* <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocol(String protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use defined by the FQN class name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocolClassName(String protocolClassName) {
doSetProperty("protocolClassName", protocolClassName);
return this;
}
/**
* Avro protocol location.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocolLocation(String protocolLocation) {
doSetProperty("protocolLocation", protocolLocation);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointBuilder reflectionProtocol(
boolean reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointBuilder reflectionProtocol(String reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointBuilder singleParameter(boolean singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*/
default AvroEndpointBuilder singleParameter(String singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* Authority to use (username and password).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointBuilder uriAuthority(String uriAuthority) {
doSetProperty("uriAuthority", uriAuthority);
return this;
}
}
/**
* Advanced builder for endpoint for the Avro component.
*/
public interface AdvancedAvroEndpointBuilder
extends
AdvancedAvroEndpointConsumerBuilder, AdvancedAvroEndpointProducerBuilder {
default AvroEndpointBuilder basic() {
return (AvroEndpointBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedAvroEndpointBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Avro (camel-avro)
* Working with Apache Avro for data serialization.
*
* Category: messaging,transformation
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-avro
*
* Syntax: <code>avro:transport:host:port/messageName</code>
*
* Path parameter: transport (required)
* Transport to use, can be either http or netty
* The value can be one of: http, netty
*
* Path parameter: port (required)
* Port number to use
*
* Path parameter: host (required)
* Hostname to use
*
* Path parameter: messageName
* The name of the message to send.
*/
default AvroEndpointBuilder avro(String path) {
class AvroEndpointBuilderImpl extends AbstractEndpointBuilder implements AvroEndpointBuilder, AdvancedAvroEndpointBuilder {
public AvroEndpointBuilderImpl(String path) {
super("avro", path);
}
}
return new AvroEndpointBuilderImpl(path);
}
} | core/camel-endpointdsl/src/main/java/org/apache/camel/builder/endpoint/dsl/AvroEndpointBuilderFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
/**
* Working with Apache Avro for data serialization.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface AvroEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the Avro component.
*/
public interface AvroEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedAvroEndpointConsumerBuilder advanced() {
return (AdvancedAvroEndpointConsumerBuilder) this;
}
/**
* Avro protocol to use.
*
* The option is a: <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocol(Object protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use.
*
* The option will be converted to a
* <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocol(String protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use defined by the FQN class name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocolClassName(
String protocolClassName) {
doSetProperty("protocolClassName", protocolClassName);
return this;
}
/**
* Avro protocol location.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder protocolLocation(
String protocolLocation) {
doSetProperty("protocolLocation", protocolLocation);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option is a: <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder reflectionProtocol(
boolean reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder reflectionProtocol(
String reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option is a: <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder singleParameter(
boolean singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder singleParameter(
String singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* Authority to use (username and password).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointConsumerBuilder uriAuthority(String uriAuthority) {
doSetProperty("uriAuthority", uriAuthority);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Group: consumer
*/
default AvroEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: consumer
*/
default AvroEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Avro component.
*/
public interface AdvancedAvroEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AvroEndpointConsumerBuilder basic() {
return (AvroEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedAvroEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointConsumerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint producers for the Avro component.
*/
public interface AvroEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedAvroEndpointProducerBuilder advanced() {
return (AdvancedAvroEndpointProducerBuilder) this;
}
/**
* Avro protocol to use.
*
* The option is a: <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocol(Object protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use.
*
* The option will be converted to a
* <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocol(String protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use defined by the FQN class name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocolClassName(
String protocolClassName) {
doSetProperty("protocolClassName", protocolClassName);
return this;
}
/**
* Avro protocol location.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder protocolLocation(
String protocolLocation) {
doSetProperty("protocolLocation", protocolLocation);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option is a: <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder reflectionProtocol(
boolean reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder reflectionProtocol(
String reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option is a: <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder singleParameter(
boolean singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder singleParameter(
String singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* Authority to use (username and password).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointProducerBuilder uriAuthority(String uriAuthority) {
doSetProperty("uriAuthority", uriAuthority);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Group: producer
*/
default AvroEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: producer
*/
default AvroEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Avro component.
*/
public interface AdvancedAvroEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AvroEndpointProducerBuilder basic() {
return (AvroEndpointProducerBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointProducerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint for the Avro component.
*/
public interface AvroEndpointBuilder
extends
AvroEndpointConsumerBuilder, AvroEndpointProducerBuilder {
default AdvancedAvroEndpointBuilder advanced() {
return (AdvancedAvroEndpointBuilder) this;
}
/**
* Avro protocol to use.
*
* The option is a: <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocol(Object protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use.
*
* The option will be converted to a
* <code>org.apache.avro.Protocol</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocol(String protocol) {
doSetProperty("protocol", protocol);
return this;
}
/**
* Avro protocol to use defined by the FQN class name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocolClassName(String protocolClassName) {
doSetProperty("protocolClassName", protocolClassName);
return this;
}
/**
* Avro protocol location.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointBuilder protocolLocation(String protocolLocation) {
doSetProperty("protocolLocation", protocolLocation);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option is a: <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointBuilder reflectionProtocol(
boolean reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointBuilder reflectionProtocol(String reflectionProtocol) {
doSetProperty("reflectionProtocol", reflectionProtocol);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option is a: <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointBuilder singleParameter(boolean singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: common
*/
default AvroEndpointBuilder singleParameter(String singleParameter) {
doSetProperty("singleParameter", singleParameter);
return this;
}
/**
* Authority to use (username and password).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default AvroEndpointBuilder uriAuthority(String uriAuthority) {
doSetProperty("uriAuthority", uriAuthority);
return this;
}
}
/**
* Advanced builder for endpoint for the Avro component.
*/
public interface AdvancedAvroEndpointBuilder
extends
AdvancedAvroEndpointConsumerBuilder, AdvancedAvroEndpointProducerBuilder {
default AvroEndpointBuilder basic() {
return (AvroEndpointBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedAvroEndpointBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Avro (camel-avro)
* Working with Apache Avro for data serialization.
*
* Category: messaging,transformation
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-avro
*
* Syntax: <code>avro:transport:host:port/messageName</code>
*
* Path parameter: transport (required)
* Transport to use, can be either http or netty
* The value can be one of: http, netty
*
* Path parameter: port (required)
* Port number to use
*
* Path parameter: host (required)
* Hostname to use
*
* Path parameter: messageName
* The name of the message to send.
*/
default AvroEndpointBuilder avro(String path) {
class AvroEndpointBuilderImpl extends AbstractEndpointBuilder implements AvroEndpointBuilder, AdvancedAvroEndpointBuilder {
public AvroEndpointBuilderImpl(String path) {
super("avro", path);
}
}
return new AvroEndpointBuilderImpl(path);
}
} | Regen
| core/camel-endpointdsl/src/main/java/org/apache/camel/builder/endpoint/dsl/AvroEndpointBuilderFactory.java | Regen | <ide><path>ore/camel-endpointdsl/src/main/java/org/apache/camel/builder/endpoint/dsl/AvroEndpointBuilderFactory.java
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointConsumerBuilder reflectionProtocol(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointConsumerBuilder reflectionProtocol(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointConsumerBuilder singleParameter(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointConsumerBuilder singleParameter(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: consumer
<ide> */
<ide> default AvroEndpointConsumerBuilder bridgeErrorHandler(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: consumer
<ide> */
<ide> default AvroEndpointConsumerBuilder bridgeErrorHandler(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointConsumerBuilder synchronous(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointConsumerBuilder synchronous(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointProducerBuilder reflectionProtocol(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointProducerBuilder reflectionProtocol(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointProducerBuilder singleParameter(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointProducerBuilder singleParameter(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: producer
<ide> */
<ide> default AvroEndpointProducerBuilder lazyStartProducer(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: producer
<ide> */
<ide> default AvroEndpointProducerBuilder lazyStartProducer(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointProducerBuilder synchronous(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointProducerBuilder synchronous(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointBuilder reflectionProtocol(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointBuilder reflectionProtocol(String reflectionProtocol) {
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointBuilder singleParameter(boolean singleParameter) {
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: common
<ide> */
<ide> default AvroEndpointBuilder singleParameter(String singleParameter) {
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointBuilder basicPropertyBinding(
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointBuilder basicPropertyBinding(
<ide> *
<ide> * The option is a: <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointBuilder synchronous(boolean synchronous) {
<ide> *
<ide> * The option will be converted to a <code>boolean</code> type.
<ide> *
<add> * Default: false
<ide> * Group: advanced
<ide> */
<ide> default AdvancedAvroEndpointBuilder synchronous(String synchronous) { |
|
Java | apache-2.0 | 3dc7a9c01dc5e88656d9cc64b4a512c0634e4b04 | 0 | kirimin/kumin | package me.kirimin.kumin.ui.service;
import java.util.List;
import me.kirimin.kumin.ui.notification.AppNotificationBuilder;
import twitter4j.Status;
import me.kirimin.kumin.AppPreferences;
import me.kirimin.kumin.Constants;
import me.kirimin.kumin.R;
import me.kirimin.kumin.Twitter;
import me.kirimin.kumin.db.HashTagDAO;
import me.kirimin.kumin.db.User;
import me.kirimin.kumin.db.UserDAO;
import me.kirimin.kumin.ui.activity.ImageUploadActivity;
import me.kirimin.kumin.ui.adapter.TimeLineListViewAdapter;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/**
* 常駐レイヤーを表示させるためのService
*
* @author kirimin
*/
public class TweetViewService extends Service implements OnClickListener, OnTouchListener, OnItemClickListener, TextWatcher, OnItemLongClickListener {
private static final int LAYOUT_TOP_ID = 1;
private static final WindowManager.LayoutParams NOT_FOCUSABLE_PARAMS = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
private static final WindowManager.LayoutParams FOCUSABLE_PARAMS = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, 0, PixelFormat.TRANSLUCENT);
private static final WindowManager.LayoutParams NOT_TOUCHABLE_PARAMS = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
private View mLayoutTop, mLayoutHandle, mLayoutTweetItems, mLayoutTimeLines, mButtonListviewResize;
private ImageButton mButtonTweet, mButtonMenu;
private Button mButtonOpen, mButtonClose, mButtonTL, mButtonAccount, mButtonHashTag;
private EditText mEditTweet;
private TextView mTextCharCount;
private ListView mListTimeLine;
/**
* ドラッグで移動した位置覚えておく変数 *
*/
private int mViewX, mViewY, mListViewResizeY;
/**
* タッチモード判定
*/
private boolean isTouchable = true;
private WindowManager mWindowManager;
private Twitter mTwitter;
private AppPreferences mAppPreferences;
private TimeLineListViewAdapter mAdapter;
@Override
public void onCreate() {
super.onCreate();
mAppPreferences = new AppPreferences(getApplicationContext());
// オーバーレイViewの設定を行う
LayoutInflater layoutInflater = LayoutInflater.from(this);
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mLayoutTop = layoutInflater.inflate(R.layout.service_tweet_view, null);
mLayoutTop.setId(LAYOUT_TOP_ID);
mLayoutHandle = mLayoutTop.findViewById(R.id.tweetViewLayoutHandle);
mLayoutTweetItems = mLayoutTop.findViewById(R.id.tweetViewLayoutTweetitems);
mLayoutTimeLines = mLayoutTop.findViewById(R.id.tweetViewLayoutTimeLines);
mButtonTweet = (ImageButton) mLayoutTop.findViewById(R.id.tweetViewButtonTweet);
mButtonMenu = (ImageButton) mLayoutTop.findViewById(R.id.tweetViewButtonMenu);
mButtonOpen = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonOpen);
mButtonTL = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonTimeLineOpen);
mButtonClose = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonClose);
mButtonAccount = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonAccount);
mButtonHashTag = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonHashTag);
mEditTweet = (EditText) mLayoutTop.findViewById(R.id.tweetViewEditTweet);
mTextCharCount = (TextView) mLayoutTop.findViewById(R.id.tweetViewTextCharCount);
mListTimeLine = (ListView) mLayoutTop.findViewById(R.id.tweetViewListTimeLine);
mButtonListviewResize = (View) mLayoutTop.findViewById(R.id.tweetViewTimeLineResizeButton);
mLayoutTop.setOnTouchListener(this);
mLayoutHandle.setOnTouchListener(this);
mButtonTweet.setOnClickListener(this);
mButtonMenu.setOnClickListener(this);
mButtonOpen.setOnClickListener(new OnOpenClickListener(mLayoutTweetItems));
mButtonTL.setOnClickListener(new OnOpenClickListener(mLayoutTimeLines));
mButtonClose.setOnClickListener(this);
mButtonAccount.setOnClickListener(this);
mButtonHashTag.setOnClickListener(this);
mEditTweet.setOnTouchListener(this);
mEditTweet.addTextChangedListener(this);
mEditTweet.setText(mAppPreferences.readTweetTextCache());
mTextCharCount.setText(String.valueOf(Constants.MAX_TWEET_LENGTH - mEditTweet.getText().length()));
mListTimeLine.setOnItemClickListener(this);
mListTimeLine.setOnItemLongClickListener(this);
mListTimeLine.setOnTouchListener(this);
mButtonListviewResize.setOnTouchListener(this);
mViewX = mAppPreferences.readTweetViewX();
mViewY = mAppPreferences.readTweetViewY();
params.x = mViewX;
params.y = mViewY;
mWindowManager.addView(mLayoutTop, params);
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
mEditTweet.setBackgroundColor(Color.argb(mAppPreferences.readEditAlpha(), 170, 170, 170));
mListTimeLine.setBackgroundColor(Color.argb(mAppPreferences.readTimeLineAlpha(), 170, 170, 170));
// Twitterインスタンス初期設定
mTwitter = new Twitter();
mTwitter.addOnStatusUpdateListener(new OnStatusUpdateListener());
mTwitter.setStreamListener(new StreamLisnter());
mAdapter = new TimeLineListViewAdapter(this, mTwitter);
mListTimeLine.setAdapter(mAdapter);
// デフォルトユーザーを設定
UserDAO dao = new UserDAO(getApplicationContext());
if (dao.getUsers().size() != 0) {
String currentUserId = mAppPreferences.readCurrentUser();
if (currentUserId.equals("")) {
currentUserId = dao.getUsers().get(0).getId();
}
User user = dao.getUser(currentUserId);
setUser(user);
} else {
Toast.makeText(this, R.string.account_not_find, Toast.LENGTH_SHORT).show();
stopSelf();
return;
}
startForeground(1, AppNotificationBuilder.create(this));
new StartStreamTask().execute(mTwitter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// タッチモード切り替え
if (isTouchable) {
mWindowManager.updateViewLayout(mLayoutTop, NOT_FOCUSABLE_PARAMS);
mEditTweet.setVisibility(View.VISIBLE);
mButtonListviewResize.setVisibility(View.VISIBLE);
mButtonClose.setVisibility(View.VISIBLE);
mButtonTweet.setVisibility(View.VISIBLE);
mTextCharCount.setVisibility(View.VISIBLE);
// 表示設定反映
if (!mAppPreferences.readIsShowAccountButton()) {
mButtonAccount.setVisibility(View.GONE);
} else {
mButtonAccount.setVisibility(View.VISIBLE);
}
if (!mAppPreferences.readIsShowHashTagButton()) {
mButtonHashTag.setVisibility(View.GONE);
} else {
mButtonHashTag.setVisibility(View.VISIBLE);
}
if (!mAppPreferences.readIsShowMenuButton()) {
mButtonMenu.setVisibility(View.GONE);
} else {
mButtonMenu.setVisibility(View.VISIBLE);
}
mButtonOpen.setText(getString(R.string.char_minimize));
} else {
NOT_TOUCHABLE_PARAMS.x = NOT_FOCUSABLE_PARAMS.x;
NOT_TOUCHABLE_PARAMS.y = NOT_FOCUSABLE_PARAMS.y;
mWindowManager.updateViewLayout(mLayoutTop, NOT_TOUCHABLE_PARAMS);
mButtonListviewResize.setVisibility(View.GONE);
mButtonClose.setVisibility(View.GONE);
mButtonHashTag.setVisibility(View.GONE);
mButtonMenu.setVisibility(View.GONE);
mButtonTweet.setVisibility(View.GONE);
mButtonAccount.setVisibility(View.GONE);
mTextCharCount.setVisibility(View.GONE);
mLayoutTimeLines.setVisibility(View.VISIBLE);
mButtonTL.setText(getString(R.string.char_minimize));
new StartStreamTask().execute(mTwitter);
mEditTweet.setVisibility(View.GONE);
mButtonOpen.setText(getString(R.string.char_open));
}
isTouchable = !isTouchable;
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
new StopStreamTask().execute(mTwitter);
mWindowManager.removeViewImmediate(mLayoutTop);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tweetViewButtonClose:
// 閉じるボタン
mAppPreferences.writeTweetViewX(mViewX);
mAppPreferences.writeTweetViewY(mViewY);
stopSelf();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, AppNotificationBuilder.create(TweetViewService.this));
break;
case R.id.tweetViewButtonAccount:
// 投稿するアカウントを入れ替える
UserDAO userDao = new UserDAO(TweetViewService.this);
final List<User> users = userDao.getUsers();
for (int i = 0; i < users.size(); i++) {
if (!users.get(i).getSName().equals(mButtonAccount.getText()))
continue;
if (users.size() == i + 1) {
setUser(users.get(0));
} else {
setUser(users.get(i + 1));
}
break;
}
break;
case R.id.tweetViewButtonHashTag:
// ハッシュタグを入れ替える
HashTagDAO hashTagDao = new HashTagDAO(TweetViewService.this);
final List<String> hashTagList = hashTagDao.getHashTagList();
hashTagList.add(getString(R.string.char_hashTag));
for (int i = 0; i < hashTagList.size(); i++) {
if (!hashTagList.get(i).equals(mButtonHashTag.getText()))
continue;
if (hashTagList.size() == i + 1) {
mButtonHashTag.setText(hashTagList.get(0));
} else {
mButtonHashTag.setText(hashTagList.get(i + 1));
}
break;
}
break;
case R.id.tweetViewButtonMenu:
// メニューボタン
Intent intent = new Intent(TweetViewService.this, ImageUploadActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
case R.id.tweetViewButtonTweet:
// ツイートボタン
String tweet = mEditTweet.getText().toString();
if (!mButtonHashTag.getText().toString().equals(getString(R.string.char_hashTag))) {
tweet += " " + mButtonHashTag.getText();
}
Toast.makeText(TweetViewService.this, getString(R.string.layer_toast_tweeting), Toast.LENGTH_SHORT).show();
mTwitter.updateStatus(tweet);
break;
default:
break;
}
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (view.getId()) {
case R.id.tweetViewEditTweet:
case R.id.tweetViewListTimeLine:
// 範囲内タッチ
WindowManager.LayoutParams innerView = FOCUSABLE_PARAMS;
innerView.x = mViewX;
innerView.y = mViewY;
mWindowManager.updateViewLayout(mLayoutTop, innerView);
return false;
case LAYOUT_TOP_ID:
// 範囲外タッチ
WindowManager.LayoutParams outerView = NOT_FOCUSABLE_PARAMS;
outerView.x = mViewX;
outerView.y = mViewY;
// 更新
mWindowManager.updateViewLayout(mLayoutTop, outerView);
return false;
case R.id.tweetViewLayoutHandle:
// Viewドラッグ処理
Display display = mWindowManager.getDefaultDisplay();
if (mLayoutTimeLines.getVisibility() == View.GONE) {
mViewY = (int) event.getRawY() - display.getHeight() / 2 - dp2Px(50);
} else if (mLayoutTimeLines.getVisibility() == View.VISIBLE && mLayoutTweetItems.getVisibility() == View.VISIBLE) {
mViewY = (int) event.getRawY() - display.getHeight() / 2 - dp2Px(50)
+ mListTimeLine.getHeight() / 2
+ mLayoutTweetItems.getHeight() / 2
- mLayoutHandle.getHeight() / 2;
} else {
mViewY = (int) event.getRawY() - display.getHeight() / 2 - dp2Px(50)
+ mListTimeLine.getHeight() / 2
- mLayoutHandle.getHeight() / 2;
}
mViewX = mLayoutTweetItems.getVisibility() == View.GONE && mLayoutTimeLines.getVisibility() == View.GONE
? (int) event.getRawX() - display.getWidth() / 2
: (int) event.getRawX() - display.getWidth() / 2 - dp2Px(140);
if (event.getAction() == MotionEvent.ACTION_MOVE) {
// タッチ位置にビューを設定
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
params.x = mViewX;
params.y = mViewY;
mWindowManager.updateViewLayout(mLayoutTop, params);
}
return true;
case R.id.tweetViewTimeLineResizeButton:
// ツイートViewリサイズ
int drag = (int) event.getRawY() - mListViewResizeY;
if (drag < dp2Px(200) && drag > -dp2Px(200) && event.getAction() == MotionEvent.ACTION_MOVE) {
int height = mListTimeLine.getHeight() + drag;
if (height > dp2Px(100)) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mListTimeLine.getWidth(), height);
mListTimeLine.setLayoutParams(params);
}
}
mListViewResizeY = (int) event.getRawY();
return true;
default:
return true;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Status status = (Status) parent.getAdapter().getItem(position);
mEditTweet.setText(getString(R.string.char_replay) + status.getUser().getScreenName() + " " + mEditTweet.getText());
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(TweetViewService.this, R.string.layer_toast_favoriting, Toast.LENGTH_SHORT).show();
Status status = (Status) parent.getAdapter().getItem(position);
mTwitter.doFavorite(status.getId());
return true;
}
@Override
public void afterTextChanged(Editable s) {
int charCount = Constants.MAX_TWEET_LENGTH - mEditTweet.getText().length();
mTextCharCount.setText(String.valueOf(charCount));
mAppPreferences.writeTweetTextCache(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
/**
* 投稿するユーザーを設定する。
*
* @param user 設定するユーザー
*/
private void setUser(User user) {
mTwitter.setUser(user);
if (mLayoutTimeLines.getVisibility() == View.VISIBLE) {
new ReStartStreamTask().execute(mTwitter);
}
mButtonAccount.setText(user.getSName());
mAppPreferences.writeCurrentUser(user.getId());
}
/**
* dpをpxに変換する
*
* @param dp dp
* @return px
*/
private int dp2Px(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
/**
* 最小化ボタン押下時処理
*/
private class OnOpenClickListener implements OnClickListener {
private View actionTargetView;
public OnOpenClickListener(View actionTargetView) {
this.actionTargetView = actionTargetView;
}
@Override
public void onClick(View view) {
Button buttonOpen = (Button) view;
if (actionTargetView.getVisibility() == View.VISIBLE) {
actionTargetView.setVisibility(View.GONE);
buttonOpen.setText("□");
if (mLayoutTweetItems.getVisibility() == View.GONE && mLayoutTimeLines.getVisibility() == View.GONE) {
updateViewLayout(140);
}
if (actionTargetView == mLayoutTimeLines) {
new StopStreamTask().execute(mTwitter);
}
} else {
actionTargetView.setVisibility(View.VISIBLE);
buttonOpen.setText("‐");
if (mLayoutTweetItems.getVisibility() == View.GONE || mLayoutTimeLines.getVisibility() == View.GONE) {
updateViewLayout(-140);
}
if (actionTargetView == mLayoutTimeLines) {
new StartStreamTask().execute(mTwitter);
}
}
}
private void updateViewLayout(int addDp) {
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
params.x = mViewX += dp2Px(addDp);
params.y = mViewY;
// 更新
mWindowManager.updateViewLayout(mLayoutTop, params);
}
}
/**
* Tweet投稿時の処理
*/
private class OnStatusUpdateListener implements Twitter.OnStatusUpdateListener {
@Override
public void onStatusUpdate() {
Toast.makeText(TweetViewService.this, R.string.layer_toast_tweet_ok, Toast.LENGTH_SHORT).show();
mEditTweet.setText("");
if (mAppPreferences.readIsCloseWhenTweet()) {
mLayoutTop.findViewById(R.id.tweetViewLayoutTweetitems).setVisibility(View.GONE);
mButtonOpen.setText("□");
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
params.x = mViewX += dp2Px(140);
params.y = mViewY;
// 更新
mWindowManager.updateViewLayout(mLayoutTop, params);
}
}
@Override
public void onFavorite() {
Toast.makeText(TweetViewService.this, R.string.layer_toast_favo_ok, Toast.LENGTH_SHORT).show();
}
@Override
public void onError() {
Toast.makeText(TweetViewService.this, R.string.twitter_exeption_network, Toast.LENGTH_SHORT).show();
}
}
/**
* UserStream取得時の処理
*/
private class StreamLisnter implements Twitter.StreamListener {
@Override
public void onStatus(Status status) {
mAdapter.insert(status, 0);
if (mAdapter.getCount() > 50) {
mAdapter.remove(mAdapter.getItem(mAdapter.getCount() - 1));
}
mAdapter.notifyDataSetChanged();
}
}
/**
* Stream開始
*/
private static class StartStreamTask extends AsyncTask<Twitter, String, String> {
@Override
protected String doInBackground(Twitter... params) {
params[0].startUserStream();
return null;
}
}
/**
* Stream停止
*/
private static class StopStreamTask extends AsyncTask<Twitter, String, String> {
@Override
protected String doInBackground(Twitter... params) {
params[0].stopUserStream();
return null;
}
}
/**
* Streamリスタート
*/
private static class ReStartStreamTask extends AsyncTask<Twitter, String, String> {
@Override
protected String doInBackground(Twitter... params) {
params[0].stopUserStream();
while (params[0].startUserStream()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
return null;
}
}
return null;
}
}
} | app/src/main/java/me/kirimin/kumin/ui/service/TweetViewService.java | package me.kirimin.kumin.ui.service;
import java.util.List;
import me.kirimin.kumin.ui.notification.AppNotificationBuilder;
import twitter4j.Status;
import me.kirimin.kumin.AppPreferences;
import me.kirimin.kumin.Constants;
import me.kirimin.kumin.R;
import me.kirimin.kumin.Twitter;
import me.kirimin.kumin.db.HashTagDAO;
import me.kirimin.kumin.db.User;
import me.kirimin.kumin.db.UserDAO;
import me.kirimin.kumin.ui.activity.ImageUploadActivity;
import me.kirimin.kumin.ui.adapter.TimeLineListViewAdapter;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/**
* 常駐レイヤーを表示させるためのService
*
* @author kirimin
*/
public class TweetViewService extends Service implements OnClickListener, OnTouchListener, OnItemClickListener, TextWatcher, OnItemLongClickListener {
private static final int LAYOUT_TOP_ID = 1;
private static final WindowManager.LayoutParams NOT_FOCUSABLE_PARAMES = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
private static final WindowManager.LayoutParams FOCUSABLE_PARAMES = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, 0, PixelFormat.TRANSLUCENT);
private static final WindowManager.LayoutParams NOT_TOUCHABLE_PARAMES = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
private View mLayoutTop, mLayoutHandle, mLayoutTweetItems, mLayoutTimeLines, mButtonListviewResize;
private ImageButton mButtonTweet, mButtonMenu;
private Button mButtonOpen, mButtonClose, mButtonTL, mButtonAccount, mButtonHashTag;
private EditText mEditTweet;
private TextView mTextCharCount;
private ListView mListTimeLine;
/**
* ドラッグで移動した位置覚えておく変数 *
*/
private int mViewX, mViewY, mListViewResizeY;
/**
* タッチモード判定
*/
private boolean isTouchable = true;
private WindowManager mWindowManager;
private Twitter mTwitter;
private AppPreferences mAppPreferences;
private TimeLineListViewAdapter mAdapter;
@Override
public void onCreate() {
super.onCreate();
mAppPreferences = new AppPreferences(getApplicationContext());
// オーバーレイViewの設定を行う
LayoutInflater layoutInflater = LayoutInflater.from(this);
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mLayoutTop = layoutInflater.inflate(R.layout.service_tweet_view, null);
mLayoutTop.setId(LAYOUT_TOP_ID);
mLayoutHandle = mLayoutTop.findViewById(R.id.tweetViewLayoutHandle);
mLayoutTweetItems = mLayoutTop.findViewById(R.id.tweetViewLayoutTweetitems);
mLayoutTimeLines = mLayoutTop.findViewById(R.id.tweetViewLayoutTimeLines);
mButtonTweet = (ImageButton) mLayoutTop.findViewById(R.id.tweetViewButtonTweet);
mButtonMenu = (ImageButton) mLayoutTop.findViewById(R.id.tweetViewButtonMenu);
mButtonOpen = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonOpen);
mButtonTL = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonTimeLineOpen);
mButtonClose = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonClose);
mButtonAccount = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonAccount);
mButtonHashTag = (Button) mLayoutTop.findViewById(R.id.tweetViewButtonHashTag);
mEditTweet = (EditText) mLayoutTop.findViewById(R.id.tweetViewEditTweet);
mTextCharCount = (TextView) mLayoutTop.findViewById(R.id.tweetViewTextCharCount);
mListTimeLine = (ListView) mLayoutTop.findViewById(R.id.tweetViewListTimeLine);
mButtonListviewResize = (View) mLayoutTop.findViewById(R.id.tweetViewTimeLineResizeButton);
mLayoutTop.setOnTouchListener(this);
mLayoutHandle.setOnTouchListener(this);
mButtonTweet.setOnClickListener(this);
mButtonMenu.setOnClickListener(this);
mButtonOpen.setOnClickListener(new OnOpenClickListener(mLayoutTweetItems));
mButtonTL.setOnClickListener(new OnOpenClickListener(mLayoutTimeLines));
mButtonClose.setOnClickListener(this);
mButtonAccount.setOnClickListener(this);
mButtonHashTag.setOnClickListener(this);
mEditTweet.setOnTouchListener(this);
mEditTweet.addTextChangedListener(this);
mEditTweet.setText(mAppPreferences.readTweetTextCache());
mTextCharCount.setText(String.valueOf(Constants.MAX_TWEET_LENGTH - mEditTweet.getText().length()));
mListTimeLine.setOnItemClickListener(this);
mListTimeLine.setOnItemLongClickListener(this);
mListTimeLine.setOnTouchListener(this);
mButtonListviewResize.setOnTouchListener(this);
mViewX = mAppPreferences.readTweetViewX();
mViewY = mAppPreferences.readTweetViewY();
params.x = mViewX;
params.y = mViewY;
mWindowManager.addView(mLayoutTop, params);
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
mEditTweet.setBackgroundColor(Color.argb(mAppPreferences.readEditAlpha(), 170, 170, 170));
mListTimeLine.setBackgroundColor(Color.argb(mAppPreferences.readTimeLineAlpha(), 170, 170, 170));
// Twitterインスタンス初期設定
mTwitter = new Twitter();
mTwitter.addOnStatusUpdateListener(new OnStatusUpdateListener());
mTwitter.setStreamListener(new StreamLisnter());
mAdapter = new TimeLineListViewAdapter(this, mTwitter);
mListTimeLine.setAdapter(mAdapter);
// デフォルトユーザーを設定
UserDAO dao = new UserDAO(getApplicationContext());
if (dao.getUsers().size() != 0) {
String currentUserId = mAppPreferences.readCurrentUser();
if (currentUserId.equals("")) {
currentUserId = dao.getUsers().get(0).getId();
}
User user = dao.getUser(currentUserId);
setUser(user);
} else {
Toast.makeText(this, R.string.account_not_find, Toast.LENGTH_SHORT).show();
stopSelf();
return;
}
startForeground(1, AppNotificationBuilder.create(this));
new StartStreamTask().execute(mTwitter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// タッチモード切り替え
if (isTouchable) {
mWindowManager.updateViewLayout(mLayoutTop, NOT_FOCUSABLE_PARAMES);
mEditTweet.setVisibility(View.VISIBLE);
mButtonListviewResize.setVisibility(View.VISIBLE);
mButtonClose.setVisibility(View.VISIBLE);
mButtonTweet.setVisibility(View.VISIBLE);
mTextCharCount.setVisibility(View.VISIBLE);
// 表示設定反映
if (!mAppPreferences.readIsShowAccountButton()) {
mButtonAccount.setVisibility(View.GONE);
} else {
mButtonAccount.setVisibility(View.VISIBLE);
}
if (!mAppPreferences.readIsShowHashTagButton()) {
mButtonHashTag.setVisibility(View.GONE);
} else {
mButtonHashTag.setVisibility(View.VISIBLE);
}
if (!mAppPreferences.readIsShowMenuButton()) {
mButtonMenu.setVisibility(View.GONE);
} else {
mButtonMenu.setVisibility(View.VISIBLE);
}
mButtonOpen.setText(getString(R.string.char_minimize));
} else {
NOT_TOUCHABLE_PARAMES.x = NOT_FOCUSABLE_PARAMES.x;
NOT_TOUCHABLE_PARAMES.y = NOT_FOCUSABLE_PARAMES.y;
mWindowManager.updateViewLayout(mLayoutTop, NOT_TOUCHABLE_PARAMES);
mButtonListviewResize.setVisibility(View.GONE);
mButtonClose.setVisibility(View.GONE);
mButtonHashTag.setVisibility(View.GONE);
mButtonMenu.setVisibility(View.GONE);
mButtonTweet.setVisibility(View.GONE);
mButtonAccount.setVisibility(View.GONE);
mTextCharCount.setVisibility(View.GONE);
mLayoutTimeLines.setVisibility(View.VISIBLE);
mButtonTL.setText(getString(R.string.char_minimize));
new StartStreamTask().execute(mTwitter);
mEditTweet.setVisibility(View.GONE);
mButtonOpen.setText(getString(R.string.char_open));
}
isTouchable = !isTouchable;
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
new StopStreamTask().execute(mTwitter);
mWindowManager.removeViewImmediate(mLayoutTop);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tweetViewButtonClose:
// 閉じるボタン
mAppPreferences.writeTweetViewX(mViewX);
mAppPreferences.writeTweetViewY(mViewY);
stopSelf();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, AppNotificationBuilder.create(TweetViewService.this));
break;
case R.id.tweetViewButtonAccount:
// 投稿するアカウントを入れ替える
UserDAO userDao = new UserDAO(TweetViewService.this);
final List<User> users = userDao.getUsers();
for (int i = 0; i < users.size(); i++) {
if (!users.get(i).getSName().equals(mButtonAccount.getText()))
continue;
if (users.size() == i + 1) {
setUser(users.get(0));
} else {
setUser(users.get(i + 1));
}
break;
}
break;
case R.id.tweetViewButtonHashTag:
// ハッシュタグを入れ替える
HashTagDAO hashTagDao = new HashTagDAO(TweetViewService.this);
final List<String> hashTagList = hashTagDao.getHashTagList();
hashTagList.add(getString(R.string.char_hashTag));
for (int i = 0; i < hashTagList.size(); i++) {
if (!hashTagList.get(i).equals(mButtonHashTag.getText()))
continue;
if (hashTagList.size() == i + 1) {
mButtonHashTag.setText(hashTagList.get(0));
} else {
mButtonHashTag.setText(hashTagList.get(i + 1));
}
break;
}
break;
case R.id.tweetViewButtonMenu:
// メニューボタン
Intent intent = new Intent(TweetViewService.this, ImageUploadActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
case R.id.tweetViewButtonTweet:
// ツイートボタン
String tweet = mEditTweet.getText().toString();
if (!mButtonHashTag.getText().toString().equals(getString(R.string.char_hashTag))) {
tweet += " " + mButtonHashTag.getText();
}
Toast.makeText(TweetViewService.this, getString(R.string.layer_toast_tweeting), Toast.LENGTH_SHORT).show();
mTwitter.updateStatus(tweet);
break;
default:
break;
}
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (view.getId()) {
case R.id.tweetViewEditTweet:
case R.id.tweetViewListTimeLine:
// 範囲内タッチ
WindowManager.LayoutParams innerView = FOCUSABLE_PARAMES;
innerView.x = mViewX;
innerView.y = mViewY;
mWindowManager.updateViewLayout(mLayoutTop, innerView);
return false;
case LAYOUT_TOP_ID:
// 範囲外タッチ
WindowManager.LayoutParams outerView = NOT_FOCUSABLE_PARAMES;
outerView.x = mViewX;
outerView.y = mViewY;
// 更新
mWindowManager.updateViewLayout(mLayoutTop, outerView);
return false;
case R.id.tweetViewLayoutHandle:
// Viewドラッグ処理
Display display = mWindowManager.getDefaultDisplay();
if (mLayoutTimeLines.getVisibility() == View.GONE) {
mViewY = (int) event.getRawY() - display.getHeight() / 2 - dp2Px(50);
} else if (mLayoutTimeLines.getVisibility() == View.VISIBLE && mLayoutTweetItems.getVisibility() == View.VISIBLE) {
mViewY = (int) event.getRawY() - display.getHeight() / 2 - dp2Px(50)
+ mListTimeLine.getHeight() / 2
+ mLayoutTweetItems.getHeight() / 2
- mLayoutHandle.getHeight() / 2;
} else {
mViewY = (int) event.getRawY() - display.getHeight() / 2 - dp2Px(50)
+ mListTimeLine.getHeight() / 2
- mLayoutHandle.getHeight() / 2;
}
mViewX = mLayoutTweetItems.getVisibility() == View.GONE && mLayoutTimeLines.getVisibility() == View.GONE
? (int) event.getRawX() - display.getWidth() / 2
: (int) event.getRawX() - display.getWidth() / 2 - dp2Px(140);
if (event.getAction() == MotionEvent.ACTION_MOVE) {
// タッチ位置にビューを設定
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
params.x = mViewX;
params.y = mViewY;
mWindowManager.updateViewLayout(mLayoutTop, params);
}
return true;
case R.id.tweetViewTimeLineResizeButton:
// ツイートViewリサイズ
int drag = (int) event.getRawY() - mListViewResizeY;
if (drag < dp2Px(200) && drag > -dp2Px(200) && event.getAction() == MotionEvent.ACTION_MOVE) {
int height = mListTimeLine.getHeight() + drag;
if (height > dp2Px(100)) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mListTimeLine.getWidth(), height);
mListTimeLine.setLayoutParams(params);
}
}
mListViewResizeY = (int) event.getRawY();
return true;
default:
return true;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Status status = (Status) parent.getAdapter().getItem(position);
mEditTweet.setText(getString(R.string.char_replay) + status.getUser().getScreenName() + " " + mEditTweet.getText());
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(TweetViewService.this, R.string.layer_toast_favoriting, Toast.LENGTH_SHORT).show();
Status status = (Status) parent.getAdapter().getItem(position);
mTwitter.doFavorite(status.getId());
return true;
}
@Override
public void afterTextChanged(Editable s) {
int charCount = Constants.MAX_TWEET_LENGTH - mEditTweet.getText().length();
mTextCharCount.setText(String.valueOf(charCount));
mAppPreferences.writeTweetTextCache(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
/**
* 投稿するユーザーを設定する。
*
* @param user 設定するユーザー
*/
private void setUser(User user) {
mTwitter.setUser(user);
if (mLayoutTimeLines.getVisibility() == View.VISIBLE) {
new ReStartStreamTask().execute(mTwitter);
}
mButtonAccount.setText(user.getSName());
mAppPreferences.writeCurrentUser(user.getId());
}
/**
* dpをpxに変換する
*
* @param dp dp
* @return px
*/
private int dp2Px(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
/**
* 最小化ボタン押下時処理
*/
private class OnOpenClickListener implements OnClickListener {
private View actionTargetView;
public OnOpenClickListener(View actionTargetView) {
this.actionTargetView = actionTargetView;
}
@Override
public void onClick(View view) {
Button buttonOpen = (Button) view;
if (actionTargetView.getVisibility() == View.VISIBLE) {
actionTargetView.setVisibility(View.GONE);
buttonOpen.setText("□");
if (mLayoutTweetItems.getVisibility() == View.GONE && mLayoutTimeLines.getVisibility() == View.GONE) {
updateViewLayout(140);
}
if (actionTargetView == mLayoutTimeLines) {
new StopStreamTask().execute(mTwitter);
}
} else {
actionTargetView.setVisibility(View.VISIBLE);
buttonOpen.setText("‐");
if (mLayoutTweetItems.getVisibility() == View.GONE || mLayoutTimeLines.getVisibility() == View.GONE) {
updateViewLayout(-140);
}
if (actionTargetView == mLayoutTimeLines) {
new StartStreamTask().execute(mTwitter);
}
}
}
private void updateViewLayout(int addDp) {
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
params.x = mViewX += dp2Px(addDp);
params.y = mViewY;
// 更新
mWindowManager.updateViewLayout(mLayoutTop, params);
}
}
/**
* Tweet投稿時の処理
*/
private class OnStatusUpdateListener implements Twitter.OnStatusUpdateListener {
@Override
public void onStatusUpdate() {
Toast.makeText(TweetViewService.this, R.string.layer_toast_tweet_ok, Toast.LENGTH_SHORT).show();
mEditTweet.setText("");
if (mAppPreferences.readIsCloseWhenTweet()) {
mLayoutTop.findViewById(R.id.tweetViewLayoutTweetitems).setVisibility(View.GONE);
mButtonOpen.setText("□");
WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
params.x = mViewX += dp2Px(140);
params.y = mViewY;
// 更新
mWindowManager.updateViewLayout(mLayoutTop, params);
}
}
@Override
public void onFavorite() {
Toast.makeText(TweetViewService.this, R.string.layer_toast_favo_ok, Toast.LENGTH_SHORT).show();
}
@Override
public void onError() {
Toast.makeText(TweetViewService.this, R.string.twitter_exeption_network, Toast.LENGTH_SHORT).show();
}
}
/**
* UserStream取得時の処理
*/
private class StreamLisnter implements Twitter.StreamListener {
@Override
public void onStatus(Status status) {
mAdapter.insert(status, 0);
if (mAdapter.getCount() > 50) {
mAdapter.remove(mAdapter.getItem(mAdapter.getCount() - 1));
}
mAdapter.notifyDataSetChanged();
}
}
/**
* Stream開始
*/
private static class StartStreamTask extends AsyncTask<Twitter, String, String> {
@Override
protected String doInBackground(Twitter... params) {
params[0].startUserStream();
return null;
}
}
/**
* Stream停止
*/
private static class StopStreamTask extends AsyncTask<Twitter, String, String> {
@Override
protected String doInBackground(Twitter... params) {
params[0].stopUserStream();
return null;
}
}
/**
* Streamリスタート
*/
private static class ReStartStreamTask extends AsyncTask<Twitter, String, String> {
@Override
protected String doInBackground(Twitter... params) {
params[0].stopUserStream();
while (params[0].startUserStream()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
return null;
}
}
return null;
}
}
} | 定数名のPARAMESをPARAMSに置換
| app/src/main/java/me/kirimin/kumin/ui/service/TweetViewService.java | 定数名のPARAMESをPARAMSに置換 | <ide><path>pp/src/main/java/me/kirimin/kumin/ui/service/TweetViewService.java
<ide>
<ide> private static final int LAYOUT_TOP_ID = 1;
<ide>
<del> private static final WindowManager.LayoutParams NOT_FOCUSABLE_PARAMES = new WindowManager.LayoutParams(
<add> private static final WindowManager.LayoutParams NOT_FOCUSABLE_PARAMS = new WindowManager.LayoutParams(
<ide> WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
<ide> WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
<ide> PixelFormat.TRANSLUCENT);
<ide>
<del> private static final WindowManager.LayoutParams FOCUSABLE_PARAMES = new WindowManager.LayoutParams(
<add> private static final WindowManager.LayoutParams FOCUSABLE_PARAMS = new WindowManager.LayoutParams(
<ide> WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
<ide> WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, 0, PixelFormat.TRANSLUCENT);
<ide>
<del> private static final WindowManager.LayoutParams NOT_TOUCHABLE_PARAMES = new WindowManager.LayoutParams(
<add> private static final WindowManager.LayoutParams NOT_TOUCHABLE_PARAMS = new WindowManager.LayoutParams(
<ide> WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
<ide> WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
<ide> PixelFormat.TRANSLUCENT);
<ide>
<ide> // オーバーレイViewの設定を行う
<ide> LayoutInflater layoutInflater = LayoutInflater.from(this);
<del> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
<add> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
<ide> mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
<ide>
<ide> mLayoutTop = layoutInflater.inflate(R.layout.service_tweet_view, null);
<ide> public int onStartCommand(Intent intent, int flags, int startId) {
<ide> // タッチモード切り替え
<ide> if (isTouchable) {
<del> mWindowManager.updateViewLayout(mLayoutTop, NOT_FOCUSABLE_PARAMES);
<add> mWindowManager.updateViewLayout(mLayoutTop, NOT_FOCUSABLE_PARAMS);
<ide> mEditTweet.setVisibility(View.VISIBLE);
<ide> mButtonListviewResize.setVisibility(View.VISIBLE);
<ide> mButtonClose.setVisibility(View.VISIBLE);
<ide>
<ide> mButtonOpen.setText(getString(R.string.char_minimize));
<ide> } else {
<del> NOT_TOUCHABLE_PARAMES.x = NOT_FOCUSABLE_PARAMES.x;
<del> NOT_TOUCHABLE_PARAMES.y = NOT_FOCUSABLE_PARAMES.y;
<del> mWindowManager.updateViewLayout(mLayoutTop, NOT_TOUCHABLE_PARAMES);
<add> NOT_TOUCHABLE_PARAMS.x = NOT_FOCUSABLE_PARAMS.x;
<add> NOT_TOUCHABLE_PARAMS.y = NOT_FOCUSABLE_PARAMS.y;
<add> mWindowManager.updateViewLayout(mLayoutTop, NOT_TOUCHABLE_PARAMS);
<ide> mButtonListviewResize.setVisibility(View.GONE);
<ide> mButtonClose.setVisibility(View.GONE);
<ide> mButtonHashTag.setVisibility(View.GONE);
<ide> case R.id.tweetViewEditTweet:
<ide> case R.id.tweetViewListTimeLine:
<ide> // 範囲内タッチ
<del> WindowManager.LayoutParams innerView = FOCUSABLE_PARAMES;
<add> WindowManager.LayoutParams innerView = FOCUSABLE_PARAMS;
<ide> innerView.x = mViewX;
<ide> innerView.y = mViewY;
<ide> mWindowManager.updateViewLayout(mLayoutTop, innerView);
<ide>
<ide> case LAYOUT_TOP_ID:
<ide> // 範囲外タッチ
<del> WindowManager.LayoutParams outerView = NOT_FOCUSABLE_PARAMES;
<add> WindowManager.LayoutParams outerView = NOT_FOCUSABLE_PARAMS;
<ide> outerView.x = mViewX;
<ide> outerView.y = mViewY;
<ide>
<ide>
<ide> if (event.getAction() == MotionEvent.ACTION_MOVE) {
<ide> // タッチ位置にビューを設定
<del> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
<add> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
<ide> params.x = mViewX;
<ide> params.y = mViewY;
<ide> mWindowManager.updateViewLayout(mLayoutTop, params);
<ide> }
<ide>
<ide> private void updateViewLayout(int addDp) {
<del> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
<add> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
<ide> params.x = mViewX += dp2Px(addDp);
<ide> params.y = mViewY;
<ide>
<ide> if (mAppPreferences.readIsCloseWhenTweet()) {
<ide> mLayoutTop.findViewById(R.id.tweetViewLayoutTweetitems).setVisibility(View.GONE);
<ide> mButtonOpen.setText("□");
<del> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMES;
<add> WindowManager.LayoutParams params = NOT_FOCUSABLE_PARAMS;
<ide> params.x = mViewX += dp2Px(140);
<ide> params.y = mViewY;
<ide> |
|
Java | apache-2.0 | 915bf5f5b7d0afa40c9921bea0025d80cb29a51a | 0 | johnou/netty,idelpivnitskiy/netty,artgon/netty,fenik17/netty,netty/netty,Squarespace/netty,andsel/netty,Apache9/netty,fenik17/netty,Spikhalskiy/netty,doom369/netty,jchambers/netty,carl-mastrangelo/netty,Spikhalskiy/netty,idelpivnitskiy/netty,carl-mastrangelo/netty,jchambers/netty,andsel/netty,NiteshKant/netty,fenik17/netty,ngocdaothanh/netty,johnou/netty,zer0se7en/netty,artgon/netty,mcobrien/netty,netty/netty,idelpivnitskiy/netty,jchambers/netty,ejona86/netty,mcobrien/netty,fenik17/netty,tbrooks8/netty,carl-mastrangelo/netty,Squarespace/netty,fengjiachun/netty,doom369/netty,artgon/netty,johnou/netty,cnoldtree/netty,fengjiachun/netty,cnoldtree/netty,johnou/netty,KatsuraKKKK/netty,tbrooks8/netty,ngocdaothanh/netty,gerdriesselmann/netty,doom369/netty,mcobrien/netty,tbrooks8/netty,KatsuraKKKK/netty,ejona86/netty,gerdriesselmann/netty,Apache9/netty,louxiu/netty,KatsuraKKKK/netty,Squarespace/netty,tbrooks8/netty,cnoldtree/netty,doom369/netty,ngocdaothanh/netty,mikkokar/netty,cnoldtree/netty,andsel/netty,louxiu/netty,Apache9/netty,Squarespace/netty,KatsuraKKKK/netty,louxiu/netty,KatsuraKKKK/netty,netty/netty,netty/netty,zer0se7en/netty,jchambers/netty,bryce-anderson/netty,andsel/netty,ejona86/netty,andsel/netty,ejona86/netty,mikkokar/netty,fenik17/netty,Spikhalskiy/netty,ngocdaothanh/netty,zer0se7en/netty,tbrooks8/netty,mcobrien/netty,artgon/netty,Squarespace/netty,bryce-anderson/netty,NiteshKant/netty,mikkokar/netty,ngocdaothanh/netty,netty/netty,gerdriesselmann/netty,Apache9/netty,idelpivnitskiy/netty,fengjiachun/netty,zer0se7en/netty,bryce-anderson/netty,NiteshKant/netty,zer0se7en/netty,carl-mastrangelo/netty,bryce-anderson/netty,skyao/netty,fengjiachun/netty,gerdriesselmann/netty,skyao/netty,jchambers/netty,mikkokar/netty,doom369/netty,artgon/netty,carl-mastrangelo/netty,skyao/netty,mcobrien/netty,ejona86/netty,Apache9/netty,NiteshKant/netty,Spikhalskiy/netty,Spikhalskiy/netty,mikkokar/netty,NiteshKant/netty,bryce-anderson/netty,fengjiachun/netty,skyao/netty,louxiu/netty,skyao/netty,cnoldtree/netty,louxiu/netty,gerdriesselmann/netty,johnou/netty,idelpivnitskiy/netty | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelPromiseNotifier;
import io.netty.channel.PendingWriteQueue;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.util.ReferenceCounted;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.ImmediateExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ThrowableUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength;
/**
* Adds <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">SSL
* · TLS</a> and StartTLS support to a {@link Channel}. Please refer
* to the <strong>"SecureChat"</strong> example in the distribution or the web
* site for the detailed usage.
*
* <h3>Beginning the handshake</h3>
* <p>
* Beside using the handshake {@link ChannelFuture} to get notified about the completion of the handshake it's
* also possible to detect it by implement the
* {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)}
* method and check for a {@link SslHandshakeCompletionEvent}.
*
* <h3>Handshake</h3>
* <p>
* The handshake will be automatically issued for you once the {@link Channel} is active and
* {@link SSLEngine#getUseClientMode()} returns {@code true}.
* So no need to bother with it by your self.
*
* <h3>Closing the session</h3>
* <p>
* To close the SSL session, the {@link #close()} method should be
* called to send the {@code close_notify} message to the remote peer. One
* exception is when you close the {@link Channel} - {@link SslHandler}
* intercepts the close request and send the {@code close_notify} message
* before the channel closure automatically. Once the SSL session is closed,
* it is not reusable, and consequently you should create a new
* {@link SslHandler} with a new {@link SSLEngine} as explained in the
* following section.
*
* <h3>Restarting the session</h3>
* <p>
* To restart the SSL session, you must remove the existing closed
* {@link SslHandler} from the {@link ChannelPipeline}, insert a new
* {@link SslHandler} with a new {@link SSLEngine} into the pipeline,
* and start the handshake process as described in the first section.
*
* <h3>Implementing StartTLS</h3>
* <p>
* <a href="http://en.wikipedia.org/wiki/STARTTLS">StartTLS</a> is the
* communication pattern that secures the wire in the middle of the plaintext
* connection. Please note that it is different from SSL · TLS, that
* secures the wire from the beginning of the connection. Typically, StartTLS
* is composed of three steps:
* <ol>
* <li>Client sends a StartTLS request to server.</li>
* <li>Server sends a StartTLS response to client.</li>
* <li>Client begins SSL handshake.</li>
* </ol>
* If you implement a server, you need to:
* <ol>
* <li>create a new {@link SslHandler} instance with {@code startTls} flag set
* to {@code true},</li>
* <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li>
* <li>write a StartTLS response.</li>
* </ol>
* Please note that you must insert {@link SslHandler} <em>before</em> sending
* the StartTLS response. Otherwise the client can send begin SSL handshake
* before {@link SslHandler} is inserted to the {@link ChannelPipeline}, causing
* data corruption.
* <p>
* The client-side implementation is much simpler.
* <ol>
* <li>Write a StartTLS request,</li>
* <li>wait for the StartTLS response,</li>
* <li>create a new {@link SslHandler} instance with {@code startTls} flag set
* to {@code false},</li>
* <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li>
* <li>Initiate SSL handshake.</li>
* </ol>
*
* <h3>Known issues</h3>
* <p>
* Because of a known issue with the current implementation of the SslEngine that comes
* with Java it may be possible that you see blocked IO-Threads while a full GC is done.
* <p>
* So if you are affected you can workaround this problem by adjust the cache settings
* like shown below:
*
* <pre>
* SslContext context = ...;
* context.getServerSessionContext().setSessionCacheSize(someSaneSize);
* context.getServerSessionContext().setSessionTime(someSameTimeout);
* </pre>
* <p>
* What values to use here depends on the nature of your application and should be set
* based on monitoring and debugging of it.
* For more details see
* <a href="https://github.com/netty/netty/issues/832">#832</a> in our issue tracker.
*/
public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundHandler {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(SslHandler.class);
private static final Pattern IGNORABLE_CLASS_IN_STACK = Pattern.compile(
"^.*(?:Socket|Datagram|Sctp|Udt)Channel.*$");
private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile(
"^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", Pattern.CASE_INSENSITIVE);
/**
* Used in {@link #unwrapNonAppData(ChannelHandlerContext)} as input for
* {@link #unwrap(ChannelHandlerContext, ByteBuf, int, int)}. Using this static instance reduce object
* creation as {@link Unpooled#EMPTY_BUFFER#nioBuffer()} creates a new {@link ByteBuffer} everytime.
*/
private static final SSLException SSLENGINE_CLOSED = ThrowableUtil.unknownStackTrace(
new SSLException("SSLEngine closed already"), SslHandler.class, "wrap(...)");
private static final SSLException HANDSHAKE_TIMED_OUT = ThrowableUtil.unknownStackTrace(
new SSLException("handshake timed out"), SslHandler.class, "handshake(...)");
private static final ClosedChannelException CHANNEL_CLOSED = ThrowableUtil.unknownStackTrace(
new ClosedChannelException(), SslHandler.class, "channelInactive(...)");
private enum SslEngineType {
TCNATIVE(true, COMPOSITE_CUMULATOR) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException {
int nioBufferCount = in.nioBufferCount();
int writerIndex = out.writerIndex();
final SSLEngineResult result;
if (nioBufferCount > 1) {
/*
* If {@link OpenSslEngine} is in use,
* we can use a special {@link OpenSslEngine#unwrap(ByteBuffer[], ByteBuffer[])} method
* that accepts multiple {@link ByteBuffer}s without additional memory copies.
*/
ReferenceCountedOpenSslEngine opensslEngine = (ReferenceCountedOpenSslEngine) handler.engine;
try {
handler.singleBuffer[0] = toByteBuffer(out, writerIndex,
out.writableBytes());
result = opensslEngine.unwrap(in.nioBuffers(readerIndex, len), handler.singleBuffer);
} finally {
handler.singleBuffer[0] = null;
}
} else {
result = handler.engine.unwrap(toByteBuffer(in, readerIndex, len),
toByteBuffer(out, writerIndex, out.writableBytes()));
}
out.writerIndex(writerIndex + result.bytesProduced());
return result;
}
@Override
int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents) {
return ReferenceCountedOpenSslEngine.calculateOutNetBufSize(pendingBytes, numComponents);
}
},
CONSCRYPT(true, COMPOSITE_CUMULATOR) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException {
int nioBufferCount = in.nioBufferCount();
int writerIndex = out.writerIndex();
final SSLEngineResult result;
if (nioBufferCount > 1) {
/*
* Use a special unwrap method without additional memory copies.
*/
try {
handler.singleBuffer[0] = toByteBuffer(out, writerIndex, out.writableBytes());
result = ((ConscryptAlpnSslEngine) handler.engine).unwrap(
in.nioBuffers(readerIndex, len),
handler.singleBuffer);
} finally {
handler.singleBuffer[0] = null;
}
} else {
result = handler.engine.unwrap(toByteBuffer(in, readerIndex, len),
toByteBuffer(out, writerIndex, out.writableBytes()));
}
out.writerIndex(writerIndex + result.bytesProduced());
return result;
}
@Override
int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents) {
return ((ConscryptAlpnSslEngine) handler.engine).calculateOutNetBufSize(pendingBytes, numComponents);
}
},
JDK(false, MERGE_CUMULATOR) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException {
int writerIndex = out.writerIndex();
final SSLEngineResult result = handler.engine.unwrap(toByteBuffer(in, readerIndex, len),
toByteBuffer(out, writerIndex, out.writableBytes()));
out.writerIndex(writerIndex + result.bytesProduced());
return result;
}
@Override
int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents) {
return handler.maxPacketBufferSize;
}
};
static SslEngineType forEngine(SSLEngine engine) {
if (engine instanceof ReferenceCountedOpenSslEngine) {
return TCNATIVE;
}
if (engine instanceof ConscryptAlpnSslEngine) {
return CONSCRYPT;
}
return JDK;
}
SslEngineType(boolean wantsDirectBuffer, Cumulator cumulator) {
this.wantsDirectBuffer = wantsDirectBuffer;
this.cumulator = cumulator;
}
abstract SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException;
abstract int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents);
// BEGIN Platform-dependent flags
/**
* {@code true} if and only if {@link SSLEngine} expects a direct buffer.
*/
final boolean wantsDirectBuffer;
// END Platform-dependent flags
/**
* When using JDK {@link SSLEngine}, we use {@link #MERGE_CUMULATOR} because it works only with
* one {@link ByteBuffer}.
*
* When using {@link OpenSslEngine}, we can use {@link #COMPOSITE_CUMULATOR} because it has
* {@link OpenSslEngine#unwrap(ByteBuffer[], ByteBuffer[])} which works with multiple {@link ByteBuffer}s
* and which does not need to do extra memory copies.
*/
final Cumulator cumulator;
}
private volatile ChannelHandlerContext ctx;
private final SSLEngine engine;
private final SslEngineType engineType;
private final int maxPacketBufferSize;
private final Executor delegatedTaskExecutor;
/**
* Used if {@link SSLEngine#wrap(ByteBuffer[], ByteBuffer)} and {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer[])}
* should be called with a {@link ByteBuf} that is only backed by one {@link ByteBuffer} to reduce the object
* creation.
*/
private final ByteBuffer[] singleBuffer = new ByteBuffer[1];
private final boolean startTls;
private boolean sentFirstMessage;
private boolean flushedBeforeHandshake;
private boolean readDuringHandshake;
private PendingWriteQueue pendingUnencryptedWrites;
private Promise<Channel> handshakePromise = new LazyChannelPromise();
private final LazyChannelPromise sslClosePromise = new LazyChannelPromise();
/**
* Set by wrap*() methods when something is produced.
* {@link #channelReadComplete(ChannelHandlerContext)} will check this flag, clear it, and call ctx.flush().
*/
private boolean needsFlush;
private boolean outboundClosed;
private int packetLength;
/**
* This flag is used to determine if we need to call {@link ChannelHandlerContext#read()} to consume more data
* when {@link ChannelConfig#isAutoRead()} is {@code false}.
*/
private boolean firedChannelRead;
private volatile long handshakeTimeoutMillis = 10000;
private volatile long closeNotifyFlushTimeoutMillis = 3000;
private volatile long closeNotifyReadTimeoutMillis;
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
*/
public SslHandler(SSLEngine engine) {
this(engine, false);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param startTls {@code true} if the first write request shouldn't be
* encrypted by the {@link SSLEngine}
*/
@SuppressWarnings("deprecation")
public SslHandler(SSLEngine engine, boolean startTls) {
this(engine, startTls, ImmediateExecutor.INSTANCE);
}
/**
* @deprecated Use {@link #SslHandler(SSLEngine)} instead.
*/
@Deprecated
public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) {
this(engine, false, delegatedTaskExecutor);
}
/**
* @deprecated Use {@link #SslHandler(SSLEngine, boolean)} instead.
*/
@Deprecated
public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) {
if (engine == null) {
throw new NullPointerException("engine");
}
if (delegatedTaskExecutor == null) {
throw new NullPointerException("delegatedTaskExecutor");
}
this.engine = engine;
engineType = SslEngineType.forEngine(engine);
this.delegatedTaskExecutor = delegatedTaskExecutor;
this.startTls = startTls;
maxPacketBufferSize = engine.getSession().getPacketBufferSize();
setCumulator(engineType.cumulator);
}
public long getHandshakeTimeoutMillis() {
return handshakeTimeoutMillis;
}
public void setHandshakeTimeout(long handshakeTimeout, TimeUnit unit) {
if (unit == null) {
throw new NullPointerException("unit");
}
setHandshakeTimeoutMillis(unit.toMillis(handshakeTimeout));
}
public void setHandshakeTimeoutMillis(long handshakeTimeoutMillis) {
if (handshakeTimeoutMillis < 0) {
throw new IllegalArgumentException(
"handshakeTimeoutMillis: " + handshakeTimeoutMillis + " (expected: >= 0)");
}
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
}
/**
* @deprecated use {@link #getCloseNotifyFlushTimeoutMillis()}
*/
@Deprecated
public long getCloseNotifyTimeoutMillis() {
return getCloseNotifyFlushTimeoutMillis();
}
/**
* @deprecated use {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}
*/
@Deprecated
public void setCloseNotifyTimeout(long closeNotifyTimeout, TimeUnit unit) {
setCloseNotifyFlushTimeout(closeNotifyTimeout, unit);
}
/**
* @deprecated use {@link #setCloseNotifyFlushTimeoutMillis(long)}
*/
@Deprecated
public void setCloseNotifyTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
setCloseNotifyFlushTimeoutMillis(closeNotifyFlushTimeoutMillis);
}
/**
* Gets the timeout for flushing the close_notify that was triggered by closing the
* {@link Channel}. If the close_notify was not flushed in the given timeout the {@link Channel} will be closed
* forcibly.
*/
public final long getCloseNotifyFlushTimeoutMillis() {
return closeNotifyFlushTimeoutMillis;
}
/**
* Sets the timeout for flushing the close_notify that was triggered by closing the
* {@link Channel}. If the close_notify was not flushed in the given timeout the {@link Channel} will be closed
* forcibly.
*/
public final void setCloseNotifyFlushTimeout(long closeNotifyFlushTimeout, TimeUnit unit) {
setCloseNotifyFlushTimeoutMillis(unit.toMillis(closeNotifyFlushTimeout));
}
/**
* See {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}.
*/
public final void setCloseNotifyFlushTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
if (closeNotifyFlushTimeoutMillis < 0) {
throw new IllegalArgumentException(
"closeNotifyFlushTimeoutMillis: " + closeNotifyFlushTimeoutMillis + " (expected: >= 0)");
}
this.closeNotifyFlushTimeoutMillis = closeNotifyFlushTimeoutMillis;
}
/**
* Gets the timeout (in ms) for receiving the response for the close_notify that was triggered by closing the
* {@link Channel}. This timeout starts after the close_notify message was successfully written to the
* remote peer. Use {@code 0} to directly close the {@link Channel} and not wait for the response.
*/
public final long getCloseNotifyReadTimeoutMillis() {
return closeNotifyReadTimeoutMillis;
}
/**
* Sets the timeout for receiving the response for the close_notify that was triggered by closing the
* {@link Channel}. This timeout starts after the close_notify message was successfully written to the
* remote peer. Use {@code 0} to directly close the {@link Channel} and not wait for the response.
*/
public final void setCloseNotifyReadTimeout(long closeNotifyReadTimeout, TimeUnit unit) {
setCloseNotifyReadTimeoutMillis(unit.toMillis(closeNotifyReadTimeout));
}
/**
* See {@link #setCloseNotifyReadTimeout(long, TimeUnit)}.
*/
public final void setCloseNotifyReadTimeoutMillis(long closeNotifyReadTimeoutMillis) {
if (closeNotifyReadTimeoutMillis < 0) {
throw new IllegalArgumentException(
"closeNotifyReadTimeoutMillis: " + closeNotifyReadTimeoutMillis + " (expected: >= 0)");
}
this.closeNotifyReadTimeoutMillis = closeNotifyReadTimeoutMillis;
}
/**
* Returns the {@link SSLEngine} which is used by this handler.
*/
public SSLEngine engine() {
return engine;
}
/**
* Returns the name of the current application-level protocol.
*
* @return the protocol name or {@code null} if application-level protocol has not been negotiated
*/
public String applicationProtocol() {
SSLSession sess = engine().getSession();
if (!(sess instanceof ApplicationProtocolAccessor)) {
return null;
}
return ((ApplicationProtocolAccessor) sess).getApplicationProtocol();
}
/**
* Returns a {@link Future} that will get notified once the current TLS handshake completes.
*
* @return the {@link Future} for the initial TLS handshake if {@link #renegotiate()} was not invoked.
* The {@link Future} for the most recent {@linkplain #renegotiate() TLS renegotiation} otherwise.
*/
public Future<Channel> handshakeFuture() {
return handshakePromise;
}
/**
* Sends an SSL {@code close_notify} message to the specified channel and
* destroys the underlying {@link SSLEngine}.
*
* @deprecated use {@link Channel#close()} or {@link ChannelHandlerContext#close()}
*/
@Deprecated
public ChannelFuture close() {
return close(ctx.newPromise());
}
/**
* See {@link #close()}
*
* @deprecated use {@link Channel#close()} or {@link ChannelHandlerContext#close()}
*/
@Deprecated
public ChannelFuture close(final ChannelPromise promise) {
final ChannelHandlerContext ctx = this.ctx;
ctx.executor().execute(new Runnable() {
@Override
public void run() {
outboundClosed = true;
engine.closeOutbound();
try {
flush(ctx, promise);
} catch (Exception e) {
if (!promise.tryFailure(e)) {
logger.warn("{} flush() raised a masked exception.", ctx.channel(), e);
}
}
}
});
return promise;
}
/**
* Return the {@link Future} that will get notified if the inbound of the {@link SSLEngine} is closed.
*
* This method will return the same {@link Future} all the time.
*
* @see SSLEngine
*/
public Future<Channel> sslCloseFuture() {
return sslClosePromise;
}
@Override
public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
if (!pendingUnencryptedWrites.isEmpty()) {
// Check if queue is not empty first because create a new ChannelException is expensive
pendingUnencryptedWrites.removeAndFailAll(new ChannelException("Pending write on removal of SslHandler"));
}
if (engine instanceof ReferenceCounted) {
((ReferenceCounted) engine).release();
}
}
@Override
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
ctx.bind(localAddress, promise);
}
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
ctx.connect(remoteAddress, localAddress, promise);
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
ctx.deregister(promise);
}
@Override
public void disconnect(final ChannelHandlerContext ctx,
final ChannelPromise promise) throws Exception {
closeOutboundAndChannel(ctx, promise, true);
}
@Override
public void close(final ChannelHandlerContext ctx,
final ChannelPromise promise) throws Exception {
closeOutboundAndChannel(ctx, promise, false);
}
@Override
public void read(ChannelHandlerContext ctx) throws Exception {
if (!handshakePromise.isDone()) {
readDuringHandshake = true;
}
ctx.read();
}
@Override
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (!(msg instanceof ByteBuf)) {
promise.setFailure(new UnsupportedMessageTypeException(msg, ByteBuf.class));
return;
}
pendingUnencryptedWrites.add(msg, promise);
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
// Do not encrypt the first write request if this handler is
// created with startTLS flag turned on.
if (startTls && !sentFirstMessage) {
sentFirstMessage = true;
pendingUnencryptedWrites.removeAndWriteAll();
forceFlush(ctx);
return;
}
try {
wrapAndFlush(ctx);
} catch (Throwable cause) {
setHandshakeFailure(ctx, cause);
PlatformDependent.throwException(cause);
}
}
private void wrapAndFlush(ChannelHandlerContext ctx) throws SSLException {
if (pendingUnencryptedWrites.isEmpty()) {
// It's important to NOT use a voidPromise here as the user
// may want to add a ChannelFutureListener to the ChannelPromise later.
//
// See https://github.com/netty/netty/issues/3364
pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, ctx.newPromise());
}
if (!handshakePromise.isDone()) {
flushedBeforeHandshake = true;
}
try {
wrap(ctx, false);
} finally {
// We may have written some parts of data before an exception was thrown so ensure we always flush.
// See https://github.com/netty/netty/issues/3900#issuecomment-172481830
forceFlush(ctx);
}
}
// This method will not call setHandshakeFailure(...) !
private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
ByteBuf out = null;
ChannelPromise promise = null;
ByteBufAllocator alloc = ctx.alloc();
boolean needUnwrap = false;
try {
// Only continue to loop if the handler was not removed in the meantime.
// See https://github.com/netty/netty/issues/5860
while (!ctx.isRemoved()) {
Object msg = pendingUnencryptedWrites.current();
if (msg == null) {
break;
}
ByteBuf buf = (ByteBuf) msg;
if (out == null) {
out = allocateOutNetBuf(ctx, buf.readableBytes(), buf.nioBufferCount());
}
SSLEngineResult result = wrap(alloc, engine, buf, out);
if (result.getStatus() == Status.CLOSED) {
// SSLEngine has been closed already.
// Any further write attempts should be denied.
pendingUnencryptedWrites.removeAndFailAll(SSLENGINE_CLOSED);
return;
} else {
if (!buf.isReadable()) {
promise = pendingUnencryptedWrites.remove();
} else {
promise = null;
}
switch (result.getHandshakeStatus()) {
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
setHandshakeSuccess();
// deliberate fall-through
case NOT_HANDSHAKING:
setHandshakeSuccessIfStillHandshaking();
// deliberate fall-through
case NEED_WRAP:
finishWrap(ctx, out, promise, inUnwrap, false);
promise = null;
out = null;
break;
case NEED_UNWRAP:
needUnwrap = true;
return;
default:
throw new IllegalStateException(
"Unknown handshake status: " + result.getHandshakeStatus());
}
}
}
} finally {
finishWrap(ctx, out, promise, inUnwrap, needUnwrap);
}
}
private void finishWrap(ChannelHandlerContext ctx, ByteBuf out, ChannelPromise promise, boolean inUnwrap,
boolean needUnwrap) {
if (out == null) {
out = Unpooled.EMPTY_BUFFER;
} else if (!out.isReadable()) {
out.release();
out = Unpooled.EMPTY_BUFFER;
}
if (promise != null) {
ctx.write(out, promise);
} else {
ctx.write(out);
}
if (inUnwrap) {
needsFlush = true;
}
if (needUnwrap) {
// The underlying engine is starving so we need to feed it with more data.
// See https://github.com/netty/netty/pull/5039
readIfNeeded(ctx);
}
}
/**
* This method will not call
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean)} or
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}.
* @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}.
*/
private void wrapNonAppData(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
ByteBuf out = null;
ByteBufAllocator alloc = ctx.alloc();
try {
// Only continue to loop if the handler was not removed in the meantime.
// See https://github.com/netty/netty/issues/5860
while (!ctx.isRemoved()) {
if (out == null) {
// As this is called for the handshake we have no real idea how big the buffer needs to be.
// That said 2048 should give us enough room to include everything like ALPN / NPN data.
// If this is not enough we will increase the buffer in wrap(...).
out = allocateOutNetBuf(ctx, 2048, 1);
}
SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out);
if (result.bytesProduced() > 0) {
ctx.write(out);
if (inUnwrap) {
needsFlush = true;
}
out = null;
}
switch (result.getHandshakeStatus()) {
case FINISHED:
setHandshakeSuccess();
break;
case NEED_TASK:
runDelegatedTasks();
break;
case NEED_UNWRAP:
if (inUnwrap) {
// If we asked for a wrap, the engine requested an unwrap, and we are in unwrap there is
// no use in trying to call wrap again because we have already attempted (or will after we
// return) to feed more data to the engine.
return;
}
unwrapNonAppData(ctx);
break;
case NEED_WRAP:
break;
case NOT_HANDSHAKING:
setHandshakeSuccessIfStillHandshaking();
// Workaround for TLS False Start problem reported at:
// https://github.com/netty/netty/issues/1108#issuecomment-14266970
if (!inUnwrap) {
unwrapNonAppData(ctx);
}
break;
default:
throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus());
}
if (result.bytesProduced() == 0) {
break;
}
// It should not consume empty buffers when it is not handshaking
// Fix for Android, where it was encrypting empty buffers even when not handshaking
if (result.bytesConsumed() == 0 && result.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) {
break;
}
}
} finally {
if (out != null) {
out.release();
}
}
}
private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
throws SSLException {
ByteBuf newDirectIn = null;
try {
int readerIndex = in.readerIndex();
int readableBytes = in.readableBytes();
// We will call SslEngine.wrap(ByteBuffer[], ByteBuffer) to allow efficient handling of
// CompositeByteBuf without force an extra memory copy when CompositeByteBuffer.nioBuffer() is called.
final ByteBuffer[] in0;
if (in.isDirect() || !engineType.wantsDirectBuffer) {
// As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed ByteBuf
// to calculate the count) we will just assume a CompositeByteBuf contains more then 1 ByteBuf.
// The worst that can happen is that we allocate an extra ByteBuffer[] in CompositeByteBuf.nioBuffers()
// which is better then walking the composed ByteBuf in most cases.
if (!(in instanceof CompositeByteBuf) && in.nioBufferCount() == 1) {
in0 = singleBuffer;
// We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object allocation
// to a minimum.
in0[0] = in.internalNioBuffer(readerIndex, readableBytes);
} else {
in0 = in.nioBuffers();
}
} else {
// We could even go further here and check if its a CompositeByteBuf and if so try to decompose it and
// only replace the ByteBuffer that are not direct. At the moment we just will replace the whole
// CompositeByteBuf to keep the complexity to a minimum
newDirectIn = alloc.directBuffer(readableBytes);
newDirectIn.writeBytes(in, readerIndex, readableBytes);
in0 = singleBuffer;
in0[0] = newDirectIn.internalNioBuffer(newDirectIn.readerIndex(), readableBytes);
}
for (;;) {
ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
SSLEngineResult result = engine.wrap(in0, out0);
in.skipBytes(result.bytesConsumed());
out.writerIndex(out.writerIndex() + result.bytesProduced());
switch (result.getStatus()) {
case BUFFER_OVERFLOW:
out.ensureWritable(maxPacketBufferSize);
break;
default:
return result;
}
}
} finally {
// Null out to allow GC of ByteBuffer
singleBuffer[0] = null;
if (newDirectIn != null) {
newDirectIn.release();
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// Make sure to release SSLEngine,
// and notify the handshake future if the connection has been closed during handshake.
setHandshakeFailure(ctx, CHANNEL_CLOSED, !outboundClosed);
// Ensure we always notify the sslClosePromise as well
notifyClosePromise(CHANNEL_CLOSED);
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (ignoreException(cause)) {
// It is safe to ignore the 'connection reset by peer' or
// 'broken pipe' error after sending close_notify.
if (logger.isDebugEnabled()) {
logger.debug(
"{} Swallowing a harmless 'connection reset by peer / broken pipe' error that occurred " +
"while writing close_notify in response to the peer's close_notify", ctx.channel(), cause);
}
// Close the connection explicitly just in case the transport
// did not close the connection automatically.
if (ctx.channel().isActive()) {
ctx.close();
}
} else {
ctx.fireExceptionCaught(cause);
}
}
/**
* Checks if the given {@link Throwable} can be ignore and just "swallowed"
*
* When an ssl connection is closed a close_notify message is sent.
* After that the peer also sends close_notify however, it's not mandatory to receive
* the close_notify. The party who sent the initial close_notify can close the connection immediately
* then the peer will get connection reset error.
*
*/
private boolean ignoreException(Throwable t) {
if (!(t instanceof SSLException) && t instanceof IOException && sslClosePromise.isDone()) {
String message = t.getMessage();
// first try to match connection reset / broke peer based on the regex. This is the fastest way
// but may fail on different jdk impls or OS's
if (message != null && IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
return true;
}
// Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not
StackTraceElement[] elements = t.getStackTrace();
for (StackTraceElement element: elements) {
String classname = element.getClassName();
String methodname = element.getMethodName();
// skip all classes that belong to the io.netty package
if (classname.startsWith("io.netty.")) {
continue;
}
// check if the method name is read if not skip it
if (!"read".equals(methodname)) {
continue;
}
// This will also match against SocketInputStream which is used by openjdk 7 and maybe
// also others
if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) {
return true;
}
try {
// No match by now.. Try to load the class via classloader and inspect it.
// This is mainly done as other JDK implementations may differ in name of
// the impl.
Class<?> clazz = PlatformDependent.getClassLoader(getClass()).loadClass(classname);
if (SocketChannel.class.isAssignableFrom(clazz)
|| DatagramChannel.class.isAssignableFrom(clazz)) {
return true;
}
// also match against SctpChannel via String matching as it may not present.
if (PlatformDependent.javaVersion() >= 7
&& "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) {
return true;
}
} catch (Throwable cause) {
logger.debug("Unexpected exception while loading class {} classname {}",
getClass(), classname, cause);
}
}
}
return false;
}
/**
* Returns {@code true} if the given {@link ByteBuf} is encrypted. Be aware that this method
* will not increase the readerIndex of the given {@link ByteBuf}.
*
* @param buffer
* The {@link ByteBuf} to read from. Be aware that it must have at least 5 bytes to read,
* otherwise it will throw an {@link IllegalArgumentException}.
* @return encrypted
* {@code true} if the {@link ByteBuf} is encrypted, {@code false} otherwise.
* @throws IllegalArgumentException
* Is thrown if the given {@link ByteBuf} has not at least 5 bytes to read.
*/
public static boolean isEncrypted(ByteBuf buffer) {
if (buffer.readableBytes() < SslUtils.SSL_RECORD_HEADER_LENGTH) {
throw new IllegalArgumentException(
"buffer must have at least " + SslUtils.SSL_RECORD_HEADER_LENGTH + " readable bytes");
}
return getEncryptedPacketLength(buffer, buffer.readerIndex()) != SslUtils.NOT_ENCRYPTED;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws SSLException {
final int startOffset = in.readerIndex();
final int endOffset = in.writerIndex();
int offset = startOffset;
int totalLength = 0;
// If we calculated the length of the current SSL record before, use that information.
if (packetLength > 0) {
if (endOffset - startOffset < packetLength) {
return;
} else {
offset += packetLength;
totalLength = packetLength;
packetLength = 0;
}
}
boolean nonSslRecord = false;
while (totalLength < ReferenceCountedOpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
final int readableBytes = endOffset - offset;
if (readableBytes < SslUtils.SSL_RECORD_HEADER_LENGTH) {
break;
}
final int packetLength = getEncryptedPacketLength(in, offset);
if (packetLength == SslUtils.NOT_ENCRYPTED) {
nonSslRecord = true;
break;
}
assert packetLength > 0;
if (packetLength > readableBytes) {
// wait until the whole packet can be read
this.packetLength = packetLength;
break;
}
int newTotalLength = totalLength + packetLength;
if (newTotalLength > ReferenceCountedOpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
// Don't read too much.
break;
}
// We have a whole packet.
// Increment the offset to handle the next packet.
offset += packetLength;
totalLength = newTotalLength;
}
if (totalLength > 0) {
// The buffer contains one or more full SSL records.
// Slice out the whole packet so unwrap will only be called with complete packets.
// Also directly reset the packetLength. This is needed as unwrap(..) may trigger
// decode(...) again via:
// 1) unwrap(..) is called
// 2) wrap(...) is called from within unwrap(...)
// 3) wrap(...) calls unwrapLater(...)
// 4) unwrapLater(...) calls decode(...)
//
// See https://github.com/netty/netty/issues/1534
in.skipBytes(totalLength);
try {
firedChannelRead = unwrap(ctx, in, startOffset, totalLength) || firedChannelRead;
} catch (Throwable cause) {
try {
// We need to flush one time as there may be an alert that we should send to the remote peer because
// of the SSLException reported here.
wrapAndFlush(ctx);
} catch (SSLException ex) {
logger.debug("SSLException during trying to call SSLEngine.wrap(...)" +
" because of an previous SSLException, ignoring...", ex);
} finally {
setHandshakeFailure(ctx, cause);
}
PlatformDependent.throwException(cause);
}
}
if (nonSslRecord) {
// Not an SSL/TLS packet
NotSslRecordException e = new NotSslRecordException(
"not an SSL/TLS record: " + ByteBufUtil.hexDump(in));
in.skipBytes(in.readableBytes());
// First fail the handshake promise as we may need to have access to the SSLEngine which may
// be released because the user will remove the SslHandler in an exceptionCaught(...) implementation.
setHandshakeFailure(ctx, e);
throw e;
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// Discard bytes of the cumulation buffer if needed.
discardSomeReadBytes();
flushIfNeeded(ctx);
readIfNeeded(ctx);
firedChannelRead = false;
ctx.fireChannelReadComplete();
}
private void readIfNeeded(ChannelHandlerContext ctx) {
// If handshake is not finished yet, we need more data.
if (!ctx.channel().config().isAutoRead() && (!firedChannelRead || !handshakePromise.isDone())) {
// No auto-read used and no message passed through the ChannelPipeline or the handshake was not complete
// yet, which means we need to trigger the read to ensure we not encounter any stalls.
ctx.read();
}
}
private void flushIfNeeded(ChannelHandlerContext ctx) {
if (needsFlush) {
forceFlush(ctx);
}
}
/**
* Calls {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} with an empty buffer to handle handshakes, etc.
*/
private void unwrapNonAppData(ChannelHandlerContext ctx) throws SSLException {
unwrap(ctx, Unpooled.EMPTY_BUFFER, 0, 0);
}
/**
* Unwraps inbound SSL records.
*/
private boolean unwrap(
ChannelHandlerContext ctx, ByteBuf packet, int offset, int length) throws SSLException {
boolean decoded = false;
boolean wrapLater = false;
boolean notifyClosure = false;
ByteBuf decodeOut = allocate(ctx, length);
try {
// Only continue to loop if the handler was not removed in the meantime.
// See https://github.com/netty/netty/issues/5860
while (!ctx.isRemoved()) {
final SSLEngineResult result = engineType.unwrap(this, packet, offset, length, decodeOut);
final Status status = result.getStatus();
final HandshakeStatus handshakeStatus = result.getHandshakeStatus();
final int produced = result.bytesProduced();
final int consumed = result.bytesConsumed();
// Update indexes for the next iteration
offset += consumed;
length -= consumed;
switch (status) {
case BUFFER_OVERFLOW:
int readableBytes = decodeOut.readableBytes();
int bufferSize = engine.getSession().getApplicationBufferSize() - readableBytes;
if (readableBytes > 0) {
decoded = true;
ctx.fireChannelRead(decodeOut);
// This buffer was handled, null it out.
decodeOut = null;
if (bufferSize <= 0) {
// It may happen that readableBytes >= engine.getSession().getApplicationBufferSize()
// while there is still more to unwrap, in this case we will just allocate a new buffer
// with the capacity of engine.getSession().getApplicationBufferSize() and call unwrap
// again.
bufferSize = engine.getSession().getApplicationBufferSize();
}
} else {
// This buffer was handled, null it out.
decodeOut.release();
decodeOut = null;
}
// Allocate a new buffer which can hold all the rest data and loop again.
// TODO: We may want to reconsider how we calculate the length here as we may
// have more then one ssl message to decode.
decodeOut = allocate(ctx, bufferSize);
continue;
case CLOSED:
// notify about the CLOSED state of the SSLEngine. See #137
notifyClosure = true;
break;
default:
break;
}
switch (handshakeStatus) {
case NEED_UNWRAP:
break;
case NEED_WRAP:
wrapNonAppData(ctx, true);
break;
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
setHandshakeSuccess();
wrapLater = true;
// We 'break' here and NOT 'continue' as android API version 21 has a bug where they consume
// data from the buffer but NOT correctly set the SSLEngineResult.bytesConsumed().
// Because of this it will raise an exception on the next iteration of the for loop on android
// API version 21. Just doing a break will work here as produced and consumed will both be 0
// and so we break out of the complete for (;;) loop and so call decode(...) again later on.
// On other platforms this will have no negative effect as we will just continue with the
// for (;;) loop if something was either consumed or produced.
//
// See:
// - https://github.com/netty/netty/issues/4116
// - https://code.google.com/p/android/issues/detail?id=198639&thanks=198639&ts=1452501203
break;
case NOT_HANDSHAKING:
if (setHandshakeSuccessIfStillHandshaking()) {
wrapLater = true;
continue;
}
if (flushedBeforeHandshake) {
// We need to call wrap(...) in case there was a flush done before the handshake completed.
//
// See https://github.com/netty/netty/pull/2437
flushedBeforeHandshake = false;
wrapLater = true;
}
break;
default:
throw new IllegalStateException("unknown handshake status: " + handshakeStatus);
}
if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) {
if (handshakeStatus == HandshakeStatus.NEED_UNWRAP) {
// The underlying engine is starving so we need to feed it with more data.
// See https://github.com/netty/netty/pull/5039
readIfNeeded(ctx);
}
break;
}
}
if (wrapLater) {
wrap(ctx, true);
}
if (notifyClosure) {
notifyClosePromise(null);
}
} finally {
if (decodeOut != null) {
if (decodeOut.isReadable()) {
decoded = true;
ctx.fireChannelRead(decodeOut);
} else {
decodeOut.release();
}
}
}
return decoded;
}
private static ByteBuffer toByteBuffer(ByteBuf out, int index, int len) {
return out.nioBufferCount() == 1 ? out.internalNioBuffer(index, len) :
out.nioBuffer(index, len);
}
/**
* Fetches all delegated tasks from the {@link SSLEngine} and runs them via the {@link #delegatedTaskExecutor}.
* If the {@link #delegatedTaskExecutor} is {@link ImmediateExecutor}, just call {@link Runnable#run()} directly
* instead of using {@link Executor#execute(Runnable)}. Otherwise, run the tasks via
* the {@link #delegatedTaskExecutor} and wait until the tasks are finished.
*/
private void runDelegatedTasks() {
if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE) {
for (;;) {
Runnable task = engine.getDelegatedTask();
if (task == null) {
break;
}
task.run();
}
} else {
final List<Runnable> tasks = new ArrayList<Runnable>(2);
for (;;) {
final Runnable task = engine.getDelegatedTask();
if (task == null) {
break;
}
tasks.add(task);
}
if (tasks.isEmpty()) {
return;
}
final CountDownLatch latch = new CountDownLatch(1);
delegatedTaskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (Runnable task: tasks) {
task.run();
}
} catch (Exception e) {
ctx.fireExceptionCaught(e);
} finally {
latch.countDown();
}
}
});
boolean interrupted = false;
while (latch.getCount() != 0) {
try {
latch.await();
} catch (InterruptedException e) {
// Interrupt later.
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Works around some Android {@link SSLEngine} implementations that skip {@link HandshakeStatus#FINISHED} and
* go straight into {@link HandshakeStatus#NOT_HANDSHAKING} when handshake is finished.
*
* @return {@code true} if and only if the workaround has been applied and thus {@link #handshakeFuture} has been
* marked as success by this method
*/
private boolean setHandshakeSuccessIfStillHandshaking() {
if (!handshakePromise.isDone()) {
setHandshakeSuccess();
return true;
}
return false;
}
/**
* Notify all the handshake futures about the successfully handshake
*/
private void setHandshakeSuccess() {
handshakePromise.trySuccess(ctx.channel());
if (logger.isDebugEnabled()) {
logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite());
}
ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
if (readDuringHandshake && !ctx.channel().config().isAutoRead()) {
readDuringHandshake = false;
ctx.read();
}
}
/**
* Notify all the handshake futures about the failure during the handshake.
*/
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) {
setHandshakeFailure(ctx, cause, true);
}
/**
* Notify all the handshake futures about the failure during the handshake.
*/
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound) {
try {
// Release all resources such as internal buffers that SSLEngine
// is managing.
engine.closeOutbound();
if (closeInbound) {
try {
engine.closeInbound();
} catch (SSLException e) {
// only log in debug mode as it most likely harmless and latest chrome still trigger
// this all the time.
//
// See https://github.com/netty/netty/issues/1340
String msg = e.getMessage();
if (msg == null || !msg.contains("possible truncation attack")) {
logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
}
}
}
notifyHandshakeFailure(cause);
} finally {
// Ensure we remove and fail all pending writes in all cases and so release memory quickly.
pendingUnencryptedWrites.removeAndFailAll(cause);
}
}
private void notifyHandshakeFailure(Throwable cause) {
if (handshakePromise.tryFailure(cause)) {
SslUtils.notifyHandshakeFailure(ctx, cause);
}
}
private void notifyClosePromise(Throwable cause) {
if (cause == null) {
if (sslClosePromise.trySuccess(ctx.channel())) {
ctx.fireUserEventTriggered(SslCloseCompletionEvent.SUCCESS);
}
} else {
if (sslClosePromise.tryFailure(cause)) {
ctx.fireUserEventTriggered(new SslCloseCompletionEvent(cause));
}
}
}
private void closeOutboundAndChannel(
final ChannelHandlerContext ctx, final ChannelPromise promise, boolean disconnect) throws Exception {
if (!ctx.channel().isActive()) {
if (disconnect) {
ctx.disconnect(promise);
} else {
ctx.close(promise);
}
return;
}
outboundClosed = true;
engine.closeOutbound();
ChannelPromise closeNotifyPromise = ctx.newPromise();
try {
flush(ctx, closeNotifyPromise);
} finally {
// It's important that we do not pass the original ChannelPromise to safeClose(...) as when flush(....)
// throws an Exception it will be propagated to the AbstractChannelHandlerContext which will try
// to fail the promise because of this. This will then fail as it was already completed by safeClose(...).
// We create a new ChannelPromise and try to notify the original ChannelPromise
// once it is complete. If we fail to do so we just ignore it as in this case it was failed already
// because of a propagated Exception.
//
// See https://github.com/netty/netty/issues/5931
safeClose(ctx, closeNotifyPromise, ctx.newPromise().addListener(
new ChannelPromiseNotifier(false, promise)));
}
}
private void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, promise);
flush(ctx);
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
pendingUnencryptedWrites = new PendingWriteQueue(ctx);
if (ctx.channel().isActive() && engine.getUseClientMode()) {
// Begin the initial handshake.
// channelActive() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
handshake(null);
} else {
// channelActive() event has not been fired yet. this.channelOpen() will be invoked
// and initialization will occur there.
}
}
/**
* Performs TLS renegotiation.
*/
public Future<Channel> renegotiate() {
ChannelHandlerContext ctx = this.ctx;
if (ctx == null) {
throw new IllegalStateException();
}
return renegotiate(ctx.executor().<Channel>newPromise());
}
/**
* Performs TLS renegotiation.
*/
public Future<Channel> renegotiate(final Promise<Channel> promise) {
if (promise == null) {
throw new NullPointerException("promise");
}
ChannelHandlerContext ctx = this.ctx;
if (ctx == null) {
throw new IllegalStateException();
}
EventExecutor executor = ctx.executor();
if (!executor.inEventLoop()) {
executor.execute(new Runnable() {
@Override
public void run() {
handshake(promise);
}
});
return promise;
}
handshake(promise);
return promise;
}
/**
* Performs TLS (re)negotiation.
*
* @param newHandshakePromise if {@code null}, use the existing {@link #handshakePromise},
* assuming that the current negotiation has not been finished.
* Currently, {@code null} is expected only for the initial handshake.
*/
private void handshake(final Promise<Channel> newHandshakePromise) {
final Promise<Channel> p;
if (newHandshakePromise != null) {
final Promise<Channel> oldHandshakePromise = handshakePromise;
if (!oldHandshakePromise.isDone()) {
// There's no need to handshake because handshake is in progress already.
// Merge the new promise into the old one.
oldHandshakePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
if (future.isSuccess()) {
newHandshakePromise.setSuccess(future.getNow());
} else {
newHandshakePromise.setFailure(future.cause());
}
}
});
return;
}
handshakePromise = p = newHandshakePromise;
} else if (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
// Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake
// is in progress. See https://github.com/netty/netty/issues/4718.
return;
} else {
// Forced to reuse the old handshake.
p = handshakePromise;
assert !p.isDone();
}
// Begin handshake.
final ChannelHandlerContext ctx = this.ctx;
try {
engine.beginHandshake();
wrapNonAppData(ctx, false);
} catch (Throwable e) {
setHandshakeFailure(ctx, e);
} finally {
forceFlush(ctx);
}
// Set timeout if necessary.
final long handshakeTimeoutMillis = this.handshakeTimeoutMillis;
if (handshakeTimeoutMillis <= 0 || p.isDone()) {
return;
}
final ScheduledFuture<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (p.isDone()) {
return;
}
notifyHandshakeFailure(HANDSHAKE_TIMED_OUT);
}
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished.
p.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> f) throws Exception {
timeoutFuture.cancel(false);
}
});
}
private void forceFlush(ChannelHandlerContext ctx) {
needsFlush = false;
ctx.flush();
}
/**
* Issues an initial TLS handshake once connected when used in client-mode
*/
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
if (!startTls && engine.getUseClientMode()) {
// Begin the initial handshake
handshake(null);
}
ctx.fireChannelActive();
}
private void safeClose(
final ChannelHandlerContext ctx, final ChannelFuture flushFuture,
final ChannelPromise promise) {
if (!ctx.channel().isActive()) {
ctx.close(promise);
return;
}
final ScheduledFuture<?> timeoutFuture;
if (!flushFuture.isDone()) {
long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
if (closeNotifyTimeout > 0) {
// Force-close the connection if close_notify is not fully sent in time.
timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
// May be done in the meantime as cancel(...) is only best effort.
if (!flushFuture.isDone()) {
logger.warn("{} Last write attempt timed out; force-closing the connection.",
ctx.channel());
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyTimeout, TimeUnit.MILLISECONDS);
} else {
timeoutFuture = null;
}
} else {
timeoutFuture = null;
}
// Close the connection if close_notify is sent in time.
flushFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f)
throws Exception {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
if (closeNotifyReadTimeout <= 0) {
// Trigger the close in all cases to make sure the promise is notified
// See https://github.com/netty/netty/issues/2358
addCloseListener(ctx.close(ctx.newPromise()), promise);
} else {
final ScheduledFuture<?> closeNotifyReadTimeoutFuture;
if (!sslClosePromise.isDone()) {
closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (!sslClosePromise.isDone()) {
logger.debug(
"{} did not receive close_notify in {}ms; force-closing the connection.",
ctx.channel(), closeNotifyReadTimeout);
// Do the close now...
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
} else {
closeNotifyReadTimeoutFuture = null;
}
// Do the close once the we received the close_notify.
sslClosePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
if (closeNotifyReadTimeoutFuture != null) {
closeNotifyReadTimeoutFuture.cancel(false);
}
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
});
}
}
});
}
private static void addCloseListener(ChannelFuture future, ChannelPromise promise) {
// We notify the promise in the ChannelPromiseNotifier as there is a "race" where the close(...) call
// by the timeoutFuture and the close call in the flushFuture listener will be called. Because of
// this we need to use trySuccess() and tryFailure(...) as otherwise we can cause an
// IllegalStateException.
// Also we not want to log if the notification happens as this is expected in some cases.
// See https://github.com/netty/netty/issues/5598
future.addListener(new ChannelPromiseNotifier(false, promise));
}
/**
* Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies
* in {@link OpenSslEngine}.
*/
private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
ByteBufAllocator alloc = ctx.alloc();
if (engineType.wantsDirectBuffer) {
return alloc.directBuffer(capacity);
} else {
return alloc.buffer(capacity);
}
}
/**
* Allocates an outbound network buffer for {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} which can encrypt
* the specified amount of pending bytes.
*/
private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) {
return allocate(ctx, engineType.calculateWrapBufferCapacity(this, pendingBytes, numComponents));
}
private final class LazyChannelPromise extends DefaultPromise<Channel> {
@Override
protected EventExecutor executor() {
if (ctx == null) {
throw new IllegalStateException();
}
return ctx.executor();
}
@Override
protected void checkDeadLock() {
if (ctx == null) {
// If ctx is null the handlerAdded(...) callback was not called, in this case the checkDeadLock()
// method was called from another Thread then the one that is used by ctx.executor(). We need to
// guard against this as a user can see a race if handshakeFuture().sync() is called but the
// handlerAdded(..) method was not yet as it is called from the EventExecutor of the
// ChannelHandlerContext. If we not guard against this super.checkDeadLock() would cause an
// IllegalStateException when trying to call executor().
return;
}
super.checkDeadLock();
}
}
}
| handler/src/main/java/io/netty/handler/ssl/SslHandler.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelPromiseNotifier;
import io.netty.channel.PendingWriteQueue;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.ImmediateExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ThrowableUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength;
/**
* Adds <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">SSL
* · TLS</a> and StartTLS support to a {@link Channel}. Please refer
* to the <strong>"SecureChat"</strong> example in the distribution or the web
* site for the detailed usage.
*
* <h3>Beginning the handshake</h3>
* <p>
* Beside using the handshake {@link ChannelFuture} to get notified about the completion of the handshake it's
* also possible to detect it by implement the
* {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)}
* method and check for a {@link SslHandshakeCompletionEvent}.
*
* <h3>Handshake</h3>
* <p>
* The handshake will be automatically issued for you once the {@link Channel} is active and
* {@link SSLEngine#getUseClientMode()} returns {@code true}.
* So no need to bother with it by your self.
*
* <h3>Closing the session</h3>
* <p>
* To close the SSL session, the {@link #close()} method should be
* called to send the {@code close_notify} message to the remote peer. One
* exception is when you close the {@link Channel} - {@link SslHandler}
* intercepts the close request and send the {@code close_notify} message
* before the channel closure automatically. Once the SSL session is closed,
* it is not reusable, and consequently you should create a new
* {@link SslHandler} with a new {@link SSLEngine} as explained in the
* following section.
*
* <h3>Restarting the session</h3>
* <p>
* To restart the SSL session, you must remove the existing closed
* {@link SslHandler} from the {@link ChannelPipeline}, insert a new
* {@link SslHandler} with a new {@link SSLEngine} into the pipeline,
* and start the handshake process as described in the first section.
*
* <h3>Implementing StartTLS</h3>
* <p>
* <a href="http://en.wikipedia.org/wiki/STARTTLS">StartTLS</a> is the
* communication pattern that secures the wire in the middle of the plaintext
* connection. Please note that it is different from SSL · TLS, that
* secures the wire from the beginning of the connection. Typically, StartTLS
* is composed of three steps:
* <ol>
* <li>Client sends a StartTLS request to server.</li>
* <li>Server sends a StartTLS response to client.</li>
* <li>Client begins SSL handshake.</li>
* </ol>
* If you implement a server, you need to:
* <ol>
* <li>create a new {@link SslHandler} instance with {@code startTls} flag set
* to {@code true},</li>
* <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li>
* <li>write a StartTLS response.</li>
* </ol>
* Please note that you must insert {@link SslHandler} <em>before</em> sending
* the StartTLS response. Otherwise the client can send begin SSL handshake
* before {@link SslHandler} is inserted to the {@link ChannelPipeline}, causing
* data corruption.
* <p>
* The client-side implementation is much simpler.
* <ol>
* <li>Write a StartTLS request,</li>
* <li>wait for the StartTLS response,</li>
* <li>create a new {@link SslHandler} instance with {@code startTls} flag set
* to {@code false},</li>
* <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li>
* <li>Initiate SSL handshake.</li>
* </ol>
*
* <h3>Known issues</h3>
* <p>
* Because of a known issue with the current implementation of the SslEngine that comes
* with Java it may be possible that you see blocked IO-Threads while a full GC is done.
* <p>
* So if you are affected you can workaround this problem by adjust the cache settings
* like shown below:
*
* <pre>
* SslContext context = ...;
* context.getServerSessionContext().setSessionCacheSize(someSaneSize);
* context.getServerSessionContext().setSessionTime(someSameTimeout);
* </pre>
* <p>
* What values to use here depends on the nature of your application and should be set
* based on monitoring and debugging of it.
* For more details see
* <a href="https://github.com/netty/netty/issues/832">#832</a> in our issue tracker.
*/
public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundHandler {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(SslHandler.class);
private static final Pattern IGNORABLE_CLASS_IN_STACK = Pattern.compile(
"^.*(?:Socket|Datagram|Sctp|Udt)Channel.*$");
private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile(
"^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", Pattern.CASE_INSENSITIVE);
/**
* Used in {@link #unwrapNonAppData(ChannelHandlerContext)} as input for
* {@link #unwrap(ChannelHandlerContext, ByteBuf, int, int)}. Using this static instance reduce object
* creation as {@link Unpooled#EMPTY_BUFFER#nioBuffer()} creates a new {@link ByteBuffer} everytime.
*/
private static final SSLException SSLENGINE_CLOSED = ThrowableUtil.unknownStackTrace(
new SSLException("SSLEngine closed already"), SslHandler.class, "wrap(...)");
private static final SSLException HANDSHAKE_TIMED_OUT = ThrowableUtil.unknownStackTrace(
new SSLException("handshake timed out"), SslHandler.class, "handshake(...)");
private static final ClosedChannelException CHANNEL_CLOSED = ThrowableUtil.unknownStackTrace(
new ClosedChannelException(), SslHandler.class, "channelInactive(...)");
private enum SslEngineType {
TCNATIVE(true, COMPOSITE_CUMULATOR) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException {
int nioBufferCount = in.nioBufferCount();
int writerIndex = out.writerIndex();
final SSLEngineResult result;
if (nioBufferCount > 1) {
/*
* If {@link OpenSslEngine} is in use,
* we can use a special {@link OpenSslEngine#unwrap(ByteBuffer[], ByteBuffer[])} method
* that accepts multiple {@link ByteBuffer}s without additional memory copies.
*/
ReferenceCountedOpenSslEngine opensslEngine = (ReferenceCountedOpenSslEngine) handler.engine;
try {
handler.singleBuffer[0] = toByteBuffer(out, writerIndex,
out.writableBytes());
result = opensslEngine.unwrap(in.nioBuffers(readerIndex, len), handler.singleBuffer);
} finally {
handler.singleBuffer[0] = null;
}
} else {
result = handler.engine.unwrap(toByteBuffer(in, readerIndex, len),
toByteBuffer(out, writerIndex, out.writableBytes()));
}
out.writerIndex(writerIndex + result.bytesProduced());
return result;
}
@Override
int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents) {
return ReferenceCountedOpenSslEngine.calculateOutNetBufSize(pendingBytes, numComponents);
}
},
CONSCRYPT(true, COMPOSITE_CUMULATOR) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException {
int nioBufferCount = in.nioBufferCount();
int writerIndex = out.writerIndex();
final SSLEngineResult result;
if (nioBufferCount > 1) {
/*
* Use a special unwrap method without additional memory copies.
*/
try {
handler.singleBuffer[0] = toByteBuffer(out, writerIndex, out.writableBytes());
result = ((ConscryptAlpnSslEngine) handler.engine).unwrap(
in.nioBuffers(readerIndex, len),
handler.singleBuffer);
} finally {
handler.singleBuffer[0] = null;
}
} else {
result = handler.engine.unwrap(toByteBuffer(in, readerIndex, len),
toByteBuffer(out, writerIndex, out.writableBytes()));
}
out.writerIndex(writerIndex + result.bytesProduced());
return result;
}
@Override
int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents) {
return ((ConscryptAlpnSslEngine) handler.engine).calculateOutNetBufSize(pendingBytes, numComponents);
}
},
JDK(false, MERGE_CUMULATOR) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException {
int writerIndex = out.writerIndex();
final SSLEngineResult result = handler.engine.unwrap(toByteBuffer(in, readerIndex, len),
toByteBuffer(out, writerIndex, out.writableBytes()));
out.writerIndex(writerIndex + result.bytesProduced());
return result;
}
@Override
int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents) {
return handler.maxPacketBufferSize;
}
};
static SslEngineType forEngine(SSLEngine engine) {
if (engine instanceof ReferenceCountedOpenSslEngine) {
return TCNATIVE;
}
if (engine instanceof ConscryptAlpnSslEngine) {
return CONSCRYPT;
}
return JDK;
}
SslEngineType(boolean wantsDirectBuffer, Cumulator cumulator) {
this.wantsDirectBuffer = wantsDirectBuffer;
this.cumulator = cumulator;
}
abstract SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int readerIndex, int len, ByteBuf out)
throws SSLException;
abstract int calculateWrapBufferCapacity(SslHandler handler, int pendingBytes, int numComponents);
// BEGIN Platform-dependent flags
/**
* {@code true} if and only if {@link SSLEngine} expects a direct buffer.
*/
final boolean wantsDirectBuffer;
// END Platform-dependent flags
/**
* When using JDK {@link SSLEngine}, we use {@link #MERGE_CUMULATOR} because it works only with
* one {@link ByteBuffer}.
*
* When using {@link OpenSslEngine}, we can use {@link #COMPOSITE_CUMULATOR} because it has
* {@link OpenSslEngine#unwrap(ByteBuffer[], ByteBuffer[])} which works with multiple {@link ByteBuffer}s
* and which does not need to do extra memory copies.
*/
final Cumulator cumulator;
}
private volatile ChannelHandlerContext ctx;
private final SSLEngine engine;
private final SslEngineType engineType;
private final int maxPacketBufferSize;
private final Executor delegatedTaskExecutor;
/**
* Used if {@link SSLEngine#wrap(ByteBuffer[], ByteBuffer)} and {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer[])}
* should be called with a {@link ByteBuf} that is only backed by one {@link ByteBuffer} to reduce the object
* creation.
*/
private final ByteBuffer[] singleBuffer = new ByteBuffer[1];
private final boolean startTls;
private boolean sentFirstMessage;
private boolean flushedBeforeHandshake;
private boolean readDuringHandshake;
private PendingWriteQueue pendingUnencryptedWrites;
private Promise<Channel> handshakePromise = new LazyChannelPromise();
private final LazyChannelPromise sslClosePromise = new LazyChannelPromise();
/**
* Set by wrap*() methods when something is produced.
* {@link #channelReadComplete(ChannelHandlerContext)} will check this flag, clear it, and call ctx.flush().
*/
private boolean needsFlush;
private boolean outboundClosed;
private int packetLength;
/**
* This flag is used to determine if we need to call {@link ChannelHandlerContext#read()} to consume more data
* when {@link ChannelConfig#isAutoRead()} is {@code false}.
*/
private boolean firedChannelRead;
private volatile long handshakeTimeoutMillis = 10000;
private volatile long closeNotifyFlushTimeoutMillis = 3000;
private volatile long closeNotifyReadTimeoutMillis;
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
*/
public SslHandler(SSLEngine engine) {
this(engine, false);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param startTls {@code true} if the first write request shouldn't be
* encrypted by the {@link SSLEngine}
*/
@SuppressWarnings("deprecation")
public SslHandler(SSLEngine engine, boolean startTls) {
this(engine, startTls, ImmediateExecutor.INSTANCE);
}
/**
* @deprecated Use {@link #SslHandler(SSLEngine)} instead.
*/
@Deprecated
public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) {
this(engine, false, delegatedTaskExecutor);
}
/**
* @deprecated Use {@link #SslHandler(SSLEngine, boolean)} instead.
*/
@Deprecated
public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) {
if (engine == null) {
throw new NullPointerException("engine");
}
if (delegatedTaskExecutor == null) {
throw new NullPointerException("delegatedTaskExecutor");
}
this.engine = engine;
engineType = SslEngineType.forEngine(engine);
this.delegatedTaskExecutor = delegatedTaskExecutor;
this.startTls = startTls;
maxPacketBufferSize = engine.getSession().getPacketBufferSize();
setCumulator(engineType.cumulator);
}
public long getHandshakeTimeoutMillis() {
return handshakeTimeoutMillis;
}
public void setHandshakeTimeout(long handshakeTimeout, TimeUnit unit) {
if (unit == null) {
throw new NullPointerException("unit");
}
setHandshakeTimeoutMillis(unit.toMillis(handshakeTimeout));
}
public void setHandshakeTimeoutMillis(long handshakeTimeoutMillis) {
if (handshakeTimeoutMillis < 0) {
throw new IllegalArgumentException(
"handshakeTimeoutMillis: " + handshakeTimeoutMillis + " (expected: >= 0)");
}
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
}
/**
* @deprecated use {@link #getCloseNotifyFlushTimeoutMillis()}
*/
@Deprecated
public long getCloseNotifyTimeoutMillis() {
return getCloseNotifyFlushTimeoutMillis();
}
/**
* @deprecated use {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}
*/
@Deprecated
public void setCloseNotifyTimeout(long closeNotifyTimeout, TimeUnit unit) {
setCloseNotifyFlushTimeout(closeNotifyTimeout, unit);
}
/**
* @deprecated use {@link #setCloseNotifyFlushTimeoutMillis(long)}
*/
@Deprecated
public void setCloseNotifyTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
setCloseNotifyFlushTimeoutMillis(closeNotifyFlushTimeoutMillis);
}
/**
* Gets the timeout for flushing the close_notify that was triggered by closing the
* {@link Channel}. If the close_notify was not flushed in the given timeout the {@link Channel} will be closed
* forcibly.
*/
public final long getCloseNotifyFlushTimeoutMillis() {
return closeNotifyFlushTimeoutMillis;
}
/**
* Sets the timeout for flushing the close_notify that was triggered by closing the
* {@link Channel}. If the close_notify was not flushed in the given timeout the {@link Channel} will be closed
* forcibly.
*/
public final void setCloseNotifyFlushTimeout(long closeNotifyFlushTimeout, TimeUnit unit) {
setCloseNotifyFlushTimeoutMillis(unit.toMillis(closeNotifyFlushTimeout));
}
/**
* See {@link #setCloseNotifyFlushTimeout(long, TimeUnit)}.
*/
public final void setCloseNotifyFlushTimeoutMillis(long closeNotifyFlushTimeoutMillis) {
if (closeNotifyFlushTimeoutMillis < 0) {
throw new IllegalArgumentException(
"closeNotifyFlushTimeoutMillis: " + closeNotifyFlushTimeoutMillis + " (expected: >= 0)");
}
this.closeNotifyFlushTimeoutMillis = closeNotifyFlushTimeoutMillis;
}
/**
* Gets the timeout (in ms) for receiving the response for the close_notify that was triggered by closing the
* {@link Channel}. This timeout starts after the close_notify message was successfully written to the
* remote peer. Use {@code 0} to directly close the {@link Channel} and not wait for the response.
*/
public final long getCloseNotifyReadTimeoutMillis() {
return closeNotifyReadTimeoutMillis;
}
/**
* Sets the timeout for receiving the response for the close_notify that was triggered by closing the
* {@link Channel}. This timeout starts after the close_notify message was successfully written to the
* remote peer. Use {@code 0} to directly close the {@link Channel} and not wait for the response.
*/
public final void setCloseNotifyReadTimeout(long closeNotifyReadTimeout, TimeUnit unit) {
setCloseNotifyReadTimeoutMillis(unit.toMillis(closeNotifyReadTimeout));
}
/**
* See {@link #setCloseNotifyReadTimeout(long, TimeUnit)}.
*/
public final void setCloseNotifyReadTimeoutMillis(long closeNotifyReadTimeoutMillis) {
if (closeNotifyReadTimeoutMillis < 0) {
throw new IllegalArgumentException(
"closeNotifyReadTimeoutMillis: " + closeNotifyReadTimeoutMillis + " (expected: >= 0)");
}
this.closeNotifyReadTimeoutMillis = closeNotifyReadTimeoutMillis;
}
/**
* Returns the {@link SSLEngine} which is used by this handler.
*/
public SSLEngine engine() {
return engine;
}
/**
* Returns the name of the current application-level protocol.
*
* @return the protocol name or {@code null} if application-level protocol has not been negotiated
*/
public String applicationProtocol() {
SSLSession sess = engine().getSession();
if (!(sess instanceof ApplicationProtocolAccessor)) {
return null;
}
return ((ApplicationProtocolAccessor) sess).getApplicationProtocol();
}
/**
* Returns a {@link Future} that will get notified once the current TLS handshake completes.
*
* @return the {@link Future} for the initial TLS handshake if {@link #renegotiate()} was not invoked.
* The {@link Future} for the most recent {@linkplain #renegotiate() TLS renegotiation} otherwise.
*/
public Future<Channel> handshakeFuture() {
return handshakePromise;
}
/**
* Sends an SSL {@code close_notify} message to the specified channel and
* destroys the underlying {@link SSLEngine}.
*
* @deprecated use {@link Channel#close()} or {@link ChannelHandlerContext#close()}
*/
@Deprecated
public ChannelFuture close() {
return close(ctx.newPromise());
}
/**
* See {@link #close()}
*
* @deprecated use {@link Channel#close()} or {@link ChannelHandlerContext#close()}
*/
@Deprecated
public ChannelFuture close(final ChannelPromise promise) {
final ChannelHandlerContext ctx = this.ctx;
ctx.executor().execute(new Runnable() {
@Override
public void run() {
outboundClosed = true;
engine.closeOutbound();
try {
flush(ctx, promise);
} catch (Exception e) {
if (!promise.tryFailure(e)) {
logger.warn("{} flush() raised a masked exception.", ctx.channel(), e);
}
}
}
});
return promise;
}
/**
* Return the {@link Future} that will get notified if the inbound of the {@link SSLEngine} is closed.
*
* This method will return the same {@link Future} all the time.
*
* @see SSLEngine
*/
public Future<Channel> sslCloseFuture() {
return sslClosePromise;
}
@Override
public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
if (!pendingUnencryptedWrites.isEmpty()) {
// Check if queue is not empty first because create a new ChannelException is expensive
pendingUnencryptedWrites.removeAndFailAll(new ChannelException("Pending write on removal of SslHandler"));
}
if (engine instanceof ReferenceCountedOpenSslEngine) {
((ReferenceCountedOpenSslEngine) engine).release();
}
}
@Override
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
ctx.bind(localAddress, promise);
}
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
ctx.connect(remoteAddress, localAddress, promise);
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
ctx.deregister(promise);
}
@Override
public void disconnect(final ChannelHandlerContext ctx,
final ChannelPromise promise) throws Exception {
closeOutboundAndChannel(ctx, promise, true);
}
@Override
public void close(final ChannelHandlerContext ctx,
final ChannelPromise promise) throws Exception {
closeOutboundAndChannel(ctx, promise, false);
}
@Override
public void read(ChannelHandlerContext ctx) throws Exception {
if (!handshakePromise.isDone()) {
readDuringHandshake = true;
}
ctx.read();
}
@Override
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (!(msg instanceof ByteBuf)) {
promise.setFailure(new UnsupportedMessageTypeException(msg, ByteBuf.class));
return;
}
pendingUnencryptedWrites.add(msg, promise);
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
// Do not encrypt the first write request if this handler is
// created with startTLS flag turned on.
if (startTls && !sentFirstMessage) {
sentFirstMessage = true;
pendingUnencryptedWrites.removeAndWriteAll();
forceFlush(ctx);
return;
}
try {
wrapAndFlush(ctx);
} catch (Throwable cause) {
setHandshakeFailure(ctx, cause);
PlatformDependent.throwException(cause);
}
}
private void wrapAndFlush(ChannelHandlerContext ctx) throws SSLException {
if (pendingUnencryptedWrites.isEmpty()) {
// It's important to NOT use a voidPromise here as the user
// may want to add a ChannelFutureListener to the ChannelPromise later.
//
// See https://github.com/netty/netty/issues/3364
pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, ctx.newPromise());
}
if (!handshakePromise.isDone()) {
flushedBeforeHandshake = true;
}
try {
wrap(ctx, false);
} finally {
// We may have written some parts of data before an exception was thrown so ensure we always flush.
// See https://github.com/netty/netty/issues/3900#issuecomment-172481830
forceFlush(ctx);
}
}
// This method will not call setHandshakeFailure(...) !
private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
ByteBuf out = null;
ChannelPromise promise = null;
ByteBufAllocator alloc = ctx.alloc();
boolean needUnwrap = false;
try {
// Only continue to loop if the handler was not removed in the meantime.
// See https://github.com/netty/netty/issues/5860
while (!ctx.isRemoved()) {
Object msg = pendingUnencryptedWrites.current();
if (msg == null) {
break;
}
ByteBuf buf = (ByteBuf) msg;
if (out == null) {
out = allocateOutNetBuf(ctx, buf.readableBytes(), buf.nioBufferCount());
}
SSLEngineResult result = wrap(alloc, engine, buf, out);
if (result.getStatus() == Status.CLOSED) {
// SSLEngine has been closed already.
// Any further write attempts should be denied.
pendingUnencryptedWrites.removeAndFailAll(SSLENGINE_CLOSED);
return;
} else {
if (!buf.isReadable()) {
promise = pendingUnencryptedWrites.remove();
} else {
promise = null;
}
switch (result.getHandshakeStatus()) {
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
setHandshakeSuccess();
// deliberate fall-through
case NOT_HANDSHAKING:
setHandshakeSuccessIfStillHandshaking();
// deliberate fall-through
case NEED_WRAP:
finishWrap(ctx, out, promise, inUnwrap, false);
promise = null;
out = null;
break;
case NEED_UNWRAP:
needUnwrap = true;
return;
default:
throw new IllegalStateException(
"Unknown handshake status: " + result.getHandshakeStatus());
}
}
}
} finally {
finishWrap(ctx, out, promise, inUnwrap, needUnwrap);
}
}
private void finishWrap(ChannelHandlerContext ctx, ByteBuf out, ChannelPromise promise, boolean inUnwrap,
boolean needUnwrap) {
if (out == null) {
out = Unpooled.EMPTY_BUFFER;
} else if (!out.isReadable()) {
out.release();
out = Unpooled.EMPTY_BUFFER;
}
if (promise != null) {
ctx.write(out, promise);
} else {
ctx.write(out);
}
if (inUnwrap) {
needsFlush = true;
}
if (needUnwrap) {
// The underlying engine is starving so we need to feed it with more data.
// See https://github.com/netty/netty/pull/5039
readIfNeeded(ctx);
}
}
/**
* This method will not call
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean)} or
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}.
* @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}.
*/
private void wrapNonAppData(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
ByteBuf out = null;
ByteBufAllocator alloc = ctx.alloc();
try {
// Only continue to loop if the handler was not removed in the meantime.
// See https://github.com/netty/netty/issues/5860
while (!ctx.isRemoved()) {
if (out == null) {
// As this is called for the handshake we have no real idea how big the buffer needs to be.
// That said 2048 should give us enough room to include everything like ALPN / NPN data.
// If this is not enough we will increase the buffer in wrap(...).
out = allocateOutNetBuf(ctx, 2048, 1);
}
SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out);
if (result.bytesProduced() > 0) {
ctx.write(out);
if (inUnwrap) {
needsFlush = true;
}
out = null;
}
switch (result.getHandshakeStatus()) {
case FINISHED:
setHandshakeSuccess();
break;
case NEED_TASK:
runDelegatedTasks();
break;
case NEED_UNWRAP:
if (inUnwrap) {
// If we asked for a wrap, the engine requested an unwrap, and we are in unwrap there is
// no use in trying to call wrap again because we have already attempted (or will after we
// return) to feed more data to the engine.
return;
}
unwrapNonAppData(ctx);
break;
case NEED_WRAP:
break;
case NOT_HANDSHAKING:
setHandshakeSuccessIfStillHandshaking();
// Workaround for TLS False Start problem reported at:
// https://github.com/netty/netty/issues/1108#issuecomment-14266970
if (!inUnwrap) {
unwrapNonAppData(ctx);
}
break;
default:
throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus());
}
if (result.bytesProduced() == 0) {
break;
}
// It should not consume empty buffers when it is not handshaking
// Fix for Android, where it was encrypting empty buffers even when not handshaking
if (result.bytesConsumed() == 0 && result.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) {
break;
}
}
} finally {
if (out != null) {
out.release();
}
}
}
private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
throws SSLException {
ByteBuf newDirectIn = null;
try {
int readerIndex = in.readerIndex();
int readableBytes = in.readableBytes();
// We will call SslEngine.wrap(ByteBuffer[], ByteBuffer) to allow efficient handling of
// CompositeByteBuf without force an extra memory copy when CompositeByteBuffer.nioBuffer() is called.
final ByteBuffer[] in0;
if (in.isDirect() || !engineType.wantsDirectBuffer) {
// As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed ByteBuf
// to calculate the count) we will just assume a CompositeByteBuf contains more then 1 ByteBuf.
// The worst that can happen is that we allocate an extra ByteBuffer[] in CompositeByteBuf.nioBuffers()
// which is better then walking the composed ByteBuf in most cases.
if (!(in instanceof CompositeByteBuf) && in.nioBufferCount() == 1) {
in0 = singleBuffer;
// We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object allocation
// to a minimum.
in0[0] = in.internalNioBuffer(readerIndex, readableBytes);
} else {
in0 = in.nioBuffers();
}
} else {
// We could even go further here and check if its a CompositeByteBuf and if so try to decompose it and
// only replace the ByteBuffer that are not direct. At the moment we just will replace the whole
// CompositeByteBuf to keep the complexity to a minimum
newDirectIn = alloc.directBuffer(readableBytes);
newDirectIn.writeBytes(in, readerIndex, readableBytes);
in0 = singleBuffer;
in0[0] = newDirectIn.internalNioBuffer(newDirectIn.readerIndex(), readableBytes);
}
for (;;) {
ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
SSLEngineResult result = engine.wrap(in0, out0);
in.skipBytes(result.bytesConsumed());
out.writerIndex(out.writerIndex() + result.bytesProduced());
switch (result.getStatus()) {
case BUFFER_OVERFLOW:
out.ensureWritable(maxPacketBufferSize);
break;
default:
return result;
}
}
} finally {
// Null out to allow GC of ByteBuffer
singleBuffer[0] = null;
if (newDirectIn != null) {
newDirectIn.release();
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// Make sure to release SSLEngine,
// and notify the handshake future if the connection has been closed during handshake.
setHandshakeFailure(ctx, CHANNEL_CLOSED, !outboundClosed);
// Ensure we always notify the sslClosePromise as well
notifyClosePromise(CHANNEL_CLOSED);
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (ignoreException(cause)) {
// It is safe to ignore the 'connection reset by peer' or
// 'broken pipe' error after sending close_notify.
if (logger.isDebugEnabled()) {
logger.debug(
"{} Swallowing a harmless 'connection reset by peer / broken pipe' error that occurred " +
"while writing close_notify in response to the peer's close_notify", ctx.channel(), cause);
}
// Close the connection explicitly just in case the transport
// did not close the connection automatically.
if (ctx.channel().isActive()) {
ctx.close();
}
} else {
ctx.fireExceptionCaught(cause);
}
}
/**
* Checks if the given {@link Throwable} can be ignore and just "swallowed"
*
* When an ssl connection is closed a close_notify message is sent.
* After that the peer also sends close_notify however, it's not mandatory to receive
* the close_notify. The party who sent the initial close_notify can close the connection immediately
* then the peer will get connection reset error.
*
*/
private boolean ignoreException(Throwable t) {
if (!(t instanceof SSLException) && t instanceof IOException && sslClosePromise.isDone()) {
String message = t.getMessage();
// first try to match connection reset / broke peer based on the regex. This is the fastest way
// but may fail on different jdk impls or OS's
if (message != null && IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
return true;
}
// Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not
StackTraceElement[] elements = t.getStackTrace();
for (StackTraceElement element: elements) {
String classname = element.getClassName();
String methodname = element.getMethodName();
// skip all classes that belong to the io.netty package
if (classname.startsWith("io.netty.")) {
continue;
}
// check if the method name is read if not skip it
if (!"read".equals(methodname)) {
continue;
}
// This will also match against SocketInputStream which is used by openjdk 7 and maybe
// also others
if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) {
return true;
}
try {
// No match by now.. Try to load the class via classloader and inspect it.
// This is mainly done as other JDK implementations may differ in name of
// the impl.
Class<?> clazz = PlatformDependent.getClassLoader(getClass()).loadClass(classname);
if (SocketChannel.class.isAssignableFrom(clazz)
|| DatagramChannel.class.isAssignableFrom(clazz)) {
return true;
}
// also match against SctpChannel via String matching as it may not present.
if (PlatformDependent.javaVersion() >= 7
&& "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) {
return true;
}
} catch (Throwable cause) {
logger.debug("Unexpected exception while loading class {} classname {}",
getClass(), classname, cause);
}
}
}
return false;
}
/**
* Returns {@code true} if the given {@link ByteBuf} is encrypted. Be aware that this method
* will not increase the readerIndex of the given {@link ByteBuf}.
*
* @param buffer
* The {@link ByteBuf} to read from. Be aware that it must have at least 5 bytes to read,
* otherwise it will throw an {@link IllegalArgumentException}.
* @return encrypted
* {@code true} if the {@link ByteBuf} is encrypted, {@code false} otherwise.
* @throws IllegalArgumentException
* Is thrown if the given {@link ByteBuf} has not at least 5 bytes to read.
*/
public static boolean isEncrypted(ByteBuf buffer) {
if (buffer.readableBytes() < SslUtils.SSL_RECORD_HEADER_LENGTH) {
throw new IllegalArgumentException(
"buffer must have at least " + SslUtils.SSL_RECORD_HEADER_LENGTH + " readable bytes");
}
return getEncryptedPacketLength(buffer, buffer.readerIndex()) != SslUtils.NOT_ENCRYPTED;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws SSLException {
final int startOffset = in.readerIndex();
final int endOffset = in.writerIndex();
int offset = startOffset;
int totalLength = 0;
// If we calculated the length of the current SSL record before, use that information.
if (packetLength > 0) {
if (endOffset - startOffset < packetLength) {
return;
} else {
offset += packetLength;
totalLength = packetLength;
packetLength = 0;
}
}
boolean nonSslRecord = false;
while (totalLength < ReferenceCountedOpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
final int readableBytes = endOffset - offset;
if (readableBytes < SslUtils.SSL_RECORD_HEADER_LENGTH) {
break;
}
final int packetLength = getEncryptedPacketLength(in, offset);
if (packetLength == SslUtils.NOT_ENCRYPTED) {
nonSslRecord = true;
break;
}
assert packetLength > 0;
if (packetLength > readableBytes) {
// wait until the whole packet can be read
this.packetLength = packetLength;
break;
}
int newTotalLength = totalLength + packetLength;
if (newTotalLength > ReferenceCountedOpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) {
// Don't read too much.
break;
}
// We have a whole packet.
// Increment the offset to handle the next packet.
offset += packetLength;
totalLength = newTotalLength;
}
if (totalLength > 0) {
// The buffer contains one or more full SSL records.
// Slice out the whole packet so unwrap will only be called with complete packets.
// Also directly reset the packetLength. This is needed as unwrap(..) may trigger
// decode(...) again via:
// 1) unwrap(..) is called
// 2) wrap(...) is called from within unwrap(...)
// 3) wrap(...) calls unwrapLater(...)
// 4) unwrapLater(...) calls decode(...)
//
// See https://github.com/netty/netty/issues/1534
in.skipBytes(totalLength);
try {
firedChannelRead = unwrap(ctx, in, startOffset, totalLength) || firedChannelRead;
} catch (Throwable cause) {
try {
// We need to flush one time as there may be an alert that we should send to the remote peer because
// of the SSLException reported here.
wrapAndFlush(ctx);
} catch (SSLException ex) {
logger.debug("SSLException during trying to call SSLEngine.wrap(...)" +
" because of an previous SSLException, ignoring...", ex);
} finally {
setHandshakeFailure(ctx, cause);
}
PlatformDependent.throwException(cause);
}
}
if (nonSslRecord) {
// Not an SSL/TLS packet
NotSslRecordException e = new NotSslRecordException(
"not an SSL/TLS record: " + ByteBufUtil.hexDump(in));
in.skipBytes(in.readableBytes());
// First fail the handshake promise as we may need to have access to the SSLEngine which may
// be released because the user will remove the SslHandler in an exceptionCaught(...) implementation.
setHandshakeFailure(ctx, e);
throw e;
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// Discard bytes of the cumulation buffer if needed.
discardSomeReadBytes();
flushIfNeeded(ctx);
readIfNeeded(ctx);
firedChannelRead = false;
ctx.fireChannelReadComplete();
}
private void readIfNeeded(ChannelHandlerContext ctx) {
// If handshake is not finished yet, we need more data.
if (!ctx.channel().config().isAutoRead() && (!firedChannelRead || !handshakePromise.isDone())) {
// No auto-read used and no message passed through the ChannelPipeline or the handshake was not complete
// yet, which means we need to trigger the read to ensure we not encounter any stalls.
ctx.read();
}
}
private void flushIfNeeded(ChannelHandlerContext ctx) {
if (needsFlush) {
forceFlush(ctx);
}
}
/**
* Calls {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} with an empty buffer to handle handshakes, etc.
*/
private void unwrapNonAppData(ChannelHandlerContext ctx) throws SSLException {
unwrap(ctx, Unpooled.EMPTY_BUFFER, 0, 0);
}
/**
* Unwraps inbound SSL records.
*/
private boolean unwrap(
ChannelHandlerContext ctx, ByteBuf packet, int offset, int length) throws SSLException {
boolean decoded = false;
boolean wrapLater = false;
boolean notifyClosure = false;
ByteBuf decodeOut = allocate(ctx, length);
try {
// Only continue to loop if the handler was not removed in the meantime.
// See https://github.com/netty/netty/issues/5860
while (!ctx.isRemoved()) {
final SSLEngineResult result = engineType.unwrap(this, packet, offset, length, decodeOut);
final Status status = result.getStatus();
final HandshakeStatus handshakeStatus = result.getHandshakeStatus();
final int produced = result.bytesProduced();
final int consumed = result.bytesConsumed();
// Update indexes for the next iteration
offset += consumed;
length -= consumed;
switch (status) {
case BUFFER_OVERFLOW:
int readableBytes = decodeOut.readableBytes();
int bufferSize = engine.getSession().getApplicationBufferSize() - readableBytes;
if (readableBytes > 0) {
decoded = true;
ctx.fireChannelRead(decodeOut);
// This buffer was handled, null it out.
decodeOut = null;
if (bufferSize <= 0) {
// It may happen that readableBytes >= engine.getSession().getApplicationBufferSize()
// while there is still more to unwrap, in this case we will just allocate a new buffer
// with the capacity of engine.getSession().getApplicationBufferSize() and call unwrap
// again.
bufferSize = engine.getSession().getApplicationBufferSize();
}
} else {
// This buffer was handled, null it out.
decodeOut.release();
decodeOut = null;
}
// Allocate a new buffer which can hold all the rest data and loop again.
// TODO: We may want to reconsider how we calculate the length here as we may
// have more then one ssl message to decode.
decodeOut = allocate(ctx, bufferSize);
continue;
case CLOSED:
// notify about the CLOSED state of the SSLEngine. See #137
notifyClosure = true;
break;
default:
break;
}
switch (handshakeStatus) {
case NEED_UNWRAP:
break;
case NEED_WRAP:
wrapNonAppData(ctx, true);
break;
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
setHandshakeSuccess();
wrapLater = true;
// We 'break' here and NOT 'continue' as android API version 21 has a bug where they consume
// data from the buffer but NOT correctly set the SSLEngineResult.bytesConsumed().
// Because of this it will raise an exception on the next iteration of the for loop on android
// API version 21. Just doing a break will work here as produced and consumed will both be 0
// and so we break out of the complete for (;;) loop and so call decode(...) again later on.
// On other platforms this will have no negative effect as we will just continue with the
// for (;;) loop if something was either consumed or produced.
//
// See:
// - https://github.com/netty/netty/issues/4116
// - https://code.google.com/p/android/issues/detail?id=198639&thanks=198639&ts=1452501203
break;
case NOT_HANDSHAKING:
if (setHandshakeSuccessIfStillHandshaking()) {
wrapLater = true;
continue;
}
if (flushedBeforeHandshake) {
// We need to call wrap(...) in case there was a flush done before the handshake completed.
//
// See https://github.com/netty/netty/pull/2437
flushedBeforeHandshake = false;
wrapLater = true;
}
break;
default:
throw new IllegalStateException("unknown handshake status: " + handshakeStatus);
}
if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) {
if (handshakeStatus == HandshakeStatus.NEED_UNWRAP) {
// The underlying engine is starving so we need to feed it with more data.
// See https://github.com/netty/netty/pull/5039
readIfNeeded(ctx);
}
break;
}
}
if (wrapLater) {
wrap(ctx, true);
}
if (notifyClosure) {
notifyClosePromise(null);
}
} finally {
if (decodeOut != null) {
if (decodeOut.isReadable()) {
decoded = true;
ctx.fireChannelRead(decodeOut);
} else {
decodeOut.release();
}
}
}
return decoded;
}
private static ByteBuffer toByteBuffer(ByteBuf out, int index, int len) {
return out.nioBufferCount() == 1 ? out.internalNioBuffer(index, len) :
out.nioBuffer(index, len);
}
/**
* Fetches all delegated tasks from the {@link SSLEngine} and runs them via the {@link #delegatedTaskExecutor}.
* If the {@link #delegatedTaskExecutor} is {@link ImmediateExecutor}, just call {@link Runnable#run()} directly
* instead of using {@link Executor#execute(Runnable)}. Otherwise, run the tasks via
* the {@link #delegatedTaskExecutor} and wait until the tasks are finished.
*/
private void runDelegatedTasks() {
if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE) {
for (;;) {
Runnable task = engine.getDelegatedTask();
if (task == null) {
break;
}
task.run();
}
} else {
final List<Runnable> tasks = new ArrayList<Runnable>(2);
for (;;) {
final Runnable task = engine.getDelegatedTask();
if (task == null) {
break;
}
tasks.add(task);
}
if (tasks.isEmpty()) {
return;
}
final CountDownLatch latch = new CountDownLatch(1);
delegatedTaskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (Runnable task: tasks) {
task.run();
}
} catch (Exception e) {
ctx.fireExceptionCaught(e);
} finally {
latch.countDown();
}
}
});
boolean interrupted = false;
while (latch.getCount() != 0) {
try {
latch.await();
} catch (InterruptedException e) {
// Interrupt later.
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Works around some Android {@link SSLEngine} implementations that skip {@link HandshakeStatus#FINISHED} and
* go straight into {@link HandshakeStatus#NOT_HANDSHAKING} when handshake is finished.
*
* @return {@code true} if and only if the workaround has been applied and thus {@link #handshakeFuture} has been
* marked as success by this method
*/
private boolean setHandshakeSuccessIfStillHandshaking() {
if (!handshakePromise.isDone()) {
setHandshakeSuccess();
return true;
}
return false;
}
/**
* Notify all the handshake futures about the successfully handshake
*/
private void setHandshakeSuccess() {
handshakePromise.trySuccess(ctx.channel());
if (logger.isDebugEnabled()) {
logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite());
}
ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
if (readDuringHandshake && !ctx.channel().config().isAutoRead()) {
readDuringHandshake = false;
ctx.read();
}
}
/**
* Notify all the handshake futures about the failure during the handshake.
*/
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) {
setHandshakeFailure(ctx, cause, true);
}
/**
* Notify all the handshake futures about the failure during the handshake.
*/
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound) {
try {
// Release all resources such as internal buffers that SSLEngine
// is managing.
engine.closeOutbound();
if (closeInbound) {
try {
engine.closeInbound();
} catch (SSLException e) {
// only log in debug mode as it most likely harmless and latest chrome still trigger
// this all the time.
//
// See https://github.com/netty/netty/issues/1340
String msg = e.getMessage();
if (msg == null || !msg.contains("possible truncation attack")) {
logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
}
}
}
notifyHandshakeFailure(cause);
} finally {
// Ensure we remove and fail all pending writes in all cases and so release memory quickly.
pendingUnencryptedWrites.removeAndFailAll(cause);
}
}
private void notifyHandshakeFailure(Throwable cause) {
if (handshakePromise.tryFailure(cause)) {
SslUtils.notifyHandshakeFailure(ctx, cause);
}
}
private void notifyClosePromise(Throwable cause) {
if (cause == null) {
if (sslClosePromise.trySuccess(ctx.channel())) {
ctx.fireUserEventTriggered(SslCloseCompletionEvent.SUCCESS);
}
} else {
if (sslClosePromise.tryFailure(cause)) {
ctx.fireUserEventTriggered(new SslCloseCompletionEvent(cause));
}
}
}
private void closeOutboundAndChannel(
final ChannelHandlerContext ctx, final ChannelPromise promise, boolean disconnect) throws Exception {
if (!ctx.channel().isActive()) {
if (disconnect) {
ctx.disconnect(promise);
} else {
ctx.close(promise);
}
return;
}
outboundClosed = true;
engine.closeOutbound();
ChannelPromise closeNotifyPromise = ctx.newPromise();
try {
flush(ctx, closeNotifyPromise);
} finally {
// It's important that we do not pass the original ChannelPromise to safeClose(...) as when flush(....)
// throws an Exception it will be propagated to the AbstractChannelHandlerContext which will try
// to fail the promise because of this. This will then fail as it was already completed by safeClose(...).
// We create a new ChannelPromise and try to notify the original ChannelPromise
// once it is complete. If we fail to do so we just ignore it as in this case it was failed already
// because of a propagated Exception.
//
// See https://github.com/netty/netty/issues/5931
safeClose(ctx, closeNotifyPromise, ctx.newPromise().addListener(
new ChannelPromiseNotifier(false, promise)));
}
}
private void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, promise);
flush(ctx);
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
pendingUnencryptedWrites = new PendingWriteQueue(ctx);
if (ctx.channel().isActive() && engine.getUseClientMode()) {
// Begin the initial handshake.
// channelActive() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
handshake(null);
} else {
// channelActive() event has not been fired yet. this.channelOpen() will be invoked
// and initialization will occur there.
}
}
/**
* Performs TLS renegotiation.
*/
public Future<Channel> renegotiate() {
ChannelHandlerContext ctx = this.ctx;
if (ctx == null) {
throw new IllegalStateException();
}
return renegotiate(ctx.executor().<Channel>newPromise());
}
/**
* Performs TLS renegotiation.
*/
public Future<Channel> renegotiate(final Promise<Channel> promise) {
if (promise == null) {
throw new NullPointerException("promise");
}
ChannelHandlerContext ctx = this.ctx;
if (ctx == null) {
throw new IllegalStateException();
}
EventExecutor executor = ctx.executor();
if (!executor.inEventLoop()) {
executor.execute(new Runnable() {
@Override
public void run() {
handshake(promise);
}
});
return promise;
}
handshake(promise);
return promise;
}
/**
* Performs TLS (re)negotiation.
*
* @param newHandshakePromise if {@code null}, use the existing {@link #handshakePromise},
* assuming that the current negotiation has not been finished.
* Currently, {@code null} is expected only for the initial handshake.
*/
private void handshake(final Promise<Channel> newHandshakePromise) {
final Promise<Channel> p;
if (newHandshakePromise != null) {
final Promise<Channel> oldHandshakePromise = handshakePromise;
if (!oldHandshakePromise.isDone()) {
// There's no need to handshake because handshake is in progress already.
// Merge the new promise into the old one.
oldHandshakePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
if (future.isSuccess()) {
newHandshakePromise.setSuccess(future.getNow());
} else {
newHandshakePromise.setFailure(future.cause());
}
}
});
return;
}
handshakePromise = p = newHandshakePromise;
} else if (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
// Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake
// is in progress. See https://github.com/netty/netty/issues/4718.
return;
} else {
// Forced to reuse the old handshake.
p = handshakePromise;
assert !p.isDone();
}
// Begin handshake.
final ChannelHandlerContext ctx = this.ctx;
try {
engine.beginHandshake();
wrapNonAppData(ctx, false);
} catch (Throwable e) {
setHandshakeFailure(ctx, e);
} finally {
forceFlush(ctx);
}
// Set timeout if necessary.
final long handshakeTimeoutMillis = this.handshakeTimeoutMillis;
if (handshakeTimeoutMillis <= 0 || p.isDone()) {
return;
}
final ScheduledFuture<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (p.isDone()) {
return;
}
notifyHandshakeFailure(HANDSHAKE_TIMED_OUT);
}
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished.
p.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> f) throws Exception {
timeoutFuture.cancel(false);
}
});
}
private void forceFlush(ChannelHandlerContext ctx) {
needsFlush = false;
ctx.flush();
}
/**
* Issues an initial TLS handshake once connected when used in client-mode
*/
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
if (!startTls && engine.getUseClientMode()) {
// Begin the initial handshake
handshake(null);
}
ctx.fireChannelActive();
}
private void safeClose(
final ChannelHandlerContext ctx, final ChannelFuture flushFuture,
final ChannelPromise promise) {
if (!ctx.channel().isActive()) {
ctx.close(promise);
return;
}
final ScheduledFuture<?> timeoutFuture;
if (!flushFuture.isDone()) {
long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
if (closeNotifyTimeout > 0) {
// Force-close the connection if close_notify is not fully sent in time.
timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
// May be done in the meantime as cancel(...) is only best effort.
if (!flushFuture.isDone()) {
logger.warn("{} Last write attempt timed out; force-closing the connection.",
ctx.channel());
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyTimeout, TimeUnit.MILLISECONDS);
} else {
timeoutFuture = null;
}
} else {
timeoutFuture = null;
}
// Close the connection if close_notify is sent in time.
flushFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f)
throws Exception {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
if (closeNotifyReadTimeout <= 0) {
// Trigger the close in all cases to make sure the promise is notified
// See https://github.com/netty/netty/issues/2358
addCloseListener(ctx.close(ctx.newPromise()), promise);
} else {
final ScheduledFuture<?> closeNotifyReadTimeoutFuture;
if (!sslClosePromise.isDone()) {
closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (!sslClosePromise.isDone()) {
logger.debug(
"{} did not receive close_notify in {}ms; force-closing the connection.",
ctx.channel(), closeNotifyReadTimeout);
// Do the close now...
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
} else {
closeNotifyReadTimeoutFuture = null;
}
// Do the close once the we received the close_notify.
sslClosePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
if (closeNotifyReadTimeoutFuture != null) {
closeNotifyReadTimeoutFuture.cancel(false);
}
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
});
}
}
});
}
private static void addCloseListener(ChannelFuture future, ChannelPromise promise) {
// We notify the promise in the ChannelPromiseNotifier as there is a "race" where the close(...) call
// by the timeoutFuture and the close call in the flushFuture listener will be called. Because of
// this we need to use trySuccess() and tryFailure(...) as otherwise we can cause an
// IllegalStateException.
// Also we not want to log if the notification happens as this is expected in some cases.
// See https://github.com/netty/netty/issues/5598
future.addListener(new ChannelPromiseNotifier(false, promise));
}
/**
* Always prefer a direct buffer when it's pooled, so that we reduce the number of memory copies
* in {@link OpenSslEngine}.
*/
private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) {
ByteBufAllocator alloc = ctx.alloc();
if (engineType.wantsDirectBuffer) {
return alloc.directBuffer(capacity);
} else {
return alloc.buffer(capacity);
}
}
/**
* Allocates an outbound network buffer for {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} which can encrypt
* the specified amount of pending bytes.
*/
private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) {
return allocate(ctx, engineType.calculateWrapBufferCapacity(this, pendingBytes, numComponents));
}
private final class LazyChannelPromise extends DefaultPromise<Channel> {
@Override
protected EventExecutor executor() {
if (ctx == null) {
throw new IllegalStateException();
}
return ctx.executor();
}
@Override
protected void checkDeadLock() {
if (ctx == null) {
// If ctx is null the handlerAdded(...) callback was not called, in this case the checkDeadLock()
// method was called from another Thread then the one that is used by ctx.executor(). We need to
// guard against this as a user can see a race if handshakeFuture().sync() is called but the
// handlerAdded(..) method was not yet as it is called from the EventExecutor of the
// ChannelHandlerContext. If we not guard against this super.checkDeadLock() would cause an
// IllegalStateException when trying to call executor().
return;
}
super.checkDeadLock();
}
}
}
| SslHandler#handlerRemoved0() shouldn't care about the SSLEngine being a specific type but only if it's ReferenceCounted
Motivation
SslHandler should release any type of SSLEngine if it implements the ReferenceCounted interface
Modifications
Change condition to check for ReferenceCounted interface
Result
Better use of interfaces
| handler/src/main/java/io/netty/handler/ssl/SslHandler.java | SslHandler#handlerRemoved0() shouldn't care about the SSLEngine being a specific type but only if it's ReferenceCounted | <ide><path>andler/src/main/java/io/netty/handler/ssl/SslHandler.java
<ide> import io.netty.channel.PendingWriteQueue;
<ide> import io.netty.handler.codec.ByteToMessageDecoder;
<ide> import io.netty.handler.codec.UnsupportedMessageTypeException;
<add>import io.netty.util.ReferenceCounted;
<ide> import io.netty.util.concurrent.DefaultPromise;
<ide> import io.netty.util.concurrent.EventExecutor;
<ide> import io.netty.util.concurrent.Future;
<ide> // Check if queue is not empty first because create a new ChannelException is expensive
<ide> pendingUnencryptedWrites.removeAndFailAll(new ChannelException("Pending write on removal of SslHandler"));
<ide> }
<del> if (engine instanceof ReferenceCountedOpenSslEngine) {
<del> ((ReferenceCountedOpenSslEngine) engine).release();
<add> if (engine instanceof ReferenceCounted) {
<add> ((ReferenceCounted) engine).release();
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | eb53e535a8033b7b67f6e10aa349de0edf4df20e | 0 | apache/ignite,vsisko/incubator-ignite,alexzaitzev/ignite,dlnufox/ignite,endian675/ignite,DoudTechData/ignite,dream-x/ignite,samaitra/ignite,chandresh-pancholi/ignite,abhishek-ch/incubator-ignite,kidaa/incubator-ignite,ntikhonov/ignite,vldpyatkov/ignite,agura/incubator-ignite,afinka77/ignite,psadusumilli/ignite,samaitra/ignite,svladykin/ignite,a1vanov/ignite,arijitt/incubator-ignite,ascherbakoff/ignite,dlnufox/ignite,wmz7year/ignite,ryanzz/ignite,tkpanther/ignite,amirakhmedov/ignite,ashutakGG/incubator-ignite,louishust/incubator-ignite,mcherkasov/ignite,ilantukh/ignite,vsisko/incubator-ignite,f7753/ignite,xtern/ignite,BiryukovVA/ignite,DoudTechData/ignite,shurun19851206/ignite,afinka77/ignite,apache/ignite,dmagda/incubator-ignite,a1vanov/ignite,vldpyatkov/ignite,mcherkasov/ignite,apacheignite/ignite,SomeFire/ignite,agoncharuk/ignite,sk0x50/ignite,alexzaitzev/ignite,ryanzz/ignite,rfqu/ignite,amirakhmedov/ignite,andrey-kuznetsov/ignite,f7753/ignite,leveyj/ignite,murador/ignite,dmagda/incubator-ignite,avinogradovgg/ignite,ascherbakoff/ignite,adeelmahmood/ignite,SharplEr/ignite,ptupitsyn/ignite,vsuslov/incubator-ignite,thuTom/ignite,murador/ignite,endian675/ignite,akuznetsov-gridgain/ignite,tkpanther/ignite,vladisav/ignite,endian675/ignite,iveselovskiy/ignite,xtern/ignite,leveyj/ignite,xtern/ignite,nivanov/ignite,alexzaitzev/ignite,gargvish/ignite,f7753/ignite,ntikhonov/ignite,dream-x/ignite,iveselovskiy/ignite,vadopolski/ignite,svladykin/ignite,pperalta/ignite,sylentprayer/ignite,psadusumilli/ignite,f7753/ignite,louishust/incubator-ignite,apache/ignite,ilantukh/ignite,VladimirErshov/ignite,wmz7year/ignite,andrey-kuznetsov/ignite,afinka77/ignite,kidaa/incubator-ignite,arijitt/incubator-ignite,arijitt/incubator-ignite,samaitra/ignite,SomeFire/ignite,WilliamDo/ignite,sk0x50/ignite,daradurvs/ignite,daradurvs/ignite,voipp/ignite,vladisav/ignite,iveselovskiy/ignite,samaitra/ignite,nivanov/ignite,amirakhmedov/ignite,tkpanther/ignite,nizhikov/ignite,iveselovskiy/ignite,rfqu/ignite,ptupitsyn/ignite,amirakhmedov/ignite,a1vanov/ignite,ptupitsyn/ignite,svladykin/ignite,gridgain/apache-ignite,wmz7year/ignite,nizhikov/ignite,ntikhonov/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,mcherkasov/ignite,arijitt/incubator-ignite,NSAmelchev/ignite,gridgain/apache-ignite,daradurvs/ignite,ascherbakoff/ignite,kidaa/incubator-ignite,leveyj/ignite,vladisav/ignite,dlnufox/ignite,daradurvs/ignite,leveyj/ignite,agura/incubator-ignite,mcherkasov/ignite,kidaa/incubator-ignite,voipp/ignite,StalkXT/ignite,leveyj/ignite,tkpanther/ignite,endian675/ignite,ryanzz/ignite,ryanzz/ignite,DoudTechData/ignite,vldpyatkov/ignite,thuTom/ignite,alexzaitzev/ignite,dlnufox/ignite,NSAmelchev/ignite,shroman/ignite,shroman/ignite,gargvish/ignite,ashutakGG/incubator-ignite,andrey-kuznetsov/ignite,SharplEr/ignite,sk0x50/ignite,a1vanov/ignite,f7753/ignite,abhishek-ch/incubator-ignite,ascherbakoff/ignite,dmagda/incubator-ignite,NSAmelchev/ignite,thuTom/ignite,SomeFire/ignite,rfqu/ignite,BiryukovVA/ignite,shurun19851206/ignite,endian675/ignite,sylentprayer/ignite,kidaa/incubator-ignite,ntikhonov/ignite,kromulan/ignite,adeelmahmood/ignite,shroman/ignite,nizhikov/ignite,VladimirErshov/ignite,ashutakGG/incubator-ignite,ilantukh/ignite,nivanov/ignite,SharplEr/ignite,vsisko/incubator-ignite,daradurvs/ignite,xtern/ignite,dream-x/ignite,shurun19851206/ignite,ascherbakoff/ignite,ntikhonov/ignite,BiryukovVA/ignite,psadusumilli/ignite,ptupitsyn/ignite,WilliamDo/ignite,ntikhonov/ignite,andrey-kuznetsov/ignite,pperalta/ignite,afinka77/ignite,shurun19851206/ignite,pperalta/ignite,thuTom/ignite,daradurvs/ignite,DoudTechData/ignite,SharplEr/ignite,StalkXT/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,sylentprayer/ignite,dream-x/ignite,apacheignite/ignite,daradurvs/ignite,samaitra/ignite,akuznetsov-gridgain/ignite,mcherkasov/ignite,VladimirErshov/ignite,vldpyatkov/ignite,zzcclp/ignite,louishust/incubator-ignite,gargvish/ignite,vldpyatkov/ignite,shurun19851206/ignite,avinogradovgg/ignite,SharplEr/ignite,nivanov/ignite,ashutakGG/incubator-ignite,shroman/ignite,rfqu/ignite,murador/ignite,tkpanther/ignite,ryanzz/ignite,vadopolski/ignite,a1vanov/ignite,louishust/incubator-ignite,sylentprayer/ignite,vsuslov/incubator-ignite,sk0x50/ignite,adeelmahmood/ignite,f7753/ignite,adeelmahmood/ignite,SharplEr/ignite,daradurvs/ignite,rfqu/ignite,StalkXT/ignite,ilantukh/ignite,VladimirErshov/ignite,akuznetsov-gridgain/ignite,apacheignite/ignite,VladimirErshov/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,kromulan/ignite,avinogradovgg/ignite,xtern/ignite,kromulan/ignite,alexzaitzev/ignite,irudyak/ignite,shroman/ignite,leveyj/ignite,NSAmelchev/ignite,shurun19851206/ignite,NSAmelchev/ignite,pperalta/ignite,thuTom/ignite,ashutakGG/incubator-ignite,thuTom/ignite,vsisko/incubator-ignite,amirakhmedov/ignite,louishust/incubator-ignite,kidaa/incubator-ignite,WilliamDo/ignite,apacheignite/ignite,voipp/ignite,chandresh-pancholi/ignite,StalkXT/ignite,murador/ignite,vsisko/incubator-ignite,ptupitsyn/ignite,vladisav/ignite,alexzaitzev/ignite,abhishek-ch/incubator-ignite,wmz7year/ignite,agoncharuk/ignite,wmz7year/ignite,amirakhmedov/ignite,shroman/ignite,SharplEr/ignite,vsuslov/incubator-ignite,WilliamDo/ignite,irudyak/ignite,voipp/ignite,sk0x50/ignite,SomeFire/ignite,vladisav/ignite,irudyak/ignite,ryanzz/ignite,agura/incubator-ignite,apacheignite/ignite,SomeFire/ignite,kromulan/ignite,endian675/ignite,mcherkasov/ignite,nivanov/ignite,zzcclp/ignite,SomeFire/ignite,nivanov/ignite,DoudTechData/ignite,samaitra/ignite,louishust/incubator-ignite,dream-x/ignite,ilantukh/ignite,ilantukh/ignite,a1vanov/ignite,BiryukovVA/ignite,voipp/ignite,voipp/ignite,samaitra/ignite,rfqu/ignite,ptupitsyn/ignite,NSAmelchev/ignite,chandresh-pancholi/ignite,abhishek-ch/incubator-ignite,pperalta/ignite,SomeFire/ignite,ntikhonov/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,shroman/ignite,svladykin/ignite,murador/ignite,zzcclp/ignite,NSAmelchev/ignite,tkpanther/ignite,ptupitsyn/ignite,SharplEr/ignite,psadusumilli/ignite,irudyak/ignite,mcherkasov/ignite,tkpanther/ignite,agoncharuk/ignite,agoncharuk/ignite,gridgain/apache-ignite,ilantukh/ignite,endian675/ignite,shurun19851206/ignite,ilantukh/ignite,ascherbakoff/ignite,zzcclp/ignite,avinogradovgg/ignite,shroman/ignite,adeelmahmood/ignite,chandresh-pancholi/ignite,dlnufox/ignite,BiryukovVA/ignite,dmagda/incubator-ignite,svladykin/ignite,dmagda/incubator-ignite,vldpyatkov/ignite,vadopolski/ignite,vladisav/ignite,rfqu/ignite,endian675/ignite,murador/ignite,sylentprayer/ignite,apacheignite/ignite,StalkXT/ignite,vsisko/incubator-ignite,pperalta/ignite,BiryukovVA/ignite,zzcclp/ignite,nizhikov/ignite,DoudTechData/ignite,andrey-kuznetsov/ignite,VladimirErshov/ignite,WilliamDo/ignite,samaitra/ignite,shroman/ignite,andrey-kuznetsov/ignite,vsisko/incubator-ignite,VladimirErshov/ignite,xtern/ignite,SomeFire/ignite,dlnufox/ignite,nivanov/ignite,adeelmahmood/ignite,svladykin/ignite,BiryukovVA/ignite,murador/ignite,vsuslov/incubator-ignite,afinka77/ignite,sylentprayer/ignite,chandresh-pancholi/ignite,apache/ignite,apache/ignite,nizhikov/ignite,adeelmahmood/ignite,wmz7year/ignite,ilantukh/ignite,irudyak/ignite,vladisav/ignite,ascherbakoff/ignite,vldpyatkov/ignite,gargvish/ignite,VladimirErshov/ignite,agura/incubator-ignite,vldpyatkov/ignite,ascherbakoff/ignite,amirakhmedov/ignite,adeelmahmood/ignite,psadusumilli/ignite,nizhikov/ignite,psadusumilli/ignite,vadopolski/ignite,samaitra/ignite,zzcclp/ignite,psadusumilli/ignite,xtern/ignite,ryanzz/ignite,dmagda/incubator-ignite,NSAmelchev/ignite,xtern/ignite,nizhikov/ignite,gridgain/apache-ignite,irudyak/ignite,agoncharuk/ignite,tkpanther/ignite,akuznetsov-gridgain/ignite,dmagda/incubator-ignite,vsuslov/incubator-ignite,leveyj/ignite,ntikhonov/ignite,gargvish/ignite,abhishek-ch/incubator-ignite,akuznetsov-gridgain/ignite,vadopolski/ignite,BiryukovVA/ignite,irudyak/ignite,ilantukh/ignite,apache/ignite,agoncharuk/ignite,vsisko/incubator-ignite,iveselovskiy/ignite,ascherbakoff/ignite,apache/ignite,amirakhmedov/ignite,a1vanov/ignite,vadopolski/ignite,shroman/ignite,amirakhmedov/ignite,shurun19851206/ignite,dlnufox/ignite,arijitt/incubator-ignite,NSAmelchev/ignite,gridgain/apache-ignite,rfqu/ignite,kromulan/ignite,dream-x/ignite,iveselovskiy/ignite,akuznetsov-gridgain/ignite,nizhikov/ignite,dream-x/ignite,nivanov/ignite,vsuslov/incubator-ignite,voipp/ignite,gargvish/ignite,alexzaitzev/ignite,sk0x50/ignite,kromulan/ignite,sk0x50/ignite,ptupitsyn/ignite,kromulan/ignite,vadopolski/ignite,gargvish/ignite,ptupitsyn/ignite,StalkXT/ignite,svladykin/ignite,gridgain/apache-ignite,xtern/ignite,vadopolski/ignite,afinka77/ignite,avinogradovgg/ignite,agura/incubator-ignite,f7753/ignite,avinogradovgg/ignite,dmagda/incubator-ignite,chandresh-pancholi/ignite,apache/ignite,thuTom/ignite,sylentprayer/ignite,gridgain/apache-ignite,dream-x/ignite,kromulan/ignite,zzcclp/ignite,agoncharuk/ignite,nizhikov/ignite,abhishek-ch/incubator-ignite,leveyj/ignite,SomeFire/ignite,alexzaitzev/ignite,dlnufox/ignite,murador/ignite,BiryukovVA/ignite,vladisav/ignite,WilliamDo/ignite,afinka77/ignite,WilliamDo/ignite,arijitt/incubator-ignite,sylentprayer/ignite,irudyak/ignite,samaitra/ignite,agura/incubator-ignite,BiryukovVA/ignite,StalkXT/ignite,WilliamDo/ignite,ryanzz/ignite,gargvish/ignite,voipp/ignite,alexzaitzev/ignite,pperalta/ignite,avinogradovgg/ignite,wmz7year/ignite,pperalta/ignite,afinka77/ignite,StalkXT/ignite,StalkXT/ignite,f7753/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,a1vanov/ignite,SomeFire/ignite,irudyak/ignite,DoudTechData/ignite,apacheignite/ignite,DoudTechData/ignite,voipp/ignite,ashutakGG/incubator-ignite,sk0x50/ignite,SharplEr/ignite,zzcclp/ignite,wmz7year/ignite,agura/incubator-ignite,agoncharuk/ignite,agura/incubator-ignite,apache/ignite,apacheignite/ignite,chandresh-pancholi/ignite,thuTom/ignite,mcherkasov/ignite | /* @java.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.cache;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.affinity.*;
import org.gridgain.grid.cache.affinity.consistenthash.*;
import org.gridgain.grid.cache.datastructures.*;
import org.gridgain.grid.cache.store.*;
import org.gridgain.grid.lang.*;
import org.jetbrains.annotations.*;
import java.util.*;
/**
* Main entry point for all <b>Data Grid APIs.</b> You can get a named cache by calling {@link Grid#cache(String)}
* method.
* <h1 class="header">Functionality</h1>
* This API extends {@link GridCacheProjection} API which contains vast majority of cache functionality
* and documentation. In addition to {@link GridCacheProjection} functionality this API provides:
* <ul>
* <li>
* Various {@code 'loadCache(..)'} methods to load cache either synchronously or asynchronously.
* These methods don't specify any keys to load, and leave it to the underlying storage to load cache
* data based on the optionally passed in arguments.
* </li>
* <li>
* Method {@link #affinity()} provides {@link GridCacheAffinityFunction} service for information on
* data partitioning and mapping keys to grid nodes responsible for caching those keys.
* </li>
* <li>
* Method {@link #dataStructures()} provides {@link GridCacheDataStructures} service for
* creating and working with distributed concurrent data structures, such as
* {@link GridCacheAtomicLong}, {@link GridCacheAtomicReference}, {@link GridCacheQueue}, etc.
* </li>
* <li>
* Methods like {@code 'tx{Un}Synchronize(..)'} witch allow to get notifications for transaction state changes.
* This feature is very useful when integrating cache transactions with some other in-house transactions.
* </li>
* <li>Method {@link #metrics()} to provide metrics for the whole cache.</li>
* <li>Method {@link #configuration()} to provide cache configuration bean.</li>
* </ul>
*
* @param <K> Cache key type.
* @param <V> Cache value type.
*/
public interface GridCache<K, V> extends GridCacheProjection<K, V> {
/**
* Gets configuration bean for this cache.
*
* @return Configuration bean for this cache.
*/
public GridCacheConfiguration configuration();
/**
* Registers transactions synchronizations for all transactions started by this cache.
* Use it whenever you need to get notifications on transaction lifecycle and possibly change
* its course. It is also particularly useful when integrating cache transactions
* with some other in-house transactions.
*
* @param syncs Transaction synchronizations to register.
*/
public void txSynchronize(@Nullable GridCacheTxSynchronization syncs);
/**
* Removes transaction synchronizations.
*
* @param syncs Transactions synchronizations to remove.
* @see #txSynchronize(GridCacheTxSynchronization)
*/
public void txUnsynchronize(@Nullable GridCacheTxSynchronization syncs);
/**
* Gets registered transaction synchronizations.
*
* @return Registered transaction synchronizations.
* @see #txSynchronize(GridCacheTxSynchronization)
*/
public Collection<GridCacheTxSynchronization> txSynchronizations();
/**
* Gets affinity service to provide information about data partitioning
* and distribution.
*
* @return Cache data affinity service.
*/
public GridCacheAffinity<K> affinity();
/**
* Gets data structures service to provide a gateway for creating various
* distributed data structures similar in APIs to {@code java.util.concurrent} package.
*
* @return Cache data structures service.
*/
public GridCacheDataStructures dataStructures();
/**
* Gets metrics (statistics) for this cache.
*
* @return Cache metrics.
*/
public GridCacheMetrics metrics();
/**
* Gets size (in bytes) of all entries swapped to disk.
*
* @return Size (in bytes) of all entries swapped to disk.
* @throws GridException In case of error.
*/
public long overflowSize() throws GridException;
/**
* Gets number of cache entries stored in off-heap memory.
*
* @return Number of cache entries stored in off-heap memory.
*/
public long offHeapEntriesCount();
/**
* Gets memory size allocated in off-heap.
*
* @return Allocated memory size.
*/
public long offHeapAllocatedSize();
/**
* Gets size in bytes for swap space.
*
* @return Size in bytes.
* @throws GridException If failed.
*/
public long swapSize() throws GridException ;
/**
* Gets number of swap entries (keys).
*
* @return Number of entries stored in swap.
* @throws GridException If failed.
*/
public long swapKeys() throws GridException;
/**
* Gets iterator over keys and values belonging to this cache swap space on local node. This
* iterator is thread-safe, which means that cache (and therefore its swap space)
* may be modified concurrently with iteration over swap.
* <p>
* Returned iterator supports {@code remove} operation which delegates to
* {@link #removex(Object, GridPredicate[])} method.
* <h2 class="header">Cache Flags</h2>
* This method is not available if any of the following flags are set on projection:
* {@link GridCacheFlag#SKIP_SWAP}.
*
* @return Iterator over keys.
* @throws GridException If failed.
* @see #promote(Object)
*/
public Iterator<Map.Entry<K, V>> swapIterator() throws GridException;
/**
* Gets iterator over keys and values belonging to this cache off-heap memory on local node. This
* iterator is thread-safe, which means that cache (and therefore its off-heap memory)
* may be modified concurrently with iteration over off-heap. To achieve better performance
* the keys and values deserialized on demand, whenever accessed.
* <p>
* Returned iterator supports {@code remove} operation which delegates to
* {@link #removex(Object, GridPredicate[])} method.
*
* @return Iterator over keys.
* @throws GridException If failed.
*/
public Iterator<Map.Entry<K, V>> offHeapIterator() throws GridException;
/**
* Delegates to {@link GridCacheStore#loadCache(GridBiInClosure,Object...)} method
* to load state from the underlying persistent storage. The loaded values
* will then be given to the optionally passed in predicate, and, if the predicate returns
* {@code true}, will be stored in cache. If predicate is {@code null}, then
* all loaded values will be stored in cache.
* <p>
* Note that this method does not receive keys as a parameter, so it is up to
* {@link GridCacheStore} implementation to provide all the data to be loaded.
* <p>
* This method is not transactional and may end up loading a stale value into
* cache if another thread has updated the value immediately after it has been
* loaded. It is mostly useful when pre-loading the cache from underlying
* data store before start, or for read-only caches.
*
* @param p Optional predicate (may be {@code null}). If provided, will be used to
* filter values to be put into cache.
* @param ttl Time to live for loaded entries ({@code 0} for infinity).
* @param args Optional user arguments to be passed into
* {@link GridCacheStore#loadCache(GridBiInClosure, Object...)} method.
* @throws GridException If loading failed.
*/
public void loadCache(@Nullable GridBiPredicate<K, V> p, long ttl, @Nullable Object... args) throws GridException;
/**
* Asynchronously delegates to {@link GridCacheStore#loadCache(GridBiInClosure, Object...)} method
* to reload state from the underlying persistent storage. The reloaded values
* will then be given to the optionally passed in predicate, and if the predicate returns
* {@code true}, will be stored in cache. If predicate is {@code null}, then
* all reloaded values will be stored in cache.
* <p>
* Note that this method does not receive keys as a parameter, so it is up to
* {@link GridCacheStore} implementation to provide all the data to be loaded.
* <p>
* This method is not transactional and may end up loading a stale value into
* cache if another thread has updated the value immediately after it has been
* loaded. It is mostly useful when pre-loading the cache from underlying
* data store before start, or for read-only caches.
*
* @param p Optional predicate (may be {@code null}). If provided, will be used to
* filter values to be put into cache.
* @param ttl Time to live for loaded entries ({@code 0} for infinity).
* @param args Optional user arguments to be passed into
* {@link GridCacheStore#loadCache(GridBiInClosure,Object...)} method.
* @return Future to be completed whenever loading completes.
*/
public GridFuture<?> loadCacheAsync(@Nullable GridBiPredicate<K, V> p, long ttl, @Nullable Object... args);
/**
* Gets a random entry out of cache. In the worst cache scenario this method
* has complexity of <pre>O(S * N/64)</pre> where {@code N} is the size of internal hash
* table and {@code S} is the number of hash table buckets to sample, which is {@code 5}
* by default. However, if the table is pretty dense, with density factor of {@code N/64},
* which is true for near fully populated caches, this method will generally perform significantly
* faster with complexity of O(S) where {@code S = 5}.
* <p>
* Note that this method is not available on {@link GridCacheProjection} API since it is
* impossible (or very hard) to deterministically return a number value when pre-filtering
* and post-filtering is involved (e.g. projection level predicate filters).
*
* @return Random entry, or {@code null} if cache is empty.
*/
@Nullable public GridCacheEntry<K, V> randomEntry();
/**
* Runs DGC procedure on demand using
* {@link GridCacheConfiguration#getDgcSuspectLockTimeout()} to identify suspect locks.
* <p>
* Method blocks current thread until locks are examined and all DGC requests are sent
* to remote nodes.
* <p>
* DGC does not remove locks if {@link GridCacheConfiguration#isDgcRemoveLocks()}
* is set to {@code false}.
*/
public void dgc();
/**
* Runs DGC procedure on demand using provided parameter to identify suspect locks.
* <p>
* Method blocks current thread until locks are examined and all DGC requests are sent
* to remote nodes and (if {@code global} is {@code true}) all nodes running this cache
* will get signal to start GC procedure.
*
* @param suspectLockTimeout Custom suspect lock timeout (should be greater than or equal to 0).
* @param global If {@code true} then GC procedure will start on all nodes having this cache.
* @param rmvLocks If {@code false} then DGC does not remove locks, just report them to log.
*/
public void dgc(long suspectLockTimeout, boolean global, boolean rmvLocks);
/**
* Forces this cache node to re-balance its partitions. This method is usually used when
* {@link GridCacheConfiguration#getPreloadPartitionedDelay()} configuration parameter has non-zero value.
* When many nodes are started or stopped almost concurrently, it is more efficient to delay
* preloading until the node topology is stable to make sure that no redundant re-partitioning
* happens.
* <p>
* In case of{@link GridCacheMode#PARTITIONED} caches, for better efficiency user should
* usually make sure that new nodes get placed on the same place of consistent hash ring as
* the left nodes, and that nodes are restarted before
* {@link GridCacheConfiguration#getPreloadPartitionedDelay() preloadDelay} expires. To place nodes
* on the same place in consistent hash ring, use
* {@link GridCacheConsistentHashAffinityFunction#setHashIdResolver(GridCacheAffinityNodeHashResolver)} to make sure that
* a node maps to the same hash ID if re-started.
* <p>
* See {@link GridCacheConfiguration#getPreloadPartitionedDelay()} for more information on how to configure
* preload re-partition delay.
* <p>
* @return Future that will be completed when preloading is finished.
*/
public GridFuture<?> forceRepartition();
/**
* Resets metrics for current cache.
*/
public void resetMetrics();
}
| modules/core/src/main/java/org/gridgain/grid/cache/GridCache.java | /* @java.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.cache;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.affinity.*;
import org.gridgain.grid.cache.affinity.consistenthash.*;
import org.gridgain.grid.cache.datastructures.*;
import org.gridgain.grid.cache.store.*;
import org.gridgain.grid.lang.*;
import org.jetbrains.annotations.*;
import java.util.*;
/**
* Main entry point for all <b>Data Grid APIs.</b> You can get a named cache by calling {@link Grid#cache(String)}
* method.
* <h1 class="header">Functionality</h1>
* This API extends {@link GridCacheProjection} API which contains vast majority of cache functionality
* and documentation. In addition to {@link GridCacheProjection} functionality this API provides:
* <ul>
* <li>
* Various {@code 'loadCache(..)'} methods to load cache either synchronously or asynchronously.
* These methods don't specify any keys to load, and leave it to the underlying storage to load cache
* data based on the optionally passed in arguments.
* </li>
* <li>
* Method {@link #affinity()} provides {@link GridCacheAffinityFunction} service for information on
* data partitioning and mapping keys to grid nodes responsible for caching those keys.
* </li>
* <li>
* Method {@link #dataStructures()} provides {@link GridCacheDataStructures} service for
* creating and working with distributed concurrent data structures, such as
* {@link GridCacheAtomicLong}, {@link GridCacheAtomicReference}, {@link GridCacheQueue}, etc.
* </li>
* <li>
* Methods like {@code 'tx{Un}Synchronize(..)'} witch allow to get notifications for transaction state changes.
* This feature is very useful when integrating cache transactions with some other in-house transactions.
* </li>
* <li>Method {@link #metrics()} to provide metrics for the whole cache.</li>
* <li>Method {@link #configuration()} to provide cache configuration bean.</li>
* </ul>
*
* @param <K> Cache key type.
* @param <V> Cache value type.
*/
public interface GridCache<K, V> extends GridCacheProjection<K, V> {
/**
* Gets configuration bean for this cache.
*
* @return Configuration bean for this cache.
*/
public GridCacheConfiguration configuration();
/**
* Registers transactions synchronizations for all transactions started by this cache.
* Use it whenever you need to get notifications on transaction lifecycle and possibly change
* its course. It is also particularly useful when integrating cache transactions
* with some other in-house transactions.
*
* @param syncs Transaction synchronizations to register.
*/
public void txSynchronize(@Nullable GridCacheTxSynchronization syncs);
/**
* Removes transaction synchronizations.
*
* @param syncs Transactions synchronizations to remove.
* @see #txSynchronize(GridCacheTxSynchronization)
*/
public void txUnsynchronize(@Nullable GridCacheTxSynchronization syncs);
/**
* Gets registered transaction synchronizations.
*
* @return Registered transaction synchronizations.
* @see #txSynchronize(GridCacheTxSynchronization)
*/
public Collection<GridCacheTxSynchronization> txSynchronizations();
/**
* Gets affinity service to provide information about data partitioning
* and distribution.
*
* @return Cache data affinity service.
*/
public GridCacheAffinity<K> affinity();
/**
* Gets data structures service to provide a gateway for creating various
* distributed data structures similar in APIs to {@code java.util.concurrent} package.
*
* @return Cache data structures service.
*/
public GridCacheDataStructures dataStructures();
/**
* Gets metrics (statistics) for this cache.
*
* @return Cache metrics.
*/
public GridCacheMetrics metrics();
/**
* Gets size (in bytes) of all entries swapped to disk.
*
* @return Size (in bytes) of all entries swapped to disk.
* @throws GridException In case of error.
*/
public long overflowSize() throws GridException;
/**
* Gets number of cache entries stored in off-heap memory.
*
* @return Number of cache entries stored in off-heap memory.
*/
public long offHeapEntriesCount();
/**
* Gets memory size allocated in off-heap.
*
* @return Allocated memory size.
*/
public long offHeapAllocatedSize();
/**
* Gets size in bytes for swap space.
*
* @return Size in bytes.
* @throws GridException If failed.
*/
public long swapSize() throws GridException ;
/**
* Gets number of swap entries (keys).
*
* @return Number of entries stored in swap.
* @throws GridException If failed.
*/
public long swapKeys() throws GridException;
/**
* Gets iterator over keys and values belonging to this cache swap space on local node. This
* iterator is thread-safe, which means that cache (and therefore its swap space)
* may be modified concurrently with iteration over swap.
* <p>
* Returned iterator supports {@code remove} operation which delegates to
* {@link #removex(Object, GridPredicate[])} method.
* <h2 class="header">Cache Flags</h2>
* This method is not available if any of the following flags are set on projection:
* {@link GridCacheFlag#SKIP_SWAP}.
*
* @return Iterator over keys.
* @throws GridException If failed.
* @see #promote(Object)
*/
public Iterator<Map.Entry<K, V>> swapIterator() throws GridException;
/**
* Gets iterator over keys and values belonging to this cache off-heap memory on local node. This
* iterator is thread-safe, which means that cache (and therefore its off-heap memory)
* may be modified concurrently with iteration over off-heap. To achieve better performance
* the keys and values deserialized on demand, whenever accessed.
* <p>
* Returned iterator supports {@code remove} operation which delegates to
* {@link #removex(Object, GridPredicate[])} method.
*
* @return Iterator over keys.
* @throws GridException If failed.
*/
public Iterator<Map.Entry<K, V>> offHeapIterator() throws GridException;
/**
* Delegates to {@link GridCacheStore#loadCache(GridBiInClosure,Object...)} method
* to load state from the underlying persistent storage. The loaded values
* will then be given to the optionally passed in predicate, and, if the predicate returns
* {@code true}, will be stored in cache. If predicate is {@code null}, then
* all loaded values will be stored in cache.
* <p>
* Note that this method does not receive keys as a parameter, so it is up to
* {@link GridCacheStore} implementation to provide all the data to be loaded.
* <p>
* This method is not transactional and may end up loading a stale value into
* cache if another thread has updated the value immediately after it has been
* loaded. It is mostly useful when pre-loading the cache from underlying
* data store before start, or for read-only caches.
*
* @param p Optional predicate (may be {@code null}). If provided, will be used to
* @param ttl Time to live for loaded entries ({@code 0} for infinity).
* filter values to be put into cache.
* @param args Optional user arguments to be passed into
* {@link GridCacheStore#loadCache(GridBiInClosure, Object...)} method.
* @throws GridException If loading failed.
*/
public void loadCache(@Nullable GridBiPredicate<K, V> p, long ttl, @Nullable Object... args) throws GridException;
/**
* Asynchronously delegates to {@link GridCacheStore#loadCache(GridBiInClosure, Object...)} method
* to reload state from the underlying persistent storage. The reloaded values
* will then be given to the optionally passed in predicate, and if the predicate returns
* {@code true}, will be stored in cache. If predicate is {@code null}, then
* all reloaded values will be stored in cache.
* <p>
* Note that this method does not receive keys as a parameter, so it is up to
* {@link GridCacheStore} implementation to provide all the data to be loaded.
* <p>
* This method is not transactional and may end up loading a stale value into
* cache if another thread has updated the value immediately after it has been
* loaded. It is mostly useful when pre-loading the cache from underlying
* data store before start, or for read-only caches.
*
* @param p Optional predicate (may be {@code null}). If provided, will be used to
* filter values to be put into cache.
* @param ttl Time to live for loaded entries ({@code 0} for infinity).
* @param args Optional user arguments to be passed into
* {@link GridCacheStore#loadCache(GridBiInClosure,Object...)} method.
* @return Future to be completed whenever loading completes.
*/
public GridFuture<?> loadCacheAsync(@Nullable GridBiPredicate<K, V> p, long ttl, @Nullable Object... args);
/**
* Gets a random entry out of cache. In the worst cache scenario this method
* has complexity of <pre>O(S * N/64)</pre> where {@code N} is the size of internal hash
* table and {@code S} is the number of hash table buckets to sample, which is {@code 5}
* by default. However, if the table is pretty dense, with density factor of {@code N/64},
* which is true for near fully populated caches, this method will generally perform significantly
* faster with complexity of O(S) where {@code S = 5}.
* <p>
* Note that this method is not available on {@link GridCacheProjection} API since it is
* impossible (or very hard) to deterministically return a number value when pre-filtering
* and post-filtering is involved (e.g. projection level predicate filters).
*
* @return Random entry, or {@code null} if cache is empty.
*/
@Nullable public GridCacheEntry<K, V> randomEntry();
/**
* Runs DGC procedure on demand using
* {@link GridCacheConfiguration#getDgcSuspectLockTimeout()} to identify suspect locks.
* <p>
* Method blocks current thread until locks are examined and all DGC requests are sent
* to remote nodes.
* <p>
* DGC does not remove locks if {@link GridCacheConfiguration#isDgcRemoveLocks()}
* is set to {@code false}.
*/
public void dgc();
/**
* Runs DGC procedure on demand using provided parameter to identify suspect locks.
* <p>
* Method blocks current thread until locks are examined and all DGC requests are sent
* to remote nodes and (if {@code global} is {@code true}) all nodes running this cache
* will get signal to start GC procedure.
*
* @param suspectLockTimeout Custom suspect lock timeout (should be greater than or equal to 0).
* @param global If {@code true} then GC procedure will start on all nodes having this cache.
* @param rmvLocks If {@code false} then DGC does not remove locks, just report them to log.
*/
public void dgc(long suspectLockTimeout, boolean global, boolean rmvLocks);
/**
* Forces this cache node to re-balance its partitions. This method is usually used when
* {@link GridCacheConfiguration#getPreloadPartitionedDelay()} configuration parameter has non-zero value.
* When many nodes are started or stopped almost concurrently, it is more efficient to delay
* preloading until the node topology is stable to make sure that no redundant re-partitioning
* happens.
* <p>
* In case of{@link GridCacheMode#PARTITIONED} caches, for better efficiency user should
* usually make sure that new nodes get placed on the same place of consistent hash ring as
* the left nodes, and that nodes are restarted before
* {@link GridCacheConfiguration#getPreloadPartitionedDelay() preloadDelay} expires. To place nodes
* on the same place in consistent hash ring, use
* {@link GridCacheConsistentHashAffinityFunction#setHashIdResolver(GridCacheAffinityNodeHashResolver)} to make sure that
* a node maps to the same hash ID if re-started.
* <p>
* See {@link GridCacheConfiguration#getPreloadPartitionedDelay()} for more information on how to configure
* preload re-partition delay.
* <p>
* @return Future that will be completed when preloading is finished.
*/
public GridFuture<?> forceRepartition();
/**
* Resets metrics for current cache.
*/
public void resetMetrics();
}
| # GG-9116 - GridCacheStore in .NET
| modules/core/src/main/java/org/gridgain/grid/cache/GridCache.java | # GG-9116 - GridCacheStore in .NET | <ide><path>odules/core/src/main/java/org/gridgain/grid/cache/GridCache.java
<ide> * data store before start, or for read-only caches.
<ide> *
<ide> * @param p Optional predicate (may be {@code null}). If provided, will be used to
<add> * filter values to be put into cache.
<ide> * @param ttl Time to live for loaded entries ({@code 0} for infinity).
<del> * filter values to be put into cache.
<ide> * @param args Optional user arguments to be passed into
<ide> * {@link GridCacheStore#loadCache(GridBiInClosure, Object...)} method.
<ide> * @throws GridException If loading failed. |
|
JavaScript | mit | 4682f97946885d10a670be38ccb25cc0bd847786 | 0 | xing/hops,xing/hops,xing/hops |
var fetch = require('isomorphic-fetch');
var bindActionCreators = require('redux').bindActionCreators;
var createAction = require('./store').createAction;
function normalizeOptions(defaults, overrides) {
if (typeof defaults === 'string') {
defaults = { url: defaults };
}
if (typeof overrides === 'string') {
overrides = { url: overrides };
}
return Object.assign({}, defaults, overrides);
}
function generateHandlers(actions, dispatch) {
var defaults = {
requestWillStart: function () {},
responseWasReceived: function () {},
errorWasReceived: function (error) { throw error; }
};
var overrides = bindActionCreators(actions, dispatch);
return Object.assign({}, defaults, overrides);
}
function composeFetchAction(defaults, actions) {
return function (overrides) {
var options = normalizeOptions(defaults, overrides);
return function (dispatch) {
var handlers = generateHandlers(actions, dispatch);
handlers.requestWillStart();
return fetch(options.url, options)
.then(function (response) {
if (response.status >= 200 && response.status <= 304) {
return response.json();
}
else {
throw Object.assign(
new Error(response.statusText),
{ response: response }
);
}
})
.then(handlers.responseWasReceived)
.catch(handlers.errorWasReceived);
};
};
}
exports.createFetchAction = function (key, defaults) {
var update = createAction(key);
var actions = {
requestWillStart: function () {
return update({'loading': {'$set': true }});
},
responseWasReceived: function (data) {
return update({'$merge': {
loading: false,
error: false,
data: data
}});
},
errorWasReceived: function (error) {
return update({'$merge': {
loading: false,
error: error.message
}});
}
};
return composeFetchAction(defaults, actions);
};
exports.composeFetchAction = composeFetchAction;
| lib/network.js |
var fetch = require('isomorphic-fetch');
var createAction = require('./store').createAction;
exports.createFetchAction = function (key, url, defaults) {
var update = createAction(key);
return function (overrides) {
var options = Object.assign({}, defaults, overrides);
return function (dispatch) {
dispatch(update({'loading': {'$set': true }}));
return fetch(url, options)
.then(function (response) {
if (response.status >= 200 && response.status <= 304) {
return response.json();
}
else {
throw new Error(response.statusText);
}
})
.then(function (data) {
dispatch(update({'$merge': {
loading: false,
error: false,
data: data
}}));
})
.catch(function (error) {
dispatch(update({'$merge': {
loading: false,
error: error
}}));
});
};
};
};
| add composeFetchAction()
| lib/network.js | add composeFetchAction() | <ide><path>ib/network.js
<ide>
<ide> var fetch = require('isomorphic-fetch');
<add>var bindActionCreators = require('redux').bindActionCreators;
<ide>
<ide> var createAction = require('./store').createAction;
<ide>
<del>exports.createFetchAction = function (key, url, defaults) {
<del> var update = createAction(key);
<add>function normalizeOptions(defaults, overrides) {
<add> if (typeof defaults === 'string') {
<add> defaults = { url: defaults };
<add> }
<add> if (typeof overrides === 'string') {
<add> overrides = { url: overrides };
<add> }
<add> return Object.assign({}, defaults, overrides);
<add>}
<add>
<add>function generateHandlers(actions, dispatch) {
<add> var defaults = {
<add> requestWillStart: function () {},
<add> responseWasReceived: function () {},
<add> errorWasReceived: function (error) { throw error; }
<add> };
<add> var overrides = bindActionCreators(actions, dispatch);
<add> return Object.assign({}, defaults, overrides);
<add>}
<add>
<add>function composeFetchAction(defaults, actions) {
<ide> return function (overrides) {
<del> var options = Object.assign({}, defaults, overrides);
<add> var options = normalizeOptions(defaults, overrides);
<ide> return function (dispatch) {
<del> dispatch(update({'loading': {'$set': true }}));
<del> return fetch(url, options)
<add> var handlers = generateHandlers(actions, dispatch);
<add> handlers.requestWillStart();
<add> return fetch(options.url, options)
<ide> .then(function (response) {
<ide> if (response.status >= 200 && response.status <= 304) {
<ide> return response.json();
<ide> }
<ide> else {
<del> throw new Error(response.statusText);
<add> throw Object.assign(
<add> new Error(response.statusText),
<add> { response: response }
<add> );
<ide> }
<ide> })
<del> .then(function (data) {
<del> dispatch(update({'$merge': {
<del> loading: false,
<del> error: false,
<del> data: data
<del> }}));
<del> })
<del> .catch(function (error) {
<del> dispatch(update({'$merge': {
<del> loading: false,
<del> error: error
<del> }}));
<del> });
<add> .then(handlers.responseWasReceived)
<add> .catch(handlers.errorWasReceived);
<ide> };
<ide> };
<add>}
<add>
<add>exports.createFetchAction = function (key, defaults) {
<add> var update = createAction(key);
<add> var actions = {
<add> requestWillStart: function () {
<add> return update({'loading': {'$set': true }});
<add> },
<add> responseWasReceived: function (data) {
<add> return update({'$merge': {
<add> loading: false,
<add> error: false,
<add> data: data
<add> }});
<add> },
<add> errorWasReceived: function (error) {
<add> return update({'$merge': {
<add> loading: false,
<add> error: error.message
<add> }});
<add> }
<add> };
<add> return composeFetchAction(defaults, actions);
<ide> };
<add>
<add>exports.composeFetchAction = composeFetchAction; |
|
Java | apache-2.0 | 247703775cca1b9c693d16c8bc6c381ec6f44951 | 0 | corcoran/okhttp-oauth2-client | package ca.mimic.oauth2library;
import java.io.IOException;
import java.util.Map;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
class Utils {
protected static boolean isJsonResponse(Response response) {
return response.body() != null && response.body().contentType() != null && response.body().contentType().subtype().equals("json");
}
protected static Authenticator getAuthenticator(final OAuth2Client oAuth2Client,
final AuthState authState) {
return new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = "";
authState.nextState();
if (authState.isBasicAuth()) {
credential = Credentials.basic(oAuth2Client.getUsername(),
oAuth2Client.getPassword());
} else if (authState.isAuthorizationAuth()) {
credential = Credentials.basic(oAuth2Client.getClientId(),
oAuth2Client.getClientSecret());
} else if (authState.isFinalAuth()) {
return null;
}
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
return response.request().newBuilder()
.header(Constants.HEADER_AUTHORIZATION, credential)
.build();
}
};
}
protected static void postAddIfValid(FormBody.Builder formBodyBuilder, Map<String, String> params) {
if (params == null) return;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (isValid(entry.getValue())) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
}
}
private static boolean isValid(String s) {
return (s != null && s.trim().length() > 0);
}
}
| oauth2library/src/main/java/ca/mimic/oauth2library/Utils.java | package ca.mimic.oauth2library;
import java.io.IOException;
import java.util.Map;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
class Utils {
protected static boolean isJsonResponse(Response response) {
return response.body() != null && response.body().contentType().subtype().equals("json");
}
protected static Authenticator getAuthenticator(final OAuth2Client oAuth2Client,
final AuthState authState) {
return new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = "";
authState.nextState();
if (authState.isBasicAuth()) {
credential = Credentials.basic(oAuth2Client.getUsername(),
oAuth2Client.getPassword());
} else if (authState.isAuthorizationAuth()) {
credential = Credentials.basic(oAuth2Client.getClientId(),
oAuth2Client.getClientSecret());
} else if (authState.isFinalAuth()) {
return null;
}
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
return response.request().newBuilder()
.header(Constants.HEADER_AUTHORIZATION, credential)
.build();
}
};
}
protected static void postAddIfValid(FormBody.Builder formBodyBuilder, Map<String, String> params) {
if (params == null) return;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (isValid(entry.getValue())) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
}
}
private static boolean isValid(String s) {
return (s != null && s.trim().length() > 0);
}
}
| Fix NPE in case the content-type is empty in the response | oauth2library/src/main/java/ca/mimic/oauth2library/Utils.java | Fix NPE in case the content-type is empty in the response | <ide><path>auth2library/src/main/java/ca/mimic/oauth2library/Utils.java
<ide> class Utils {
<ide>
<ide> protected static boolean isJsonResponse(Response response) {
<del> return response.body() != null && response.body().contentType().subtype().equals("json");
<add> return response.body() != null && response.body().contentType() != null && response.body().contentType().subtype().equals("json");
<ide> }
<ide>
<ide> protected static Authenticator getAuthenticator(final OAuth2Client oAuth2Client, |
|
Java | apache-2.0 | 0976f42cb7818394aeaae974203981c71cff418c | 0 | jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient | package org.sagebionetworks.web.client.widget.entity.renderer;
import org.sagebionetworks.web.client.DisplayUtils;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class WikiSubpagesViewImpl extends LayoutContainer implements WikiSubpagesView {
private Presenter presenter;
@Inject
public WikiSubpagesViewImpl() {
this.setLayout(new FitLayout());
}
@Override
protected void onRender(com.google.gwt.user.client.Element parent, int index) {
super.onRender(parent, index);
};
@Override
public void configure(TreeItem root) {
clear();
//this widget shows nothing if it doesn't have any pages!
if (root == null)
return;
SimplePanel p = new SimplePanel();
p.addStyleName("pagesTree");
//only show the tree if the root has children
if (root != null && root.getChildCount() > 0) {
Tree t = new Tree();
t.addItem(root);
root.setState(true);
p.setWidget(t);
}
this.add(p);
this.layout(true);
}
@Override
public String getHTML(String href, String title, boolean isCurrentPage) {
StringBuilder html = new StringBuilder();
html.append("<a class=\"link");
if (isCurrentPage)
html.append(" boldText");
html.append("\" href=\"");
html.append(href);
html.append("\">");
html.append(title);
html.append("</a>");
return html.toString();
}
@Override
public Widget asWidget() {
return this;
}
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
@Override
public void showErrorMessage(String message) {
DisplayUtils.showErrorMessage(message);
}
@Override
public void showLoading() {
}
@Override
public void showInfo(String title, String message) {
DisplayUtils.showInfo(title, message);
}
@Override
public void clear() {
this.removeAll(true);
}
}
| src/main/java/org/sagebionetworks/web/client/widget/entity/renderer/WikiSubpagesViewImpl.java | package org.sagebionetworks.web.client.widget.entity.renderer;
import org.sagebionetworks.web.client.DisplayUtils;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class WikiSubpagesViewImpl extends LayoutContainer implements WikiSubpagesView {
private Presenter presenter;
@Inject
public WikiSubpagesViewImpl() {
this.setLayout(new FitLayout());
}
@Override
protected void onRender(com.google.gwt.user.client.Element parent, int index) {
super.onRender(parent, index);
};
@Override
public void configure(TreeItem root) {
clear();
//this widget shows nothing if it doesn't have any pages!
if (root == null)
return;
LayoutContainer lc = new LayoutContainer();
lc.addStyleName("span-24 notopmargin");
lc.setAutoWidth(true);
lc.setAutoHeight(true);
//only show the tree if the root has children
if (root != null && root.getChildCount() > 0) {
LayoutContainer files = new LayoutContainer();
files.setStyleName("pagesTree span-24 notopmargin");
Tree t = new Tree();
t.addItem(root);
root.setState(true);
files.add(t);
lc.add(files);
}
lc.layout(true);
this.add(lc);
this.layout(true);
}
@Override
public String getHTML(String href, String title, boolean isCurrentPage) {
StringBuilder html = new StringBuilder();
html.append("<a class=\"link");
if (isCurrentPage)
html.append(" boldText");
html.append("\" href=\"");
html.append(href);
html.append("\">");
html.append(title);
html.append("</a>");
return html.toString();
}
@Override
public Widget asWidget() {
return this;
}
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
@Override
public void showErrorMessage(String message) {
DisplayUtils.showErrorMessage(message);
}
@Override
public void showLoading() {
}
@Override
public void showInfo(String title, String message) {
DisplayUtils.showInfo(title, message);
}
@Override
public void clear() {
this.removeAll(true);
}
}
| SWC-677: greatly simplify layout for wiki subpage widget
| src/main/java/org/sagebionetworks/web/client/widget/entity/renderer/WikiSubpagesViewImpl.java | SWC-677: greatly simplify layout for wiki subpage widget | <ide><path>rc/main/java/org/sagebionetworks/web/client/widget/entity/renderer/WikiSubpagesViewImpl.java
<ide>
<ide> import com.extjs.gxt.ui.client.widget.LayoutContainer;
<ide> import com.extjs.gxt.ui.client.widget.layout.FitLayout;
<add>import com.google.gwt.user.client.ui.SimplePanel;
<ide> import com.google.gwt.user.client.ui.Tree;
<ide> import com.google.gwt.user.client.ui.TreeItem;
<ide> import com.google.gwt.user.client.ui.Widget;
<ide> //this widget shows nothing if it doesn't have any pages!
<ide> if (root == null)
<ide> return;
<del> LayoutContainer lc = new LayoutContainer();
<del> lc.addStyleName("span-24 notopmargin");
<del> lc.setAutoWidth(true);
<del> lc.setAutoHeight(true);
<del>
<add> SimplePanel p = new SimplePanel();
<add> p.addStyleName("pagesTree");
<ide> //only show the tree if the root has children
<ide> if (root != null && root.getChildCount() > 0) {
<del> LayoutContainer files = new LayoutContainer();
<del> files.setStyleName("pagesTree span-24 notopmargin");
<ide> Tree t = new Tree();
<ide> t.addItem(root);
<ide> root.setState(true);
<del> files.add(t);
<del> lc.add(files);
<add> p.setWidget(t);
<ide> }
<ide>
<del> lc.layout(true);
<del> this.add(lc);
<add> this.add(p);
<ide> this.layout(true);
<ide> }
<ide> |
|
Java | agpl-3.0 | 2ec3d529f0ab6ed891fe376981eb74d0a656612c | 0 | roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,aihua/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,aihua/opennms,aihua/opennms,rdkgit/opennms | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2005 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
package org.opennms.netmgt.collectd;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.DataCollectionConfigFactory;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSnmpInterface;
public class CollectionSet {
private CollectionAgent m_agent;
private String m_collectionName;
private Map m_ifMap = new TreeMap();
public CollectionSet(CollectionAgent agent, String collectionName) {
m_agent = agent;
m_collectionName = collectionName;
addSnmpInterfacesToCollectionSet();
}
public Map getIfMap() {
return m_ifMap;
}
public void setIfMap(Map ifMap) {
m_ifMap = ifMap;
}
public NodeInfo getNodeInfo() {
return new NodeInfo(m_agent, m_collectionName);
}
void addIfInfo(IfInfo ifInfo) {
getIfMap().put(new Integer(ifInfo.getIndex()), ifInfo);
}
boolean hasDataToCollect() {
if (!getNodeInfo().getAttributeList().isEmpty()) return true;
return hasInterfaceDataToCollect();
}
boolean hasInterfaceDataToCollect() {
Iterator iter = getIfMap().values().iterator();
while (iter.hasNext()) {
CollectionResource ifInfo = (CollectionResource) iter.next();
if (!ifInfo.getAttributeList().isEmpty()) {
return true;
}
}
return false;
}
public String getCollectionName() {
return m_collectionName;
}
public CollectionAgent getCollectionAgent() {
return m_agent;
}
void addSnmpInterface(OnmsSnmpInterface snmpIface) {
addIfInfo(new IfInfo(m_agent, m_collectionName, snmpIface));
}
void logInitializeSnmpIface(OnmsSnmpInterface snmpIface) {
if (log().isDebugEnabled()) {
log()
.debug(
"initialize: snmpifindex = " + snmpIface.getIfIndex().intValue()
+ ", snmpifname = " + snmpIface.getIfName()
+ ", snmpifdescr = " + snmpIface.getIfDescr()
+ ", snmpphysaddr = -"+ snmpIface.getPhysAddr() + "-");
}
if (log().isDebugEnabled()) {
log().debug("initialize: ifLabel = '" + snmpIface.computeLabelForRRD() + "'");
}
}
private Category log() {
return ThreadCategory.getInstance(getClass());
}
void addSnmpInterfacesToCollectionSet() {
CollectionAgent agent = getCollectionAgent();
OnmsNode node = agent.getNode();
Set snmpIfs = node.getSnmpInterfaces();
for (Iterator it = snmpIfs.iterator(); it.hasNext();) {
OnmsSnmpInterface snmpIface = (OnmsSnmpInterface) it.next();
logInitializeSnmpIface(snmpIface);
addSnmpInterface(snmpIface);
}
}
public String getStorageFlag() {
String collectionName = m_collectionName;
String storageFlag = DataCollectionConfigFactory.getInstance()
.getSnmpStorageFlag(collectionName);
if (storageFlag == null) {
if (log().isEnabledFor(Priority.WARN)) {
log().warn(
"initialize: Configuration error, failed to "
+ "retrieve SNMP storage flag for collection: "
+ collectionName);
}
storageFlag = SnmpCollector.SNMP_STORAGE_PRIMARY;
}
return storageFlag;
}
int getMaxVarsPerPdu() {
// Retrieve configured value for max number of vars per PDU
int maxVarsPerPdu = DataCollectionConfigFactory.getInstance().getMaxVarsPerPdu(m_collectionName);
if (maxVarsPerPdu == -1) {
if (log().isEnabledFor(Priority.WARN)) {
log().warn(
"initialize: Configuration error, failed to "
+ "retrieve max vars per pdu from collection: "
+ m_collectionName);
}
maxVarsPerPdu = SnmpCollector.DEFAULT_MAX_VARS_PER_PDU;
}
return maxVarsPerPdu;
}
void verifyCollectionIsNecessary(CollectionAgent agent) {
/*
* Verify that there is something to collect from this primary SMP
* interface. If no node objects and no interface objects then throw
* exception
*/
if (!hasDataToCollect()) {
throw new RuntimeException("collection '" + getCollectionName()
+ "' defines nothing to collect for "
+ agent);
}
}
List getAttributeList() {
return getNodeInfo().getAttributeList();
}
List getCombinedInterfaceAttributes() {
Set attributes = new LinkedHashSet();
for (Iterator it = getIfMap().values().iterator(); it.hasNext();) {
CollectionResource ifInfo = (CollectionResource) it.next();
attributes.addAll(ifInfo.getAttributeList());
}
return new ArrayList(attributes);
}
IfInfo getIfInfo(int ifIndex) {
return (IfInfo) getIfMap().get(new Integer(ifIndex));
}
public Collection getIfInfos() {
return getIfMap().values();
}
}
| src/services/org/opennms/netmgt/collectd/CollectionSet.java | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2005 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
package org.opennms.netmgt.collectd;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.DataCollectionConfigFactory;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSnmpInterface;
public class CollectionSet {
private CollectionAgent m_agent;
private String m_collectionName;
private Map m_ifMap = new TreeMap();
public CollectionSet(CollectionAgent agent, String collectionName) {
m_agent = agent;
m_collectionName = collectionName;
addSnmpInterfacesToCollectionSet();
}
public Map getIfMap() {
return m_ifMap;
}
public void setIfMap(Map ifMap) {
m_ifMap = ifMap;
}
public NodeInfo getNodeInfo() {
return new NodeInfo(m_agent, m_collectionName);
}
void addIfInfo(IfInfo ifInfo) {
getIfMap().put(new Integer(ifInfo.getIndex()), ifInfo);
}
boolean hasDataToCollect() {
if (!getNodeInfo().getAttributeList().isEmpty()) return true;
return hasInterfaceDataToCollect();
}
boolean hasInterfaceDataToCollect() {
Iterator iter = getIfMap().values().iterator();
while (iter.hasNext()) {
CollectionResource ifInfo = (CollectionResource) iter.next();
if (!ifInfo.getAttributeList().isEmpty()) {
return true;
}
}
return false;
}
public String getCollectionName() {
return m_collectionName;
}
public CollectionAgent getCollectionAgent() {
return m_agent;
}
void addSnmpInterface(OnmsSnmpInterface snmpIface) {
addIfInfo(new IfInfo(m_agent, m_collectionName, snmpIface));
}
void logInitializeSnmpIface(OnmsSnmpInterface snmpIface) {
if (log().isDebugEnabled()) {
log()
.debug(
"initialize: snmpifindex = " + snmpIface.getIfIndex().intValue()
+ ", snmpifname = " + snmpIface.getIfName()
+ ", snmpifdescr = " + snmpIface.getIfDescr()
+ ", snmpphysaddr = -"+ snmpIface.getPhysAddr() + "-");
}
if (log().isDebugEnabled()) {
log().debug("initialize: ifLabel = '" + snmpIface.computeLabelForRRD() + "'");
}
}
private Category log() {
return ThreadCategory.getInstance(getClass());
}
void addSnmpInterfacesToCollectionSet() {
CollectionAgent agent = getCollectionAgent();
OnmsNode node = agent.getNode();
Set snmpIfs = node.getSnmpInterfaces();
for (Iterator it = snmpIfs.iterator(); it.hasNext();) {
OnmsSnmpInterface snmpIface = (OnmsSnmpInterface) it.next();
logInitializeSnmpIface(snmpIface);
addSnmpInterface(snmpIface);
}
}
public String getStorageFlag() {
String collectionName = m_collectionName;
String storageFlag = DataCollectionConfigFactory.getInstance()
.getSnmpStorageFlag(collectionName);
if (storageFlag == null) {
if (log().isEnabledFor(Priority.WARN)) {
log().warn(
"initialize: Configuration error, failed to "
+ "retrieve SNMP storage flag for collection: "
+ collectionName);
}
storageFlag = SnmpCollector.SNMP_STORAGE_PRIMARY;
}
return storageFlag;
}
int getMaxVarsPerPdu() {
// Retrieve configured value for max number of vars per PDU
int maxVarsPerPdu = DataCollectionConfigFactory.getInstance().getMaxVarsPerPdu(m_collectionName);
if (maxVarsPerPdu == -1) {
if (log().isEnabledFor(Priority.WARN)) {
log().warn(
"initialize: Configuration error, failed to "
+ "retrieve max vars per pdu from collection: "
+ m_collectionName);
}
maxVarsPerPdu = SnmpCollector.DEFAULT_MAX_VARS_PER_PDU;
}
return maxVarsPerPdu;
}
void verifyCollectionIsNecessary(CollectionAgent agent) {
/*
* Verify that there is something to collect from this primary SMP
* interface. If no node objects and no interface objects then throw
* exception
*/
if (!hasDataToCollect()) {
throw new RuntimeException("collection '" + getCollectionName()
+ "' defines nothing to collect for "
+ agent);
}
}
List getAttributeList() {
return getNodeInfo().getAttributeList();
}
List getCombinedInterfaceAttributes() {
Set attributes = new LinkedHashSet();
for (Iterator it = getIfMap().values().iterator(); it.hasNext();) {
CollectionResource ifInfo = (CollectionResource) it.next();
attributes.addAll(ifInfo.getAttributeList());
}
return new ArrayList(attributes);
}
IfInfo getIfInfo(int ifIndex) {
return (IfInfo) getIfMap().get(new Integer(ifIndex));
}
public Collection getIfInfos() {
return getIfMap().keySet();
}
}
| fix getIfInfos to use values rather than keySet.. oops
| src/services/org/opennms/netmgt/collectd/CollectionSet.java | fix getIfInfos to use values rather than keySet.. oops | <ide><path>rc/services/org/opennms/netmgt/collectd/CollectionSet.java
<ide> }
<ide>
<ide> public Collection getIfInfos() {
<del> return getIfMap().keySet();
<add> return getIfMap().values();
<ide> }
<ide>
<ide> } |
|
Java | mit | 2743eeab870dc53adc838731b1a94bc88af6c21e | 0 | samarth-math/project-connect | package LogMaintainence;
import globalfunctions.Contact;
import java.io.*;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import GuiElements.ChatWindowPanelReceiver;
import GuiElements.ChatWindowPanelSender;
import serverclient.MainStart;
public class GettingChatLogs extends Object{
@SuppressWarnings("unchecked")
public static void readLog(String userId)
{
String chatFileName = userId+".json"; // file name based on userId
String oldPathString = System.getProperty("user.dir");
String newPathString = oldPathString+"/chatlogs";
File newPath = new File(newPathString);
File chatFilePath = new File(newPath,chatFileName);
String myId = MainStart.myID;
Contact person = MainStart.people.get(userId); //person needed to get the correct chat window
long sessionTraversalCount = 0;
JSONParser parser = new JSONParser();
if(chatFilePath.exists())
{
try {
Object obj = parser.parse(new FileReader(chatFilePath));
JSONObject logInfo = (JSONObject)obj;
long sessionValue = (long)logInfo.get("lastUpdatedSession");
sessionTraversalCount = sessionValue;
JSONObject oldSessionObject = (JSONObject)logInfo.get("session");
JSONArray oldMessageArray;
int i=1;
while(i<=sessionTraversalCount)
{
//System.out.println("session : "+i);
oldMessageArray = (JSONArray)oldSessionObject.get(""+i);
Iterator<JSONObject> oldMessageIterator = oldMessageArray.iterator();
while (oldMessageIterator.hasNext())
{
JSONObject messageObject = (JSONObject)oldMessageIterator.next();
if(messageObject.get("userId").equals(myId))
{
String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
ChatWindowPanelSender cwsp = new ChatWindowPanelSender(s1, messageObject.get("timeStamp").toString());
person.getWindow().chatconsole(cwsp);
}
else
{
String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
ChatWindowPanelReceiver cwrp = new ChatWindowPanelReceiver(s1, messageObject.get("timeStamp").toString());
person.getWindow().chatconsole(cwrp);
}
}
System.out.println();
i++;
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParseException e)
{
e.printStackTrace();
}
}
else
{
//System.out.println("No chats exist\n");
}
}
}
| IPml/src/LogMaintainence/GettingChatLogs.java | package LogMaintainence;
import globalfunctions.Contact;
import java.io.*;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import GuiElements.ChatWindowPanelReceiver;
import GuiElements.ChatWindowPanelSender;
import serverclient.MainStart;
public class GettingChatLogs extends Object{
@SuppressWarnings("unchecked")
public static void readLog(String userId)
{
String chatFileName = userId+".json"; // file name based on userId
String oldPathString = System.getProperty("user.dir");
String newPathString = oldPathString+"/chatlogs";
File newPath = new File(newPathString);
File chatFilePath = new File(newPath,chatFileName);
String myId = MainStart.myID;
Contact person = MainStart.people.get(userId); //person needed to get the correct chat window
long sessionTraversalCount = 0;
JSONParser parser = new JSONParser();
if(chatFilePath.exists())
{
try {
Object obj = parser.parse(new FileReader(chatFilePath));
JSONObject logInfo = (JSONObject)obj;
long sessionValue = (long)logInfo.get("lastUpdatedSession");
sessionTraversalCount = sessionValue;
JSONObject oldSessionObject = (JSONObject)logInfo.get("session");
JSONArray oldMessageArray;
int i=1;
while(i<=sessionTraversalCount)
{
//System.out.println("session : "+i);
oldMessageArray = (JSONArray)oldSessionObject.get(""+i);
Iterator<JSONObject> oldMessageIterator = oldMessageArray.iterator();
while (oldMessageIterator.hasNext())
{
JSONObject messageObject = (JSONObject)oldMessageIterator.next();
if(messageObject.get("userId").equals(myId))
{
String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
ChatWindowPanelSender cwsp = new ChatWindowPanelSender(s1, messageObject.get("timeStamp").toString());
person.getWindow().chatconsole(cwsp);
}
else
{
String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
ChatWindowPanelReceiver cwrp = new ChatWindowPanelReceiver(s1, messageObject.get("timeStamp").toString());
person.getWindow().chatconsole(cwrp);
}
}
System.out.println();
i++;
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParseException e)
{
e.printStackTrace();
}
}
else
{
System.out.println("No chats exist\n");
}
}
}
| Minor change in GeetingChatLogs | IPml/src/LogMaintainence/GettingChatLogs.java | Minor change in GeetingChatLogs | <ide><path>Pml/src/LogMaintainence/GettingChatLogs.java
<ide> if(chatFilePath.exists())
<ide> {
<ide> try {
<del> Object obj = parser.parse(new FileReader(chatFilePath));
<del> JSONObject logInfo = (JSONObject)obj;
<add> Object obj = parser.parse(new FileReader(chatFilePath));
<add> JSONObject logInfo = (JSONObject)obj;
<ide>
<del> long sessionValue = (long)logInfo.get("lastUpdatedSession");
<add> long sessionValue = (long)logInfo.get("lastUpdatedSession");
<ide>
<del> sessionTraversalCount = sessionValue;
<add> sessionTraversalCount = sessionValue;
<ide>
<del> JSONObject oldSessionObject = (JSONObject)logInfo.get("session");
<del> JSONArray oldMessageArray;
<del> int i=1;
<del> while(i<=sessionTraversalCount)
<del> {
<del> //System.out.println("session : "+i);
<add> JSONObject oldSessionObject = (JSONObject)logInfo.get("session");
<add> JSONArray oldMessageArray;
<add> int i=1;
<add> while(i<=sessionTraversalCount)
<add> {
<add> //System.out.println("session : "+i);
<ide>
<del> oldMessageArray = (JSONArray)oldSessionObject.get(""+i);
<add> oldMessageArray = (JSONArray)oldSessionObject.get(""+i);
<ide>
<del> Iterator<JSONObject> oldMessageIterator = oldMessageArray.iterator();
<del> while (oldMessageIterator.hasNext())
<del> {
<del> JSONObject messageObject = (JSONObject)oldMessageIterator.next();
<del> if(messageObject.get("userId").equals(myId))
<del> {
<del> String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
<del> ChatWindowPanelSender cwsp = new ChatWindowPanelSender(s1, messageObject.get("timeStamp").toString());
<del> person.getWindow().chatconsole(cwsp);
<add> Iterator<JSONObject> oldMessageIterator = oldMessageArray.iterator();
<add> while (oldMessageIterator.hasNext())
<add> {
<add> JSONObject messageObject = (JSONObject)oldMessageIterator.next();
<add> if(messageObject.get("userId").equals(myId))
<add> {
<add> String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
<add> ChatWindowPanelSender cwsp = new ChatWindowPanelSender(s1, messageObject.get("timeStamp").toString());
<add> person.getWindow().chatconsole(cwsp);
<ide>
<add> }
<add> else
<add> {
<add> String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
<add> ChatWindowPanelReceiver cwrp = new ChatWindowPanelReceiver(s1, messageObject.get("timeStamp").toString());
<add> person.getWindow().chatconsole(cwrp);
<add>
<add> }
<add>
<ide> }
<del> else
<del> {
<del> String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText"));
<del> ChatWindowPanelReceiver cwrp = new ChatWindowPanelReceiver(s1, messageObject.get("timeStamp").toString());
<del> person.getWindow().chatconsole(cwrp);
<del>
<del> }
<del>
<add> System.out.println();
<add> i++;
<ide> }
<del> System.out.println();
<del> i++;
<add>
<add> }
<add>
<add> catch (FileNotFoundException e)
<add> {
<add> e.printStackTrace();
<add> }
<add> catch (IOException e)
<add> {
<add> e.printStackTrace();
<add> }
<add> catch (ParseException e)
<add> {
<add> e.printStackTrace();
<add> }
<ide> }
<del>
<del> }
<del>
<del> catch (FileNotFoundException e)
<del> {
<del> e.printStackTrace();
<del> }
<del> catch (IOException e)
<del> {
<del> e.printStackTrace();
<del> }
<del> catch (ParseException e)
<del> {
<del> e.printStackTrace();
<del> }
<add> else
<add> {
<add> //System.out.println("No chats exist\n");
<ide> }
<del> else
<del> {
<del> System.out.println("No chats exist\n");
<ide> }
<del> }
<ide>
<ide> } |
|
JavaScript | mit | c26e37b06b2f379499d2cc487142d0951861565f | 0 | matreshkajs/matreshka_examples,matreshkajs/matreshka_examples | // store html binder in a short variable
const htmlBinder = Matreshka.binders.html;
// create a class that inherits Matreshka
class Application extends Matreshka {
constructor() {
super();
// bind the property x and the text field
this.bindNode('x', '.my-input');
// bind the property x and the ".my-output" block
this.bindNode('x', '.my-output', htmlBinder());
// if the property "х" has changed,
// inform about it in the console
this.on('change:x', () =>
console.log(`x изменен на "${this.x}"`));
}
}
const app = new Application();
app.x = 'Hello World!';
| hello-world/js/app.js | // сохраняем html байндер в переменную с коротким именем
const htmlBinder = Matreshka.binders.html;
// создаём класс, который наследуется от Matreshka
class Application extends Matreshka {
constructor() {
super();
// связываем свойство x и текстовое поле
this.bindNode('x', '.my-input');
// связываем свойство x и блок с классом my-output
this.bindNode('x', '.my-output', htmlBinder());
// слушаем изменения свойства x
this.on('change:x', () =>
console.log(`x изменен на "${this.x}"`));
}
}
const app = new Application();
| update hello-world
| hello-world/js/app.js | update hello-world | <ide><path>ello-world/js/app.js
<del>// сохраняем html байндер в переменную с коротким именем
<add>// store html binder in a short variable
<ide> const htmlBinder = Matreshka.binders.html;
<ide>
<del>// создаём класс, который наследуется от Matreshka
<add>// create a class that inherits Matreshka
<ide> class Application extends Matreshka {
<ide> constructor() {
<ide> super();
<ide>
<del> // связываем свойство x и текстовое поле
<add> // bind the property x and the text field
<ide> this.bindNode('x', '.my-input');
<ide>
<del> // связываем свойство x и блок с классом my-output
<add> // bind the property x and the ".my-output" block
<ide> this.bindNode('x', '.my-output', htmlBinder());
<ide>
<del> // слушаем изменения свойства x
<add> // if the property "х" has changed,
<add> // inform about it in the console
<ide> this.on('change:x', () =>
<ide> console.log(`x изменен на "${this.x}"`));
<ide> }
<ide> }
<ide>
<ide> const app = new Application();
<add>
<add>app.x = 'Hello World!'; |
|
Java | apache-2.0 | 5e2745d04020f46860c3471d11e0d6c5ea82d724 | 0 | DigitalPebble/storm-crawler,DigitalPebble/storm-crawler | /**
* Licensed to DigitalPebble Ltd under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* DigitalPebble licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpebble.stormcrawler.solr.persistence;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.digitalpebble.stormcrawler.Metadata;
import com.digitalpebble.stormcrawler.persistence.AbstractStatusUpdaterBolt;
import com.digitalpebble.stormcrawler.persistence.Status;
import com.digitalpebble.stormcrawler.solr.SolrConnection;
import com.digitalpebble.stormcrawler.util.ConfUtils;
import com.digitalpebble.stormcrawler.util.URLUtil;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
public class StatusUpdaterBolt extends AbstractStatusUpdaterBolt {
private static final Logger LOG = LoggerFactory
.getLogger(StatusUpdaterBolt.class);
private static final String BOLT_TYPE = "status";
private static final String SolrMetadataPrefix = "solr.status.metadata.prefix";
private String mdPrefix;
private SolrConnection connection;
@Override
public void prepare(Map stormConf, TopologyContext context,
OutputCollector collector) {
super.prepare(stormConf, context, collector);
mdPrefix = ConfUtils.getString(stormConf, SolrMetadataPrefix,
"metadata");
try {
connection = SolrConnection.getConnection(stormConf, BOLT_TYPE);
} catch (Exception e) {
LOG.error("Can't connect to Solr: {}", e);
throw new RuntimeException(e);
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
@Override
public void store(String url, Status status, Metadata metadata,
Date nextFetch) throws Exception {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("url", url);
doc.setField("host", URLUtil.getHost(url));
doc.setField("status", status.name());
Iterator<String> keyIterator = metadata.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
String[] values = metadata.getValues(key);
doc.setField(String.format("%s.%s", mdPrefix, key), values);
}
doc.setField("nextFetchDate", nextFetch);
connection.getClient().add(doc);
}
@Override
public void cleanup() {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
LOG.error("Can't close connection to Solr: {}", e);
}
}
}
}
| external/solr/src/main/java/com/digitalpebble/stormcrawler/solr/persistence/StatusUpdaterBolt.java | /**
* Licensed to DigitalPebble Ltd under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* DigitalPebble licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpebble.stormcrawler.solr.persistence;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.digitalpebble.stormcrawler.Metadata;
import com.digitalpebble.stormcrawler.persistence.AbstractStatusUpdaterBolt;
import com.digitalpebble.stormcrawler.persistence.Status;
import com.digitalpebble.stormcrawler.solr.SolrConnection;
import com.digitalpebble.stormcrawler.util.ConfUtils;
import com.digitalpebble.stormcrawler.util.URLUtil;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
public class StatusUpdaterBolt extends AbstractStatusUpdaterBolt {
private static final Logger LOG = LoggerFactory
.getLogger(StatusUpdaterBolt.class);
private static final String BOLT_TYPE = "status";
private static final String SolrMetadataPrefix = "solr.status.metadata.prefix";
private String mdPrefix;
private SolrConnection connection;
@Override
public void prepare(Map stormConf, TopologyContext context,
OutputCollector collector) {
super.prepare(stormConf, context, collector);
mdPrefix = ConfUtils.getString(stormConf, SolrMetadataPrefix,
"metadata");
try {
connection = SolrConnection.getConnection(stormConf, BOLT_TYPE);
} catch (Exception e) {
LOG.error("Can't connect to Solr: {}", e);
throw new RuntimeException(e);
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
@Override
public void store(String url, Status status, Metadata metadata,
Date nextFetch) throws Exception {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("url", url);
doc.setField("host", URLUtil.getHost(url));
doc.setField("status", status);
Iterator<String> keyIterator = metadata.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
String[] values = metadata.getValues(key);
doc.setField(String.format("%s.%s", mdPrefix, key), values);
}
doc.setField("nextFetchDate", nextFetch);
connection.getClient().add(doc);
}
@Override
public void cleanup() {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
LOG.error("Can't close connection to Solr: {}", e);
}
}
}
}
| SOLR StatusUpdater use short status name, fixes #627
| external/solr/src/main/java/com/digitalpebble/stormcrawler/solr/persistence/StatusUpdaterBolt.java | SOLR StatusUpdater use short status name, fixes #627 | <ide><path>xternal/solr/src/main/java/com/digitalpebble/stormcrawler/solr/persistence/StatusUpdaterBolt.java
<ide>
<ide> doc.setField("host", URLUtil.getHost(url));
<ide>
<del> doc.setField("status", status);
<add> doc.setField("status", status.name());
<ide>
<ide> Iterator<String> keyIterator = metadata.keySet().iterator();
<ide> while (keyIterator.hasNext()) { |
|
Java | apache-2.0 | 008aa2621ad9809638f0f1703d941ed7e236c2ff | 0 | campbe13/JavaSourceSamples360 | //package fromslides.S09;
import java.util.Scanner;
/**
* This class illustrates exercises from the slide deck for the course
* 360-420-DW Intro to Java
* @author PMCampbell
* @version today
**/
public class PassByValue
{
public static void main(String[] args)
{
int number = 99;
System.out.println("Number is "+number);
changeMe(number); // Call changeMe
// Display the value in number again
System.out.println("number is " + number); // Display the value in number
} // main()
/**
* The changeMe method accepts an argument and then
* changes the value of the parameter
* what really happens?
*
* @param number int
@author PMC
@version today
*/
public static void changeMe(int myValue)
{
System.out.println("I am changing the value.");
myValue = 0;
System.out.println("Now the value is " + myValue);
} //changeMe()
} // PassByValue | fromslides/S09/PassByValue.java | //package fromslides.S08;
import java.util.Scanner;
/**
* This class illustrates exercises from the slide deck for the course
* 360-420-DW Intro to Java
* @author PMCampbell
* @version today
**/
public class SimpleMethods2
{
public static void main(String[] args)
{
int num1, num2;
message("Teachers");
num1 = readInt();
num2 = readInt();
showMinMax(num1, num2);
message("P. M. Campbell");
} // main()
/**
* Compares the two parameters
* returns the smallest of the two
*
* @param a integer
* @param b integer
* @return smallest of a and b integer
* @author PMCampbell
* @version today
* */
public static int min(int a, int b) {
int small;
if ( a > b)
small = b;
else
small = a;
return small;
} // min()
/**
* Compares the two parameters
* returns the largest of the two
*
* @param a integer
* @param b integer
* @return largest of a and b
* @author PMCampbell
* @version today
* */
public static int max(int a, int b) {
int big;
if ( a > b)
big = a;
else
big = b;
return big;
} // max()
/**
* Displays the numbers given as params
* Determines the smallest of the two and displays it
* Determines the largest of the two and displays it
*
* @param num1 int
* @param num2 int
* @author PMCampbell
* @version today
* */
public static void showMinMax(int num1, int num2) {
System.out.printf("Given %d and %d\n", num1, num2);
System.out.println("Smallest is "+ min(num1,num2));
System.out.println("Biggest is "+ max(num1,num2));
} // showMinMax()
/**
* Displays a prompt, reads in an int
*
* @return int
* @author PMCampbell
* @version today
* */
public static int readInt() {
int num;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
num = keyboard.nextInt();
return num;
} // readInt()
/**
* Displays a message
*
* @param programmer name String
* @author PMCampbell
* @version today
* */
public static void message(String programmer) {
System.out.println("Brought to you by Dawson College "+programmer);
} // message()
} // SimpleMethods2
| source for slides 9
| fromslides/S09/PassByValue.java | source for slides 9 | <ide><path>romslides/S09/PassByValue.java
<del>//package fromslides.S08;
<add>//package fromslides.S09;
<ide> import java.util.Scanner;
<ide> /**
<ide> * This class illustrates exercises from the slide deck for the course
<ide> * @author PMCampbell
<ide> * @version today
<ide> **/
<del>public class SimpleMethods2
<add>public class PassByValue
<ide> {
<del>
<ide> public static void main(String[] args)
<ide> {
<del> int num1, num2;
<add> int number = 99;
<ide>
<del> message("Teachers");
<del>
<del> num1 = readInt();
<del> num2 = readInt();
<del>
<del> showMinMax(num1, num2);
<del>
<del> message("P. M. Campbell");
<del> } // main()
<del>
<del> /**
<del> * Compares the two parameters
<del> * returns the smallest of the two
<del> *
<del> * @param a integer
<del> * @param b integer
<del> * @return smallest of a and b integer
<del> * @author PMCampbell
<del> * @version today
<del> * */
<del>
<del> public static int min(int a, int b) {
<del> int small;
<del> if ( a > b)
<del> small = b;
<del> else
<del> small = a;
<del>
<del> return small;
<del> } // min()
<del>
<del> /**
<del> * Compares the two parameters
<del> * returns the largest of the two
<del> *
<del> * @param a integer
<del> * @param b integer
<del> * @return largest of a and b
<del> * @author PMCampbell
<del> * @version today
<del> * */
<del>
<del> public static int max(int a, int b) {
<del> int big;
<del> if ( a > b)
<del> big = a;
<del> else
<del> big = b;
<del>
<del> return big;
<del> } // max()
<del>
<del> /**
<del> * Displays the numbers given as params
<del> * Determines the smallest of the two and displays it
<del> * Determines the largest of the two and displays it
<del> *
<del> * @param num1 int
<del> * @param num2 int
<del> * @author PMCampbell
<del> * @version today
<del> * */
<del>
<del>
<del> public static void showMinMax(int num1, int num2) {
<del> System.out.printf("Given %d and %d\n", num1, num2);
<del> System.out.println("Smallest is "+ min(num1,num2));
<del> System.out.println("Biggest is "+ max(num1,num2));
<del> } // showMinMax()
<del>
<del> /**
<del> * Displays a prompt, reads in an int
<del> *
<del> * @return int
<del> * @author PMCampbell
<del> * @version today
<del> * */
<del>
<del> public static int readInt() {
<del> int num;
<del> Scanner keyboard = new Scanner(System.in);
<del>
<del> System.out.print("Enter an integer: ");
<del> num = keyboard.nextInt();
<del> return num;
<del>
<del> } // readInt()
<del>
<del> /**
<del> * Displays a message
<del> *
<del> * @param programmer name String
<del> * @author PMCampbell
<del> * @version today
<del> * */
<del>
<del> public static void message(String programmer) {
<del> System.out.println("Brought to you by Dawson College "+programmer);
<del> } // message()
<del>} // SimpleMethods2
<add> System.out.println("Number is "+number);
<add>
<add> changeMe(number); // Call changeMe
<add>
<add> // Display the value in number again
<add> System.out.println("number is " + number); // Display the value in number
<add> } // main()
<add>
<add> /**
<add> * The changeMe method accepts an argument and then
<add> * changes the value of the parameter
<add> * what really happens?
<add> *
<add> * @param number int
<add> @author PMC
<add> @version today
<add> */
<add> public static void changeMe(int myValue)
<add> {
<add> System.out.println("I am changing the value.");
<add> myValue = 0;
<add> System.out.println("Now the value is " + myValue);
<add> } //changeMe()
<add>} // PassByValue |
|
Java | apache-2.0 | 66955576db2bff6daf27a3b75165848c48dff71e | 0 | happy6666/remote_r | import org.jsoup.Jsoup;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.RList;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;
public abstract class EmailRecSend {
public static boolean retry = false;
private static Store store = null;
private static final String host = "pop.sina.com";
private static final String provider = "pop3";
private static final String username;
private static final String password;
private static final String keyword;
static {
username = Configurator.getProperties("username");
password = Configurator.getProperties("password");
keyword = Configurator.getProperties("keyword");
}
public static List<Pair> ReceiveMail() throws REXPMismatchException, MessagingException {
System.out.println("Receive email");
List<Pair> res = new ArrayList<Pair>();
Properties props = System.getProperties();
String cin = "";
Folder inbox = null;
try {
if (store == null) {
// 连接到POP3服务器
Session ss = Session.getDefaultInstance(props, null);
// 向回话"请求"一个某种提供者的存储库,是一个POP3提供者
System.out.println("Get store");
store = ss.getStore(provider);
} else {
System.out.println("Store is ready");
}
if (!store.isConnected()) {
// 连接存储库,从而可以打开存储库中的文件夹,此时是面向IMAP的
System.out.println("Connect to store");
TimeoutConnect.timeoutConnect(store, host, username, password, 10 * 1000);
} else {
System.out.println("Connection is ready");
}
// 打开文件夹,此时是关闭的,只能对其进行删除或重命名,无法获取关闭文件夹的信息
// 从存储库的默认文件夹INBOX中读取邮件
System.out.println("Get inbox");
inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("NO INBOX");
System.exit(1);
}
// 打开文件夹,读取信息
System.out.println("Open inbox");
inbox.open(Folder.READ_WRITE);
System.out.println("TOTAL EMAIL:" + inbox.getMessageCount());
// 获取邮件服务器中的邮件
Message[] messages = inbox.getMessages();
String from = null;
cin = null;
for (int i = messages.length - 1; i >= 0; i--) {
Set<String> codeset = new HashSet<String>();
// 解析地址为字符串
from = InternetAddress.toString(messages[i].getFrom());
if (from != null) {
cin = getChineseFrom(from);
}
String subject = messages[i].getSubject().trim();
if (subject.toLowerCase().contains(keyword)) {
StringBuffer errorcontent = new StringBuffer();
StringBuffer content = new StringBuffer(30);
getMailTextContent(messages[i], content);
System.out.println("------------Message--" + (i + 1) + "------------");
System.out.println("From:" + cin);
if (subject != null) System.out.println("Subject:" + subject);
System.out.println(content.toString());
System.out.println("----------------------------");
for (String part : content.toString().trim().split("\n")) {
String[] slist = part.trim().split("[\\s\\r\\n]");
for (String subq : slist) {
if (subq.contains(":")) {
String[] q = subq.split(":");
try {
if (q.length == 2 && q[0].length() == 6 && (!codeset.contains(q[0].trim()))) {
codeset.add(q[0].trim());
System.out.println("Find:" + q[0].trim() + "\t" + q[1].trim());
res.add(new Pair(cin, q[0].trim(), Double.parseDouble(q[1].trim())));
} else {
errorcontent.append(subq).append("\n");
}
} catch (NumberFormatException e) {
errorcontent.append(subq).append("\n");
}
} else {
errorcontent.append(subq).append("\n");
}
}
}
if (errorcontent.toString().length() > 0) {
System.out.println("Error content:" + errorcontent.toString());
System.out.println("Report to:" + cin);
SendEmail(cin, "格式错误:(正确格式为: 基金代码:预测净值)\n错误文本:" + errorcontent.toString() + "\n错误文本结束");
}
messages[i].setFlag(Flags.Flag.DELETED, true);
} else {
System.out.println("Unknown subject:" + subject.trim());
messages[i].setFlag(Flags.Flag.DELETED, true);
}
}
retry = false;
} catch (javax.mail.AuthenticationFailedException e) {
System.out.println("Authentication failed");
try {
Thread.currentThread().sleep(60 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
retry = true;
} catch (TimeoutException e) {
retry = true;
} catch (Exception e) {
SendEmail(cin, e.getMessage());
e.printStackTrace(System.err);
System.out.println("Need retry");
retry = true;
} finally {
try {
System.out.println("Email check done");
if (inbox != null) {
inbox.close(true);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
return res;
}
public static void SendEmail(String to, String errormessage) {
try {
StringBuffer sb = new StringBuffer();
sb.append(errormessage);
sb.append("\n");
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "false");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.sina.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 设置环境信息
Session session = Session.getInstance(props);
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject("NEUFUND预测");
// 设置邮件内容
msg.setText(sb.toString());
// 设置发件人
msg.setFrom(new InternetAddress(username + "@sina.com"));
Transport transport = session.getTransport();
// 连接邮件服务器
transport.connect(username, password);
// 发送邮件
transport.sendMessage(msg, new Address[]{new InternetAddress(to)});
// 关闭连接
transport.close();
} catch (javax.mail.internet.AddressException e) {
System.out.println("[ERROR-EMAIL-ADDRESS]" + to);
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void SendEmail(String to, String code, RList pres) throws REXPMismatchException, MessagingException {
StringBuffer sb = new StringBuffer();
try {
sb.append("基金代码:" + pres.at(0).asString()).append("\n").append("2015年1月至今收益率:" + pres.at(1).asDouble())
.append("\n交易策略(1买入2卖出0不操作):");
for (int i : pres.at(2).asIntegers()) {
sb.append(i + " ");
}
} catch (NullPointerException e) {
sb.append("基金代码不存在:" + code);
}
sb.append("\n");
try {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "false");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.sina.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 设置环境信息
Session session = Session.getInstance(props);
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject("NEUFUND预测");
// 设置邮件内容
msg.setText(sb.toString());
// 设置发件人
msg.setFrom(new InternetAddress(username + "@sina.com"));
Transport transport = session.getTransport();
// 连接邮件服务器
transport.connect(username, password);
// 发送邮件
transport.sendMessage(msg, new Address[]{new InternetAddress(to)});
// 关闭连接
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 解决中文乱码问题
public static String getChineseFrom(String res) {
String from = res;
try {
if (from.startsWith("=?GB") || from.startsWith("=?gb") || from.startsWith("=?UTF")) {
from = MimeUtility.decodeText(from);
} else {
from = new String(from.getBytes("ISO8859_1"), "GBK");
}
} catch (Exception e) {
e.printStackTrace();
}
return from;
}
public static void getMailTextContent(Message message, StringBuffer result) throws MessagingException,
IOException {
/*
* boolean isContainTextAttach = part.getContentType().indexOf("name") >
* 0; if (part.isMimeType("text/*") && !isContainTextAttach) {
* result.append(part.getContent().toString()); } else if
* (part.isMimeType("message/rfc822")) { getMailTextContent((Part)
* part.getContent(), result); } else if
* (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart)
* part.getContent(); int partCount = multipart.getCount(); for (int i =
* 0; i < partCount; i++) { BodyPart bodyPart =
* multipart.getBodyPart(i); getMailTextContent(bodyPart, result);
* result.append("\n"); } }
*/
if (message instanceof MimeMessage) {
MimeMessage m = (MimeMessage) message;
Object contentObject = m.getContent();
if (contentObject instanceof Multipart) {
BodyPart clearTextPart = null;
BodyPart htmlTextPart = null;
Multipart content = (Multipart) contentObject;
int count = content.getCount();
for (int i = 0; i < count; i++) {
BodyPart part = content.getBodyPart(i);
if (part.isMimeType("text/plain")) {
clearTextPart = part;
break;
} else if (part.isMimeType("text/html")) {
htmlTextPart = part;
}
}
if (clearTextPart != null) {
result.append(clearTextPart.getContent().toString()).append("\n");
} else if (htmlTextPart != null) {
String html = (String) htmlTextPart.getContent();
result.append(Jsoup.parse(html).text()).append("\n");
}
} else if (contentObject instanceof String) // a simple text message
{
result.append(contentObject).append("\n");
}
} else // not a mime message
{
result.append("无法识别邮件正文内容");
}
}
}
| src/main/java/EmailRecSend.java | import org.jsoup.Jsoup;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.RList;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;
public abstract class EmailRecSend {
public static boolean retry = false;
private static Store store = null;
private static final String host = "pop.sina.com";
private static final String provider = "pop3";
private static final String username;
private static final String password;
private static final String keyword;
static {
username = Configurator.getProperties("username");
password = Configurator.getProperties("password");
keyword = Configurator.getProperties("keyword");
}
public static List<Pair> ReceiveMail() throws REXPMismatchException, MessagingException {
System.out.println("Receive email");
List<Pair> res = new ArrayList<Pair>();
Properties props = System.getProperties();
String cin = "";
Folder inbox = null;
try {
if (store == null) {
// 连接到POP3服务器
Session ss = Session.getDefaultInstance(props, null);
// 向回话"请求"一个某种提供者的存储库,是一个POP3提供者
System.out.println("Get store");
store = ss.getStore(provider);
}
if (!store.isConnected()) {
// 连接存储库,从而可以打开存储库中的文件夹,此时是面向IMAP的
System.out.println("Connect to store");
TimeoutConnect.timeoutConnect(store, host, username, password, 10 * 1000);
}
// 打开文件夹,此时是关闭的,只能对其进行删除或重命名,无法获取关闭文件夹的信息
// 从存储库的默认文件夹INBOX中读取邮件
System.out.println("Get inbox");
inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("NO INBOX");
System.exit(1);
}
// 打开文件夹,读取信息
System.out.println("Open inbox");
inbox.open(Folder.READ_WRITE);
System.out.println("TOTAL EMAIL:" + inbox.getMessageCount());
// 获取邮件服务器中的邮件
Message[] messages = inbox.getMessages();
String from = null;
cin = null;
for (int i = messages.length - 1; i >= 0; i--) {
Set<String> codeset = new HashSet<String>();
// 解析地址为字符串
from = InternetAddress.toString(messages[i].getFrom());
if (from != null) {
cin = getChineseFrom(from);
}
String subject = messages[i].getSubject().trim();
if (subject.toLowerCase().contains(keyword)) {
StringBuffer errorcontent = new StringBuffer();
StringBuffer content = new StringBuffer(30);
getMailTextContent(messages[i], content);
System.out.println("------------Message--" + (i + 1) + "------------");
System.out.println("From:" + cin);
if (subject != null) System.out.println("Subject:" + subject);
System.out.println(content.toString());
System.out.println("----------------------------");
for (String part : content.toString().trim().split("\n")) {
String[] slist = part.trim().split("[\\s\\r\\n]");
for (String subq : slist) {
if (subq.contains(":")) {
String[] q = subq.split(":");
try {
if (q.length == 2 && q[0].length() == 6 && (!codeset.contains(q[0].trim()))) {
codeset.add(q[0].trim());
System.out.println("Find:" + q[0].trim() + "\t" + q[1].trim());
res.add(new Pair(cin, q[0].trim(), Double.parseDouble(q[1].trim())));
} else {
errorcontent.append(subq).append("\n");
}
} catch (NumberFormatException e) {
errorcontent.append(subq).append("\n");
}
} else {
errorcontent.append(subq).append("\n");
}
}
}
if (errorcontent.toString().length() > 0) {
System.out.println("Error content:" + errorcontent.toString());
System.out.println("Report to:" + cin);
SendEmail(cin, "格式错误:(正确格式为: 基金代码:预测净值)\n错误文本:" + errorcontent.toString() + "\n错误文本结束");
}
messages[i].setFlag(Flags.Flag.DELETED, true);
} else {
System.out.println("Unknown subject:" + subject.trim());
messages[i].setFlag(Flags.Flag.DELETED, true);
}
}
retry = false;
} catch (javax.mail.AuthenticationFailedException e) {
System.out.println("Authentication failed");
try {
Thread.currentThread().sleep(60 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
retry = true;
} catch (TimeoutException e) {
retry = true;
} catch (Exception e) {
SendEmail(cin, e.getMessage());
e.printStackTrace(System.err);
System.out.println("Need retry");
retry = true;
} finally {
try {
System.out.println("Email check done");
if (inbox != null) {
inbox.close(true);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
return res;
}
public static void SendEmail(String to, String errormessage) {
try {
StringBuffer sb = new StringBuffer();
sb.append(errormessage);
sb.append("\n");
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "false");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.sina.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 设置环境信息
Session session = Session.getInstance(props);
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject("NEUFUND预测");
// 设置邮件内容
msg.setText(sb.toString());
// 设置发件人
msg.setFrom(new InternetAddress(username + "@sina.com"));
Transport transport = session.getTransport();
// 连接邮件服务器
transport.connect(username, password);
// 发送邮件
transport.sendMessage(msg, new Address[]{new InternetAddress(to)});
// 关闭连接
transport.close();
} catch (javax.mail.internet.AddressException e) {
System.out.println("[ERROR-EMAIL-ADDRESS]" + to);
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void SendEmail(String to, String code, RList pres) throws REXPMismatchException, MessagingException {
StringBuffer sb = new StringBuffer();
try {
sb.append("基金代码:" + pres.at(0).asString()).append("\n").append("2015年1月至今收益率:" + pres.at(1).asDouble())
.append("\n交易策略(1买入2卖出0不操作):");
for (int i : pres.at(2).asIntegers()) {
sb.append(i + " ");
}
} catch (NullPointerException e) {
sb.append("基金代码不存在:" + code);
}
sb.append("\n");
try {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "false");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.sina.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 设置环境信息
Session session = Session.getInstance(props);
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject("NEUFUND预测");
// 设置邮件内容
msg.setText(sb.toString());
// 设置发件人
msg.setFrom(new InternetAddress(username + "@sina.com"));
Transport transport = session.getTransport();
// 连接邮件服务器
transport.connect(username, password);
// 发送邮件
transport.sendMessage(msg, new Address[]{new InternetAddress(to)});
// 关闭连接
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 解决中文乱码问题
public static String getChineseFrom(String res) {
String from = res;
try {
if (from.startsWith("=?GB") || from.startsWith("=?gb") || from.startsWith("=?UTF")) {
from = MimeUtility.decodeText(from);
} else {
from = new String(from.getBytes("ISO8859_1"), "GBK");
}
} catch (Exception e) {
e.printStackTrace();
}
return from;
}
public static void getMailTextContent(Message message, StringBuffer result) throws MessagingException,
IOException {
/*
* boolean isContainTextAttach = part.getContentType().indexOf("name") >
* 0; if (part.isMimeType("text/*") && !isContainTextAttach) {
* result.append(part.getContent().toString()); } else if
* (part.isMimeType("message/rfc822")) { getMailTextContent((Part)
* part.getContent(), result); } else if
* (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart)
* part.getContent(); int partCount = multipart.getCount(); for (int i =
* 0; i < partCount; i++) { BodyPart bodyPart =
* multipart.getBodyPart(i); getMailTextContent(bodyPart, result);
* result.append("\n"); } }
*/
if (message instanceof MimeMessage) {
MimeMessage m = (MimeMessage) message;
Object contentObject = m.getContent();
if (contentObject instanceof Multipart) {
BodyPart clearTextPart = null;
BodyPart htmlTextPart = null;
Multipart content = (Multipart) contentObject;
int count = content.getCount();
for (int i = 0; i < count; i++) {
BodyPart part = content.getBodyPart(i);
if (part.isMimeType("text/plain")) {
clearTextPart = part;
break;
} else if (part.isMimeType("text/html")) {
htmlTextPart = part;
}
}
if (clearTextPart != null) {
result.append(clearTextPart.getContent().toString()).append("\n");
} else if (htmlTextPart != null) {
String html = (String) htmlTextPart.getContent();
result.append(Jsoup.parse(html).text()).append("\n");
}
} else if (contentObject instanceof String) // a simple text message
{
result.append(contentObject).append("\n");
}
} else // not a mime message
{
result.append("无法识别邮件正文内容");
}
}
}
| Add debug information
| src/main/java/EmailRecSend.java | Add debug information | <ide><path>rc/main/java/EmailRecSend.java
<ide> // 向回话"请求"一个某种提供者的存储库,是一个POP3提供者
<ide> System.out.println("Get store");
<ide> store = ss.getStore(provider);
<add> } else {
<add> System.out.println("Store is ready");
<ide> }
<ide> if (!store.isConnected()) {
<ide> // 连接存储库,从而可以打开存储库中的文件夹,此时是面向IMAP的
<ide> System.out.println("Connect to store");
<ide> TimeoutConnect.timeoutConnect(store, host, username, password, 10 * 1000);
<add> } else {
<add> System.out.println("Connection is ready");
<ide> }
<ide> // 打开文件夹,此时是关闭的,只能对其进行删除或重命名,无法获取关闭文件夹的信息
<ide> // 从存储库的默认文件夹INBOX中读取邮件 |
|
Java | apache-2.0 | error: pathspec 'src/main/java/org/apdplat/extractor/html/ExtractRegular.java' did not match any file(s) known to git
| 25c34f897693a42f85d39c15fcc154cdabd1be98 | 1 | ysc/HtmlExtractor | /**
*
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 杨尚川, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.apdplat.extractor.html;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apdplat.extractor.html.model.CssPath;
import org.apdplat.extractor.html.model.ExtractFunction;
import org.apdplat.extractor.html.model.HtmlTemplate;
import org.apdplat.extractor.html.model.UrlPattern;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
/**
* URL抽取规则
* 订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
* 初始化:
* 1、从配置管理web服务器获取完整的规则集合
* 2、抽取规则
* 3、构造规则查找结构
*
* @author 杨尚川
*
*/
public class ExtractRegular {
private static final Logger LOGGER = LoggerFactory.getLogger(ExtractRegular.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static ExtractRegular extractRegular = null;
private volatile Map<String, List<UrlPattern>> urlPatternMap = null;
/**
* 私有构造函数
*/
private ExtractRegular() {
}
/**
* 获取抽取规则实例
*
* @param serverUrl 配置管理WEB服务器的抽取规则下载地址
* @param redisHost Redis服务器主机
* @param redisPort Redis服务器端口
* @return 抽取规则实例
*/
public static ExtractRegular getInstance(String serverUrl, String redisHost, int redisPort) {
if (extractRegular != null) {
return extractRegular;
}
synchronized (ExtractRegular.class) {
if (extractRegular == null) {
extractRegular = new ExtractRegular();
//订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
extractRegular.subscribeRedis(redisHost, redisPort, serverUrl);
//初始化抽取规则
extractRegular.init(serverUrl);
}
}
return extractRegular;
}
/**
* 初始化:
* 1、从配置管理web服务器获取完整的抽取规则的json表示
* 2、抽取json,构造对应的java对象结构
* 3、构造抽取规则查找结构
*/
private synchronized void init(String serverUrl) {
LOGGER.info("开始初始化URL抽取规则");
LOGGER.info("serverUrl: " + serverUrl);
//从配置管理web服务器获取完整的抽取规则
String json = downJson(serverUrl);
//抽取规则
List<UrlPattern> urlPatterns = parseJson(json);
//构造抽取规则查找结构
Map<String, List<UrlPattern>> newUrlPatterns = toMap(urlPatterns);
if (!newUrlPatterns.isEmpty()) {
Map<String, List<UrlPattern>> oldUrlPatterns = urlPatternMap;
urlPatternMap = newUrlPatterns;
//清空之前的抽取规则查找结构(如果有)
if (oldUrlPatterns != null) {
for (List<UrlPattern> list : oldUrlPatterns.values()) {
list.clear();
}
oldUrlPatterns.clear();
}
}
LOGGER.info("完成初始化URL抽取规则");
}
/**
* 订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
*/
private void subscribeRedis(final String redisHost, final int redisPort, final String serverUrl) {
if (null == redisHost || redisPort < 1) {
LOGGER.error("没有指定redis服务器配置!");
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
String channel = "pr";
LOGGER.info("redis服务器配置信息 host:" + redisHost + ",port:" + redisPort + ",channel:" + channel);
while (true) {
try {
JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort);
Jedis jedis = jedisPool.getResource();
LOGGER.info("redis守护线程启动");
jedis.subscribe(new ExtractRegularChangeRedisListener(serverUrl), new String[]{channel});
jedisPool.returnResource(jedis);
LOGGER.info("redis守护线程结束");
break;
} catch (Exception e) {
LOGGER.info("redis未启动,暂停一分钟后重新连接");
try {
Thread.sleep(600000);
} catch (InterruptedException ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
}
}
});
thread.setDaemon(true);
thread.setName("redis守护线程,用于动态加载抽取规则");
thread.start();
}
/**
* Redis监听器,监听抽取规则的变化
*
* @author 杨尚川
*
*/
private class ExtractRegularChangeRedisListener extends JedisPubSub {
private final String serverUrl;
public ExtractRegularChangeRedisListener(String serverUrl) {
this.serverUrl = serverUrl;
}
@Override
public void onMessage(String channel, String message) {
LOGGER.debug("onMessage channel:" + channel + " and message:" + message);
if ("pr".equals(channel) && "CHANGE".equals(message)) {
synchronized (ExtractRegularChangeRedisListener.class) {
init(serverUrl);
}
}
}
@Override
public void onPMessage(String pattern, String channel, String message) {
LOGGER.debug("pattern:" + pattern + " and channel:" + channel + " and message:" + message);
onMessage(channel, message);
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
LOGGER.debug("psubscribe pattern:" + pattern + " and subscribedChannels:" + subscribedChannels);
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
LOGGER.debug("punsubscribe pattern:" + pattern + " and subscribedChannels:" + subscribedChannels);
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
LOGGER.debug("subscribe channel:" + channel + " and subscribedChannels:" + subscribedChannels);
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
LOGGER.debug("unsubscribe channel:" + channel + " and subscribedChannels:" + subscribedChannels);
}
}
/**
* 从配置管理WEB服务器下载规则(json表示)
*
* @param url 配置管理WEB服务器下载规则的地址
* @return json字符串
*/
private String downJson(String url) {
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 创建GET方法的实例
GetMethod method = new GetMethod(url);
try {
// 执行GetMethod
int statusCode = httpClient.executeMethod(method);
LOGGER.info("响应代码:" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
LOGGER.error("请求失败: " + method.getStatusLine());
}
// 读取内容
String responseBody = new String(method.getResponseBody(), "utf-8");
return responseBody;
} catch (IOException e) {
LOGGER.error("检查请求的路径:" + url, e);
} finally {
// 释放连接
method.releaseConnection();
}
return "";
}
/**
* 将json格式的URL模式转换为JAVA对象表示
*
* @param json URL模式的JSON表示
* @return URL模式的JAVA对象表示
*/
private List<UrlPattern> parseJson(String json) {
List<UrlPattern> urlPatterns = new ArrayList<>();
try {
List<Map<String, Object>> ups = MAPPER.readValue(json, List.class);
for (Map<String, Object> up : ups) {
try {
UrlPattern urlPattern = new UrlPattern();
urlPatterns.add(urlPattern);
urlPattern.setUrlPattern(up.get("urlPattern").toString());
List<Map<String, Object>> pageTemplates = (List<Map<String, Object>>) up.get("pageTemplates");
for (Map<String, Object> pt : pageTemplates) {
try {
HtmlTemplate htmlTemplate = new HtmlTemplate();
urlPattern.addHtmlTemplate(htmlTemplate);
htmlTemplate.setTemplateName(pt.get("templateName").toString());
htmlTemplate.setTableName(pt.get("tableName").toString());
List<Map<String, Object>> cssPaths = (List<Map<String, Object>>) pt.get("cssPaths");
for (Map<String, Object> cp : cssPaths) {
try {
CssPath cssPath = new CssPath();
htmlTemplate.addCssPath(cssPath);
cssPath.setCssPath(cp.get("cssPath").toString());
cssPath.setFieldName(cp.get("fieldName").toString());
cssPath.setFieldDescription(cp.get("fieldDescription").toString());
List<Map<String, Object>> extractFunctions = (List<Map<String, Object>>) cp.get("extractFunctions");
for (Map<String, Object> pf : extractFunctions) {
try {
ExtractFunction extractFunction = new ExtractFunction();
cssPath.addExtractFunction(extractFunction);
extractFunction.setExtractExpression(pf.get("extractExpression").toString());
extractFunction.setFieldName(pf.get("fieldName").toString());
extractFunction.setFieldDescription(pf.get("fieldDescription").toString());
} catch (Exception e) {
LOGGER.error("JSON抽取失败", e);
}
}
} catch (Exception e) {
LOGGER.error("JSON抽取失败", e);
}
}
} catch (Exception e) {
LOGGER.error("JSON抽取失败", e);
}
}
} catch (Exception e) {
LOGGER.error("JSON抽取失败", e);
}
}
} catch (Exception e) {
LOGGER.error("JSON抽取失败", e);
}
return urlPatterns;
}
/**
* 多个url模式可能会有相同的url前缀
* map结构+url前缀定位
* 用于快速查找一个url需要匹配的模式
*
* @param urlPatterns url模式列表
* @return 以url前缀为key的map结构
*/
private Map<String, List<UrlPattern>> toMap(List<UrlPattern> urlPatterns) {
Map<String, List<UrlPattern>> map = new ConcurrentHashMap<>();
for (UrlPattern urlPattern : urlPatterns) {
try {
URL url = new URL(urlPattern.getUrlPattern());
String key = urlPrefix(url);
List<UrlPattern> value = map.get(key);
if (value == null) {
value = new ArrayList<>();
map.put(key, value);
}
value.add(urlPattern);
} catch (Exception e) {
LOGGER.error("URL规则初始化失败:" + urlPattern.getUrlPattern(), e);
}
}
return map;
}
/**
* 获取一个url的前缀表示,用于快速定位URL模式
* 规则为:
* 协议+域名(去掉.)+端口(可选)
*
* @param url
* @return
*/
private String urlPrefix(URL url) {
StringBuilder result = new StringBuilder();
result.append(url.getProtocol());
String[] splits = StringUtils.split(url.getHost(), '.');
if (splits.length > 0) {
for (String split : splits) {
result.append(split);
}
}
if (url.getPort() > -1) {
result.append(Integer.toString(url.getPort()));
}
return result.toString();
}
/**
* 获取一个可以用来抽取特定URL的页面模板集合
*
* @param urlString url
* @return 页面模板集合
*/
public List<HtmlTemplate> getHtmlTemplate(String urlString) {
List<HtmlTemplate> pageTemplates = new ArrayList<>();
if (urlPatternMap != null) {
try {
URL url = new URL(urlString);
String key = urlPrefix(url);
List<UrlPattern> patterns = urlPatternMap.get(key);
for (UrlPattern urlPattern : patterns) {
Matcher matcher = urlPattern.getRegexPattern().matcher(urlString);
if (matcher.find()) {
//匹配成功
pageTemplates.addAll(urlPattern.getHtmlTemplates());
}
}
} catch (Exception e) {
LOGGER.error("获取URL抽取规则失败:" + urlString, e);
}
}
return pageTemplates;
}
public static void main(String[] args) throws Exception {
ExtractRegular extractRegular = ExtractRegular.getInstance("http://localhost:8080/ExtractRegularServer/api/all_extract_regular.jsp", null, -1);
List<HtmlTemplate> pageTemplates = extractRegular.getHtmlTemplate("http://money.163.com/14/0529/19/9TEGPK5T00252G50.html");
for (HtmlTemplate pageTemplate : pageTemplates) {
System.out.println(pageTemplate);
}
pageTemplates = extractRegular.getHtmlTemplate("http://finance.qq.com/a/20140530/004254.htm");
for (HtmlTemplate pageTemplate : pageTemplates) {
System.out.println(pageTemplate);
}
}
}
| src/main/java/org/apdplat/extractor/html/ExtractRegular.java | URL抽取规则 | src/main/java/org/apdplat/extractor/html/ExtractRegular.java | URL抽取规则 | <ide><path>rc/main/java/org/apdplat/extractor/html/ExtractRegular.java
<add>/**
<add> *
<add> * APDPlat - Application Product Development Platform
<add> * Copyright (c) 2013, 杨尚川, [email protected]
<add> *
<add> * This program is free software: you can redistribute it and/or modify
<add> * it under the terms of the GNU General Public License as published by
<add> * the Free Software Foundation, either version 3 of the License, or
<add> * (at your option) any later version.
<add> *
<add> * This program is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add> * GNU General Public License for more details.
<add> *
<add> * You should have received a copy of the GNU General Public License
<add> * along with this program. If not, see <http://www.gnu.org/licenses/>.
<add> *
<add> */
<add>
<add>package org.apdplat.extractor.html;
<add>
<add>import java.io.IOException;
<add>import java.net.URL;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.regex.Matcher;
<add>
<add>import org.apache.commons.httpclient.HttpClient;
<add>import org.apache.commons.httpclient.HttpStatus;
<add>import org.apache.commons.httpclient.methods.GetMethod;
<add>import org.apache.commons.lang.StringUtils;
<add>import org.apdplat.extractor.html.model.CssPath;
<add>import org.apdplat.extractor.html.model.ExtractFunction;
<add>import org.apdplat.extractor.html.model.HtmlTemplate;
<add>import org.apdplat.extractor.html.model.UrlPattern;
<add>import org.codehaus.jackson.map.ObjectMapper;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<add>
<add>import redis.clients.jedis.Jedis;
<add>import redis.clients.jedis.JedisPool;
<add>import redis.clients.jedis.JedisPoolConfig;
<add>import redis.clients.jedis.JedisPubSub;
<add>
<add>/**
<add> * URL抽取规则
<add> * 订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
<add> * 初始化:
<add> * 1、从配置管理web服务器获取完整的规则集合
<add> * 2、抽取规则
<add> * 3、构造规则查找结构
<add> *
<add> * @author 杨尚川
<add> *
<add> */
<add>public class ExtractRegular {
<add> private static final Logger LOGGER = LoggerFactory.getLogger(ExtractRegular.class);
<add> private static final ObjectMapper MAPPER = new ObjectMapper();
<add> private static ExtractRegular extractRegular = null;
<add> private volatile Map<String, List<UrlPattern>> urlPatternMap = null;
<add>
<add> /**
<add> * 私有构造函数
<add> */
<add> private ExtractRegular() {
<add> }
<add>
<add> /**
<add> * 获取抽取规则实例
<add> *
<add> * @param serverUrl 配置管理WEB服务器的抽取规则下载地址
<add> * @param redisHost Redis服务器主机
<add> * @param redisPort Redis服务器端口
<add> * @return 抽取规则实例
<add> */
<add> public static ExtractRegular getInstance(String serverUrl, String redisHost, int redisPort) {
<add> if (extractRegular != null) {
<add> return extractRegular;
<add> }
<add> synchronized (ExtractRegular.class) {
<add> if (extractRegular == null) {
<add> extractRegular = new ExtractRegular();
<add> //订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
<add> extractRegular.subscribeRedis(redisHost, redisPort, serverUrl);
<add> //初始化抽取规则
<add> extractRegular.init(serverUrl);
<add> }
<add> }
<add> return extractRegular;
<add> }
<add>
<add> /**
<add> * 初始化:
<add> * 1、从配置管理web服务器获取完整的抽取规则的json表示
<add> * 2、抽取json,构造对应的java对象结构
<add> * 3、构造抽取规则查找结构
<add> */
<add> private synchronized void init(String serverUrl) {
<add> LOGGER.info("开始初始化URL抽取规则");
<add> LOGGER.info("serverUrl: " + serverUrl);
<add> //从配置管理web服务器获取完整的抽取规则
<add> String json = downJson(serverUrl);
<add> //抽取规则
<add> List<UrlPattern> urlPatterns = parseJson(json);
<add> //构造抽取规则查找结构
<add> Map<String, List<UrlPattern>> newUrlPatterns = toMap(urlPatterns);
<add> if (!newUrlPatterns.isEmpty()) {
<add> Map<String, List<UrlPattern>> oldUrlPatterns = urlPatternMap;
<add> urlPatternMap = newUrlPatterns;
<add> //清空之前的抽取规则查找结构(如果有)
<add> if (oldUrlPatterns != null) {
<add> for (List<UrlPattern> list : oldUrlPatterns.values()) {
<add> list.clear();
<add> }
<add> oldUrlPatterns.clear();
<add> }
<add> }
<add> LOGGER.info("完成初始化URL抽取规则");
<add> }
<add>
<add> /**
<add> * 订阅Redis服务器Channel:pr,当规则改变的时候会收到通知消息CHANGE并重新初始化规则集合
<add> */
<add> private void subscribeRedis(final String redisHost, final int redisPort, final String serverUrl) {
<add> if (null == redisHost || redisPort < 1) {
<add> LOGGER.error("没有指定redis服务器配置!");
<add> return;
<add> }
<add> Thread thread = new Thread(new Runnable() {
<add> @Override
<add> public void run() {
<add> String channel = "pr";
<add> LOGGER.info("redis服务器配置信息 host:" + redisHost + ",port:" + redisPort + ",channel:" + channel);
<add> while (true) {
<add> try {
<add> JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort);
<add> Jedis jedis = jedisPool.getResource();
<add> LOGGER.info("redis守护线程启动");
<add> jedis.subscribe(new ExtractRegularChangeRedisListener(serverUrl), new String[]{channel});
<add> jedisPool.returnResource(jedis);
<add> LOGGER.info("redis守护线程结束");
<add> break;
<add> } catch (Exception e) {
<add> LOGGER.info("redis未启动,暂停一分钟后重新连接");
<add> try {
<add> Thread.sleep(600000);
<add> } catch (InterruptedException ex) {
<add> LOGGER.error(ex.getMessage(), ex);
<add> }
<add> }
<add> }
<add> }
<add> });
<add> thread.setDaemon(true);
<add> thread.setName("redis守护线程,用于动态加载抽取规则");
<add> thread.start();
<add> }
<add>
<add> /**
<add> * Redis监听器,监听抽取规则的变化
<add> *
<add> * @author 杨尚川
<add> *
<add> */
<add> private class ExtractRegularChangeRedisListener extends JedisPubSub {
<add> private final String serverUrl;
<add>
<add> public ExtractRegularChangeRedisListener(String serverUrl) {
<add> this.serverUrl = serverUrl;
<add> }
<add>
<add> @Override
<add> public void onMessage(String channel, String message) {
<add> LOGGER.debug("onMessage channel:" + channel + " and message:" + message);
<add> if ("pr".equals(channel) && "CHANGE".equals(message)) {
<add> synchronized (ExtractRegularChangeRedisListener.class) {
<add> init(serverUrl);
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onPMessage(String pattern, String channel, String message) {
<add> LOGGER.debug("pattern:" + pattern + " and channel:" + channel + " and message:" + message);
<add> onMessage(channel, message);
<add> }
<add>
<add> @Override
<add> public void onPSubscribe(String pattern, int subscribedChannels) {
<add> LOGGER.debug("psubscribe pattern:" + pattern + " and subscribedChannels:" + subscribedChannels);
<add> }
<add>
<add> @Override
<add> public void onPUnsubscribe(String pattern, int subscribedChannels) {
<add> LOGGER.debug("punsubscribe pattern:" + pattern + " and subscribedChannels:" + subscribedChannels);
<add> }
<add>
<add> @Override
<add> public void onSubscribe(String channel, int subscribedChannels) {
<add> LOGGER.debug("subscribe channel:" + channel + " and subscribedChannels:" + subscribedChannels);
<add> }
<add>
<add> @Override
<add> public void onUnsubscribe(String channel, int subscribedChannels) {
<add> LOGGER.debug("unsubscribe channel:" + channel + " and subscribedChannels:" + subscribedChannels);
<add> }
<add> }
<add>
<add> /**
<add> * 从配置管理WEB服务器下载规则(json表示)
<add> *
<add> * @param url 配置管理WEB服务器下载规则的地址
<add> * @return json字符串
<add> */
<add> private String downJson(String url) {
<add> // 构造HttpClient的实例
<add> HttpClient httpClient = new HttpClient();
<add> // 创建GET方法的实例
<add> GetMethod method = new GetMethod(url);
<add> try {
<add> // 执行GetMethod
<add> int statusCode = httpClient.executeMethod(method);
<add> LOGGER.info("响应代码:" + statusCode);
<add> if (statusCode != HttpStatus.SC_OK) {
<add> LOGGER.error("请求失败: " + method.getStatusLine());
<add> }
<add> // 读取内容
<add> String responseBody = new String(method.getResponseBody(), "utf-8");
<add> return responseBody;
<add> } catch (IOException e) {
<add> LOGGER.error("检查请求的路径:" + url, e);
<add> } finally {
<add> // 释放连接
<add> method.releaseConnection();
<add> }
<add> return "";
<add> }
<add>
<add> /**
<add> * 将json格式的URL模式转换为JAVA对象表示
<add> *
<add> * @param json URL模式的JSON表示
<add> * @return URL模式的JAVA对象表示
<add> */
<add> private List<UrlPattern> parseJson(String json) {
<add> List<UrlPattern> urlPatterns = new ArrayList<>();
<add> try {
<add> List<Map<String, Object>> ups = MAPPER.readValue(json, List.class);
<add> for (Map<String, Object> up : ups) {
<add> try {
<add> UrlPattern urlPattern = new UrlPattern();
<add> urlPatterns.add(urlPattern);
<add> urlPattern.setUrlPattern(up.get("urlPattern").toString());
<add> List<Map<String, Object>> pageTemplates = (List<Map<String, Object>>) up.get("pageTemplates");
<add> for (Map<String, Object> pt : pageTemplates) {
<add> try {
<add> HtmlTemplate htmlTemplate = new HtmlTemplate();
<add> urlPattern.addHtmlTemplate(htmlTemplate);
<add> htmlTemplate.setTemplateName(pt.get("templateName").toString());
<add> htmlTemplate.setTableName(pt.get("tableName").toString());
<add> List<Map<String, Object>> cssPaths = (List<Map<String, Object>>) pt.get("cssPaths");
<add> for (Map<String, Object> cp : cssPaths) {
<add> try {
<add> CssPath cssPath = new CssPath();
<add> htmlTemplate.addCssPath(cssPath);
<add> cssPath.setCssPath(cp.get("cssPath").toString());
<add> cssPath.setFieldName(cp.get("fieldName").toString());
<add> cssPath.setFieldDescription(cp.get("fieldDescription").toString());
<add> List<Map<String, Object>> extractFunctions = (List<Map<String, Object>>) cp.get("extractFunctions");
<add> for (Map<String, Object> pf : extractFunctions) {
<add> try {
<add> ExtractFunction extractFunction = new ExtractFunction();
<add> cssPath.addExtractFunction(extractFunction);
<add> extractFunction.setExtractExpression(pf.get("extractExpression").toString());
<add> extractFunction.setFieldName(pf.get("fieldName").toString());
<add> extractFunction.setFieldDescription(pf.get("fieldDescription").toString());
<add> } catch (Exception e) {
<add> LOGGER.error("JSON抽取失败", e);
<add> }
<add> }
<add> } catch (Exception e) {
<add> LOGGER.error("JSON抽取失败", e);
<add> }
<add> }
<add> } catch (Exception e) {
<add> LOGGER.error("JSON抽取失败", e);
<add> }
<add> }
<add> } catch (Exception e) {
<add> LOGGER.error("JSON抽取失败", e);
<add> }
<add> }
<add> } catch (Exception e) {
<add> LOGGER.error("JSON抽取失败", e);
<add> }
<add> return urlPatterns;
<add> }
<add>
<add> /**
<add> * 多个url模式可能会有相同的url前缀
<add> * map结构+url前缀定位
<add> * 用于快速查找一个url需要匹配的模式
<add> *
<add> * @param urlPatterns url模式列表
<add> * @return 以url前缀为key的map结构
<add> */
<add> private Map<String, List<UrlPattern>> toMap(List<UrlPattern> urlPatterns) {
<add> Map<String, List<UrlPattern>> map = new ConcurrentHashMap<>();
<add> for (UrlPattern urlPattern : urlPatterns) {
<add> try {
<add> URL url = new URL(urlPattern.getUrlPattern());
<add> String key = urlPrefix(url);
<add> List<UrlPattern> value = map.get(key);
<add> if (value == null) {
<add> value = new ArrayList<>();
<add> map.put(key, value);
<add> }
<add> value.add(urlPattern);
<add> } catch (Exception e) {
<add> LOGGER.error("URL规则初始化失败:" + urlPattern.getUrlPattern(), e);
<add> }
<add> }
<add> return map;
<add> }
<add>
<add> /**
<add> * 获取一个url的前缀表示,用于快速定位URL模式
<add> * 规则为:
<add> * 协议+域名(去掉.)+端口(可选)
<add> *
<add> * @param url
<add> * @return
<add> */
<add> private String urlPrefix(URL url) {
<add> StringBuilder result = new StringBuilder();
<add> result.append(url.getProtocol());
<add> String[] splits = StringUtils.split(url.getHost(), '.');
<add> if (splits.length > 0) {
<add> for (String split : splits) {
<add> result.append(split);
<add> }
<add> }
<add> if (url.getPort() > -1) {
<add> result.append(Integer.toString(url.getPort()));
<add> }
<add> return result.toString();
<add> }
<add>
<add> /**
<add> * 获取一个可以用来抽取特定URL的页面模板集合
<add> *
<add> * @param urlString url
<add> * @return 页面模板集合
<add> */
<add> public List<HtmlTemplate> getHtmlTemplate(String urlString) {
<add> List<HtmlTemplate> pageTemplates = new ArrayList<>();
<add> if (urlPatternMap != null) {
<add> try {
<add> URL url = new URL(urlString);
<add> String key = urlPrefix(url);
<add> List<UrlPattern> patterns = urlPatternMap.get(key);
<add> for (UrlPattern urlPattern : patterns) {
<add> Matcher matcher = urlPattern.getRegexPattern().matcher(urlString);
<add> if (matcher.find()) {
<add> //匹配成功
<add> pageTemplates.addAll(urlPattern.getHtmlTemplates());
<add> }
<add> }
<add> } catch (Exception e) {
<add> LOGGER.error("获取URL抽取规则失败:" + urlString, e);
<add> }
<add> }
<add> return pageTemplates;
<add> }
<add>
<add> public static void main(String[] args) throws Exception {
<add> ExtractRegular extractRegular = ExtractRegular.getInstance("http://localhost:8080/ExtractRegularServer/api/all_extract_regular.jsp", null, -1);
<add>
<add> List<HtmlTemplate> pageTemplates = extractRegular.getHtmlTemplate("http://money.163.com/14/0529/19/9TEGPK5T00252G50.html");
<add> for (HtmlTemplate pageTemplate : pageTemplates) {
<add> System.out.println(pageTemplate);
<add> }
<add>
<add> pageTemplates = extractRegular.getHtmlTemplate("http://finance.qq.com/a/20140530/004254.htm");
<add> for (HtmlTemplate pageTemplate : pageTemplates) {
<add> System.out.println(pageTemplate);
<add> }
<add> }
<add>} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.