file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
156490_18 | /*
* 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 io.undertow.util;
import io.undertow.UndertowMessages;
import io.undertow.server.handlers.Cookie;
/**
* Class that contains static constants and utility methods for legacy Set-Cookie format.
* Porting from JBossWeb and Tomcat code.
*
* Note that in general we do not use system properties for configuration, however as these are
* legacy options that are not widely used an exception has been made in this case.
*
*/
public final class LegacyCookieSupport {
// --------------------------------------------------------------- Constants
/**
* If true, separators that are not explicitly dis-allowed by the v0 cookie
* spec but are disallowed by the HTTP spec will be allowed in v0 cookie
* names and values. These characters are: \"()/:<=>?@[\\]{} Note that the
* inclusion of / depend on the value of {@link #FWD_SLASH_IS_SEPARATOR}.
*
* Defaults to false.
*/
static final boolean ALLOW_HTTP_SEPARATORS_IN_V0 = Boolean.getBoolean("io.undertow.legacy.cookie.ALLOW_HTTP_SEPARATORS_IN_V0");
/**
* If set to true, the <code>/</code> character will be treated as a
* separator. Default is false.
*/
private static final boolean FWD_SLASH_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.FWD_SLASH_IS_SEPARATOR");
/**
* If set to true, the <code,</code> character will be treated as a
* separator in Cookie: headers.
*/
static final boolean COMMA_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.COMMA_IS_SEPARATOR");
/**
* The list of separators that apply to version 0 cookies. To quote the
* spec, these are comma, semi-colon and white-space. The HTTP spec
* definition of linear white space is [CRLF] 1*( SP | HT )
*/
private static final char[] V0_SEPARATORS = {',', ';', ' ', '\t'};
private static final boolean[] V0_SEPARATOR_FLAGS = new boolean[128];
/**
* The list of separators that apply to version 1 cookies. This may or may
* not include '/' depending on the setting of
* {@link #FWD_SLASH_IS_SEPARATOR}.
*/
private static final char[] HTTP_SEPARATORS;
private static final boolean[] HTTP_SEPARATOR_FLAGS = new boolean[128];
static {
/*
Excluding the '/' char by default violates the RFC, but
it looks like a lot of people put '/'
in unquoted values: '/': ; //47
'\t':9 ' ':32 '\"':34 '(':40 ')':41 ',':44 ':':58 ';':59 '<':60
'=':61 '>':62 '?':63 '@':64 '[':91 '\\':92 ']':93 '{':123 '}':125
*/
if (FWD_SLASH_IS_SEPARATOR) {
HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',', '/',
':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'};
} else {
HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',',
':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'};
}
for (int i = 0; i < 128; i++) {
V0_SEPARATOR_FLAGS[i] = false;
HTTP_SEPARATOR_FLAGS[i] = false;
}
for (char V0_SEPARATOR : V0_SEPARATORS) {
V0_SEPARATOR_FLAGS[V0_SEPARATOR] = true;
}
for (char HTTP_SEPARATOR : HTTP_SEPARATORS) {
HTTP_SEPARATOR_FLAGS[HTTP_SEPARATOR] = true;
}
}
// ----------------------------------------------------------------- Methods
/**
* Returns true if the byte is a separator as defined by V0 of the cookie
* spec.
*/
private static boolean isV0Separator(final char c) {
if (c < 0x20 || c >= 0x7f) {
if (c != 0x09) {
throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c));
}
}
return V0_SEPARATOR_FLAGS[c];
}
private static boolean isV0Token(String value) {
if( value==null) return false;
int i = 0;
int len = value.length();
if (alreadyQuoted(value)) {
i++;
len--;
}
for (; i < len; i++) {
char c = value.charAt(i);
if (isV0Separator(c))
return true;
}
return false;
}
/**
* Returns true if the byte is a separator as defined by V1 of the cookie
* spec, RFC2109.
* @throws IllegalArgumentException if a control character was supplied as
* input
*/
static boolean isHttpSeparator(final char c) {
if (c < 0x20 || c >= 0x7f) {
if (c != 0x09) {
throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c));
}
}
return HTTP_SEPARATOR_FLAGS[c];
}
private static boolean isHttpToken(String value) {
if( value==null) return false;
int i = 0;
int len = value.length();
if (alreadyQuoted(value)) {
i++;
len--;
}
for (; i < len; i++) {
char c = value.charAt(i);
if (isHttpSeparator(c))
return true;
}
return false;
}
private static boolean alreadyQuoted(String value) {
if (value==null || value.length() < 2) return false;
return (value.charAt(0)=='\"' && value.charAt(value.length()-1)=='\"');
}
/**
* Quotes values if required.
* @param buf
* @param value
*/
public static void maybeQuote(StringBuilder buf, String value) {
if (value==null || value.length()==0) {
buf.append("\"\"");
} else if (alreadyQuoted(value)) {
buf.append('"');
buf.append(escapeDoubleQuotes(value,1,value.length()-1));
buf.append('"');
} else if ((isHttpToken(value) && !ALLOW_HTTP_SEPARATORS_IN_V0) ||
(isV0Token(value) && ALLOW_HTTP_SEPARATORS_IN_V0)) {
buf.append('"');
buf.append(escapeDoubleQuotes(value,0,value.length()));
buf.append('"');
} else {
buf.append(value);
}
}
/**
* Escapes any double quotes in the given string.
*
* @param s the input string
* @param beginIndex start index inclusive
* @param endIndex exclusive
* @return The (possibly) escaped string
*/
private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) {
if (s == null || s.length() == 0 || s.indexOf('"') == -1) {
return s;
}
StringBuilder b = new StringBuilder();
for (int i = beginIndex; i < endIndex; i++) {
char c = s.charAt(i);
if (c == '\\' ) {
b.append(c);
//ignore the character after an escape, just append it
if (++i>=endIndex) throw UndertowMessages.MESSAGES.invalidEscapeCharacter();
b.append(s.charAt(i));
} else if (c == '"')
b.append('\\').append('"');
else
b.append(c);
}
return b.toString();
}
public static int adjustedCookieVersion(Cookie cookie) {
/*
* The spec allows some latitude on when to send the version attribute
* with a Set-Cookie header. To be nice to clients, we'll make sure the
* version attribute is first. That means checking the various things
* that can cause us to switch to a v1 cookie first.
*_
* Note that by checking for tokens we will also throw an exception if a
* control character is encountered.
*/
int version = cookie.getVersion();
String value = cookie.getValue();
String path = cookie.getPath();
String domain = cookie.getDomain();
String comment = cookie.getComment();
// If it is v0, check if we need to switch
if (version == 0 &&
(!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(value) ||
ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(value))) {
// HTTP token in value - need to use v1
version = 1;
}
if (version == 0 && comment != null) {
// Using a comment makes it a v1 cookie
version = 1;
}
if (version == 0 &&
(!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(path) ||
ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(path))) {
// HTTP token in path - need to use v1
version = 1;
}
if (version == 0 &&
(!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(domain) ||
ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(domain))) {
// HTTP token in domain - need to use v1
version = 1;
}
return version;
}
// ------------------------------------------------------------- Constructor
private LegacyCookieSupport() {
// Utility class. Don't allow instances to be created.
}
}
| undertow-io/undertow | core/src/main/java/io/undertow/util/LegacyCookieSupport.java | 2,901 | // HTTP token in domain - need to use v1 | line_comment | nl | /*
* 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 io.undertow.util;
import io.undertow.UndertowMessages;
import io.undertow.server.handlers.Cookie;
/**
* Class that contains static constants and utility methods for legacy Set-Cookie format.
* Porting from JBossWeb and Tomcat code.
*
* Note that in general we do not use system properties for configuration, however as these are
* legacy options that are not widely used an exception has been made in this case.
*
*/
public final class LegacyCookieSupport {
// --------------------------------------------------------------- Constants
/**
* If true, separators that are not explicitly dis-allowed by the v0 cookie
* spec but are disallowed by the HTTP spec will be allowed in v0 cookie
* names and values. These characters are: \"()/:<=>?@[\\]{} Note that the
* inclusion of / depend on the value of {@link #FWD_SLASH_IS_SEPARATOR}.
*
* Defaults to false.
*/
static final boolean ALLOW_HTTP_SEPARATORS_IN_V0 = Boolean.getBoolean("io.undertow.legacy.cookie.ALLOW_HTTP_SEPARATORS_IN_V0");
/**
* If set to true, the <code>/</code> character will be treated as a
* separator. Default is false.
*/
private static final boolean FWD_SLASH_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.FWD_SLASH_IS_SEPARATOR");
/**
* If set to true, the <code,</code> character will be treated as a
* separator in Cookie: headers.
*/
static final boolean COMMA_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.COMMA_IS_SEPARATOR");
/**
* The list of separators that apply to version 0 cookies. To quote the
* spec, these are comma, semi-colon and white-space. The HTTP spec
* definition of linear white space is [CRLF] 1*( SP | HT )
*/
private static final char[] V0_SEPARATORS = {',', ';', ' ', '\t'};
private static final boolean[] V0_SEPARATOR_FLAGS = new boolean[128];
/**
* The list of separators that apply to version 1 cookies. This may or may
* not include '/' depending on the setting of
* {@link #FWD_SLASH_IS_SEPARATOR}.
*/
private static final char[] HTTP_SEPARATORS;
private static final boolean[] HTTP_SEPARATOR_FLAGS = new boolean[128];
static {
/*
Excluding the '/' char by default violates the RFC, but
it looks like a lot of people put '/'
in unquoted values: '/': ; //47
'\t':9 ' ':32 '\"':34 '(':40 ')':41 ',':44 ':':58 ';':59 '<':60
'=':61 '>':62 '?':63 '@':64 '[':91 '\\':92 ']':93 '{':123 '}':125
*/
if (FWD_SLASH_IS_SEPARATOR) {
HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',', '/',
':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'};
} else {
HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',',
':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'};
}
for (int i = 0; i < 128; i++) {
V0_SEPARATOR_FLAGS[i] = false;
HTTP_SEPARATOR_FLAGS[i] = false;
}
for (char V0_SEPARATOR : V0_SEPARATORS) {
V0_SEPARATOR_FLAGS[V0_SEPARATOR] = true;
}
for (char HTTP_SEPARATOR : HTTP_SEPARATORS) {
HTTP_SEPARATOR_FLAGS[HTTP_SEPARATOR] = true;
}
}
// ----------------------------------------------------------------- Methods
/**
* Returns true if the byte is a separator as defined by V0 of the cookie
* spec.
*/
private static boolean isV0Separator(final char c) {
if (c < 0x20 || c >= 0x7f) {
if (c != 0x09) {
throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c));
}
}
return V0_SEPARATOR_FLAGS[c];
}
private static boolean isV0Token(String value) {
if( value==null) return false;
int i = 0;
int len = value.length();
if (alreadyQuoted(value)) {
i++;
len--;
}
for (; i < len; i++) {
char c = value.charAt(i);
if (isV0Separator(c))
return true;
}
return false;
}
/**
* Returns true if the byte is a separator as defined by V1 of the cookie
* spec, RFC2109.
* @throws IllegalArgumentException if a control character was supplied as
* input
*/
static boolean isHttpSeparator(final char c) {
if (c < 0x20 || c >= 0x7f) {
if (c != 0x09) {
throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c));
}
}
return HTTP_SEPARATOR_FLAGS[c];
}
private static boolean isHttpToken(String value) {
if( value==null) return false;
int i = 0;
int len = value.length();
if (alreadyQuoted(value)) {
i++;
len--;
}
for (; i < len; i++) {
char c = value.charAt(i);
if (isHttpSeparator(c))
return true;
}
return false;
}
private static boolean alreadyQuoted(String value) {
if (value==null || value.length() < 2) return false;
return (value.charAt(0)=='\"' && value.charAt(value.length()-1)=='\"');
}
/**
* Quotes values if required.
* @param buf
* @param value
*/
public static void maybeQuote(StringBuilder buf, String value) {
if (value==null || value.length()==0) {
buf.append("\"\"");
} else if (alreadyQuoted(value)) {
buf.append('"');
buf.append(escapeDoubleQuotes(value,1,value.length()-1));
buf.append('"');
} else if ((isHttpToken(value) && !ALLOW_HTTP_SEPARATORS_IN_V0) ||
(isV0Token(value) && ALLOW_HTTP_SEPARATORS_IN_V0)) {
buf.append('"');
buf.append(escapeDoubleQuotes(value,0,value.length()));
buf.append('"');
} else {
buf.append(value);
}
}
/**
* Escapes any double quotes in the given string.
*
* @param s the input string
* @param beginIndex start index inclusive
* @param endIndex exclusive
* @return The (possibly) escaped string
*/
private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) {
if (s == null || s.length() == 0 || s.indexOf('"') == -1) {
return s;
}
StringBuilder b = new StringBuilder();
for (int i = beginIndex; i < endIndex; i++) {
char c = s.charAt(i);
if (c == '\\' ) {
b.append(c);
//ignore the character after an escape, just append it
if (++i>=endIndex) throw UndertowMessages.MESSAGES.invalidEscapeCharacter();
b.append(s.charAt(i));
} else if (c == '"')
b.append('\\').append('"');
else
b.append(c);
}
return b.toString();
}
public static int adjustedCookieVersion(Cookie cookie) {
/*
* The spec allows some latitude on when to send the version attribute
* with a Set-Cookie header. To be nice to clients, we'll make sure the
* version attribute is first. That means checking the various things
* that can cause us to switch to a v1 cookie first.
*_
* Note that by checking for tokens we will also throw an exception if a
* control character is encountered.
*/
int version = cookie.getVersion();
String value = cookie.getValue();
String path = cookie.getPath();
String domain = cookie.getDomain();
String comment = cookie.getComment();
// If it is v0, check if we need to switch
if (version == 0 &&
(!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(value) ||
ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(value))) {
// HTTP token in value - need to use v1
version = 1;
}
if (version == 0 && comment != null) {
// Using a comment makes it a v1 cookie
version = 1;
}
if (version == 0 &&
(!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(path) ||
ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(path))) {
// HTTP token in path - need to use v1
version = 1;
}
if (version == 0 &&
(!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(domain) ||
ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(domain))) {
// HTTP token<SUF>
version = 1;
}
return version;
}
// ------------------------------------------------------------- Constructor
private LegacyCookieSupport() {
// Utility class. Don't allow instances to be created.
}
}
|
15115_10 | /*
* Unit OpenAPI specifications
* An OpenAPI specifications for unit-sdk clients
*
* The version of the OpenAPI document: 0.0.3
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package unit.java.sdk.model;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.StringJoiner;
import java.util.Objects;
import java.util.Map;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Arrays;
import unit.java.sdk.model.ReturnedAchTransactionAllOfAttributes;
import unit.java.sdk.model.Transaction;
import unit.java.sdk.model.TransactionRelationships;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import unit.java.sdk.JSON;
/**
* ReturnedAchTransaction
*/
@JsonPropertyOrder({
ReturnedAchTransaction.JSON_PROPERTY_ATTRIBUTES,
ReturnedAchTransaction.JSON_PROPERTY_RELATIONSHIPS
})
@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
@JsonIgnoreProperties(
value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
public class ReturnedAchTransaction extends Transaction {
public static final String JSON_PROPERTY_ATTRIBUTES = "attributes";
private ReturnedAchTransactionAllOfAttributes attributes;
public static final String JSON_PROPERTY_RELATIONSHIPS = "relationships";
private TransactionRelationships relationships;
public ReturnedAchTransaction() {
}
public ReturnedAchTransaction attributes(ReturnedAchTransactionAllOfAttributes attributes) {
this.attributes = attributes;
return this;
}
/**
* Get attributes
* @return attributes
**/
@jakarta.annotation.Nonnull
@JsonProperty(JSON_PROPERTY_ATTRIBUTES)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public ReturnedAchTransactionAllOfAttributes getAttributes() {
return attributes;
}
@JsonProperty(JSON_PROPERTY_ATTRIBUTES)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public void setAttributes(ReturnedAchTransactionAllOfAttributes attributes) {
this.attributes = attributes;
}
public ReturnedAchTransaction relationships(TransactionRelationships relationships) {
this.relationships = relationships;
return this;
}
/**
* Get relationships
* @return relationships
**/
@jakarta.annotation.Nonnull
@JsonProperty(JSON_PROPERTY_RELATIONSHIPS)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public TransactionRelationships getRelationships() {
return relationships;
}
@JsonProperty(JSON_PROPERTY_RELATIONSHIPS)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public void setRelationships(TransactionRelationships relationships) {
this.relationships = relationships;
}
@Override
public ReturnedAchTransaction id(String id) {
this.setId(id);
return this;
}
@Override
public ReturnedAchTransaction type(String type) {
this.setType(type);
return this;
}
/**
* Return true if this ReturnedAchTransaction object is equal to o.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReturnedAchTransaction returnedAchTransaction = (ReturnedAchTransaction) o;
return Objects.equals(this.attributes, returnedAchTransaction.attributes) &&
Objects.equals(this.relationships, returnedAchTransaction.relationships) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(attributes, relationships, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ReturnedAchTransaction {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n");
sb.append(" relationships: ").append(toIndentedString(relationships)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
/**
* Convert the instance into URL query string.
*
* @return URL query string
*/
public String toUrlQueryString() {
return toUrlQueryString(null);
}
/**
* Convert the instance into URL query string.
*
* @param prefix prefix of the query string
* @return URL query string
*/
public String toUrlQueryString(String prefix) {
String suffix = "";
String containerSuffix = "";
String containerPrefix = "";
if (prefix == null) {
// style=form, explode=true, e.g. /pet?name=cat&type=manx
prefix = "";
} else {
// deepObject style e.g. /pet?id[name]=cat&id[type]=manx
prefix = prefix + "[";
suffix = "]";
containerSuffix = "]";
containerPrefix = "[";
}
StringJoiner joiner = new StringJoiner("&");
// add `id` to the URL query string
if (getId() != null) {
joiner.add(String.format("%sid%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
}
// add `type` to the URL query string
if (getType() != null) {
joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
}
// add `attributes` to the URL query string
if (getAttributes() != null) {
joiner.add(getAttributes().toUrlQueryString(prefix + "attributes" + suffix));
}
// add `relationships` to the URL query string
if (getRelationships() != null) {
joiner.add(getRelationships().toUrlQueryString(prefix + "relationships" + suffix));
}
return joiner.toString();
}
static {
// Initialize and register the discriminator mappings.
Map<String, Class<?>> mappings = new HashMap<String, Class<?>>();
mappings.put("ReturnedAchTransaction", ReturnedAchTransaction.class);
JSON.registerDiscriminator(ReturnedAchTransaction.class, "type", mappings);
}
}
| unit-finance/unit-openapi-java-sdk | src/main/java/unit/java/sdk/model/ReturnedAchTransaction.java | 2,118 | // deepObject style e.g. /pet?id[name]=cat&id[type]=manx | line_comment | nl | /*
* Unit OpenAPI specifications
* An OpenAPI specifications for unit-sdk clients
*
* The version of the OpenAPI document: 0.0.3
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package unit.java.sdk.model;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.StringJoiner;
import java.util.Objects;
import java.util.Map;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Arrays;
import unit.java.sdk.model.ReturnedAchTransactionAllOfAttributes;
import unit.java.sdk.model.Transaction;
import unit.java.sdk.model.TransactionRelationships;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import unit.java.sdk.JSON;
/**
* ReturnedAchTransaction
*/
@JsonPropertyOrder({
ReturnedAchTransaction.JSON_PROPERTY_ATTRIBUTES,
ReturnedAchTransaction.JSON_PROPERTY_RELATIONSHIPS
})
@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
@JsonIgnoreProperties(
value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
public class ReturnedAchTransaction extends Transaction {
public static final String JSON_PROPERTY_ATTRIBUTES = "attributes";
private ReturnedAchTransactionAllOfAttributes attributes;
public static final String JSON_PROPERTY_RELATIONSHIPS = "relationships";
private TransactionRelationships relationships;
public ReturnedAchTransaction() {
}
public ReturnedAchTransaction attributes(ReturnedAchTransactionAllOfAttributes attributes) {
this.attributes = attributes;
return this;
}
/**
* Get attributes
* @return attributes
**/
@jakarta.annotation.Nonnull
@JsonProperty(JSON_PROPERTY_ATTRIBUTES)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public ReturnedAchTransactionAllOfAttributes getAttributes() {
return attributes;
}
@JsonProperty(JSON_PROPERTY_ATTRIBUTES)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public void setAttributes(ReturnedAchTransactionAllOfAttributes attributes) {
this.attributes = attributes;
}
public ReturnedAchTransaction relationships(TransactionRelationships relationships) {
this.relationships = relationships;
return this;
}
/**
* Get relationships
* @return relationships
**/
@jakarta.annotation.Nonnull
@JsonProperty(JSON_PROPERTY_RELATIONSHIPS)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public TransactionRelationships getRelationships() {
return relationships;
}
@JsonProperty(JSON_PROPERTY_RELATIONSHIPS)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public void setRelationships(TransactionRelationships relationships) {
this.relationships = relationships;
}
@Override
public ReturnedAchTransaction id(String id) {
this.setId(id);
return this;
}
@Override
public ReturnedAchTransaction type(String type) {
this.setType(type);
return this;
}
/**
* Return true if this ReturnedAchTransaction object is equal to o.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReturnedAchTransaction returnedAchTransaction = (ReturnedAchTransaction) o;
return Objects.equals(this.attributes, returnedAchTransaction.attributes) &&
Objects.equals(this.relationships, returnedAchTransaction.relationships) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(attributes, relationships, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ReturnedAchTransaction {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n");
sb.append(" relationships: ").append(toIndentedString(relationships)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
/**
* Convert the instance into URL query string.
*
* @return URL query string
*/
public String toUrlQueryString() {
return toUrlQueryString(null);
}
/**
* Convert the instance into URL query string.
*
* @param prefix prefix of the query string
* @return URL query string
*/
public String toUrlQueryString(String prefix) {
String suffix = "";
String containerSuffix = "";
String containerPrefix = "";
if (prefix == null) {
// style=form, explode=true, e.g. /pet?name=cat&type=manx
prefix = "";
} else {
// deepObject style<SUF>
prefix = prefix + "[";
suffix = "]";
containerSuffix = "]";
containerPrefix = "[";
}
StringJoiner joiner = new StringJoiner("&");
// add `id` to the URL query string
if (getId() != null) {
joiner.add(String.format("%sid%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getId()), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
}
// add `type` to the URL query string
if (getType() != null) {
joiner.add(String.format("%stype%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getType()), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
}
// add `attributes` to the URL query string
if (getAttributes() != null) {
joiner.add(getAttributes().toUrlQueryString(prefix + "attributes" + suffix));
}
// add `relationships` to the URL query string
if (getRelationships() != null) {
joiner.add(getRelationships().toUrlQueryString(prefix + "relationships" + suffix));
}
return joiner.toString();
}
static {
// Initialize and register the discriminator mappings.
Map<String, Class<?>> mappings = new HashMap<String, Class<?>>();
mappings.put("ReturnedAchTransaction", ReturnedAchTransaction.class);
JSON.registerDiscriminator(ReturnedAchTransaction.class, "type", mappings);
}
}
|
87401_60 | package Uno.UI;
import android.graphics.Matrix;
import android.view.*;
import android.view.animation.Transformation;
import android.util.Log;
import java.lang.*;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public abstract class UnoViewGroup
extends android.view.ViewGroup
implements Uno.UI.UnoMotionTarget {
private static final String LOGTAG = "UnoViewGroup";
private static boolean _isLayoutingFromMeasure = false;
private static ArrayList<UnoViewGroup> callToRequestLayout = new ArrayList<UnoViewGroup>();
private boolean _inLocalAddView, _inLocalRemoveView;
private boolean _isEnabled;
private boolean _isHitTestVisible;
private boolean _isManagedLoaded;
private boolean _needsLayoutOnAttachedToWindow;
private Map<View, Matrix> _childrenTransformations = new HashMap<View, Matrix>();
private static Method _setFrameMethod;
static {
try {
buildSetFrameReflection();
}
catch(Exception e) {
Log.e(LOGTAG, "Failed to initialize NativeSetFrame method. " + e.toString());
}
}
private static void buildSetFrameReflection() throws ClassNotFoundException, InstantiationException, Exception
{
// This is required because we need to set the view bounds before calling onLayout()
Class viewClass = java.lang.Class.forName("android.view.View");
Method[] methods = viewClass.getDeclaredMethods();
for(int i=0; i < methods.length; i++) {
if(methods[i].getName().equals("setFrame") && methods[i].getParameterTypes().length == 4) {
_setFrameMethod = methods[i];
_setFrameMethod.setAccessible(true);
}
}
// This block is commented for easier logging.
//
// if(_setFrameMethod != null) {
// Log.i(LOGTAG, "Found android.view.View.setFrame(), arrange fast-path is ENABLED.");
// }
// else {
// Log.i(LOGTAG, "Unable to find android.view.View.setFrame(), arrange fast-path is DISABLED.");
// }
}
public UnoViewGroup(android.content.Context ctx)
{
super(ctx);
_isEnabled = true;
_isHitTestVisible = true;
setOnHierarchyChangeListener(
new OnHierarchyChangeListener()
{
@Override
public void onChildViewAdded(View parent, View child)
{
if(!_inLocalAddView)
{
onLocalViewAdded(child, indexOfChild(child));
}
}
@Override
public void onChildViewRemoved(View parent, View child)
{
if(!_inLocalRemoveView)
{
onLocalViewRemoved(child);
}
}
}
);
setClipChildren(false); // The actual clipping will be calculated in managed code
setClipToPadding(false); // Same as above
}
@Override
public boolean hasOverlappingRendering()
{
// This override is to prevent the Android framework from creating a layer for this view,
// which would cause a clipping issue because the layer could potentially be too small for
// the view's content.
// By preventing Android from creating that layer, the view will be drawn directly into
// the parent's layer, so the problem is avoided.
// A slight performance hit is expected, but it's should be negligible when it's only
// on elements having opacity < 1f.
// Original bug: https://github.com/unoplatform/Uno.Gallery/issues/898
// Check for opacity (Alpha) and return false if it's less than 1f
return getAlpha() >= 1 && super.hasOverlappingRendering();
}
private boolean _unoLayoutOverride;
public final void nativeStartLayoutOverride(int left, int top, int right, int bottom) throws IllegalAccessException, InvocationTargetException {
_unoLayoutOverride = true;
if(_setFrameMethod != null) {
// When Uno overrides the layout pass, the setFrame method must be called to
// set the bounds of the frame, while not calling layout().
_setFrameMethod.invoke(this, new Object[]{ left, top, right, bottom });
}
else {
// This method is present as a fallback in case google would remove the
// setFrame method.
layout(left, top, right, bottom);
// Force layout is required to ensure that the children added during the layout phase
// are properly layouted. Failing to call this method will make controls
// like the ContentPresenter not display their content, if added late.
forceLayout();
}
}
public final void nativeFinishLayoutOverride(){
// Call the actual layout method, so the FORCE_LAYOUT flag is cleared.
// This must be called before setting _unoLayoutOverride to false, to avoid onLayout calling
// onLayoutCore.
layout(getLeft(), getTop(), getRight(), getBottom());
_unoLayoutOverride = false;
}
protected abstract void onLayoutCore(boolean changed, int left, int top, int right, int bottom, boolean isLayoutRequested);
protected final void onLayout(boolean changed, int left, int top, int right, int bottom)
{
if(!_unoLayoutOverride)
{
onLayoutCore(changed, left, top, right, bottom, isLayoutRequested());
}
}
protected abstract void onLocalViewAdded(View view, int index);
protected abstract void onLocalViewRemoved(View view);
public static long getMeasuredDimensions(View view) {
// This method is called often enough that returning one long
// instead of two calls returning two integers improves
// the layouting performance.
return view.getMeasuredWidth() | (((long)view.getMeasuredHeight()) << 32);
}
/**
* Fast invocation for the request layout logic.
*
* Implemented in java to avoid the interop cost of android-only APIs from managed code.
*/
public static void tryFastRequestLayout(View view, boolean needsForceLayout) {
if (needsForceLayout) {
// Bypass Android cache, to ensure the Child's Measure() is actually invoked.
view.forceLayout();
// This could occur when one of the dimension is _Infinite_: Android will cache the
// value, which is not something we want. Specially when the container is a <StackPanel>.
// Issue: https://github.com/unoplatform/uno/issues/2879
}
if (view.isLayoutRequested())
{
ViewParent parent = view.getParent();
if(parent != null && !parent.isLayoutRequested())
{
// If a view has requested layout but its Parent hasn't, then the tree is in a broken state, because RequestLayout() calls
// cannot bubble up from below the view, and remeasures cannot bubble down from above the parent. This can arise, eg, when
// ForceLayout() is used. To fix this state, call RequestLayout() on the parent. Since MeasureChildOverride() is called
// from the top down, we should be able to assume that the tree above the parent is already in a good state.
parent.requestLayout();
}
}
}
protected final void addViewFast(View view)
{
try
{
_inLocalAddView = true;
addView(view, -1, generateDefaultLayoutParams());
}
finally
{
_inLocalAddView = false;
}
}
protected final void addViewFast(View view, int position)
{
try
{
_inLocalAddView = true;
addView(view, position, generateDefaultLayoutParams());
}
finally
{
_inLocalAddView = false;
}
}
protected final void removeViewFast(View view)
{
try
{
_inLocalRemoveView = true;
removeView(view);
notifyChildRemoved(view);
}
finally
{
_inLocalRemoveView = false;
}
}
protected final void removeViewAtFast(int position)
{
try
{
_inLocalRemoveView = true;
View child = getChildAt(position);
removeViewAt(position);
notifyChildRemoved(child);
}
finally
{
_inLocalRemoveView = false;
}
}
private android.text.Layout _textBlockLayout;
private int _leftTextBlockPadding, _topTextBlockPadding;
// Provides a fast path for textblock text drawing, to avoid overriding
// it in C#, for improved performance.
public final void setNativeTextBlockLayout(android.text.Layout layout, int leftPadding, int topPadding) {
_textBlockLayout = layout;
_leftTextBlockPadding = leftPadding;
_topTextBlockPadding = topPadding;
}
@Override
protected void onDraw(android.graphics.Canvas canvas)
{
if(_textBlockLayout != null) {
canvas.translate(_leftTextBlockPadding, _topTextBlockPadding);
_textBlockLayout.draw(canvas);
}
}
private void notifyChildRemoved(View child)
{
UnoViewGroup childViewGroup = child instanceof UnoViewGroup
? (UnoViewGroup)child
: null;
if(childViewGroup != null)
{
// This is required because the Parent property is set to null
// after the onDetachedFromWindow is called.
childViewGroup.onRemovedFromParent();
}
}
protected abstract void onRemovedFromParent();
protected final void measureChild(View view, int widthSpec, int heightSpec)
{
super.measureChild(view, widthSpec, heightSpec);
}
public final boolean getIsNativeLoaded() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
return super.getWindowId() != null;
}
else {
return super.getWindowToken() != null;
}
}
public final void requestLayout()
{
if(nativeRequestLayout())
{
if (getIsManagedLoaded() && !getIsNativeLoaded()) {
// If we're here, managed load is enabled (AndroidUseManagedLoadedUnloaded = true) and requestLayout() has been called from OnLoaded
// prior to dispatchAttachedToWindow() being called. This can cause the request to fall through the cracks, because mAttachInfo
// isn't set yet. (See ViewRootImpl.requestLayoutDuringLayout()). If we're in a layout pass already, we have to ensure that requestLayout()
// is called again once the view is fully natively initialized.
_needsLayoutOnAttachedToWindow = true;
}
if(_isLayoutingFromMeasure){
callToRequestLayout.add(this);
return;
}
super.requestLayout();
}
}
public final void invalidate()
{
super.invalidate();
}
protected abstract boolean nativeRequestLayout();
public final boolean isLayoutRequested()
{
return super.isLayoutRequested();
}
public final float getAlpha()
{
return super.getAlpha();
}
public final void setAlpha(float opacity)
{
super.setAlpha(opacity);
}
private class TouchMotionTarget extends Uno.UI.TouchMotionTarget
{
TouchMotionTarget() { super(UnoViewGroup.this); }
@Override public boolean dispatchToSuper(MotionEvent event) { return Uno.UI.UnoViewGroup.super.dispatchTouchEvent(event); }
}
private class GenericMotionTarget extends Uno.UI.GenericMotionTarget
{
GenericMotionTarget() { super(UnoViewGroup.this); }
@Override public boolean dispatchToSuper(MotionEvent event) { return Uno.UI.UnoViewGroup.super.dispatchGenericMotionEvent(event); }
}
private final Uno.UI.MotionTargetAdapter _thisAsTouchTarget = new TouchMotionTarget();
private final Uno.UI.MotionTargetAdapter _thisAsGenericMotionTarget = new GenericMotionTarget();
@Override public /* TODO: final */ boolean dispatchTouchEvent(MotionEvent event) {
return Uno.UI.UnoMotionHelper.Instance.dispatchMotionEvent(_thisAsTouchTarget, event);
}
@Override public final boolean dispatchGenericMotionEvent(MotionEvent event) {
return Uno.UI.UnoMotionHelper.Instance.dispatchMotionEvent(_thisAsGenericMotionTarget, event);
}
private boolean _isNativeMotionEventsInterceptForbidden = false;
@Override public /* protected in C# */ final boolean getIsNativeMotionEventsInterceptForbidden(){ return _isNativeMotionEventsInterceptForbidden; }
public /* protected in C# */ final void setIsNativeMotionEventsInterceptForbidden(boolean isNativeMotionEventsInterceptForbidden){ _isNativeMotionEventsInterceptForbidden = isNativeMotionEventsInterceptForbidden; }
private boolean _isNativeMotionEventsEnabled = true;
@Override public /* protected in C# */ final boolean getIsNativeMotionEventsEnabled(){ return _isNativeMotionEventsEnabled; }
public /* protected in C# */ final void setIsNativeMotionEventsEnabled(boolean isNativeMotionEventsEnabled){ _isNativeMotionEventsEnabled = isNativeMotionEventsEnabled; }
@Override public /* protected in C# */ boolean onNativeMotionEvent(MotionEvent event, View originalSource, boolean isInView) {
return false;
}
public final void setNativeIsHitTestVisible(boolean hitTestVisible) { _isHitTestVisible = hitTestVisible; }
public /* hidden to C# */ final boolean getNativeIsHitTestVisible() { return _isHitTestVisible; }
public final void setNativeIsEnabled(boolean isEnabled) { _isEnabled = isEnabled; }
public /* hidden to C# */ final boolean getNativeIsEnabled() { return _isEnabled; }
public /* protected in C# */ abstract boolean nativeHitCheck();
/**
* Call this method if a view is to be laid out outside of a framework layout pass, to ensure that requestLayout() requests are captured
* and propagated later. (Equivalent of ViewRootImpl.requestLayoutDuringLayout())
*/
public static void startLayoutingFromMeasure() {
_isLayoutingFromMeasure = true;
}
/**
* This should always be called immediately after {{@link #startLayoutingFromMeasure()}} has been called.
*/
public static void endLayoutingFromMeasure() {
_isLayoutingFromMeasure = false;
}
/**
* This should be called subsequently to {{@link #endLayoutingFromMeasure()}}, typically during a true layout pass, to flush any captured layout requests.
*/
public static void measureBeforeLayout() {
if (_isLayoutingFromMeasure)
{
// This can happen when nested controls call startLayoutingFromMeasure()/measureBeforeLayout()
return;
}
try {
for (int i = 0; i < callToRequestLayout.size(); i++) {
UnoViewGroup view = callToRequestLayout.get(i);
if (view.isAttachedToWindow()) {
view.requestLayout();
}
}
}
finally {
callToRequestLayout.clear();
}
}
protected final void onAttachedToWindow()
{
super.onAttachedToWindow();
if(!_isManagedLoaded) {
onNativeLoaded();
_isManagedLoaded = true;
}
else if (_needsLayoutOnAttachedToWindow && isInLayout()) {
requestLayout();
}
_needsLayoutOnAttachedToWindow = false;
}
protected abstract void onNativeLoaded();
protected final void onDetachedFromWindow()
{
super.onDetachedFromWindow();
if(_isManagedLoaded) {
onNativeUnloaded();
_isManagedLoaded = false;
}
}
protected abstract void onNativeUnloaded();
/**
* Marks this view as loaded from the managed side, so onAttachedToWindow can skip
* calling onNativeLoaded.
*/
public final void setIsManagedLoaded(boolean value)
{
_isManagedLoaded = value;
}
/**
* Gets if this view is loaded from the managed side.
*/
public final boolean getIsManagedLoaded()
{
return _isManagedLoaded;
}
public final void setVisibility(int visibility)
{
super.setVisibility(visibility);
}
public final int getVisibility()
{
return super.getVisibility();
}
public final void setBackgroundColor(int color)
{
super.setBackgroundColor(color);
}
public final void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
}
public final boolean isEnabled()
{
return super.isEnabled();
}
/*
// Not supported because set is no virtual
public final void setFocusable(boolean focusable)
{
super.setFocusable(focusable);
}
public final boolean getFocusable()
{
return super.isFocusable();
}
*/
/**
* Sets the static transform matrix to apply to the given child view.
* This will be used by the {@link #getChildStaticTransformation(View, Transformation)}
*
* @param child The view to which the matrix applies.
* @param transform The transformation matrix to apply.
*/
protected final void setChildRenderTransform(View child, Matrix transform) {
_childrenTransformations.put(child, transform);
if (_childrenTransformations.size() == 1) {
setStaticTransformationsEnabled(true);
}
}
/**
* Removes the static transform matrix applied to the given child view.
*
* @param child The view to which the matrix applies.
*/
protected final void removeChildRenderTransform(View child) {
_childrenTransformations.remove(child);
if (_childrenTransformations.size() == 0) {
setStaticTransformationsEnabled(false);
}
}
@Override
protected final boolean getChildStaticTransformation(View child, Transformation outTransform) {
Matrix renderTransform = _childrenTransformations.get(child);
if (renderTransform == null || renderTransform.isIdentity()) {
outTransform.clear();
} else {
outTransform.getMatrix().set(renderTransform);
}
return true;
}
public /* hidden to C# */ int getChildrenRenderTransformCount() { return _childrenTransformations.size(); }
public /* hidden to C# */ Matrix findChildRenderTransform(View child) { return _childrenTransformations.get(child); }
@Override
public void getLocationInWindow(int[] outLocation) {
super.getLocationInWindow(outLocation);
ViewParent currentParent = getParent();
View currentChild = this;
float[] points = null;
while (currentParent instanceof View) {
if (currentParent instanceof UnoViewGroup) {
final UnoViewGroup currentUVGParent = (UnoViewGroup)currentParent;
Matrix parentMatrix = currentUVGParent.findChildRenderTransform(currentChild);
if (parentMatrix != null && !parentMatrix.isIdentity()) {
if (points == null) {
points = new float[2];
}
// Apply the offset from the ancestor's RenderTransform, because the base Android method doesn't take
// StaticTransformation into account.
Matrix inverse = new Matrix();
parentMatrix.invert(inverse);
inverse.mapPoints(points);
}
}
currentChild = (View)currentParent;
currentParent = currentParent.getParent();
}
if (points != null) {
outLocation[0]-=(int)points[0];
outLocation[1]-=(int)points[1];
}
}
// Allows UI automation operations to look for a single 'Text' property for both ViewGroup and TextView elements.
// Is mapped to the UIAutomationText property
public String getText() {
return null;
}
/**
* Get the depth of this view in the visual tree. For debugging use only.
*
* @return Depth
*/
public int getViewDepth() {
int viewDepth = 0;
ViewParent parent = getParent();
while (parent != null) {
viewDepth++;
parent = parent.getParent();
}
return viewDepth;
}
}
| unoplatform/uno | src/Uno.UI.BindingHelper.Android/Uno/UI/UnoViewGroup.java | 5,357 | /* hidden to C# */ | block_comment | nl | package Uno.UI;
import android.graphics.Matrix;
import android.view.*;
import android.view.animation.Transformation;
import android.util.Log;
import java.lang.*;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public abstract class UnoViewGroup
extends android.view.ViewGroup
implements Uno.UI.UnoMotionTarget {
private static final String LOGTAG = "UnoViewGroup";
private static boolean _isLayoutingFromMeasure = false;
private static ArrayList<UnoViewGroup> callToRequestLayout = new ArrayList<UnoViewGroup>();
private boolean _inLocalAddView, _inLocalRemoveView;
private boolean _isEnabled;
private boolean _isHitTestVisible;
private boolean _isManagedLoaded;
private boolean _needsLayoutOnAttachedToWindow;
private Map<View, Matrix> _childrenTransformations = new HashMap<View, Matrix>();
private static Method _setFrameMethod;
static {
try {
buildSetFrameReflection();
}
catch(Exception e) {
Log.e(LOGTAG, "Failed to initialize NativeSetFrame method. " + e.toString());
}
}
private static void buildSetFrameReflection() throws ClassNotFoundException, InstantiationException, Exception
{
// This is required because we need to set the view bounds before calling onLayout()
Class viewClass = java.lang.Class.forName("android.view.View");
Method[] methods = viewClass.getDeclaredMethods();
for(int i=0; i < methods.length; i++) {
if(methods[i].getName().equals("setFrame") && methods[i].getParameterTypes().length == 4) {
_setFrameMethod = methods[i];
_setFrameMethod.setAccessible(true);
}
}
// This block is commented for easier logging.
//
// if(_setFrameMethod != null) {
// Log.i(LOGTAG, "Found android.view.View.setFrame(), arrange fast-path is ENABLED.");
// }
// else {
// Log.i(LOGTAG, "Unable to find android.view.View.setFrame(), arrange fast-path is DISABLED.");
// }
}
public UnoViewGroup(android.content.Context ctx)
{
super(ctx);
_isEnabled = true;
_isHitTestVisible = true;
setOnHierarchyChangeListener(
new OnHierarchyChangeListener()
{
@Override
public void onChildViewAdded(View parent, View child)
{
if(!_inLocalAddView)
{
onLocalViewAdded(child, indexOfChild(child));
}
}
@Override
public void onChildViewRemoved(View parent, View child)
{
if(!_inLocalRemoveView)
{
onLocalViewRemoved(child);
}
}
}
);
setClipChildren(false); // The actual clipping will be calculated in managed code
setClipToPadding(false); // Same as above
}
@Override
public boolean hasOverlappingRendering()
{
// This override is to prevent the Android framework from creating a layer for this view,
// which would cause a clipping issue because the layer could potentially be too small for
// the view's content.
// By preventing Android from creating that layer, the view will be drawn directly into
// the parent's layer, so the problem is avoided.
// A slight performance hit is expected, but it's should be negligible when it's only
// on elements having opacity < 1f.
// Original bug: https://github.com/unoplatform/Uno.Gallery/issues/898
// Check for opacity (Alpha) and return false if it's less than 1f
return getAlpha() >= 1 && super.hasOverlappingRendering();
}
private boolean _unoLayoutOverride;
public final void nativeStartLayoutOverride(int left, int top, int right, int bottom) throws IllegalAccessException, InvocationTargetException {
_unoLayoutOverride = true;
if(_setFrameMethod != null) {
// When Uno overrides the layout pass, the setFrame method must be called to
// set the bounds of the frame, while not calling layout().
_setFrameMethod.invoke(this, new Object[]{ left, top, right, bottom });
}
else {
// This method is present as a fallback in case google would remove the
// setFrame method.
layout(left, top, right, bottom);
// Force layout is required to ensure that the children added during the layout phase
// are properly layouted. Failing to call this method will make controls
// like the ContentPresenter not display their content, if added late.
forceLayout();
}
}
public final void nativeFinishLayoutOverride(){
// Call the actual layout method, so the FORCE_LAYOUT flag is cleared.
// This must be called before setting _unoLayoutOverride to false, to avoid onLayout calling
// onLayoutCore.
layout(getLeft(), getTop(), getRight(), getBottom());
_unoLayoutOverride = false;
}
protected abstract void onLayoutCore(boolean changed, int left, int top, int right, int bottom, boolean isLayoutRequested);
protected final void onLayout(boolean changed, int left, int top, int right, int bottom)
{
if(!_unoLayoutOverride)
{
onLayoutCore(changed, left, top, right, bottom, isLayoutRequested());
}
}
protected abstract void onLocalViewAdded(View view, int index);
protected abstract void onLocalViewRemoved(View view);
public static long getMeasuredDimensions(View view) {
// This method is called often enough that returning one long
// instead of two calls returning two integers improves
// the layouting performance.
return view.getMeasuredWidth() | (((long)view.getMeasuredHeight()) << 32);
}
/**
* Fast invocation for the request layout logic.
*
* Implemented in java to avoid the interop cost of android-only APIs from managed code.
*/
public static void tryFastRequestLayout(View view, boolean needsForceLayout) {
if (needsForceLayout) {
// Bypass Android cache, to ensure the Child's Measure() is actually invoked.
view.forceLayout();
// This could occur when one of the dimension is _Infinite_: Android will cache the
// value, which is not something we want. Specially when the container is a <StackPanel>.
// Issue: https://github.com/unoplatform/uno/issues/2879
}
if (view.isLayoutRequested())
{
ViewParent parent = view.getParent();
if(parent != null && !parent.isLayoutRequested())
{
// If a view has requested layout but its Parent hasn't, then the tree is in a broken state, because RequestLayout() calls
// cannot bubble up from below the view, and remeasures cannot bubble down from above the parent. This can arise, eg, when
// ForceLayout() is used. To fix this state, call RequestLayout() on the parent. Since MeasureChildOverride() is called
// from the top down, we should be able to assume that the tree above the parent is already in a good state.
parent.requestLayout();
}
}
}
protected final void addViewFast(View view)
{
try
{
_inLocalAddView = true;
addView(view, -1, generateDefaultLayoutParams());
}
finally
{
_inLocalAddView = false;
}
}
protected final void addViewFast(View view, int position)
{
try
{
_inLocalAddView = true;
addView(view, position, generateDefaultLayoutParams());
}
finally
{
_inLocalAddView = false;
}
}
protected final void removeViewFast(View view)
{
try
{
_inLocalRemoveView = true;
removeView(view);
notifyChildRemoved(view);
}
finally
{
_inLocalRemoveView = false;
}
}
protected final void removeViewAtFast(int position)
{
try
{
_inLocalRemoveView = true;
View child = getChildAt(position);
removeViewAt(position);
notifyChildRemoved(child);
}
finally
{
_inLocalRemoveView = false;
}
}
private android.text.Layout _textBlockLayout;
private int _leftTextBlockPadding, _topTextBlockPadding;
// Provides a fast path for textblock text drawing, to avoid overriding
// it in C#, for improved performance.
public final void setNativeTextBlockLayout(android.text.Layout layout, int leftPadding, int topPadding) {
_textBlockLayout = layout;
_leftTextBlockPadding = leftPadding;
_topTextBlockPadding = topPadding;
}
@Override
protected void onDraw(android.graphics.Canvas canvas)
{
if(_textBlockLayout != null) {
canvas.translate(_leftTextBlockPadding, _topTextBlockPadding);
_textBlockLayout.draw(canvas);
}
}
private void notifyChildRemoved(View child)
{
UnoViewGroup childViewGroup = child instanceof UnoViewGroup
? (UnoViewGroup)child
: null;
if(childViewGroup != null)
{
// This is required because the Parent property is set to null
// after the onDetachedFromWindow is called.
childViewGroup.onRemovedFromParent();
}
}
protected abstract void onRemovedFromParent();
protected final void measureChild(View view, int widthSpec, int heightSpec)
{
super.measureChild(view, widthSpec, heightSpec);
}
public final boolean getIsNativeLoaded() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
return super.getWindowId() != null;
}
else {
return super.getWindowToken() != null;
}
}
public final void requestLayout()
{
if(nativeRequestLayout())
{
if (getIsManagedLoaded() && !getIsNativeLoaded()) {
// If we're here, managed load is enabled (AndroidUseManagedLoadedUnloaded = true) and requestLayout() has been called from OnLoaded
// prior to dispatchAttachedToWindow() being called. This can cause the request to fall through the cracks, because mAttachInfo
// isn't set yet. (See ViewRootImpl.requestLayoutDuringLayout()). If we're in a layout pass already, we have to ensure that requestLayout()
// is called again once the view is fully natively initialized.
_needsLayoutOnAttachedToWindow = true;
}
if(_isLayoutingFromMeasure){
callToRequestLayout.add(this);
return;
}
super.requestLayout();
}
}
public final void invalidate()
{
super.invalidate();
}
protected abstract boolean nativeRequestLayout();
public final boolean isLayoutRequested()
{
return super.isLayoutRequested();
}
public final float getAlpha()
{
return super.getAlpha();
}
public final void setAlpha(float opacity)
{
super.setAlpha(opacity);
}
private class TouchMotionTarget extends Uno.UI.TouchMotionTarget
{
TouchMotionTarget() { super(UnoViewGroup.this); }
@Override public boolean dispatchToSuper(MotionEvent event) { return Uno.UI.UnoViewGroup.super.dispatchTouchEvent(event); }
}
private class GenericMotionTarget extends Uno.UI.GenericMotionTarget
{
GenericMotionTarget() { super(UnoViewGroup.this); }
@Override public boolean dispatchToSuper(MotionEvent event) { return Uno.UI.UnoViewGroup.super.dispatchGenericMotionEvent(event); }
}
private final Uno.UI.MotionTargetAdapter _thisAsTouchTarget = new TouchMotionTarget();
private final Uno.UI.MotionTargetAdapter _thisAsGenericMotionTarget = new GenericMotionTarget();
@Override public /* TODO: final */ boolean dispatchTouchEvent(MotionEvent event) {
return Uno.UI.UnoMotionHelper.Instance.dispatchMotionEvent(_thisAsTouchTarget, event);
}
@Override public final boolean dispatchGenericMotionEvent(MotionEvent event) {
return Uno.UI.UnoMotionHelper.Instance.dispatchMotionEvent(_thisAsGenericMotionTarget, event);
}
private boolean _isNativeMotionEventsInterceptForbidden = false;
@Override public /* protected in C# */ final boolean getIsNativeMotionEventsInterceptForbidden(){ return _isNativeMotionEventsInterceptForbidden; }
public /* protected in C# */ final void setIsNativeMotionEventsInterceptForbidden(boolean isNativeMotionEventsInterceptForbidden){ _isNativeMotionEventsInterceptForbidden = isNativeMotionEventsInterceptForbidden; }
private boolean _isNativeMotionEventsEnabled = true;
@Override public /* protected in C# */ final boolean getIsNativeMotionEventsEnabled(){ return _isNativeMotionEventsEnabled; }
public /* protected in C# */ final void setIsNativeMotionEventsEnabled(boolean isNativeMotionEventsEnabled){ _isNativeMotionEventsEnabled = isNativeMotionEventsEnabled; }
@Override public /* protected in C# */ boolean onNativeMotionEvent(MotionEvent event, View originalSource, boolean isInView) {
return false;
}
public final void setNativeIsHitTestVisible(boolean hitTestVisible) { _isHitTestVisible = hitTestVisible; }
public /* hidden to C# */ final boolean getNativeIsHitTestVisible() { return _isHitTestVisible; }
public final void setNativeIsEnabled(boolean isEnabled) { _isEnabled = isEnabled; }
public /* hidden to C# */ final boolean getNativeIsEnabled() { return _isEnabled; }
public /* protected in C# */ abstract boolean nativeHitCheck();
/**
* Call this method if a view is to be laid out outside of a framework layout pass, to ensure that requestLayout() requests are captured
* and propagated later. (Equivalent of ViewRootImpl.requestLayoutDuringLayout())
*/
public static void startLayoutingFromMeasure() {
_isLayoutingFromMeasure = true;
}
/**
* This should always be called immediately after {{@link #startLayoutingFromMeasure()}} has been called.
*/
public static void endLayoutingFromMeasure() {
_isLayoutingFromMeasure = false;
}
/**
* This should be called subsequently to {{@link #endLayoutingFromMeasure()}}, typically during a true layout pass, to flush any captured layout requests.
*/
public static void measureBeforeLayout() {
if (_isLayoutingFromMeasure)
{
// This can happen when nested controls call startLayoutingFromMeasure()/measureBeforeLayout()
return;
}
try {
for (int i = 0; i < callToRequestLayout.size(); i++) {
UnoViewGroup view = callToRequestLayout.get(i);
if (view.isAttachedToWindow()) {
view.requestLayout();
}
}
}
finally {
callToRequestLayout.clear();
}
}
protected final void onAttachedToWindow()
{
super.onAttachedToWindow();
if(!_isManagedLoaded) {
onNativeLoaded();
_isManagedLoaded = true;
}
else if (_needsLayoutOnAttachedToWindow && isInLayout()) {
requestLayout();
}
_needsLayoutOnAttachedToWindow = false;
}
protected abstract void onNativeLoaded();
protected final void onDetachedFromWindow()
{
super.onDetachedFromWindow();
if(_isManagedLoaded) {
onNativeUnloaded();
_isManagedLoaded = false;
}
}
protected abstract void onNativeUnloaded();
/**
* Marks this view as loaded from the managed side, so onAttachedToWindow can skip
* calling onNativeLoaded.
*/
public final void setIsManagedLoaded(boolean value)
{
_isManagedLoaded = value;
}
/**
* Gets if this view is loaded from the managed side.
*/
public final boolean getIsManagedLoaded()
{
return _isManagedLoaded;
}
public final void setVisibility(int visibility)
{
super.setVisibility(visibility);
}
public final int getVisibility()
{
return super.getVisibility();
}
public final void setBackgroundColor(int color)
{
super.setBackgroundColor(color);
}
public final void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
}
public final boolean isEnabled()
{
return super.isEnabled();
}
/*
// Not supported because set is no virtual
public final void setFocusable(boolean focusable)
{
super.setFocusable(focusable);
}
public final boolean getFocusable()
{
return super.isFocusable();
}
*/
/**
* Sets the static transform matrix to apply to the given child view.
* This will be used by the {@link #getChildStaticTransformation(View, Transformation)}
*
* @param child The view to which the matrix applies.
* @param transform The transformation matrix to apply.
*/
protected final void setChildRenderTransform(View child, Matrix transform) {
_childrenTransformations.put(child, transform);
if (_childrenTransformations.size() == 1) {
setStaticTransformationsEnabled(true);
}
}
/**
* Removes the static transform matrix applied to the given child view.
*
* @param child The view to which the matrix applies.
*/
protected final void removeChildRenderTransform(View child) {
_childrenTransformations.remove(child);
if (_childrenTransformations.size() == 0) {
setStaticTransformationsEnabled(false);
}
}
@Override
protected final boolean getChildStaticTransformation(View child, Transformation outTransform) {
Matrix renderTransform = _childrenTransformations.get(child);
if (renderTransform == null || renderTransform.isIdentity()) {
outTransform.clear();
} else {
outTransform.getMatrix().set(renderTransform);
}
return true;
}
public /* hidden to C#<SUF>*/ int getChildrenRenderTransformCount() { return _childrenTransformations.size(); }
public /* hidden to C# */ Matrix findChildRenderTransform(View child) { return _childrenTransformations.get(child); }
@Override
public void getLocationInWindow(int[] outLocation) {
super.getLocationInWindow(outLocation);
ViewParent currentParent = getParent();
View currentChild = this;
float[] points = null;
while (currentParent instanceof View) {
if (currentParent instanceof UnoViewGroup) {
final UnoViewGroup currentUVGParent = (UnoViewGroup)currentParent;
Matrix parentMatrix = currentUVGParent.findChildRenderTransform(currentChild);
if (parentMatrix != null && !parentMatrix.isIdentity()) {
if (points == null) {
points = new float[2];
}
// Apply the offset from the ancestor's RenderTransform, because the base Android method doesn't take
// StaticTransformation into account.
Matrix inverse = new Matrix();
parentMatrix.invert(inverse);
inverse.mapPoints(points);
}
}
currentChild = (View)currentParent;
currentParent = currentParent.getParent();
}
if (points != null) {
outLocation[0]-=(int)points[0];
outLocation[1]-=(int)points[1];
}
}
// Allows UI automation operations to look for a single 'Text' property for both ViewGroup and TextView elements.
// Is mapped to the UIAutomationText property
public String getText() {
return null;
}
/**
* Get the depth of this view in the visual tree. For debugging use only.
*
* @return Depth
*/
public int getViewDepth() {
int viewDepth = 0;
ViewParent parent = getParent();
while (parent != null) {
viewDepth++;
parent = parent.getParent();
}
return viewDepth;
}
}
|
79125_11 | import exceptions.BlackWonException;
import exceptions.IllegalAddToColumnException;
import exceptions.RedWonException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
/**
* This class will create the Connect N object
* This is based on Connect 4, but this should
* be able to handle arbitrary sizes and rules
*/
public class ConnectN {
public static void main(String[] args) throws BlackWonException, IllegalAddToColumnException, RedWonException, InterruptedException {
/*
|-|-|R|-|-|-|-|
|-|-|b|-|-|-|-|
|-|-|b|-|-|R|-|
|-|R|b|R|b|b|-|
|R|R|R|b|R|b|R|
|b|b|b|R|R|b|R|
30616205231212422545543-2147483647
*/
// System.out.println(ConnectNSolver.minimax(new ConnectN("20211533130562641")));
// System.out.println(ConnectNSolver.minimax(new ConnectN("30216526011666332")));
// ConnectN c = new ConnectN("32210010160");
// System.out.println(c);
// System.out.println(c);
// System.out.println(ConnectNSolver.minimax(c));
// System.out.println(c.getHeuristic());
// playVsComputer();
// ConnectN c = new ConnectN();
// System.out.println(ConnectNSolver.minimax(c));
// randomPlay();
// ConnectN c = new ConnectN("0535440512505610115016031463343344");
//// ConnectN c = new ConnectN("010100");
// System.out.println(c);
// System.out.println(c.getHeuristic());
// try {
// c.addColorToColumn(5);
//// for(char cc : "06023616623160316444241365122065".toCharArray())
//// c.addColorToColumn(Integer.parseInt(cc+""));
// }catch (Exception e){
// e.printStackTrace();
// }
// ConnectN c = new ConnectN();
// System.out.println(c);
// int maxDepth = 7;
// while (true){
// if(c.colorTurn==RED)
// maxDepth = 4;
// else maxDepth = 6;
// c.addColorToColumn(new ConnectNSolver(maxDepth).minimax(c));
// System.out.println(c);
// }
playVsComputer();
}
public static void randomPlay(){
List<Integer> moves = new ArrayList<>();
ConnectN c = new ConnectN();
try {
Random r = new Random();
System.out.println(c);
while (true) {
try {
int m = r.nextInt(c.columns);
c.addColorToColumn(m);
moves.add(m);
System.out.println(c);
}catch (IllegalAddToColumnException e){
continue;
}
}
}catch (Exception e){
e.printStackTrace();
System.out.println(c);
moves.forEach(System.out::print);
}
}
public static void playTwoOnTwo() throws BlackWonException, IllegalAddToColumnException, RedWonException {
ConnectN c = new ConnectN();
Scanner s = new Scanner(System.in);
System.out.println(c);
while (true) {
c.addColorToColumn(s.nextInt());
System.out.println(c);
}
}
public static void playVsComputer() throws BlackWonException, IllegalAddToColumnException, RedWonException {
ConnectN c = new ConnectN();
ConnectNSolver solver = new ConnectNSolver();
Scanner s = new Scanner(System.in);
System.out.println(c);
while (true) {
try {
if(c.colorTurn==RED)
c.addColorToColumn(s.nextInt());
else
c.addColorToColumn(solver.minimax(c));
}catch (Exception e){
c.moves.forEach(System.out::print);
throw e;
}
System.out.println(c);
}
}
List<Integer> moves = new ArrayList<>();
public static final int BLACK = 2, RED = 1, EMPTY = 0;
Column[] columnRows;
int winCount = 4, rows = 6, columns = 7, colorTurn = 1;
public ConnectN(Column[] columnRows, int winCount, int rows, int columns, int colorTurn) {
this.columnRows = columnRows;
this.winCount = winCount;
this.rows = rows;
this.columns = columns;
this.colorTurn = colorTurn;
}
public ConnectN() {
init();
}
public ConnectN(int rows, int columns){
this.rows = rows;
this.columns = columns;
init();
}
public ConnectN(String s) throws BlackWonException, IllegalAddToColumnException, RedWonException {
this();
for(char c : s.toCharArray())
addColorToColumn(Integer.parseInt(c+""));
}
private void init(){
columnRows=new Column[columns];
for (int i = 0; i < columns; i++)
columnRows[i] = new Column(rows,winCount);
}
public int addColorToColumn(int column) throws BlackWonException, IllegalAddToColumnException, RedWonException {
return addColorToColumn(colorTurn,column);
}
public int addColorToColumn(int color, int column) throws BlackWonException, IllegalAddToColumnException, RedWonException {
// this handles up and down or vertically
moves.add(column);
int c = -1, colorCountHor = 0, colorCountNegDiag = 0, colorCountPosDiag = 0;
try {
c = columnRows[column].addColor(color);
} catch (BlackWonException e){
throw new BlackWonException(String.format("Column: %s", column));
} catch (RedWonException e){
throw new RedWonException(String.format("Column: %s", column));
}
for (int i = column - winCount < 0 ? 0 : column - winCount;
i < (column + winCount > columnRows.length ? columnRows.length : column + winCount); i++) {
int sD = i-column+c, sU = -i+column+c;
// check left and right or horizontally
if(columnRows[i].column[c]==color)
colorCountHor++;
else colorCountHor=0;
// finally check diagonally negative (or check left up right down) and positive (or left down right up) diagonals
// negative diagonal
if(sD >=0 && sD < rows && columnRows[i].column[sD]==color)
colorCountNegDiag++;
else colorCountNegDiag=0;
// positive diagonal
if(sU >=0 && sU < rows && columnRows[i].column[sU]==color)
colorCountPosDiag++;
else colorCountPosDiag=0;
if(colorCountHor>=winCount || colorCountNegDiag>=winCount || colorCountPosDiag>=winCount)
if(color==1)
throw new RedWonException(String.format("%s: %s, col: %s, neg diag: %s, pos diag: %s, hor: %s", "row", c, column, colorCountNegDiag, colorCountPosDiag, colorCountHor));
else throw new BlackWonException(String.format("%s: %s, col: %s, neg diag: %s, pos diag: %s, hor: %s", "row", c, column, colorCountNegDiag, colorCountPosDiag, colorCountHor));
}
colorTurn=colorTurn==1?2:1;
return c;
}
public void removeColorFromColumn(int column){
columnRows[column].pop();
colorTurn=colorTurn==1?2:1;
}
@Override
public String toString() {
return getStringRepresentation();
}
private String getStringRepresentation() {
StringBuilder[] builders = new StringBuilder[columns];
for (int i = 0; i < columns; i++)
builders[i] = new StringBuilder();
for(Column c : columnRows)
for (int i = 0; i < c.column.length; i++)
builders[i].append(String.format("|%s", c.column[i]==1?"R":c.column[i]==2?"b":"-"));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < columns; i++)
builder.append(builders[columns-i-1].toString()+"|\n");
return builder.toString();
}
public boolean hasMovesLeft(){
for(Column c : columnRows)
if(c.canHaveMorePieces())
return true;
return false;
}
/**
* Positive means Red is closer to winning, negative means black is closer to winning
* high value to 3 in a row with unblocked 4th, lower to 2 in a row with unblocked 3 and 4
* and since only one move per turn zero for single pieces,
* count disjoint sets as well x xx is still 3 in a row if not blocked, x x is still two in a row ect
*
* TODO check if next turn win if opponent doesn't block xx x vs xx x/nyy y
* TODO don't add to heuristic if you can't make that move yet
*
* TODO don't loop over everything, just remaining moves, simulate each remaining move and victory is Double.MAX_VALUE maybe simulate opponent move too...
* @return
*/
public int getHeuristic(){
int heuristic = 0;
// loop over all columns, and subsequently all available moves. Add the move, check the value, then remove the move
for (int column = 0; column < columnRows.length; column++) {
try{
int row = addColorToColumn(column), colorCountHor = 0, colorCountNegDiag = 0, colorCountPosDiag = 0;
// since we made it here, this color hasn't won by that move, so check for
for (int i = column - winCount < 0 ? 0 : column - winCount;
i < (column + winCount > columnRows.length ? columnRows.length : column + winCount) - 1; i++) {
int sD = i - column + row, sU = -i + column + row;
// check left and right or horizontally
if (columnRows[i].column[row] == colorTurn || columnRows[i].column[row] == EMPTY)
colorCountHor++;
else colorCountHor = 0;
// finally check diagonally negative (or check left up right down) and positive (or left down right up) diagonals
// negative diagonal
if (sD >= 0 && sD < rows && (columnRows[i].column[sD] == colorTurn || columnRows[i].column[sD] == EMPTY))
colorCountNegDiag++;
else colorCountNegDiag = 0;
// positive diagonal
if (sU >= 0 && sU < rows && (columnRows[i].column[sU] == colorTurn || columnRows[i].column[sU] == EMPTY))
colorCountPosDiag++;
else colorCountPosDiag = 0;
}
heuristic+=colorCountHor+colorCountNegDiag+colorCountPosDiag;
}catch (RedWonException | BlackWonException e){
return Integer.MAX_VALUE;
} catch (IllegalAddToColumnException e) {
/* DO NOTHING */
continue;
}
removeColorFromColumn(column);
}
return heuristic;
}
@Override public ConnectN clone(){
Column[] cr = new Column[columnRows.length];
for (int i = 0; i < columnRows.length; i++)
cr[i]=columnRows[i].clone();
return new ConnectN(cr, winCount, rows, columns, colorTurn);
}
}
| unsupo/connectN | src/main/java/ConnectN.java | 3,297 | // else maxDepth = 6; | line_comment | nl | import exceptions.BlackWonException;
import exceptions.IllegalAddToColumnException;
import exceptions.RedWonException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
/**
* This class will create the Connect N object
* This is based on Connect 4, but this should
* be able to handle arbitrary sizes and rules
*/
public class ConnectN {
public static void main(String[] args) throws BlackWonException, IllegalAddToColumnException, RedWonException, InterruptedException {
/*
|-|-|R|-|-|-|-|
|-|-|b|-|-|-|-|
|-|-|b|-|-|R|-|
|-|R|b|R|b|b|-|
|R|R|R|b|R|b|R|
|b|b|b|R|R|b|R|
30616205231212422545543-2147483647
*/
// System.out.println(ConnectNSolver.minimax(new ConnectN("20211533130562641")));
// System.out.println(ConnectNSolver.minimax(new ConnectN("30216526011666332")));
// ConnectN c = new ConnectN("32210010160");
// System.out.println(c);
// System.out.println(c);
// System.out.println(ConnectNSolver.minimax(c));
// System.out.println(c.getHeuristic());
// playVsComputer();
// ConnectN c = new ConnectN();
// System.out.println(ConnectNSolver.minimax(c));
// randomPlay();
// ConnectN c = new ConnectN("0535440512505610115016031463343344");
//// ConnectN c = new ConnectN("010100");
// System.out.println(c);
// System.out.println(c.getHeuristic());
// try {
// c.addColorToColumn(5);
//// for(char cc : "06023616623160316444241365122065".toCharArray())
//// c.addColorToColumn(Integer.parseInt(cc+""));
// }catch (Exception e){
// e.printStackTrace();
// }
// ConnectN c = new ConnectN();
// System.out.println(c);
// int maxDepth = 7;
// while (true){
// if(c.colorTurn==RED)
// maxDepth = 4;
// else maxDepth<SUF>
// c.addColorToColumn(new ConnectNSolver(maxDepth).minimax(c));
// System.out.println(c);
// }
playVsComputer();
}
public static void randomPlay(){
List<Integer> moves = new ArrayList<>();
ConnectN c = new ConnectN();
try {
Random r = new Random();
System.out.println(c);
while (true) {
try {
int m = r.nextInt(c.columns);
c.addColorToColumn(m);
moves.add(m);
System.out.println(c);
}catch (IllegalAddToColumnException e){
continue;
}
}
}catch (Exception e){
e.printStackTrace();
System.out.println(c);
moves.forEach(System.out::print);
}
}
public static void playTwoOnTwo() throws BlackWonException, IllegalAddToColumnException, RedWonException {
ConnectN c = new ConnectN();
Scanner s = new Scanner(System.in);
System.out.println(c);
while (true) {
c.addColorToColumn(s.nextInt());
System.out.println(c);
}
}
public static void playVsComputer() throws BlackWonException, IllegalAddToColumnException, RedWonException {
ConnectN c = new ConnectN();
ConnectNSolver solver = new ConnectNSolver();
Scanner s = new Scanner(System.in);
System.out.println(c);
while (true) {
try {
if(c.colorTurn==RED)
c.addColorToColumn(s.nextInt());
else
c.addColorToColumn(solver.minimax(c));
}catch (Exception e){
c.moves.forEach(System.out::print);
throw e;
}
System.out.println(c);
}
}
List<Integer> moves = new ArrayList<>();
public static final int BLACK = 2, RED = 1, EMPTY = 0;
Column[] columnRows;
int winCount = 4, rows = 6, columns = 7, colorTurn = 1;
public ConnectN(Column[] columnRows, int winCount, int rows, int columns, int colorTurn) {
this.columnRows = columnRows;
this.winCount = winCount;
this.rows = rows;
this.columns = columns;
this.colorTurn = colorTurn;
}
public ConnectN() {
init();
}
public ConnectN(int rows, int columns){
this.rows = rows;
this.columns = columns;
init();
}
public ConnectN(String s) throws BlackWonException, IllegalAddToColumnException, RedWonException {
this();
for(char c : s.toCharArray())
addColorToColumn(Integer.parseInt(c+""));
}
private void init(){
columnRows=new Column[columns];
for (int i = 0; i < columns; i++)
columnRows[i] = new Column(rows,winCount);
}
public int addColorToColumn(int column) throws BlackWonException, IllegalAddToColumnException, RedWonException {
return addColorToColumn(colorTurn,column);
}
public int addColorToColumn(int color, int column) throws BlackWonException, IllegalAddToColumnException, RedWonException {
// this handles up and down or vertically
moves.add(column);
int c = -1, colorCountHor = 0, colorCountNegDiag = 0, colorCountPosDiag = 0;
try {
c = columnRows[column].addColor(color);
} catch (BlackWonException e){
throw new BlackWonException(String.format("Column: %s", column));
} catch (RedWonException e){
throw new RedWonException(String.format("Column: %s", column));
}
for (int i = column - winCount < 0 ? 0 : column - winCount;
i < (column + winCount > columnRows.length ? columnRows.length : column + winCount); i++) {
int sD = i-column+c, sU = -i+column+c;
// check left and right or horizontally
if(columnRows[i].column[c]==color)
colorCountHor++;
else colorCountHor=0;
// finally check diagonally negative (or check left up right down) and positive (or left down right up) diagonals
// negative diagonal
if(sD >=0 && sD < rows && columnRows[i].column[sD]==color)
colorCountNegDiag++;
else colorCountNegDiag=0;
// positive diagonal
if(sU >=0 && sU < rows && columnRows[i].column[sU]==color)
colorCountPosDiag++;
else colorCountPosDiag=0;
if(colorCountHor>=winCount || colorCountNegDiag>=winCount || colorCountPosDiag>=winCount)
if(color==1)
throw new RedWonException(String.format("%s: %s, col: %s, neg diag: %s, pos diag: %s, hor: %s", "row", c, column, colorCountNegDiag, colorCountPosDiag, colorCountHor));
else throw new BlackWonException(String.format("%s: %s, col: %s, neg diag: %s, pos diag: %s, hor: %s", "row", c, column, colorCountNegDiag, colorCountPosDiag, colorCountHor));
}
colorTurn=colorTurn==1?2:1;
return c;
}
public void removeColorFromColumn(int column){
columnRows[column].pop();
colorTurn=colorTurn==1?2:1;
}
@Override
public String toString() {
return getStringRepresentation();
}
private String getStringRepresentation() {
StringBuilder[] builders = new StringBuilder[columns];
for (int i = 0; i < columns; i++)
builders[i] = new StringBuilder();
for(Column c : columnRows)
for (int i = 0; i < c.column.length; i++)
builders[i].append(String.format("|%s", c.column[i]==1?"R":c.column[i]==2?"b":"-"));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < columns; i++)
builder.append(builders[columns-i-1].toString()+"|\n");
return builder.toString();
}
public boolean hasMovesLeft(){
for(Column c : columnRows)
if(c.canHaveMorePieces())
return true;
return false;
}
/**
* Positive means Red is closer to winning, negative means black is closer to winning
* high value to 3 in a row with unblocked 4th, lower to 2 in a row with unblocked 3 and 4
* and since only one move per turn zero for single pieces,
* count disjoint sets as well x xx is still 3 in a row if not blocked, x x is still two in a row ect
*
* TODO check if next turn win if opponent doesn't block xx x vs xx x/nyy y
* TODO don't add to heuristic if you can't make that move yet
*
* TODO don't loop over everything, just remaining moves, simulate each remaining move and victory is Double.MAX_VALUE maybe simulate opponent move too...
* @return
*/
public int getHeuristic(){
int heuristic = 0;
// loop over all columns, and subsequently all available moves. Add the move, check the value, then remove the move
for (int column = 0; column < columnRows.length; column++) {
try{
int row = addColorToColumn(column), colorCountHor = 0, colorCountNegDiag = 0, colorCountPosDiag = 0;
// since we made it here, this color hasn't won by that move, so check for
for (int i = column - winCount < 0 ? 0 : column - winCount;
i < (column + winCount > columnRows.length ? columnRows.length : column + winCount) - 1; i++) {
int sD = i - column + row, sU = -i + column + row;
// check left and right or horizontally
if (columnRows[i].column[row] == colorTurn || columnRows[i].column[row] == EMPTY)
colorCountHor++;
else colorCountHor = 0;
// finally check diagonally negative (or check left up right down) and positive (or left down right up) diagonals
// negative diagonal
if (sD >= 0 && sD < rows && (columnRows[i].column[sD] == colorTurn || columnRows[i].column[sD] == EMPTY))
colorCountNegDiag++;
else colorCountNegDiag = 0;
// positive diagonal
if (sU >= 0 && sU < rows && (columnRows[i].column[sU] == colorTurn || columnRows[i].column[sU] == EMPTY))
colorCountPosDiag++;
else colorCountPosDiag = 0;
}
heuristic+=colorCountHor+colorCountNegDiag+colorCountPosDiag;
}catch (RedWonException | BlackWonException e){
return Integer.MAX_VALUE;
} catch (IllegalAddToColumnException e) {
/* DO NOTHING */
continue;
}
removeColorFromColumn(column);
}
return heuristic;
}
@Override public ConnectN clone(){
Column[] cr = new Column[columnRows.length];
for (int i = 0; i < columnRows.length; i++)
cr[i]=columnRows[i].clone();
return new ConnectN(cr, winCount, rows, columns, colorTurn);
}
}
|
155216_1 | package project_Java;
import javafx.event.EventHandler;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.*;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import sun.rmi.runtime.Log;
import java.awt.*;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
public class Controller implements Initializable {
public ImageView rope;
public AnchorPane backrope;
public static AnchorPane back;
private double xOffset, yOffset, BEFORE, AFTER;
private static Stage stage;
private boolean isRunning;
static class Loog {
static void e(String str1, String str2) {
System.err.println(str1 + " " + str2);
}
}
public static void blink(StackPane root) {
new Thread(() -> {
while (true) {
root.setStyle("-fx-background-color:#f03232");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
root.setStyle("-fx-background-color:purple");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
root.setStyle("-fx-background-color:green");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void rotation(ImageView imageView) {
new Thread(() -> {
for (int i = 0; ; i += 90) {
imageView.setRotate(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}).start();
}
public static void crowdEffect(ImageView imageView) {
new Thread(() -> {
while (true) {
for (int i = 0; i < 90; i++) {
imageView.setTranslateY(i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
for (int j = 90; j > 0; j--) {
imageView.setTranslateY(-j);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
}).start();
}
class Player {
ImageView rope;
Player(ImageView rope) {
this.rope = rope;
}
void play(int value) {
Loog.e("Media", "실행됨");
rope.setVisible(false);
Dimension res = Toolkit.getDefaultToolkit().getScreenSize();
Stage stage = new Stage();
StackPane root = new StackPane();
StackPane back = new StackPane();
Scene scene = new Scene(root, javafx.scene.paint.Color.TRANSPARENT);
ArrayList<Image> images = new ArrayList<>();
ArrayList<ImageView> imageView = new ArrayList<>();
String path;
Media media;
MediaPlayer mp;
int imageCount = 6;
switch (value) {
case 1:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 2:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 3:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 4:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 5:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 6:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
default:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
}
for (int i = 0; i < imageCount; i++)
imageView.add(new ImageView(images.get(i)));
switch (value) {
case 0:
path = "project_Java/source/bgm1.mp3";
case 1:
path = "project_Java/source/bgm1.mp3";
break;
case 2:
path = "project_Java/source/bgm1.mp3";
break;
case 3:
path = "project_Java/source/bgm1.mp3";
break;
case 4:
path = "project_Java/source/bgm1.mp3";
break;
case 5:
path = "project_Java/source/bgm1.mp3";
break;
default:
path = "project_Java/source/bgm1.mp3";
}
media = (new Media(new File(path).toURI().toString()));
mp = (new MediaPlayer(media));
for (int i = 0; i < imageCount; i++)
root.getChildren().add(imageView.get(i));
stage.setFullScreenExitKeyCombination(new KeyCombination() {
@Override
public boolean match(KeyEvent event) {
return false;
}
});
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
stage.hide();
mp.stop();
rope.setVisible(true);
back.setTranslateY(-80);
isRunning = false;
}
});
for (int i = 0; i < imageCount; i++) {
imageView.get(i).setPreserveRatio(true);
}
imageView.get(3).setStyle("-fx-background-color:transparent");
imageView.get(3).setFitWidth(res.getWidth());
imageView.get(3).setTranslateY(-900);
imageView.get(0).setStyle("-fx-background-color:transparent");
imageView.get(0).setFitHeight(500);
imageView.get(0).setTranslateX(-450);
imageView.get(0).setTranslateY(200);
back.setPrefSize(res.getWidth(), res.getHeight());
back.setOpacity(0.5f);
root.setMaxSize(res.getWidth(), res.getHeight());
root.setStyle("-fx-background-color:transparent");
root.getChildren().add(0, back);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setWidth(res.width);
stage.setHeight(res.height);
stage.setScene(scene);
stage.setAlwaysOnTop(true);
crowdEffect(imageView.get(3));
blink(back);
mp.play();
stage.show();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
Image img = new Image("project_Java/img/rope.png");
rope.setImage(img);
rope.setTranslateY(-80);
back = backrope;
rope.setOnMouseDragged(event -> {
double x;
double y;
x = event.getScreenX();
y = event.getScreenY();
Loog.e("Log :", x + " " + y);
// stage.setX(x + xOffset);
stage.setY(y + yOffset);
AFTER = y;
if (!isRunning) {
if (AFTER - BEFORE > 300) {
Player mPlayer = new Player(rope);
mPlayer.play(0);
isRunning=true;
}
}
});
rope.setOnMousePressed(event -> {
stage = (Stage) rope.getScene().getWindow();
// xOffset = stage.getX() - event.getScreenX();
yOffset = stage.getY() - event.getScreenY();
BEFORE = event.getScreenY();
});
rope.setOnMouseReleased(event -> {
stage.setX(0);
stage.setY(-550);
back.setTranslateY(-80);
});
rope.setOnMouseEntered(event -> {
});
rope.setOnMouseExited(event -> {
});
}
}
| uowol/Project_Party | Project_java/Controller.java | 3,278 | // xOffset = stage.getX() - event.getScreenX(); | line_comment | nl | package project_Java;
import javafx.event.EventHandler;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.*;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import sun.rmi.runtime.Log;
import java.awt.*;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
public class Controller implements Initializable {
public ImageView rope;
public AnchorPane backrope;
public static AnchorPane back;
private double xOffset, yOffset, BEFORE, AFTER;
private static Stage stage;
private boolean isRunning;
static class Loog {
static void e(String str1, String str2) {
System.err.println(str1 + " " + str2);
}
}
public static void blink(StackPane root) {
new Thread(() -> {
while (true) {
root.setStyle("-fx-background-color:#f03232");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
root.setStyle("-fx-background-color:purple");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
root.setStyle("-fx-background-color:green");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void rotation(ImageView imageView) {
new Thread(() -> {
for (int i = 0; ; i += 90) {
imageView.setRotate(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}).start();
}
public static void crowdEffect(ImageView imageView) {
new Thread(() -> {
while (true) {
for (int i = 0; i < 90; i++) {
imageView.setTranslateY(i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
for (int j = 90; j > 0; j--) {
imageView.setTranslateY(-j);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
}).start();
}
class Player {
ImageView rope;
Player(ImageView rope) {
this.rope = rope;
}
void play(int value) {
Loog.e("Media", "실행됨");
rope.setVisible(false);
Dimension res = Toolkit.getDefaultToolkit().getScreenSize();
Stage stage = new Stage();
StackPane root = new StackPane();
StackPane back = new StackPane();
Scene scene = new Scene(root, javafx.scene.paint.Color.TRANSPARENT);
ArrayList<Image> images = new ArrayList<>();
ArrayList<ImageView> imageView = new ArrayList<>();
String path;
Media media;
MediaPlayer mp;
int imageCount = 6;
switch (value) {
case 1:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 2:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 3:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 4:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 5:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
case 6:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
break;
default:
images.add(new Image("project_Java/source/shark.gif"));
images.add(new Image("project_Java/source/giphy.gif"));
images.add(new Image("project_Java/source/Garfield.gif"));
images.add(new Image("project_Java/source/crowd.png"));
images.add(new Image("project_Java/source/fishDancer.gif"));
images.add(new Image("project_Java/source/fishDancer.gif"));
}
for (int i = 0; i < imageCount; i++)
imageView.add(new ImageView(images.get(i)));
switch (value) {
case 0:
path = "project_Java/source/bgm1.mp3";
case 1:
path = "project_Java/source/bgm1.mp3";
break;
case 2:
path = "project_Java/source/bgm1.mp3";
break;
case 3:
path = "project_Java/source/bgm1.mp3";
break;
case 4:
path = "project_Java/source/bgm1.mp3";
break;
case 5:
path = "project_Java/source/bgm1.mp3";
break;
default:
path = "project_Java/source/bgm1.mp3";
}
media = (new Media(new File(path).toURI().toString()));
mp = (new MediaPlayer(media));
for (int i = 0; i < imageCount; i++)
root.getChildren().add(imageView.get(i));
stage.setFullScreenExitKeyCombination(new KeyCombination() {
@Override
public boolean match(KeyEvent event) {
return false;
}
});
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
stage.hide();
mp.stop();
rope.setVisible(true);
back.setTranslateY(-80);
isRunning = false;
}
});
for (int i = 0; i < imageCount; i++) {
imageView.get(i).setPreserveRatio(true);
}
imageView.get(3).setStyle("-fx-background-color:transparent");
imageView.get(3).setFitWidth(res.getWidth());
imageView.get(3).setTranslateY(-900);
imageView.get(0).setStyle("-fx-background-color:transparent");
imageView.get(0).setFitHeight(500);
imageView.get(0).setTranslateX(-450);
imageView.get(0).setTranslateY(200);
back.setPrefSize(res.getWidth(), res.getHeight());
back.setOpacity(0.5f);
root.setMaxSize(res.getWidth(), res.getHeight());
root.setStyle("-fx-background-color:transparent");
root.getChildren().add(0, back);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setWidth(res.width);
stage.setHeight(res.height);
stage.setScene(scene);
stage.setAlwaysOnTop(true);
crowdEffect(imageView.get(3));
blink(back);
mp.play();
stage.show();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
Image img = new Image("project_Java/img/rope.png");
rope.setImage(img);
rope.setTranslateY(-80);
back = backrope;
rope.setOnMouseDragged(event -> {
double x;
double y;
x = event.getScreenX();
y = event.getScreenY();
Loog.e("Log :", x + " " + y);
// stage.setX(x + xOffset);
stage.setY(y + yOffset);
AFTER = y;
if (!isRunning) {
if (AFTER - BEFORE > 300) {
Player mPlayer = new Player(rope);
mPlayer.play(0);
isRunning=true;
}
}
});
rope.setOnMousePressed(event -> {
stage = (Stage) rope.getScene().getWindow();
// xOffset =<SUF>
yOffset = stage.getY() - event.getScreenY();
BEFORE = event.getScreenY();
});
rope.setOnMouseReleased(event -> {
stage.setX(0);
stage.setY(-550);
back.setTranslateY(-80);
});
rope.setOnMouseEntered(event -> {
});
rope.setOnMouseExited(event -> {
});
}
}
|
24459_13 | package nl.uscki.appcki.android.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import de.greenrobot.event.EventBus;
import nl.uscki.appcki.android.R;
import nl.uscki.appcki.android.Utils;
import nl.uscki.appcki.android.api.Callback;
import nl.uscki.appcki.android.api.MediaAPI;
import nl.uscki.appcki.android.api.Services;
import nl.uscki.appcki.android.events.ContentLoadedEvent;
import nl.uscki.appcki.android.events.CurrentUserUpdateRequiredDirectiveEvent;
import nl.uscki.appcki.android.events.OpenFragmentEvent;
import nl.uscki.appcki.android.events.SwitchTabEvent;
import nl.uscki.appcki.android.events.UserLoggedInEvent;
import nl.uscki.appcki.android.fragments.AppInfoFragment;
import nl.uscki.appcki.android.fragments.LoginFragment;
import nl.uscki.appcki.android.fragments.agenda.AgendaDetailTabsFragment;
import nl.uscki.appcki.android.fragments.forum.ForumLandingFragment;
import nl.uscki.appcki.android.fragments.forum.ForumPostOverviewFragment;
import nl.uscki.appcki.android.fragments.home.HomeFragment;
import nl.uscki.appcki.android.fragments.home.HomeNewsTab;
import nl.uscki.appcki.android.fragments.media.MediaCaptionContestSharedFragment;
import nl.uscki.appcki.android.fragments.media.MediaCollectionFragment;
import nl.uscki.appcki.android.fragments.meeting.MeetingDetailTabsFragment;
import nl.uscki.appcki.android.fragments.meeting.MeetingOverviewFragment;
import nl.uscki.appcki.android.fragments.poll.PollOverviewFragment;
import nl.uscki.appcki.android.fragments.poll.PollResultFragment;
import nl.uscki.appcki.android.fragments.quotes.QuoteFragment;
import nl.uscki.appcki.android.fragments.search.SmoboSearch;
import nl.uscki.appcki.android.fragments.shop.StoreFragment;
import nl.uscki.appcki.android.fragments.shop.StoreSelectionFragment;
import nl.uscki.appcki.android.generated.organisation.CurrentUser;
import nl.uscki.appcki.android.helpers.ShopPreferenceHelper;
import nl.uscki.appcki.android.helpers.UserHelper;
import retrofit2.Response;
public class MainActivity extends BasicActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
public static final String ACTION_NEWS_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_NEWS_OVERVIEW";
public static final String ACTION_AGENDA_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_AGENDA_OVERVIEW";
public static final String ACTION_SHOUTBOX_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_SHOUTBOX_OVERVIEW";
public static final String ACTION_MEETING_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_MEETING_OVERVIEW";
public static final String ACTION_POLL_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_POLL_OVERVIEW";
public static final String ACTION_VIEW_STORE = "nl.uscki.appcki.android.actions.MainActivity.ACTION_VIEW_STORE";
public static final String ACTION_VIEW_COLLECTION = "nl.uscki.appcki.android.actions.MainActivity.ACTION_VIEW_COLLECTION";
public static final String ACTION_VIEW_FORUM_TOPIC = "nl.uscki.appcki.android.actions.MainActivity.ACTION_VIEW_FORUM_TOPIC";
public static final String ACTION_VIEW_NEWSITEM
= "nl.uscki.appcki.android.activities.action.ACTION_VIEW_NEWSITEM";
public static final String PARAM_NEWS_ID
= "nl.uscki.appcki.android.activities.param.PARAM_NEWS_ID";
public static final String PARAM_POLL_ID
= "nl.uscki.appcki.android.activities.param.PARAM_POLL_ID";
private int focusNewsId = -1;
private int focusTriesSoFar = 0;
private static boolean homeScreenExists = false;
Toolbar toolbar;
NavigationView navigationView;
DrawerLayout drawer;
TextView logout;
LoginFragment loginFragment = new LoginFragment();
public enum Screen {
LOGIN(-1),
NEWS(R.id.nav_news),
AGENDA(R.id.nav_agenda),
POLL_OVERVIEW(R.id.nav_poll),
ROEPHOEK(R.id.nav_roephoek),
AGENDA_DETAIL(R.id.nav_agenda),
MEETING_OVERVIEW(R.id.nav_meeting),
MEETING_PLANNER(R.id.nav_meeting),
MEETING_DETAIL(R.id.nav_meeting),
QUOTE_OVERVIEW(R.id.nav_quotes),
POLL_DETAIL(R.id.nav_poll),
POLL_ACTIVE(R.id.nav_poll),
SMOBO_SEARCH(R.id.nav_search),
STORE_SELECTION(R.id.nav_shop),
STORE_BUY(R.id.nav_shop),
MEDIA_COLLECTION_OVERVIEW(R.id.nav_media),
MEDIA_LANDING_PAGE(R.id.nav_media),
FORUM(R.id.nav_forum),
FORUM_LANDING_PAGE(R.id.nav_forum);
private int menuItemId;
Screen(int menuItemId) {
this.menuItemId = menuItemId;
}
public int getMenuItemId() {
return this.menuItemId;
}
}
public static Screen currentScreen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
navigationView = findViewById(R.id.nav_view);
drawer = findViewById(R.id.drawer_layout);
logout = findViewById(R.id.menu_logout);
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
if (!UserHelper.getInstance().isLoggedIn()) {
initLoggedOutUI();
} else {
initLoggedInUI();
logout.setClickable(true);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserHelper.getInstance().logout();
initLoggedOutUI();
currentScreen = Screen.LOGIN;
}
});
// Ensure a full user info object is loaded
UserHelper.getInstance().getCurrentUser(MainActivity.this);
// Get the intent, verify the action and get the query
handleIntention(getIntent());
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntention(intent);
}
private void handleIntention(Intent intent) {
if(intent != null) {
if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getStringExtra("item") != null) {
handleAgendaItemIntent(intent);
} else if(ACTION_VIEW_NEWSITEM.equals(intent.getAction())) {
handleNewsItemIntent(intent);
} else if (ACTION_NEWS_OVERVIEW.equals(intent.getAction())) {
openTab(HomeFragment.NEWS);
} else if (ACTION_AGENDA_OVERVIEW.equals(intent.getAction())) {
openTab(HomeFragment.AGENDA);
} else if (ACTION_SHOUTBOX_OVERVIEW.equals(intent.getAction())) {
openTab(HomeFragment.ROEPHOEK);
} else if (ACTION_MEETING_OVERVIEW.equals(intent.getAction())) {
openFragment(new MeetingOverviewFragment(), null, false);
currentScreen = Screen.MEETING_OVERVIEW;
} else if (ACTION_POLL_OVERVIEW.equals(intent.getAction())) {
openFragment(new PollOverviewFragment(), null, false);
} else if (ACTION_VIEW_STORE.equals(intent.getAction())) {
Bundle args = new Bundle();
args.putInt("id", intent.getIntExtra(StoreFragment.PARAM_STORE_ID, -1));
openFragment(new StoreFragment(), args, false);
} else if (ACTION_VIEW_COLLECTION.equals(intent.getAction())) {
openFragment(new MediaCollectionFragment(), intent.getExtras(), false);
} else if (ACTION_VIEW_FORUM_TOPIC.equals(intent.getAction())) {
openFragment(new ForumPostOverviewFragment(), intent.getExtras(), true);
} else {
openTab(HomeFragment.NEWS, false);
}
// TODO add forum from notification
}
}
private void handleAgendaItemIntent(Intent intent) {
Bundle args = new Bundle();
args.putString("item", getIntent().getStringExtra("item"));
openFragment(new AgendaDetailTabsFragment(), args, false);
}
private void handleNewsItemIntent(Intent intent) {
focusNewsId = intent.getIntExtra(PARAM_NEWS_ID, -1);
focusTriesSoFar = 0;
openTab(HomeFragment.NEWS, focusNewsId, false);
}
@Override
public void onLowMemory() {
Log.e("Main", "Low memory! onLow");
UserHelper.getInstance().save(); // save before the app gets removed from memory(?)
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
Log.e("Main", "Low memory! onTrim");
UserHelper.getInstance().save(); // save before the app gets removed from memory(?)
super.onTrimMemory(level);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
FragmentManager sfm = getSupportFragmentManager();
if(handleChildFragmentStack(sfm)) {
// Stop here, as a back action has been performed
return;
} else if (sfm.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry entry = sfm.getBackStackEntryAt(sfm.getBackStackEntryCount() - 1);
String name = entry.getBreadCrumbTitle() == null ? null : entry.getBreadCrumbTitle().toString();
getSupportFragmentManager().popBackStack();
currentScreen = Screen.valueOf(name);
} else {
super.onBackPressed();
}
changeDrawerMenuSelection();
}
}
private boolean handleChildFragmentStack(FragmentManager fm) {
Class currentFragmentClass = Utils.getClassForScreen(currentScreen);
if(currentFragmentClass == null) return false;
for(Fragment f : fm.getFragments()) {
if(f.getClass() == currentFragmentClass) {
FragmentManager cfm = f.getChildFragmentManager();
if(cfm.getBackStackEntryCount() > 0) {
cfm.popBackStack();
return true;
}
// Nothing to do here
return false;
} else {
if(handleChildFragmentStack(f.getChildFragmentManager()))
return true;
}
}
// No fragment found
return false;
}
public static void setHomescreenDestroyed() {
homeScreenExists = false;
}
public static void setHomeScreenExists() {
homeScreenExists = true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.clear();
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
} else if (id == R.id.action_about) {
openFragment(new AppInfoFragment(), null, true);
} else if (id == R.id.action_poll_archive) {
openFragment(new PollOverviewFragment(), null, true);
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (UserHelper.getInstance().isLoggedIn()) {
if (id == R.id.nav_news) {
openTab(HomeFragment.NEWS);
} else if (id == R.id.nav_agenda) {
openTab(HomeFragment.AGENDA);
} else if (id == R.id.nav_shop) {
ShopPreferenceHelper shopPreferenceHelper = new ShopPreferenceHelper(this);
if(shopPreferenceHelper.getShop() < 0) {
openFragment(new StoreSelectionFragment(), null, true);
} else {
Bundle bundle = new Bundle();
bundle.putInt("id", shopPreferenceHelper.getShop());
openFragment(new StoreFragment(), bundle, true);
}
} else if (id == R.id.nav_quotes) {
openFragment(new QuoteFragment(), null, true);
} else if (id == R.id.nav_poll) {
openFragment(new PollResultFragment(), null, true);
} else if (id == R.id.nav_roephoek) {
openTab(HomeFragment.ROEPHOEK);
} else if (id == R.id.nav_meeting) {
openFragment(new MeetingOverviewFragment(), null, true);
currentScreen = Screen.MEETING_OVERVIEW;
} else if (id == R.id.nav_search) {
openFragment(new SmoboSearch(), null, true);
currentScreen = Screen.SMOBO_SEARCH;
} else if (id == R.id.nav_media) {
openFragment(new MediaCaptionContestSharedFragment(), null, true);
currentScreen = Screen.MEDIA_LANDING_PAGE;
} else if (id == R.id.nav_forum) {
openFragment(new ForumLandingFragment(), null, true);
currentScreen = Screen.FORUM_LANDING_PAGE;
}
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void openTab(int index) {
openTab(index, -1, true);
}
private void openTab(int index, boolean addToBackStack) {
openTab(index, -1, addToBackStack);
}
private void openTab(int index, int scrollToId, boolean addToBackStack) {
if (
homeScreenExists &&
(currentScreen == Screen.ROEPHOEK ||
currentScreen == Screen.NEWS ||
currentScreen == Screen.AGENDA
)
) {
// HomeFragment luistert naar dit event om daarin de tab te switchen
EventBus.getDefault().post(new SwitchTabEvent(index, scrollToId));
} else {
Bundle bundle = new Bundle();
bundle.putInt("index", index);
openFragment(new HomeFragment(), bundle, addToBackStack);
homeScreenExists = true;
}
setMenuToTab(index);
}
private void setMenuToTab(int homeFragmentTabIndex) {
changeDrawerMenuSelection();
}
public void changeDrawerMenuSelection(int menuItemId) {
Menu navMenu = navigationView.getMenu();
for(int i = 0; i < navMenu.size(); i++) {
if(navMenu.getItem(i).getItemId() == menuItemId) {
navMenu.getItem(i).setChecked(true);
return;
}
}
}
public void changeDrawerMenuSelection() {
if(currentScreen != null)
changeDrawerMenuSelection(currentScreen.getMenuItemId());
}
private void openFragment(Fragment fragment, Bundle arguments, boolean addToBackStack) {
if (fragment instanceof LoginFragment) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else {
// TODO: 5/28/16 currently keyboard overlaps in agenda detail, but this needs a new
// TODO implementation. Check if it's still the case with the new one
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
if (arguments != null) {
fragment.setArguments(arguments);
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment);
if(addToBackStack && currentScreen != null) {
transaction.addToBackStack(null)
.setBreadCrumbTitle(currentScreen.name());
}
transaction.commit();
changeDrawerMenuSelection();
}
private void initLoggedInUI() {
toolbar.setVisibility(View.VISIBLE);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
hideKeyboard(findViewById(R.id.drawer_layout));
logout.setVisibility(View.VISIBLE);
CurrentUser user = UserHelper.getInstance().getCurrentUser();
if(user != null) {
setUserDependentFeatures(user);
} else {
Services.getInstance().userService.currentUser().enqueue(new Callback<CurrentUser>() {
@Override
public void onSucces(Response<CurrentUser> response) {
UserHelper.getInstance().setCurrentUser(response.body());
setUserDependentFeatures(response.body());
}
});
}
}
private void setUserDependentFeatures(final CurrentUser user) {
TextView name = navigationView.getHeaderView(0).findViewById(R.id.nav_header_name);
name.setText(user.getPostalname());
final ImageView profile = navigationView.getHeaderView(0).findViewById(R.id.nav_header_profilepic);
profile.setOnClickListener(v -> {
openSmoboFor(user);
EventBus.getDefault().post(new CurrentUserUpdateRequiredDirectiveEvent());
});
if (user.getPhotomediaid() != null) {
Glide.with(this)
.load(MediaAPI.getMediaUri(user.getPhotomediaid(), MediaAPI.MediaSize.SMALL))
.fitCenter()
.optionalCircleCrop()
.placeholder(R.drawable.account)
.into(profile);
}
}
private void initLoggedOutUI() {
toolbar.setVisibility(View.GONE);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
openFragment(new LoginFragment(), null, false);
currentScreen = Screen.LOGIN;
logout.setVisibility(View.GONE);
TextView name = navigationView.getHeaderView(0).findViewById(R.id.nav_header_name);
name.setText("");
ImageView profile = navigationView.getHeaderView(0).findViewById(R.id.nav_header_profilepic);
profile.setImageResource(R.drawable.account);
}
public void resizeOnKeyboard() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
public static void hideKeyboard(View someView) {
InputMethodManager imm = (InputMethodManager) someView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null)
imm.hideSoftInputFromWindow(someView.getWindowToken(), 0);
}
// EVENT HANDLING
public void onEventMainThread(UserLoggedInEvent event) {
if (event.loggedIn) {
initLoggedInUI();
openTab(HomeFragment.NEWS);
} else {
initLoggedOutUI();
}
}
public void onEventMainThread(OpenFragmentEvent event) {
//TODO refactor this
if(event.screen instanceof AgendaDetailTabsFragment) {
Intent agenda = new Intent(this, AgendaActivity.class);
agenda.putExtras(event.arguments);
startActivity(agenda);
return;
} else if(event.screen instanceof MeetingDetailTabsFragment) {
Intent meeting = new Intent(this, MeetingActivity.class);
meeting.putExtras(event.arguments);
startActivity(meeting);
return;
}
openFragment(event.screen, event.arguments, true);
}
public void onEventMainThread(ContentLoadedEvent event) {
if (focusNewsId > 0 && event.updatedPageableFragment instanceof HomeNewsTab) {
if (((HomeNewsTab) event.updatedPageableFragment)
.scrollToItemWithId(focusNewsId, focusTriesSoFar >= 3) ||
focusTriesSoFar >= 3) {
focusNewsId = -1;
}
focusTriesSoFar++;
}
}
public void onEventMainThread(SwitchTabEvent event) {
setMenuToTab(event.index);
}
}
| uscki/Wilson-Android | app/src/main/java/nl/uscki/appcki/android/activities/MainActivity.java | 6,407 | // HomeFragment luistert naar dit event om daarin de tab te switchen | line_comment | nl | package nl.uscki.appcki.android.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import de.greenrobot.event.EventBus;
import nl.uscki.appcki.android.R;
import nl.uscki.appcki.android.Utils;
import nl.uscki.appcki.android.api.Callback;
import nl.uscki.appcki.android.api.MediaAPI;
import nl.uscki.appcki.android.api.Services;
import nl.uscki.appcki.android.events.ContentLoadedEvent;
import nl.uscki.appcki.android.events.CurrentUserUpdateRequiredDirectiveEvent;
import nl.uscki.appcki.android.events.OpenFragmentEvent;
import nl.uscki.appcki.android.events.SwitchTabEvent;
import nl.uscki.appcki.android.events.UserLoggedInEvent;
import nl.uscki.appcki.android.fragments.AppInfoFragment;
import nl.uscki.appcki.android.fragments.LoginFragment;
import nl.uscki.appcki.android.fragments.agenda.AgendaDetailTabsFragment;
import nl.uscki.appcki.android.fragments.forum.ForumLandingFragment;
import nl.uscki.appcki.android.fragments.forum.ForumPostOverviewFragment;
import nl.uscki.appcki.android.fragments.home.HomeFragment;
import nl.uscki.appcki.android.fragments.home.HomeNewsTab;
import nl.uscki.appcki.android.fragments.media.MediaCaptionContestSharedFragment;
import nl.uscki.appcki.android.fragments.media.MediaCollectionFragment;
import nl.uscki.appcki.android.fragments.meeting.MeetingDetailTabsFragment;
import nl.uscki.appcki.android.fragments.meeting.MeetingOverviewFragment;
import nl.uscki.appcki.android.fragments.poll.PollOverviewFragment;
import nl.uscki.appcki.android.fragments.poll.PollResultFragment;
import nl.uscki.appcki.android.fragments.quotes.QuoteFragment;
import nl.uscki.appcki.android.fragments.search.SmoboSearch;
import nl.uscki.appcki.android.fragments.shop.StoreFragment;
import nl.uscki.appcki.android.fragments.shop.StoreSelectionFragment;
import nl.uscki.appcki.android.generated.organisation.CurrentUser;
import nl.uscki.appcki.android.helpers.ShopPreferenceHelper;
import nl.uscki.appcki.android.helpers.UserHelper;
import retrofit2.Response;
public class MainActivity extends BasicActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
public static final String ACTION_NEWS_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_NEWS_OVERVIEW";
public static final String ACTION_AGENDA_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_AGENDA_OVERVIEW";
public static final String ACTION_SHOUTBOX_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_SHOUTBOX_OVERVIEW";
public static final String ACTION_MEETING_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_MEETING_OVERVIEW";
public static final String ACTION_POLL_OVERVIEW = "nl.uscki.appcki.android.actions.MainActivity.ACTION_POLL_OVERVIEW";
public static final String ACTION_VIEW_STORE = "nl.uscki.appcki.android.actions.MainActivity.ACTION_VIEW_STORE";
public static final String ACTION_VIEW_COLLECTION = "nl.uscki.appcki.android.actions.MainActivity.ACTION_VIEW_COLLECTION";
public static final String ACTION_VIEW_FORUM_TOPIC = "nl.uscki.appcki.android.actions.MainActivity.ACTION_VIEW_FORUM_TOPIC";
public static final String ACTION_VIEW_NEWSITEM
= "nl.uscki.appcki.android.activities.action.ACTION_VIEW_NEWSITEM";
public static final String PARAM_NEWS_ID
= "nl.uscki.appcki.android.activities.param.PARAM_NEWS_ID";
public static final String PARAM_POLL_ID
= "nl.uscki.appcki.android.activities.param.PARAM_POLL_ID";
private int focusNewsId = -1;
private int focusTriesSoFar = 0;
private static boolean homeScreenExists = false;
Toolbar toolbar;
NavigationView navigationView;
DrawerLayout drawer;
TextView logout;
LoginFragment loginFragment = new LoginFragment();
public enum Screen {
LOGIN(-1),
NEWS(R.id.nav_news),
AGENDA(R.id.nav_agenda),
POLL_OVERVIEW(R.id.nav_poll),
ROEPHOEK(R.id.nav_roephoek),
AGENDA_DETAIL(R.id.nav_agenda),
MEETING_OVERVIEW(R.id.nav_meeting),
MEETING_PLANNER(R.id.nav_meeting),
MEETING_DETAIL(R.id.nav_meeting),
QUOTE_OVERVIEW(R.id.nav_quotes),
POLL_DETAIL(R.id.nav_poll),
POLL_ACTIVE(R.id.nav_poll),
SMOBO_SEARCH(R.id.nav_search),
STORE_SELECTION(R.id.nav_shop),
STORE_BUY(R.id.nav_shop),
MEDIA_COLLECTION_OVERVIEW(R.id.nav_media),
MEDIA_LANDING_PAGE(R.id.nav_media),
FORUM(R.id.nav_forum),
FORUM_LANDING_PAGE(R.id.nav_forum);
private int menuItemId;
Screen(int menuItemId) {
this.menuItemId = menuItemId;
}
public int getMenuItemId() {
return this.menuItemId;
}
}
public static Screen currentScreen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
navigationView = findViewById(R.id.nav_view);
drawer = findViewById(R.id.drawer_layout);
logout = findViewById(R.id.menu_logout);
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
if (!UserHelper.getInstance().isLoggedIn()) {
initLoggedOutUI();
} else {
initLoggedInUI();
logout.setClickable(true);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserHelper.getInstance().logout();
initLoggedOutUI();
currentScreen = Screen.LOGIN;
}
});
// Ensure a full user info object is loaded
UserHelper.getInstance().getCurrentUser(MainActivity.this);
// Get the intent, verify the action and get the query
handleIntention(getIntent());
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntention(intent);
}
private void handleIntention(Intent intent) {
if(intent != null) {
if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getStringExtra("item") != null) {
handleAgendaItemIntent(intent);
} else if(ACTION_VIEW_NEWSITEM.equals(intent.getAction())) {
handleNewsItemIntent(intent);
} else if (ACTION_NEWS_OVERVIEW.equals(intent.getAction())) {
openTab(HomeFragment.NEWS);
} else if (ACTION_AGENDA_OVERVIEW.equals(intent.getAction())) {
openTab(HomeFragment.AGENDA);
} else if (ACTION_SHOUTBOX_OVERVIEW.equals(intent.getAction())) {
openTab(HomeFragment.ROEPHOEK);
} else if (ACTION_MEETING_OVERVIEW.equals(intent.getAction())) {
openFragment(new MeetingOverviewFragment(), null, false);
currentScreen = Screen.MEETING_OVERVIEW;
} else if (ACTION_POLL_OVERVIEW.equals(intent.getAction())) {
openFragment(new PollOverviewFragment(), null, false);
} else if (ACTION_VIEW_STORE.equals(intent.getAction())) {
Bundle args = new Bundle();
args.putInt("id", intent.getIntExtra(StoreFragment.PARAM_STORE_ID, -1));
openFragment(new StoreFragment(), args, false);
} else if (ACTION_VIEW_COLLECTION.equals(intent.getAction())) {
openFragment(new MediaCollectionFragment(), intent.getExtras(), false);
} else if (ACTION_VIEW_FORUM_TOPIC.equals(intent.getAction())) {
openFragment(new ForumPostOverviewFragment(), intent.getExtras(), true);
} else {
openTab(HomeFragment.NEWS, false);
}
// TODO add forum from notification
}
}
private void handleAgendaItemIntent(Intent intent) {
Bundle args = new Bundle();
args.putString("item", getIntent().getStringExtra("item"));
openFragment(new AgendaDetailTabsFragment(), args, false);
}
private void handleNewsItemIntent(Intent intent) {
focusNewsId = intent.getIntExtra(PARAM_NEWS_ID, -1);
focusTriesSoFar = 0;
openTab(HomeFragment.NEWS, focusNewsId, false);
}
@Override
public void onLowMemory() {
Log.e("Main", "Low memory! onLow");
UserHelper.getInstance().save(); // save before the app gets removed from memory(?)
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
Log.e("Main", "Low memory! onTrim");
UserHelper.getInstance().save(); // save before the app gets removed from memory(?)
super.onTrimMemory(level);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
FragmentManager sfm = getSupportFragmentManager();
if(handleChildFragmentStack(sfm)) {
// Stop here, as a back action has been performed
return;
} else if (sfm.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry entry = sfm.getBackStackEntryAt(sfm.getBackStackEntryCount() - 1);
String name = entry.getBreadCrumbTitle() == null ? null : entry.getBreadCrumbTitle().toString();
getSupportFragmentManager().popBackStack();
currentScreen = Screen.valueOf(name);
} else {
super.onBackPressed();
}
changeDrawerMenuSelection();
}
}
private boolean handleChildFragmentStack(FragmentManager fm) {
Class currentFragmentClass = Utils.getClassForScreen(currentScreen);
if(currentFragmentClass == null) return false;
for(Fragment f : fm.getFragments()) {
if(f.getClass() == currentFragmentClass) {
FragmentManager cfm = f.getChildFragmentManager();
if(cfm.getBackStackEntryCount() > 0) {
cfm.popBackStack();
return true;
}
// Nothing to do here
return false;
} else {
if(handleChildFragmentStack(f.getChildFragmentManager()))
return true;
}
}
// No fragment found
return false;
}
public static void setHomescreenDestroyed() {
homeScreenExists = false;
}
public static void setHomeScreenExists() {
homeScreenExists = true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.clear();
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
} else if (id == R.id.action_about) {
openFragment(new AppInfoFragment(), null, true);
} else if (id == R.id.action_poll_archive) {
openFragment(new PollOverviewFragment(), null, true);
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (UserHelper.getInstance().isLoggedIn()) {
if (id == R.id.nav_news) {
openTab(HomeFragment.NEWS);
} else if (id == R.id.nav_agenda) {
openTab(HomeFragment.AGENDA);
} else if (id == R.id.nav_shop) {
ShopPreferenceHelper shopPreferenceHelper = new ShopPreferenceHelper(this);
if(shopPreferenceHelper.getShop() < 0) {
openFragment(new StoreSelectionFragment(), null, true);
} else {
Bundle bundle = new Bundle();
bundle.putInt("id", shopPreferenceHelper.getShop());
openFragment(new StoreFragment(), bundle, true);
}
} else if (id == R.id.nav_quotes) {
openFragment(new QuoteFragment(), null, true);
} else if (id == R.id.nav_poll) {
openFragment(new PollResultFragment(), null, true);
} else if (id == R.id.nav_roephoek) {
openTab(HomeFragment.ROEPHOEK);
} else if (id == R.id.nav_meeting) {
openFragment(new MeetingOverviewFragment(), null, true);
currentScreen = Screen.MEETING_OVERVIEW;
} else if (id == R.id.nav_search) {
openFragment(new SmoboSearch(), null, true);
currentScreen = Screen.SMOBO_SEARCH;
} else if (id == R.id.nav_media) {
openFragment(new MediaCaptionContestSharedFragment(), null, true);
currentScreen = Screen.MEDIA_LANDING_PAGE;
} else if (id == R.id.nav_forum) {
openFragment(new ForumLandingFragment(), null, true);
currentScreen = Screen.FORUM_LANDING_PAGE;
}
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void openTab(int index) {
openTab(index, -1, true);
}
private void openTab(int index, boolean addToBackStack) {
openTab(index, -1, addToBackStack);
}
private void openTab(int index, int scrollToId, boolean addToBackStack) {
if (
homeScreenExists &&
(currentScreen == Screen.ROEPHOEK ||
currentScreen == Screen.NEWS ||
currentScreen == Screen.AGENDA
)
) {
// HomeFragment luistert<SUF>
EventBus.getDefault().post(new SwitchTabEvent(index, scrollToId));
} else {
Bundle bundle = new Bundle();
bundle.putInt("index", index);
openFragment(new HomeFragment(), bundle, addToBackStack);
homeScreenExists = true;
}
setMenuToTab(index);
}
private void setMenuToTab(int homeFragmentTabIndex) {
changeDrawerMenuSelection();
}
public void changeDrawerMenuSelection(int menuItemId) {
Menu navMenu = navigationView.getMenu();
for(int i = 0; i < navMenu.size(); i++) {
if(navMenu.getItem(i).getItemId() == menuItemId) {
navMenu.getItem(i).setChecked(true);
return;
}
}
}
public void changeDrawerMenuSelection() {
if(currentScreen != null)
changeDrawerMenuSelection(currentScreen.getMenuItemId());
}
private void openFragment(Fragment fragment, Bundle arguments, boolean addToBackStack) {
if (fragment instanceof LoginFragment) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else {
// TODO: 5/28/16 currently keyboard overlaps in agenda detail, but this needs a new
// TODO implementation. Check if it's still the case with the new one
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
if (arguments != null) {
fragment.setArguments(arguments);
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment);
if(addToBackStack && currentScreen != null) {
transaction.addToBackStack(null)
.setBreadCrumbTitle(currentScreen.name());
}
transaction.commit();
changeDrawerMenuSelection();
}
private void initLoggedInUI() {
toolbar.setVisibility(View.VISIBLE);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
hideKeyboard(findViewById(R.id.drawer_layout));
logout.setVisibility(View.VISIBLE);
CurrentUser user = UserHelper.getInstance().getCurrentUser();
if(user != null) {
setUserDependentFeatures(user);
} else {
Services.getInstance().userService.currentUser().enqueue(new Callback<CurrentUser>() {
@Override
public void onSucces(Response<CurrentUser> response) {
UserHelper.getInstance().setCurrentUser(response.body());
setUserDependentFeatures(response.body());
}
});
}
}
private void setUserDependentFeatures(final CurrentUser user) {
TextView name = navigationView.getHeaderView(0).findViewById(R.id.nav_header_name);
name.setText(user.getPostalname());
final ImageView profile = navigationView.getHeaderView(0).findViewById(R.id.nav_header_profilepic);
profile.setOnClickListener(v -> {
openSmoboFor(user);
EventBus.getDefault().post(new CurrentUserUpdateRequiredDirectiveEvent());
});
if (user.getPhotomediaid() != null) {
Glide.with(this)
.load(MediaAPI.getMediaUri(user.getPhotomediaid(), MediaAPI.MediaSize.SMALL))
.fitCenter()
.optionalCircleCrop()
.placeholder(R.drawable.account)
.into(profile);
}
}
private void initLoggedOutUI() {
toolbar.setVisibility(View.GONE);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
openFragment(new LoginFragment(), null, false);
currentScreen = Screen.LOGIN;
logout.setVisibility(View.GONE);
TextView name = navigationView.getHeaderView(0).findViewById(R.id.nav_header_name);
name.setText("");
ImageView profile = navigationView.getHeaderView(0).findViewById(R.id.nav_header_profilepic);
profile.setImageResource(R.drawable.account);
}
public void resizeOnKeyboard() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
public static void hideKeyboard(View someView) {
InputMethodManager imm = (InputMethodManager) someView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null)
imm.hideSoftInputFromWindow(someView.getWindowToken(), 0);
}
// EVENT HANDLING
public void onEventMainThread(UserLoggedInEvent event) {
if (event.loggedIn) {
initLoggedInUI();
openTab(HomeFragment.NEWS);
} else {
initLoggedOutUI();
}
}
public void onEventMainThread(OpenFragmentEvent event) {
//TODO refactor this
if(event.screen instanceof AgendaDetailTabsFragment) {
Intent agenda = new Intent(this, AgendaActivity.class);
agenda.putExtras(event.arguments);
startActivity(agenda);
return;
} else if(event.screen instanceof MeetingDetailTabsFragment) {
Intent meeting = new Intent(this, MeetingActivity.class);
meeting.putExtras(event.arguments);
startActivity(meeting);
return;
}
openFragment(event.screen, event.arguments, true);
}
public void onEventMainThread(ContentLoadedEvent event) {
if (focusNewsId > 0 && event.updatedPageableFragment instanceof HomeNewsTab) {
if (((HomeNewsTab) event.updatedPageableFragment)
.scrollToItemWithId(focusNewsId, focusTriesSoFar >= 3) ||
focusTriesSoFar >= 3) {
focusNewsId = -1;
}
focusTriesSoFar++;
}
}
public void onEventMainThread(SwitchTabEvent event) {
setMenuToTab(event.index);
}
}
|
201850_35 | /**
* Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors.
* All rights reserved.
*
* This file is licensed under the BSD 2-Clause License, which accompanies this project
* and is available under https://opensource.org/licenses/BSD-2-Clause.
*/
package io.usethesource.capsule.core.trie;
import java.util.ListIterator;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
/**
* Mapper that traverses a trie and converts each node (of {@code SN}) to a node of type {@code DN}.
*/
public class BottomUpTransientNodeTransformer<SN extends Node, DN extends Node> {
private static final int MAX_DEPTH = 7;
private final BiFunction<SN, AtomicReference<Thread>, DN> nodeMapper;
private final AtomicReference<Thread> mutator;
private final DN dstRootNode;
private int stackIndex = -1;
private final ListIterator<SN>[] srcIteratorStack = new ListIterator[MAX_DEPTH];
private final ListIterator<DN>[] dstIteratorStack = new ListIterator[MAX_DEPTH];
public BottomUpTransientNodeTransformer(final SN srcRootNode,
final BiFunction<SN, AtomicReference<Thread>, DN> nodeMapper) {
this.nodeMapper = nodeMapper;
this.mutator = new AtomicReference<>(Thread.currentThread());
this.dstRootNode = nodeMapper.apply(srcRootNode, mutator);
final ListIterator<SN> srcIterator = (ListIterator<SN>) srcRootNode.nodeArray().iterator();
if (srcIterator.hasNext()) {
final ListIterator<DN> dstIterator = (ListIterator<DN>) dstRootNode.nodeArray().iterator();
pushOnStack(srcIterator, dstIterator);
}
}
public final DN apply() {
if (!isStackEmpty()) {
processStack();
}
mutator.set(null);
return dstRootNode;
}
private final boolean isStackEmpty() {
return stackIndex == -1;
}
private final void pushOnStack(ListIterator<SN> srcNode, ListIterator<DN> dstNode) {
// push on stack
final int nextIndex = ++stackIndex;
srcIteratorStack[nextIndex] = srcNode;
dstIteratorStack[nextIndex] = dstNode;
}
private final void dropFromStack() {
// pop from stack
final int previousIndex = stackIndex--;
srcIteratorStack[previousIndex] = null;
dstIteratorStack[previousIndex] = null;
}
/*
* Traverse trie and convert nodes at first encounter. Sub-trie references are updated
* incrementally throughout iteration.
*/
private final void processStack() {
while (!isStackEmpty()) {
final ListIterator<SN> srcIterator = srcIteratorStack[stackIndex];
final ListIterator<DN> dstIterator = dstIteratorStack[stackIndex];
boolean stackModified = false;
while (!stackModified) {
if (srcIterator.hasNext()) {
final SN src = srcIterator.next();
final DN dst = nodeMapper.apply(src, mutator);
dstIterator.next();
dstIterator.set(dst);
final ListIterator<SN> nextSrcIterator = (ListIterator<SN>) src.nodeArray().iterator();
if (nextSrcIterator.hasNext()) {
final ListIterator<DN> nextDstIterator = (ListIterator<DN>) dst.nodeArray().iterator();
pushOnStack(nextSrcIterator, nextDstIterator);
stackModified = true;
}
} else {
dropFromStack();
stackModified = true;
}
}
}
}
// /*
// * search for next node that can be mapped
// */
// private final Optional<SN> applyNodeTranformation(boolean yieldIntermediate) {
// SN result = null;
//
// while (stackLevel >= 0 && result == null) {
// final ListIterator<MN> srcSubNodeIterator = srcIteratorStack[stackLevel];
// final ListIterator<SN> dstSubNodeIterator = dstIteratorStack[stackLevel];
//
// if (srcSubNodeIterator.hasNext()) {
// final MN nextMapNode = srcSubNodeIterator.next();
// final SN nextSetNode = nodeMapper.apply(nextMapNode, mutator);
//
// dstSubNodeIterator.next();
// dstSubNodeIterator.set(nextSetNode);
//
// final ListIterator<MN> subNodeIterator =
// (ListIterator<MN>) nextMapNode.nodeArray().iterator();
//
// if (subNodeIterator.hasNext()) {
// // next node == (to process) intermediate node
// // put node on next stack level for depth-first traversal
//// final SN nextSetNode = nodeMapper.apply(nextMapNode, mutator);
//
// final int nextStackLevel = ++stackLevel;
// srcIteratorStack[nextStackLevel] = subNodeIterator;
// dstIteratorStack[nextStackLevel] =
// (ListIterator<SN>) nextSetNode.nodeArray().iterator();
// } else if (yieldIntermediate) {
// // nextNode == (finished) leaf node
// result = nextSetNode;
// }
// } else {
// if (yieldIntermediate) {
// // nextNode == (finished) intermidate node
// // result = setNodes[stackLevel]; // ???
// throw new IllegalStateException("TODO: figure out how to return previous element.");
// } else if (stackLevel == 0) {
// result = setRootNode;
// }
//
// // pop from stack
// srcIteratorStack[stackLevel] = null;
// dstIteratorStack[stackLevel] = null;
// stackLevel--;
// }
// }
//
// return Optional.ofNullable(result);
// }
// @Override
// public boolean hasNext() {
// if (next.get().isPresent()) {
// return true;
// } else {
// final Optional<SN> result = applyNodeTranformation(true);
// next.set(result);
// return result.isPresent();
// }
// }
//
// /**
// * Returns transformed --either internal or leaf-- node.
// *
// * @return mapped node
// */
// @Override
// public SN next() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// } else {
// return next.getAndSet(Optional.empty()).get();
// }
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException();
// }
}
| usethesource/capsule | src/main/java/io/usethesource/capsule/core/trie/BottomUpTransientNodeTransformer.java | 1,748 | // if (next.get().isPresent()) { | line_comment | nl | /**
* Copyright (c) Michael Steindorfer <Centrum Wiskunde & Informatica> and Contributors.
* All rights reserved.
*
* This file is licensed under the BSD 2-Clause License, which accompanies this project
* and is available under https://opensource.org/licenses/BSD-2-Clause.
*/
package io.usethesource.capsule.core.trie;
import java.util.ListIterator;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
/**
* Mapper that traverses a trie and converts each node (of {@code SN}) to a node of type {@code DN}.
*/
public class BottomUpTransientNodeTransformer<SN extends Node, DN extends Node> {
private static final int MAX_DEPTH = 7;
private final BiFunction<SN, AtomicReference<Thread>, DN> nodeMapper;
private final AtomicReference<Thread> mutator;
private final DN dstRootNode;
private int stackIndex = -1;
private final ListIterator<SN>[] srcIteratorStack = new ListIterator[MAX_DEPTH];
private final ListIterator<DN>[] dstIteratorStack = new ListIterator[MAX_DEPTH];
public BottomUpTransientNodeTransformer(final SN srcRootNode,
final BiFunction<SN, AtomicReference<Thread>, DN> nodeMapper) {
this.nodeMapper = nodeMapper;
this.mutator = new AtomicReference<>(Thread.currentThread());
this.dstRootNode = nodeMapper.apply(srcRootNode, mutator);
final ListIterator<SN> srcIterator = (ListIterator<SN>) srcRootNode.nodeArray().iterator();
if (srcIterator.hasNext()) {
final ListIterator<DN> dstIterator = (ListIterator<DN>) dstRootNode.nodeArray().iterator();
pushOnStack(srcIterator, dstIterator);
}
}
public final DN apply() {
if (!isStackEmpty()) {
processStack();
}
mutator.set(null);
return dstRootNode;
}
private final boolean isStackEmpty() {
return stackIndex == -1;
}
private final void pushOnStack(ListIterator<SN> srcNode, ListIterator<DN> dstNode) {
// push on stack
final int nextIndex = ++stackIndex;
srcIteratorStack[nextIndex] = srcNode;
dstIteratorStack[nextIndex] = dstNode;
}
private final void dropFromStack() {
// pop from stack
final int previousIndex = stackIndex--;
srcIteratorStack[previousIndex] = null;
dstIteratorStack[previousIndex] = null;
}
/*
* Traverse trie and convert nodes at first encounter. Sub-trie references are updated
* incrementally throughout iteration.
*/
private final void processStack() {
while (!isStackEmpty()) {
final ListIterator<SN> srcIterator = srcIteratorStack[stackIndex];
final ListIterator<DN> dstIterator = dstIteratorStack[stackIndex];
boolean stackModified = false;
while (!stackModified) {
if (srcIterator.hasNext()) {
final SN src = srcIterator.next();
final DN dst = nodeMapper.apply(src, mutator);
dstIterator.next();
dstIterator.set(dst);
final ListIterator<SN> nextSrcIterator = (ListIterator<SN>) src.nodeArray().iterator();
if (nextSrcIterator.hasNext()) {
final ListIterator<DN> nextDstIterator = (ListIterator<DN>) dst.nodeArray().iterator();
pushOnStack(nextSrcIterator, nextDstIterator);
stackModified = true;
}
} else {
dropFromStack();
stackModified = true;
}
}
}
}
// /*
// * search for next node that can be mapped
// */
// private final Optional<SN> applyNodeTranformation(boolean yieldIntermediate) {
// SN result = null;
//
// while (stackLevel >= 0 && result == null) {
// final ListIterator<MN> srcSubNodeIterator = srcIteratorStack[stackLevel];
// final ListIterator<SN> dstSubNodeIterator = dstIteratorStack[stackLevel];
//
// if (srcSubNodeIterator.hasNext()) {
// final MN nextMapNode = srcSubNodeIterator.next();
// final SN nextSetNode = nodeMapper.apply(nextMapNode, mutator);
//
// dstSubNodeIterator.next();
// dstSubNodeIterator.set(nextSetNode);
//
// final ListIterator<MN> subNodeIterator =
// (ListIterator<MN>) nextMapNode.nodeArray().iterator();
//
// if (subNodeIterator.hasNext()) {
// // next node == (to process) intermediate node
// // put node on next stack level for depth-first traversal
//// final SN nextSetNode = nodeMapper.apply(nextMapNode, mutator);
//
// final int nextStackLevel = ++stackLevel;
// srcIteratorStack[nextStackLevel] = subNodeIterator;
// dstIteratorStack[nextStackLevel] =
// (ListIterator<SN>) nextSetNode.nodeArray().iterator();
// } else if (yieldIntermediate) {
// // nextNode == (finished) leaf node
// result = nextSetNode;
// }
// } else {
// if (yieldIntermediate) {
// // nextNode == (finished) intermidate node
// // result = setNodes[stackLevel]; // ???
// throw new IllegalStateException("TODO: figure out how to return previous element.");
// } else if (stackLevel == 0) {
// result = setRootNode;
// }
//
// // pop from stack
// srcIteratorStack[stackLevel] = null;
// dstIteratorStack[stackLevel] = null;
// stackLevel--;
// }
// }
//
// return Optional.ofNullable(result);
// }
// @Override
// public boolean hasNext() {
// if (next.get().isPresent())<SUF>
// return true;
// } else {
// final Optional<SN> result = applyNodeTranformation(true);
// next.set(result);
// return result.isPresent();
// }
// }
//
// /**
// * Returns transformed --either internal or leaf-- node.
// *
// * @return mapped node
// */
// @Override
// public SN next() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// } else {
// return next.getAndSet(Optional.empty()).get();
// }
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException();
// }
}
|
12522_104 | //package org.rascalmpl.eclipse.library.vis.figure.keys;
//
//import io.usethesource.vallang.IValue;
//import io.usethesource.vallang.impl.fast.ValueFactory;
//import org.rascalmpl.eclipse.library.vis.figure.Figure;
//import org.rascalmpl.eclipse.library.vis.figure.combine.WithInnerFig;
//import org.rascalmpl.eclipse.library.vis.graphics.GraphicsContext;
//import org.rascalmpl.eclipse.library.vis.properties.Properties;
//import org.rascalmpl.eclipse.library.vis.properties.PropertyManager;
//import org.rascalmpl.eclipse.library.vis.properties.PropertyParsers;
//import org.rascalmpl.eclipse.library.vis.util.Key;
//<<<<<<< .mine
//import org.rascalmpl.eclipse.library.vis.util.vector.Rectangle;
//=======
//>>>>>>> .r35942
//
//public class HAxis extends WithInnerFig implements Key {
//
//
// final static double majorTickHeight = 5;
// final static double minorTickHeight = 2;
// final static double textTickSpacing = 2;
// final static double borderSpacing = 3;
// final static double labelSpacing = 25;
//
// double labelY;
// double axisY;
// double scale;
// static final boolean debug = true;
// boolean flip, bottom;
// double minVal, maxVal;
// double minOffset,maxOffset;
// double inheritedSpacing;
// String label;
//
// public HAxis(String label,boolean flip, boolean bottom,Figure inner,PropertyManager properties) {
// super(inner , properties);
// this.flip = flip;
// this.bottom = bottom;
// this.label = label;
// }
//
// public HAxis(String label,boolean bottom, Figure inner,PropertyManager properties) {
// this(label,false,bottom,inner,properties);
// }
//
// public void init(){
// minVal = Double.MAX_VALUE;
// maxVal = Double.MIN_VALUE;
// super.init();
// }
//
// private boolean isNumber(IValue val){
// return val.getType().isNumberType() || val.getType().isIntegerType() || val.getType().isRealType();
// }
//
// public void registerValue(Properties prop,IValue val) {
// if(isNumber(val)){
// double pval = PropertyParsers.parseNum(val);
// minVal = Math.min(minVal,pval);
// maxVal = Math.max(maxVal,pval);
// //System.out.printf("Registering at axis %f\n",pval);
// }
// }
//
// public IValue scaleValue(IValue val) {
// if(isNumber(val)){
// double pval = PropertyParsers.parseNum(val);
// //System.out.printf("Converted %f\n", scale * pval);
// //System.out.printf("%s -> %f -> %f %f\n", val, pval, scale * (pval-minVal) ,minVal);
// return ValueFactory.getInstance().real(scale * (pval-minVal)) ;
// }
// return ValueFactory.getInstance().real(0.0);
// }
//
// void computeScale(double pixelSpace){
// scale = pixelSpace / ((maxVal - minVal) );
// }
//
// @Override
// public void bbox() {
// innerFig.bbox();
// //System.out.printf("axissize %s %s\n",size,minSize);
// for(boolean flip : BOTH_DIMENSIONS){
// minSize.setWidth(flip,innerFig.minSize.getWidth(flip) * getHGrowProperty(flip));
// }
// resizableX = innerFig.resizableX;
// resizableY = innerFig.resizableY;
// setResizable();
// minSize.addHeight(flip,axisHeight());
//
// }
//
// double pixelSpace(){
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// return size.getWidth(flip) / getHGrowProperty(flip) - ((HAxis)innerFig).axisHeight();
// } else {
// return size.getWidth(flip) / getHGrowProperty(flip);
// }
// }
//
// double spacing(){
// return size.getWidth(flip) * (1.0 - (1.0 /getHGrowProperty(flip))) ;
// }
//
// double outerSpace(){
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// return size.getWidth(flip) - ((VAxis)innerFig).axisHeight();
// } else {
// return size.getWidth(flip) ;
// }
// }
//
// public Properties alignProp(){
// return Properties.HALIGN;
// }
//
// public void layout(){
// computeScale(pixelSpace());
// //System.out.printf("Computing scale %f %f %f %f\n",minVal,maxVal,pixelSpace(),scale);
// double axisHeight = axisHeight();
// double spacing ;
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// spacing = 0;
// } else {
// spacing = spacing() ;
// }
// innerFig.takeDesiredWidth(flip, size.getWidth(flip) - spacing);
//
// innerFig.takeDesiredHeight(flip, size.getHeight(flip) - axisHeight - inheritedSpacing);
// innerFigLocation.setX(flip,spacing * innerFig.getRealProperty(alignProp()) );
//
// if(bottom){
// innerFigLocation.setY(flip,inheritedSpacing);
// } else {
// innerFigLocation.setY(flip,axisHeight + inheritedSpacing);
// }
// for(boolean flip : BOTH_DIMENSIONS){
// innerFig.globalLocation.setX(flip, globalLocation.getX(flip) + innerFigLocation.getX(flip));
// }
//
//
// innerFig.layout();
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// ((HAxis)innerFig).inheritedSpacing = spacing() * innerFig.getRealProperty(alignProp());
// }
// }
//
// double minimumMajorTicksInterval(){
// return labelWidth() * 7.0 ;
// }
//
// double axisHeight(){
// return majorTickHeight + textTickSpacing
// + borderSpacing + (label.equals("") ? getTextAscent() + getTextDescent() : labelSpacing + 2 * (getTextAscent() + getTextDescent()) ) ;
// }
//
// int standardExtraPrecision(){
// return 1;
// }
//
// int highestPrecision(){
// return (int)Math.ceil(Math.max(Math.log10(maxVal),Math.log10(minVal)));
// }
//
// int lowestPrecision(){
// return (int)Math.min(Math.ceil(Math.log10(maxVal-minVal)), -standardExtraPrecision());
// }
//
// double labelWidth(){
// int length = highestPrecision() + Math.max(0,-lowestPrecision()) + 1;
// return getTextWidth(String.format("%0" + length + "d", 0));
// }
//
// String formatString(){
// return "%" + String.format("%d.%df",
// Math.max(1, highestPrecision()),Math.max(0, -lowestPrecision()));
// }
//
// void drawAxis(GraphicsContext gc){
// double axisTop ;
// if(bottom){
// axisTop = innerFig.size.getHeight(flip);
// } else {
// axisTop = axisHeight();
// }
//
// double pixelSpace = pixelSpace();
// double leftOffset ;
// if(innerFig instanceof VAxis && !((VAxis)innerFig).bottom){
// //System.out.printf("Data dan weer wel\n");
// leftOffset = ((VAxis)innerFig).axisHeight();
// } else {
// leftOffset =0.0;
// }
// double spacing = spacing();
// double outerSpace = outerSpace();
// //System.out.printf("left offset %f\n",leftOffset);
// Tick[] ticks = getTicks(minimumMajorTicksInterval(),
// getLeft() + leftOffset
// , getLeft() + leftOffset + spacing * innerFig.getRealProperty(alignProp())
// ,getLeft() + leftOffset + spacing * innerFig.getRealProperty(alignProp()) + pixelSpace
// ,getLeft() + leftOffset + outerSpace
// ,minVal,maxVal
// );
//
// applyProperties(gc);
//
// double direction = bottom ? 1.0f : -1.0f;
// gc.fill(255);
// //fpa.rect(left,top, size.getWidth(),size.getHeight());
// String format = formatString();
// for(Tick tick : ticks){
// double tickHeight = direction * (tick.major ? majorTickHeight : minorTickHeight);
// String label = String.format(format,tick.measurePos );
//
// //System.out.printf("tick %f",tick.measurePos);
// if(tick.major){
// if(tick.measurePos == 0.0){
// gc.stroke(getColorProperty(Properties.LINE_COLOR));
// } else {
// gc.stroke(getColorProperty(Properties.GUIDE_COLOR));
// }
// gc.line( tick.pixelPos ,
// getTop() + axisTop,
// tick.pixelPos,
// getTop() + axisTop + -direction * innerFig.size.getHeight());
//
//
// applyProperties(gc);
// gc.text(label, tick.pixelPos , getTop() + axisTop + tickHeight + (bottom ? getTextAscent() : -getTextDescent()));
// }
// gc.line(tick.pixelPos ,
// getTop() + axisTop + tickHeight,
// tick.pixelPos,
// getTop() + axisTop );
// }
// if(!this.label.equals("")){
// gc.text(this.label,
// getLeft() + leftOffset + (0.5 * (innerFig.size.getWidth() - getTextWidth(this.label))),
// getTop() + axisTop + direction* (majorTickHeight + textTickSpacing
// + borderSpacing + getTextAscent() + getTextDescent()) + (bottom ? getTextAscent() : getTextDescent()));
// }
// }
// @Override
// public void draw(GraphicsContext gc){
// drawAxis(gc);
// innerFig.draw(gc);
// }
//
// class Tick{
// double pixelPos;
// double measurePos;
// boolean major;
// }
//
// Tick[] getTicks(double majorTickPixelsInteval, double leftBorder, double leftInnerBorder, double rightInnerBorder,double rightBorder, double leftVal, double rightVal){
// //if(debug)System.out.printf("left %f leftInner %f rightInner %f right %f",leftBorder,leftInnerBorder,rightInnerBorder,rightBorder);
// //double pixelsWidth = rightBorder - leftBorder;
// // TODO: this is sometimes beyond the actual range
// double pixelsInnerWidth = rightInnerBorder - leftInnerBorder;
// double rangeInterval = rightVal - leftVal;
// double nrOfInnerMajorTickIntervals = pixelsInnerWidth / (majorTickPixelsInteval / 2.5);
// double tickInterval = rangeInterval / nrOfInnerMajorTickIntervals;
// int numberOfDigits = (int)Math.floor(Math.log10(tickInterval));
// double closest10fold = Math.pow(10.0, numberOfDigits);
// double tenMultiple = (int)(tickInterval / closest10fold);
// int nrMinorTicks;
// double closestRoundedNumber;
// if(tenMultiple < 2.5){
// closestRoundedNumber = closest10fold * 2.5;
// nrMinorTicks=2;
// } else if(tenMultiple < 5){
// closestRoundedNumber = closest10fold * 5.0;
// nrMinorTicks = 5;
// } else if(tenMultiple < 7.5){
// closestRoundedNumber = closest10fold * 7.5;
// nrMinorTicks = 4;
// } else {
// closestRoundedNumber = closest10fold * 10.0;
// nrMinorTicks = 10;
// }
//
//
//
// double widthPixelsPerMajorTick = closestRoundedNumber * scale;
// double widthPixelsPerMinorTick = widthPixelsPerMajorTick / nrMinorTicks;
// double startOffset = Math.signum(leftVal) *
// (Math.ceil(Math.abs(leftVal) / closestRoundedNumber)) * closestRoundedNumber;
//
// double startOffsetPixels = leftInnerBorder + (startOffset - leftVal)* scale;
// int startOffsetTickIndex = (int)((startOffsetPixels - leftBorder ) / widthPixelsPerMinorTick);
// //int startOffsetTickIndex = PApplet.floor((startOffsetPixels - leftBorder) / widthPixelsPerMinorTick);
// //if(debug) System.out.printf("\nstartOffsetTickIndex %f %d\n", (startOffsetPixels - leftBorder ) / widthPixelsPerMinorTick, startOffsetTickIndex);
// int numberOfTicks = startOffsetTickIndex + (int)((rightBorder - startOffsetPixels) / widthPixelsPerMinorTick) + 1;
// Tick[] result = new Tick[numberOfTicks];
// double measurePerTick = closestRoundedNumber / nrMinorTicks;
// double measureHere = startOffset - startOffsetTickIndex * measurePerTick;
// double measureHereMajor = startOffset - (startOffsetTickIndex / nrMinorTicks) * closestRoundedNumber;
// for(int i = 0 ; i < numberOfTicks ; i++){
// result[i] = new Tick();
// result[i].measurePos = measureHere ;
// result[i].pixelPos = startOffsetPixels + (i - startOffsetTickIndex) * widthPixelsPerMinorTick ;
// result[i].major = (i - startOffsetTickIndex) % nrMinorTicks == 0;
//
// measureHere += measurePerTick;
// if((i + 1 - startOffsetTickIndex) % nrMinorTicks == 0){
// measureHereMajor += closestRoundedNumber;
// measureHere = measureHereMajor;
// //System.out.printf("closest rounded %f\n", measureHere);
// }
// //if(debug) System.out.printf("Tick %d measure %f pixels %f major %s\n",i - startOffsetTickIndex,result[i].measurePos,result[i].pixelPos,result[i].major);
// }
//
// return result;
// }
//
// public String getId() {
// return getIdProperty();
// }
//
// public void registerOffset(double offset) {
// //System.out.printf("Registering offset %f",offset);
// minOffset = Math.min(minOffset, offset);
// maxOffset = Math.max(maxOffset, offset);
//
// }
//
//
//}
| usethesource/rascal-eclipse | rascal-eclipse/src/org/rascalmpl/eclipse/library/vis/figure/keys/HAxis.java | 4,283 | // getTop() + axisTop ); | line_comment | nl | //package org.rascalmpl.eclipse.library.vis.figure.keys;
//
//import io.usethesource.vallang.IValue;
//import io.usethesource.vallang.impl.fast.ValueFactory;
//import org.rascalmpl.eclipse.library.vis.figure.Figure;
//import org.rascalmpl.eclipse.library.vis.figure.combine.WithInnerFig;
//import org.rascalmpl.eclipse.library.vis.graphics.GraphicsContext;
//import org.rascalmpl.eclipse.library.vis.properties.Properties;
//import org.rascalmpl.eclipse.library.vis.properties.PropertyManager;
//import org.rascalmpl.eclipse.library.vis.properties.PropertyParsers;
//import org.rascalmpl.eclipse.library.vis.util.Key;
//<<<<<<< .mine
//import org.rascalmpl.eclipse.library.vis.util.vector.Rectangle;
//=======
//>>>>>>> .r35942
//
//public class HAxis extends WithInnerFig implements Key {
//
//
// final static double majorTickHeight = 5;
// final static double minorTickHeight = 2;
// final static double textTickSpacing = 2;
// final static double borderSpacing = 3;
// final static double labelSpacing = 25;
//
// double labelY;
// double axisY;
// double scale;
// static final boolean debug = true;
// boolean flip, bottom;
// double minVal, maxVal;
// double minOffset,maxOffset;
// double inheritedSpacing;
// String label;
//
// public HAxis(String label,boolean flip, boolean bottom,Figure inner,PropertyManager properties) {
// super(inner , properties);
// this.flip = flip;
// this.bottom = bottom;
// this.label = label;
// }
//
// public HAxis(String label,boolean bottom, Figure inner,PropertyManager properties) {
// this(label,false,bottom,inner,properties);
// }
//
// public void init(){
// minVal = Double.MAX_VALUE;
// maxVal = Double.MIN_VALUE;
// super.init();
// }
//
// private boolean isNumber(IValue val){
// return val.getType().isNumberType() || val.getType().isIntegerType() || val.getType().isRealType();
// }
//
// public void registerValue(Properties prop,IValue val) {
// if(isNumber(val)){
// double pval = PropertyParsers.parseNum(val);
// minVal = Math.min(minVal,pval);
// maxVal = Math.max(maxVal,pval);
// //System.out.printf("Registering at axis %f\n",pval);
// }
// }
//
// public IValue scaleValue(IValue val) {
// if(isNumber(val)){
// double pval = PropertyParsers.parseNum(val);
// //System.out.printf("Converted %f\n", scale * pval);
// //System.out.printf("%s -> %f -> %f %f\n", val, pval, scale * (pval-minVal) ,minVal);
// return ValueFactory.getInstance().real(scale * (pval-minVal)) ;
// }
// return ValueFactory.getInstance().real(0.0);
// }
//
// void computeScale(double pixelSpace){
// scale = pixelSpace / ((maxVal - minVal) );
// }
//
// @Override
// public void bbox() {
// innerFig.bbox();
// //System.out.printf("axissize %s %s\n",size,minSize);
// for(boolean flip : BOTH_DIMENSIONS){
// minSize.setWidth(flip,innerFig.minSize.getWidth(flip) * getHGrowProperty(flip));
// }
// resizableX = innerFig.resizableX;
// resizableY = innerFig.resizableY;
// setResizable();
// minSize.addHeight(flip,axisHeight());
//
// }
//
// double pixelSpace(){
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// return size.getWidth(flip) / getHGrowProperty(flip) - ((HAxis)innerFig).axisHeight();
// } else {
// return size.getWidth(flip) / getHGrowProperty(flip);
// }
// }
//
// double spacing(){
// return size.getWidth(flip) * (1.0 - (1.0 /getHGrowProperty(flip))) ;
// }
//
// double outerSpace(){
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// return size.getWidth(flip) - ((VAxis)innerFig).axisHeight();
// } else {
// return size.getWidth(flip) ;
// }
// }
//
// public Properties alignProp(){
// return Properties.HALIGN;
// }
//
// public void layout(){
// computeScale(pixelSpace());
// //System.out.printf("Computing scale %f %f %f %f\n",minVal,maxVal,pixelSpace(),scale);
// double axisHeight = axisHeight();
// double spacing ;
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// spacing = 0;
// } else {
// spacing = spacing() ;
// }
// innerFig.takeDesiredWidth(flip, size.getWidth(flip) - spacing);
//
// innerFig.takeDesiredHeight(flip, size.getHeight(flip) - axisHeight - inheritedSpacing);
// innerFigLocation.setX(flip,spacing * innerFig.getRealProperty(alignProp()) );
//
// if(bottom){
// innerFigLocation.setY(flip,inheritedSpacing);
// } else {
// innerFigLocation.setY(flip,axisHeight + inheritedSpacing);
// }
// for(boolean flip : BOTH_DIMENSIONS){
// innerFig.globalLocation.setX(flip, globalLocation.getX(flip) + innerFigLocation.getX(flip));
// }
//
//
// innerFig.layout();
// if(innerFig instanceof HAxis && ((HAxis)innerFig).flip != flip){
// ((HAxis)innerFig).inheritedSpacing = spacing() * innerFig.getRealProperty(alignProp());
// }
// }
//
// double minimumMajorTicksInterval(){
// return labelWidth() * 7.0 ;
// }
//
// double axisHeight(){
// return majorTickHeight + textTickSpacing
// + borderSpacing + (label.equals("") ? getTextAscent() + getTextDescent() : labelSpacing + 2 * (getTextAscent() + getTextDescent()) ) ;
// }
//
// int standardExtraPrecision(){
// return 1;
// }
//
// int highestPrecision(){
// return (int)Math.ceil(Math.max(Math.log10(maxVal),Math.log10(minVal)));
// }
//
// int lowestPrecision(){
// return (int)Math.min(Math.ceil(Math.log10(maxVal-minVal)), -standardExtraPrecision());
// }
//
// double labelWidth(){
// int length = highestPrecision() + Math.max(0,-lowestPrecision()) + 1;
// return getTextWidth(String.format("%0" + length + "d", 0));
// }
//
// String formatString(){
// return "%" + String.format("%d.%df",
// Math.max(1, highestPrecision()),Math.max(0, -lowestPrecision()));
// }
//
// void drawAxis(GraphicsContext gc){
// double axisTop ;
// if(bottom){
// axisTop = innerFig.size.getHeight(flip);
// } else {
// axisTop = axisHeight();
// }
//
// double pixelSpace = pixelSpace();
// double leftOffset ;
// if(innerFig instanceof VAxis && !((VAxis)innerFig).bottom){
// //System.out.printf("Data dan weer wel\n");
// leftOffset = ((VAxis)innerFig).axisHeight();
// } else {
// leftOffset =0.0;
// }
// double spacing = spacing();
// double outerSpace = outerSpace();
// //System.out.printf("left offset %f\n",leftOffset);
// Tick[] ticks = getTicks(minimumMajorTicksInterval(),
// getLeft() + leftOffset
// , getLeft() + leftOffset + spacing * innerFig.getRealProperty(alignProp())
// ,getLeft() + leftOffset + spacing * innerFig.getRealProperty(alignProp()) + pixelSpace
// ,getLeft() + leftOffset + outerSpace
// ,minVal,maxVal
// );
//
// applyProperties(gc);
//
// double direction = bottom ? 1.0f : -1.0f;
// gc.fill(255);
// //fpa.rect(left,top, size.getWidth(),size.getHeight());
// String format = formatString();
// for(Tick tick : ticks){
// double tickHeight = direction * (tick.major ? majorTickHeight : minorTickHeight);
// String label = String.format(format,tick.measurePos );
//
// //System.out.printf("tick %f",tick.measurePos);
// if(tick.major){
// if(tick.measurePos == 0.0){
// gc.stroke(getColorProperty(Properties.LINE_COLOR));
// } else {
// gc.stroke(getColorProperty(Properties.GUIDE_COLOR));
// }
// gc.line( tick.pixelPos ,
// getTop() + axisTop,
// tick.pixelPos,
// getTop() + axisTop + -direction * innerFig.size.getHeight());
//
//
// applyProperties(gc);
// gc.text(label, tick.pixelPos , getTop() + axisTop + tickHeight + (bottom ? getTextAscent() : -getTextDescent()));
// }
// gc.line(tick.pixelPos ,
// getTop() + axisTop + tickHeight,
// tick.pixelPos,
// getTop() +<SUF>
// }
// if(!this.label.equals("")){
// gc.text(this.label,
// getLeft() + leftOffset + (0.5 * (innerFig.size.getWidth() - getTextWidth(this.label))),
// getTop() + axisTop + direction* (majorTickHeight + textTickSpacing
// + borderSpacing + getTextAscent() + getTextDescent()) + (bottom ? getTextAscent() : getTextDescent()));
// }
// }
// @Override
// public void draw(GraphicsContext gc){
// drawAxis(gc);
// innerFig.draw(gc);
// }
//
// class Tick{
// double pixelPos;
// double measurePos;
// boolean major;
// }
//
// Tick[] getTicks(double majorTickPixelsInteval, double leftBorder, double leftInnerBorder, double rightInnerBorder,double rightBorder, double leftVal, double rightVal){
// //if(debug)System.out.printf("left %f leftInner %f rightInner %f right %f",leftBorder,leftInnerBorder,rightInnerBorder,rightBorder);
// //double pixelsWidth = rightBorder - leftBorder;
// // TODO: this is sometimes beyond the actual range
// double pixelsInnerWidth = rightInnerBorder - leftInnerBorder;
// double rangeInterval = rightVal - leftVal;
// double nrOfInnerMajorTickIntervals = pixelsInnerWidth / (majorTickPixelsInteval / 2.5);
// double tickInterval = rangeInterval / nrOfInnerMajorTickIntervals;
// int numberOfDigits = (int)Math.floor(Math.log10(tickInterval));
// double closest10fold = Math.pow(10.0, numberOfDigits);
// double tenMultiple = (int)(tickInterval / closest10fold);
// int nrMinorTicks;
// double closestRoundedNumber;
// if(tenMultiple < 2.5){
// closestRoundedNumber = closest10fold * 2.5;
// nrMinorTicks=2;
// } else if(tenMultiple < 5){
// closestRoundedNumber = closest10fold * 5.0;
// nrMinorTicks = 5;
// } else if(tenMultiple < 7.5){
// closestRoundedNumber = closest10fold * 7.5;
// nrMinorTicks = 4;
// } else {
// closestRoundedNumber = closest10fold * 10.0;
// nrMinorTicks = 10;
// }
//
//
//
// double widthPixelsPerMajorTick = closestRoundedNumber * scale;
// double widthPixelsPerMinorTick = widthPixelsPerMajorTick / nrMinorTicks;
// double startOffset = Math.signum(leftVal) *
// (Math.ceil(Math.abs(leftVal) / closestRoundedNumber)) * closestRoundedNumber;
//
// double startOffsetPixels = leftInnerBorder + (startOffset - leftVal)* scale;
// int startOffsetTickIndex = (int)((startOffsetPixels - leftBorder ) / widthPixelsPerMinorTick);
// //int startOffsetTickIndex = PApplet.floor((startOffsetPixels - leftBorder) / widthPixelsPerMinorTick);
// //if(debug) System.out.printf("\nstartOffsetTickIndex %f %d\n", (startOffsetPixels - leftBorder ) / widthPixelsPerMinorTick, startOffsetTickIndex);
// int numberOfTicks = startOffsetTickIndex + (int)((rightBorder - startOffsetPixels) / widthPixelsPerMinorTick) + 1;
// Tick[] result = new Tick[numberOfTicks];
// double measurePerTick = closestRoundedNumber / nrMinorTicks;
// double measureHere = startOffset - startOffsetTickIndex * measurePerTick;
// double measureHereMajor = startOffset - (startOffsetTickIndex / nrMinorTicks) * closestRoundedNumber;
// for(int i = 0 ; i < numberOfTicks ; i++){
// result[i] = new Tick();
// result[i].measurePos = measureHere ;
// result[i].pixelPos = startOffsetPixels + (i - startOffsetTickIndex) * widthPixelsPerMinorTick ;
// result[i].major = (i - startOffsetTickIndex) % nrMinorTicks == 0;
//
// measureHere += measurePerTick;
// if((i + 1 - startOffsetTickIndex) % nrMinorTicks == 0){
// measureHereMajor += closestRoundedNumber;
// measureHere = measureHereMajor;
// //System.out.printf("closest rounded %f\n", measureHere);
// }
// //if(debug) System.out.printf("Tick %d measure %f pixels %f major %s\n",i - startOffsetTickIndex,result[i].measurePos,result[i].pixelPos,result[i].major);
// }
//
// return result;
// }
//
// public String getId() {
// return getIdProperty();
// }
//
// public void registerOffset(double offset) {
// //System.out.printf("Registering offset %f",offset);
// minOffset = Math.min(minOffset, offset);
// maxOffset = Math.max(maxOffset, offset);
//
// }
//
//
//}
|
172153_14 | /**
*/
package org.hl7.fhir;
import java.lang.String;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Link Type List</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.hl7.fhir.FhirPackage#getLinkTypeList()
* @model extendedMetaData="name='LinkType-list'"
* @generated
*/
public enum LinkTypeList implements Enumerator {
/**
* The '<em><b>Replace</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REPLACE_VALUE
* @generated
* @ordered
*/
REPLACE(0, "replace", "replace"),
/**
* The '<em><b>Refer</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REFER_VALUE
* @generated
* @ordered
*/
REFER(1, "refer", "refer"),
/**
* The '<em><b>Seealso</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SEEALSO_VALUE
* @generated
* @ordered
*/
SEEALSO(2, "seealso", "seealso");
/**
* The '<em><b>Replace</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains this link.
* vervangen
* <!-- end-model-doc -->
* @see #REPLACE
* @model name="replace"
* @generated
* @ordered
*/
public static final int REPLACE_VALUE = 0;
/**
* The '<em><b>Refer</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information.
* verwijzing
* <!-- end-model-doc -->
* @see #REFER
* @model name="refer"
* @generated
* @ordered
*/
public static final int REFER_VALUE = 1;
/**
* The '<em><b>Seealso</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid.
* zie ook
* <!-- end-model-doc -->
* @see #SEEALSO
* @model name="seealso"
* @generated
* @ordered
*/
public static final int SEEALSO_VALUE = 2;
/**
* An array of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final LinkTypeList[] VALUES_ARRAY =
new LinkTypeList[] {
REPLACE,
REFER,
SEEALSO,
};
/**
* A public read-only list of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<LinkTypeList> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(int value) {
switch (value) {
case REPLACE_VALUE: return REPLACE;
case REFER_VALUE: return REFER;
case SEEALSO_VALUE: return SEEALSO;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private LinkTypeList(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //LinkTypeList
| usnistgov/fhir.emf | gen/main/java/org/hl7/fhir/LinkTypeList.java | 2,000 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
*/
package org.hl7.fhir;
import java.lang.String;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Link Type List</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.hl7.fhir.FhirPackage#getLinkTypeList()
* @model extendedMetaData="name='LinkType-list'"
* @generated
*/
public enum LinkTypeList implements Enumerator {
/**
* The '<em><b>Replace</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REPLACE_VALUE
* @generated
* @ordered
*/
REPLACE(0, "replace", "replace"),
/**
* The '<em><b>Refer</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REFER_VALUE
* @generated
* @ordered
*/
REFER(1, "refer", "refer"),
/**
* The '<em><b>Seealso</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SEEALSO_VALUE
* @generated
* @ordered
*/
SEEALSO(2, "seealso", "seealso");
/**
* The '<em><b>Replace</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains this link.
* vervangen
* <!-- end-model-doc -->
* @see #REPLACE
* @model name="replace"
* @generated
* @ordered
*/
public static final int REPLACE_VALUE = 0;
/**
* The '<em><b>Refer</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information.
* verwijzing
* <!-- end-model-doc -->
* @see #REFER
* @model name="refer"
* @generated
* @ordered
*/
public static final int REFER_VALUE = 1;
/**
* The '<em><b>Seealso</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid.
* zie ook
* <!-- end-model-doc -->
* @see #SEEALSO
* @model name="seealso"
* @generated
* @ordered
*/
public static final int SEEALSO_VALUE = 2;
/**
* An array of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final LinkTypeList[] VALUES_ARRAY =
new LinkTypeList[] {
REPLACE,
REFER,
SEEALSO,
};
/**
* A public read-only list of all the '<em><b>Link Type List</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<LinkTypeList> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
LinkTypeList result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Link Type List</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static LinkTypeList get(int value) {
switch (value) {
case REPLACE_VALUE: return REPLACE;
case REFER_VALUE: return REFER;
case SEEALSO_VALUE: return SEEALSO;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc --><SUF>*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private LinkTypeList(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //LinkTypeList
|
18136_14 | package br.usp.model.replicado;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Classe de entidade Emailpessoa
*
* @author marcelo.modesto
*/
@Entity
@Table(name = "EMAILPESSOA", catalog = "replicado", schema = "dbo")
public class EmailPessoa implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6556818505163343118L;
/**
* Campo de chave primária embutido
*/
@EmbeddedId
protected EmailPessoaPK EmailPessoaPK;
@Column(name = "codema", nullable = false)
private String codema;
@Column(name = "stamtr")
private Character stamtr;
@Column(name = "timestamp")
private byte[] timestamp;
@Column(name = "staatzdvg")
private Character staatzdvg;
/** Creates a new instance of EmailPessoa */
public EmailPessoa() {
}
/**
* Cria uma nova instância de EmailPessoa com os valores especificados.
*
* @param EmailPessoaPK
* o EmailPessoaPK do EmailPessoa
*/
public EmailPessoa(EmailPessoaPK EmailPessoaPK) {
this.EmailPessoaPK = EmailPessoaPK;
}
/**
* Cria uma nova instância de EmailPessoa com os valores especificados.
*
* @param EmailPessoaPK
* o EmailPessoaPK do EmailPessoa
* @param codema
* o codema do EmailPessoa
*/
public EmailPessoa(EmailPessoaPK EmailPessoaPK, String codema) {
this.EmailPessoaPK = EmailPessoaPK;
this.codema = codema;
}
/**
* Cria uma nova instância de EmailPessoaPK com os valores especificados.
*
* @param numseqema
* o numseqema do EmailPessoaPK
* @param codpes
* o codpes do EmailPessoaPK
*/
public EmailPessoa(short numseqema, int codpes) {
this.EmailPessoaPK = new EmailPessoaPK(numseqema, codpes);
}
/**
* Define o EmailPessoaPK deste EmailPessoa.
*
* @return o EmailPessoaPK
*/
public EmailPessoaPK getEmailPessoaPK() {
return this.EmailPessoaPK;
}
/**
* Define o EmailPessoaPK deste EmailPessoa para o valor especificado.
*
* @param EmailPessoaPK
* o novo EmailPessoaPK
*/
public void setEmailPessoaPK(EmailPessoaPK EmailPessoaPK) {
this.EmailPessoaPK = EmailPessoaPK;
}
/**
* Define o codema deste EmailPessoa.
*
* @return o codema
*/
public String getCodema() {
return this.codema;
}
/**
* Define o codema deste EmailPessoa para o valor especificado.
*
* @param codema
* o novo codema
*/
public void setCodema(String codema) {
this.codema = codema;
}
/**
* Define o stamtr deste EmailPessoa.
*
* @return o stamtr
*/
public Character getStamtr() {
return this.stamtr;
}
/**
* Define o stamtr deste EmailPessoa para o valor especificado.
*
* @param stamtr
* o novo stamtr
*/
public void setStamtr(Character stamtr) {
this.stamtr = stamtr;
}
/**
* Define o timestamp deste EmailPessoa.
*
* @return o timestamp
*/
public byte[] getTimestamp() {
return this.timestamp;
}
/**
* Define o timestamp deste EmailPessoa para o valor especificado.
*
* @param timestamp
* o novo timestamp
*/
public void setTimestamp(byte[] timestamp) {
this.timestamp = timestamp;
}
/**
* Define o staatzdvg deste EmailPessoa.
*
* @return o staatzdvg
*/
public Character getStaatzdvg() {
return this.staatzdvg;
}
/**
* Define o staatzdvg deste EmailPessoa para o valor especificado.
*
* @param staatzdvg
* o novo staatzdvg
*/
public void setStaatzdvg(Character staatzdvg) {
this.staatzdvg = staatzdvg;
}
/**
* Retorna um valor de código hash para o objeto. Esta implementação computa
* um valor de código hash baseado nos campos id deste objeto.
*
* @return um valor de código hash para este objeto.
*/
@Override
public int hashCode() {
int hash = 0;
hash += (this.EmailPessoaPK != null ? this.EmailPessoaPK.hashCode() : 0);
return hash;
}
/**
* Determina se outro objeto é igual a este EmailPessoa. O resultado é
* <code>true</code> se e somente se o argumento não for nulo e for um
* objeto EmailPessoa o qual tem o mesmo valor para o campo id como este
* objeto.
*
* @param object
* o objeto de referência com o qual comparar
* @return <code>true</code> se este objeto é o mesmo como o argumento;
* <code>false</code> caso contrário.
*/
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof EmailPessoa)) {
return false;
}
EmailPessoa other = (EmailPessoa) object;
if (this.EmailPessoaPK != other.EmailPessoaPK
&& (this.EmailPessoaPK == null || !this.EmailPessoaPK.equals(other.EmailPessoaPK)))
return false;
return true;
}
/**
* Retorna uma representação literal deste objeto. Esta implementação cria
* uma representação baseada nos campos id.
*
* @return uma representação literal deste objeto.
*/
@Override
public String toString() {
return "br.usp.poli.icaro.model.EmailPessoa[EmailPessoaPK=" + EmailPessoaPK + "]";
}
}
| uspdev/ganimedes | src/main/java/br/usp/model/replicado/EmailPessoa.java | 2,040 | /**
* Define o staatzdvg deste EmailPessoa.
*
* @return o staatzdvg
*/ | block_comment | nl | package br.usp.model.replicado;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Classe de entidade Emailpessoa
*
* @author marcelo.modesto
*/
@Entity
@Table(name = "EMAILPESSOA", catalog = "replicado", schema = "dbo")
public class EmailPessoa implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6556818505163343118L;
/**
* Campo de chave primária embutido
*/
@EmbeddedId
protected EmailPessoaPK EmailPessoaPK;
@Column(name = "codema", nullable = false)
private String codema;
@Column(name = "stamtr")
private Character stamtr;
@Column(name = "timestamp")
private byte[] timestamp;
@Column(name = "staatzdvg")
private Character staatzdvg;
/** Creates a new instance of EmailPessoa */
public EmailPessoa() {
}
/**
* Cria uma nova instância de EmailPessoa com os valores especificados.
*
* @param EmailPessoaPK
* o EmailPessoaPK do EmailPessoa
*/
public EmailPessoa(EmailPessoaPK EmailPessoaPK) {
this.EmailPessoaPK = EmailPessoaPK;
}
/**
* Cria uma nova instância de EmailPessoa com os valores especificados.
*
* @param EmailPessoaPK
* o EmailPessoaPK do EmailPessoa
* @param codema
* o codema do EmailPessoa
*/
public EmailPessoa(EmailPessoaPK EmailPessoaPK, String codema) {
this.EmailPessoaPK = EmailPessoaPK;
this.codema = codema;
}
/**
* Cria uma nova instância de EmailPessoaPK com os valores especificados.
*
* @param numseqema
* o numseqema do EmailPessoaPK
* @param codpes
* o codpes do EmailPessoaPK
*/
public EmailPessoa(short numseqema, int codpes) {
this.EmailPessoaPK = new EmailPessoaPK(numseqema, codpes);
}
/**
* Define o EmailPessoaPK deste EmailPessoa.
*
* @return o EmailPessoaPK
*/
public EmailPessoaPK getEmailPessoaPK() {
return this.EmailPessoaPK;
}
/**
* Define o EmailPessoaPK deste EmailPessoa para o valor especificado.
*
* @param EmailPessoaPK
* o novo EmailPessoaPK
*/
public void setEmailPessoaPK(EmailPessoaPK EmailPessoaPK) {
this.EmailPessoaPK = EmailPessoaPK;
}
/**
* Define o codema deste EmailPessoa.
*
* @return o codema
*/
public String getCodema() {
return this.codema;
}
/**
* Define o codema deste EmailPessoa para o valor especificado.
*
* @param codema
* o novo codema
*/
public void setCodema(String codema) {
this.codema = codema;
}
/**
* Define o stamtr deste EmailPessoa.
*
* @return o stamtr
*/
public Character getStamtr() {
return this.stamtr;
}
/**
* Define o stamtr deste EmailPessoa para o valor especificado.
*
* @param stamtr
* o novo stamtr
*/
public void setStamtr(Character stamtr) {
this.stamtr = stamtr;
}
/**
* Define o timestamp deste EmailPessoa.
*
* @return o timestamp
*/
public byte[] getTimestamp() {
return this.timestamp;
}
/**
* Define o timestamp deste EmailPessoa para o valor especificado.
*
* @param timestamp
* o novo timestamp
*/
public void setTimestamp(byte[] timestamp) {
this.timestamp = timestamp;
}
/**
* Define o staatzdvg<SUF>*/
public Character getStaatzdvg() {
return this.staatzdvg;
}
/**
* Define o staatzdvg deste EmailPessoa para o valor especificado.
*
* @param staatzdvg
* o novo staatzdvg
*/
public void setStaatzdvg(Character staatzdvg) {
this.staatzdvg = staatzdvg;
}
/**
* Retorna um valor de código hash para o objeto. Esta implementação computa
* um valor de código hash baseado nos campos id deste objeto.
*
* @return um valor de código hash para este objeto.
*/
@Override
public int hashCode() {
int hash = 0;
hash += (this.EmailPessoaPK != null ? this.EmailPessoaPK.hashCode() : 0);
return hash;
}
/**
* Determina se outro objeto é igual a este EmailPessoa. O resultado é
* <code>true</code> se e somente se o argumento não for nulo e for um
* objeto EmailPessoa o qual tem o mesmo valor para o campo id como este
* objeto.
*
* @param object
* o objeto de referência com o qual comparar
* @return <code>true</code> se este objeto é o mesmo como o argumento;
* <code>false</code> caso contrário.
*/
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof EmailPessoa)) {
return false;
}
EmailPessoa other = (EmailPessoa) object;
if (this.EmailPessoaPK != other.EmailPessoaPK
&& (this.EmailPessoaPK == null || !this.EmailPessoaPK.equals(other.EmailPessoaPK)))
return false;
return true;
}
/**
* Retorna uma representação literal deste objeto. Esta implementação cria
* uma representação baseada nos campos id.
*
* @return uma representação literal deste objeto.
*/
@Override
public String toString() {
return "br.usp.poli.icaro.model.EmailPessoa[EmailPessoaPK=" + EmailPessoaPK + "]";
}
}
|
148522_29 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing.ch;
import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.graphhopper.storage.CHStorageBuilder;
import com.graphhopper.util.BitUtil;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.PMap;
import com.graphhopper.util.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Locale;
import static com.graphhopper.routing.ch.CHParameters.*;
import static com.graphhopper.util.GHUtility.reverseEdgeKey;
import static com.graphhopper.util.Helper.nf;
/**
* This class is used to calculate the priority of or contract a given node in edge-based Contraction Hierarchies as it
* is required to support turn-costs. This implementation follows the 'aggressive' variant described in
* 'Efficient Routing in Road Networks with Turn Costs' by R. Geisberger and C. Vetter. Here, we do not store the center
* node for each shortcut, but introduce helper shortcuts when a loop shortcut is encountered.
* <p>
* This class is mostly concerned with triggering the required local searches and introducing the necessary shortcuts
* or calculating the node priority, while the actual searches for witness paths are delegated to
* {@link EdgeBasedWitnessPathSearcher}.
*
* @author easbar
*/
class EdgeBasedNodeContractor implements NodeContractor {
private static final Logger LOGGER = LoggerFactory.getLogger(EdgeBasedNodeContractor.class);
private final CHPreparationGraph prepareGraph;
private PrepareGraphEdgeExplorer inEdgeExplorer;
private PrepareGraphEdgeExplorer outEdgeExplorer;
private PrepareGraphEdgeExplorer existingShortcutExplorer;
private PrepareGraphOrigEdgeExplorer sourceNodeOrigInEdgeExplorer;
private CHStorageBuilder chBuilder;
private final Params params = new Params();
private final StopWatch dijkstraSW = new StopWatch();
// temporary data used during node contraction
private final IntSet sourceNodes = new IntHashSet(10);
private final IntSet targetNodes = new IntHashSet(10);
private final LongSet addedShortcuts = new LongHashSet();
private final Stats addingStats = new Stats();
private final Stats countingStats = new Stats();
private Stats activeStats;
private int[] hierarchyDepths;
private EdgeBasedWitnessPathSearcher witnessPathSearcher;
private BridgePathFinder bridgePathFinder;
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsHeur = new EdgeBasedWitnessPathSearcher.Stats();
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsContr = new EdgeBasedWitnessPathSearcher.Stats();
// counts the total number of added shortcuts
private int addedShortcutsCount;
// edge counts used to calculate priority
private int numShortcuts;
private int numPrevEdges;
private int numOrigEdges;
private int numPrevOrigEdges;
private int numAllEdges;
private double meanDegree;
public EdgeBasedNodeContractor(CHPreparationGraph prepareGraph, CHStorageBuilder chBuilder, PMap pMap) {
this.prepareGraph = prepareGraph;
this.chBuilder = chBuilder;
extractParams(pMap);
}
private void extractParams(PMap pMap) {
params.edgeQuotientWeight = pMap.getFloat(EDGE_QUOTIENT_WEIGHT, params.edgeQuotientWeight);
params.originalEdgeQuotientWeight = pMap.getFloat(ORIGINAL_EDGE_QUOTIENT_WEIGHT, params.originalEdgeQuotientWeight);
params.hierarchyDepthWeight = pMap.getFloat(HIERARCHY_DEPTH_WEIGHT, params.hierarchyDepthWeight);
params.maxPollFactorHeuristic = pMap.getDouble(MAX_POLL_FACTOR_HEURISTIC_EDGE, params.maxPollFactorHeuristic);
params.maxPollFactorContraction = pMap.getDouble(MAX_POLL_FACTOR_CONTRACTION_EDGE, params.maxPollFactorContraction);
}
@Override
public void initFromGraph() {
inEdgeExplorer = prepareGraph.createInEdgeExplorer();
outEdgeExplorer = prepareGraph.createOutEdgeExplorer();
existingShortcutExplorer = prepareGraph.createOutEdgeExplorer();
sourceNodeOrigInEdgeExplorer = prepareGraph.createInOrigEdgeExplorer();
hierarchyDepths = new int[prepareGraph.getNodes()];
witnessPathSearcher = new EdgeBasedWitnessPathSearcher(prepareGraph);
bridgePathFinder = new BridgePathFinder(prepareGraph);
meanDegree = prepareGraph.getOriginalEdges() * 1.0 / prepareGraph.getNodes();
}
@Override
public float calculatePriority(int node) {
activeStats = countingStats;
resetEdgeCounters();
countPreviousEdges(node);
if (numAllEdges == 0)
// this node is isolated, maybe it belongs to a removed subnetwork, in any case we can quickly contract it
// no shortcuts will be introduced
return Float.NEGATIVE_INFINITY;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::countShortcuts, (int) (meanDegree * params.maxPollFactorHeuristic), wpsStatsHeur);
stats().stopWatch.stop();
// the higher the priority the later (!) this node will be contracted
float edgeQuotient = numShortcuts / (float) (prepareGraph.getDegree(node));
float origEdgeQuotient = numOrigEdges / (float) numPrevOrigEdges;
int hierarchyDepth = hierarchyDepths[node];
float priority = params.edgeQuotientWeight * edgeQuotient +
params.originalEdgeQuotientWeight * origEdgeQuotient +
params.hierarchyDepthWeight * hierarchyDepth;
if (LOGGER.isTraceEnabled())
LOGGER.trace("node: {}, eq: {} / {} = {}, oeq: {} / {} = {}, depth: {} --> {}",
node,
numShortcuts, numPrevEdges, edgeQuotient,
numOrigEdges, numPrevOrigEdges, origEdgeQuotient,
hierarchyDepth, priority);
return priority;
}
@Override
public IntContainer contractNode(int node) {
activeStats = addingStats;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::addShortcutsToPrepareGraph, (int) (meanDegree * params.maxPollFactorContraction), wpsStatsContr);
insertShortcuts(node);
IntContainer neighbors = prepareGraph.disconnect(node);
// We maintain an approximation of the mean degree which we update after every contracted node.
// We do it the same way as for node-based CH for now.
meanDegree = (meanDegree * 2 + neighbors.size()) / 3;
updateHierarchyDepthsOfNeighbors(node, neighbors);
stats().stopWatch.stop();
return neighbors;
}
@Override
public void finishContraction() {
chBuilder.replaceSkippedEdges(prepareGraph::getShortcutForPrepareEdge);
}
@Override
public long getAddedShortcutsCount() {
return addedShortcutsCount;
}
@Override
public float getDijkstraSeconds() {
return dijkstraSW.getCurrentSeconds();
}
@Override
public String getStatisticsString() {
return String.format(Locale.ROOT, "degree_approx: %3.1f", meanDegree) + ", priority : " + countingStats + ", " + wpsStatsHeur + ", contraction: " + addingStats + ", " + wpsStatsContr;
}
/**
* This method performs witness searches between all nodes adjacent to the given node and calls the
* given handler for all required shortcuts.
*/
private void findAndHandlePrepareShortcuts(int node, PrepareShortcutHandler shortcutHandler, int maxPolls, EdgeBasedWitnessPathSearcher.Stats wpsStats) {
stats().nodes++;
addedShortcuts.clear();
sourceNodes.clear();
// traverse incoming edges/shortcuts to find all the source nodes
PrepareGraphEdgeIterator incomingEdges = inEdgeExplorer.setBaseNode(node);
while (incomingEdges.next()) {
final int sourceNode = incomingEdges.getAdjNode();
if (sourceNode == node)
continue;
// make sure we process each source node only once
if (!sourceNodes.add(sourceNode))
continue;
// for each source node we need to look at every incoming original edge and check which target edges are reachable
PrepareGraphOrigEdgeIterator origInIter = sourceNodeOrigInEdgeExplorer.setBaseNode(sourceNode);
while (origInIter.next()) {
int origInKey = reverseEdgeKey(origInIter.getOrigEdgeKeyLast());
// we search 'bridge paths' leading to the target edges
IntObjectMap<BridgePathFinder.BridePathEntry> bridgePaths = bridgePathFinder.find(origInKey, sourceNode, node);
if (bridgePaths.isEmpty())
continue;
witnessPathSearcher.initSearch(origInKey, sourceNode, node, wpsStats);
for (IntObjectCursor<BridgePathFinder.BridePathEntry> bridgePath : bridgePaths) {
if (!Double.isFinite(bridgePath.value.weight))
throw new IllegalStateException("Bridge entry weights should always be finite");
int targetEdgeKey = bridgePath.key;
dijkstraSW.start();
double weight = witnessPathSearcher.runSearch(bridgePath.value.chEntry.adjNode, targetEdgeKey, bridgePath.value.weight, maxPolls);
dijkstraSW.stop();
if (weight <= bridgePath.value.weight)
// we found a witness, nothing to do
continue;
PrepareCHEntry root = bridgePath.value.chEntry;
while (EdgeIterator.Edge.isValid(root.parent.prepareEdge))
root = root.getParent();
// we make sure to add each shortcut only once. when we are actually adding shortcuts we check for existing
// shortcuts anyway, but at least this is important when we *count* shortcuts.
long addedShortcutKey = BitUtil.LITTLE.combineIntsToLong(root.firstEdgeKey, bridgePath.value.chEntry.incEdgeKey);
if (!addedShortcuts.add(addedShortcutKey))
continue;
double initialTurnCost = prepareGraph.getTurnWeight(origInKey, sourceNode, root.firstEdgeKey);
bridgePath.value.chEntry.weight -= initialTurnCost;
LOGGER.trace("Adding shortcuts for target entry {}", bridgePath.value.chEntry);
// todo: re-implement loop-avoidance heuristic as it existed in GH 1.0? it did not work the
// way it was implemented so it was removed at some point
shortcutHandler.handleShortcut(root, bridgePath.value.chEntry, bridgePath.value.chEntry.origEdges);
}
witnessPathSearcher.finishSearch();
}
}
}
/**
* Calls the shortcut handler for all edges and shortcuts adjacent to the given node. After this method is called
* these edges and shortcuts will be removed from the prepare graph, so this method offers the last chance to deal
* with them.
*/
private void insertShortcuts(int node) {
insertOutShortcuts(node);
insertInShortcuts(node);
}
private void insertOutShortcuts(int node) {
PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScFwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void insertInShortcuts(int node) {
PrepareGraphEdgeIterator iter = inEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
// we added loops already using the outEdgeExplorer
if (iter.getAdjNode() == node)
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScBwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void countPreviousEdges(int node) {
// todo: this edge counting can probably be simplified, but we might need to re-optimize heuristic parameters then
PrepareGraphEdgeIterator outIter = outEdgeExplorer.setBaseNode(node);
while (outIter.next()) {
numAllEdges++;
numPrevEdges++;
numPrevOrigEdges += outIter.getOrigEdgeCount();
}
PrepareGraphEdgeIterator inIter = inEdgeExplorer.setBaseNode(node);
while (inIter.next()) {
numAllEdges++;
// do not consider loop edges a second time
if (inIter.getBaseNode() == inIter.getAdjNode())
continue;
numPrevEdges++;
numPrevOrigEdges += inIter.getOrigEdgeCount();
}
}
private void updateHierarchyDepthsOfNeighbors(int node, IntContainer neighbors) {
int level = hierarchyDepths[node];
for (IntCursor n : neighbors) {
if (n.value == node)
continue;
hierarchyDepths[n.value] = Math.max(hierarchyDepths[n.value], level + 1);
}
}
private PrepareCHEntry addShortcutsToPrepareGraph(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
if (edgeTo.parent.prepareEdge != edgeFrom.prepareEdge) {
// counting origEdgeCount correctly is tricky with loop shortcuts and the recursion we use here. so we
// simply ignore this, it probably does not matter that much
PrepareCHEntry prev = addShortcutsToPrepareGraph(edgeFrom, edgeTo.getParent(), origEdgeCount);
return doAddShortcut(prev, edgeTo, origEdgeCount);
} else {
return doAddShortcut(edgeFrom, edgeTo, origEdgeCount);
}
}
private PrepareCHEntry doAddShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int from = edgeFrom.parent.adjNode;
int adjNode = edgeTo.adjNode;
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(from);
while (iter.next()) {
if (!isSameShortcut(iter, adjNode, edgeFrom.firstEdgeKey, edgeTo.incEdgeKey)) {
// this is some other (shortcut) edge -> we do not care
continue;
}
final double existingWeight = iter.getWeight();
if (existingWeight <= edgeTo.weight) {
// our shortcut already exists with lower weight --> do nothing
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, existingWeight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
} else {
// update weight
iter.setSkippedEdges(edgeFrom.prepareEdge, edgeTo.prepareEdge);
iter.setWeight(edgeTo.weight);
iter.setOrigEdgeCount(origEdgeCount);
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
}
// our shortcut is new --> add it
int origFirstKey = edgeFrom.firstEdgeKey;
LOGGER.trace("Adding shortcut from {} to {}, weight: {}, firstOrigEdgeKey: {}, lastOrigEdgeKey: {}",
from, adjNode, edgeTo.weight, origFirstKey, edgeTo.incEdgeKey);
int prepareEdge = prepareGraph.addShortcut(from, adjNode, origFirstKey, edgeTo.incEdgeKey, edgeFrom.prepareEdge, edgeTo.prepareEdge, edgeTo.weight, origEdgeCount);
// does not matter here
int incEdgeKey = -1;
PrepareCHEntry entry = new PrepareCHEntry(prepareEdge, origFirstKey, incEdgeKey, edgeTo.adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
private boolean isSameShortcut(PrepareGraphEdgeIterator iter, int adjNode, int firstOrigEdgeKey, int lastOrigEdgeKey) {
return iter.isShortcut()
&& (iter.getAdjNode() == adjNode)
&& (iter.getOrigEdgeKeyFirst() == firstOrigEdgeKey)
&& (iter.getOrigEdgeKeyLast() == lastOrigEdgeKey);
}
private void resetEdgeCounters() {
numShortcuts = 0;
numPrevEdges = 0;
numOrigEdges = 0;
numPrevOrigEdges = 0;
numAllEdges = 0;
}
@Override
public void close() {
prepareGraph.close();
inEdgeExplorer = null;
outEdgeExplorer = null;
existingShortcutExplorer = null;
sourceNodeOrigInEdgeExplorer = null;
chBuilder = null;
witnessPathSearcher.close();
sourceNodes.release();
targetNodes.release();
addedShortcuts.release();
hierarchyDepths = null;
}
private Stats stats() {
return activeStats;
}
@FunctionalInterface
private interface PrepareShortcutHandler {
void handleShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount);
}
private void countShortcuts(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int fromNode = edgeFrom.parent.adjNode;
int toNode = edgeTo.adjNode;
int firstOrigEdgeKey = edgeFrom.firstEdgeKey;
int lastOrigEdgeKey = edgeTo.incEdgeKey;
// check if this shortcut already exists
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(fromNode);
while (iter.next()) {
if (isSameShortcut(iter, toNode, firstOrigEdgeKey, lastOrigEdgeKey)) {
// this shortcut exists already, maybe its weight will be updated but we should not count it as
// a new edge
return;
}
}
// this shortcut is new --> increase counts
while (edgeTo != edgeFrom) {
numShortcuts++;
edgeTo = edgeTo.parent;
}
numOrigEdges += origEdgeCount;
}
long getNumPolledEdges() {
return wpsStatsContr.numPolls + wpsStatsHeur.numPolls;
}
public static class Params {
private float edgeQuotientWeight = 100;
private float originalEdgeQuotientWeight = 100;
private float hierarchyDepthWeight = 20;
// Increasing these parameters (heuristic especially) will lead to a longer preparation time but also to fewer
// shortcuts and possibly (slightly) faster queries.
private double maxPollFactorHeuristic = 5;
private double maxPollFactorContraction = 200;
}
private static class Stats {
int nodes;
StopWatch stopWatch = new StopWatch();
@Override
public String toString() {
return String.format(Locale.ROOT,
"time: %7.2fs, nodes: %10s", stopWatch.getCurrentSeconds(), nf(nodes));
}
}
}
| utagawal/mtb-router | mtb-router/core/src/main/java/com/graphhopper/routing/ch/EdgeBasedNodeContractor.java | 5,702 | // does not matter here | line_comment | nl | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing.ch;
import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.graphhopper.storage.CHStorageBuilder;
import com.graphhopper.util.BitUtil;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.PMap;
import com.graphhopper.util.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Locale;
import static com.graphhopper.routing.ch.CHParameters.*;
import static com.graphhopper.util.GHUtility.reverseEdgeKey;
import static com.graphhopper.util.Helper.nf;
/**
* This class is used to calculate the priority of or contract a given node in edge-based Contraction Hierarchies as it
* is required to support turn-costs. This implementation follows the 'aggressive' variant described in
* 'Efficient Routing in Road Networks with Turn Costs' by R. Geisberger and C. Vetter. Here, we do not store the center
* node for each shortcut, but introduce helper shortcuts when a loop shortcut is encountered.
* <p>
* This class is mostly concerned with triggering the required local searches and introducing the necessary shortcuts
* or calculating the node priority, while the actual searches for witness paths are delegated to
* {@link EdgeBasedWitnessPathSearcher}.
*
* @author easbar
*/
class EdgeBasedNodeContractor implements NodeContractor {
private static final Logger LOGGER = LoggerFactory.getLogger(EdgeBasedNodeContractor.class);
private final CHPreparationGraph prepareGraph;
private PrepareGraphEdgeExplorer inEdgeExplorer;
private PrepareGraphEdgeExplorer outEdgeExplorer;
private PrepareGraphEdgeExplorer existingShortcutExplorer;
private PrepareGraphOrigEdgeExplorer sourceNodeOrigInEdgeExplorer;
private CHStorageBuilder chBuilder;
private final Params params = new Params();
private final StopWatch dijkstraSW = new StopWatch();
// temporary data used during node contraction
private final IntSet sourceNodes = new IntHashSet(10);
private final IntSet targetNodes = new IntHashSet(10);
private final LongSet addedShortcuts = new LongHashSet();
private final Stats addingStats = new Stats();
private final Stats countingStats = new Stats();
private Stats activeStats;
private int[] hierarchyDepths;
private EdgeBasedWitnessPathSearcher witnessPathSearcher;
private BridgePathFinder bridgePathFinder;
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsHeur = new EdgeBasedWitnessPathSearcher.Stats();
private final EdgeBasedWitnessPathSearcher.Stats wpsStatsContr = new EdgeBasedWitnessPathSearcher.Stats();
// counts the total number of added shortcuts
private int addedShortcutsCount;
// edge counts used to calculate priority
private int numShortcuts;
private int numPrevEdges;
private int numOrigEdges;
private int numPrevOrigEdges;
private int numAllEdges;
private double meanDegree;
public EdgeBasedNodeContractor(CHPreparationGraph prepareGraph, CHStorageBuilder chBuilder, PMap pMap) {
this.prepareGraph = prepareGraph;
this.chBuilder = chBuilder;
extractParams(pMap);
}
private void extractParams(PMap pMap) {
params.edgeQuotientWeight = pMap.getFloat(EDGE_QUOTIENT_WEIGHT, params.edgeQuotientWeight);
params.originalEdgeQuotientWeight = pMap.getFloat(ORIGINAL_EDGE_QUOTIENT_WEIGHT, params.originalEdgeQuotientWeight);
params.hierarchyDepthWeight = pMap.getFloat(HIERARCHY_DEPTH_WEIGHT, params.hierarchyDepthWeight);
params.maxPollFactorHeuristic = pMap.getDouble(MAX_POLL_FACTOR_HEURISTIC_EDGE, params.maxPollFactorHeuristic);
params.maxPollFactorContraction = pMap.getDouble(MAX_POLL_FACTOR_CONTRACTION_EDGE, params.maxPollFactorContraction);
}
@Override
public void initFromGraph() {
inEdgeExplorer = prepareGraph.createInEdgeExplorer();
outEdgeExplorer = prepareGraph.createOutEdgeExplorer();
existingShortcutExplorer = prepareGraph.createOutEdgeExplorer();
sourceNodeOrigInEdgeExplorer = prepareGraph.createInOrigEdgeExplorer();
hierarchyDepths = new int[prepareGraph.getNodes()];
witnessPathSearcher = new EdgeBasedWitnessPathSearcher(prepareGraph);
bridgePathFinder = new BridgePathFinder(prepareGraph);
meanDegree = prepareGraph.getOriginalEdges() * 1.0 / prepareGraph.getNodes();
}
@Override
public float calculatePriority(int node) {
activeStats = countingStats;
resetEdgeCounters();
countPreviousEdges(node);
if (numAllEdges == 0)
// this node is isolated, maybe it belongs to a removed subnetwork, in any case we can quickly contract it
// no shortcuts will be introduced
return Float.NEGATIVE_INFINITY;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::countShortcuts, (int) (meanDegree * params.maxPollFactorHeuristic), wpsStatsHeur);
stats().stopWatch.stop();
// the higher the priority the later (!) this node will be contracted
float edgeQuotient = numShortcuts / (float) (prepareGraph.getDegree(node));
float origEdgeQuotient = numOrigEdges / (float) numPrevOrigEdges;
int hierarchyDepth = hierarchyDepths[node];
float priority = params.edgeQuotientWeight * edgeQuotient +
params.originalEdgeQuotientWeight * origEdgeQuotient +
params.hierarchyDepthWeight * hierarchyDepth;
if (LOGGER.isTraceEnabled())
LOGGER.trace("node: {}, eq: {} / {} = {}, oeq: {} / {} = {}, depth: {} --> {}",
node,
numShortcuts, numPrevEdges, edgeQuotient,
numOrigEdges, numPrevOrigEdges, origEdgeQuotient,
hierarchyDepth, priority);
return priority;
}
@Override
public IntContainer contractNode(int node) {
activeStats = addingStats;
stats().stopWatch.start();
findAndHandlePrepareShortcuts(node, this::addShortcutsToPrepareGraph, (int) (meanDegree * params.maxPollFactorContraction), wpsStatsContr);
insertShortcuts(node);
IntContainer neighbors = prepareGraph.disconnect(node);
// We maintain an approximation of the mean degree which we update after every contracted node.
// We do it the same way as for node-based CH for now.
meanDegree = (meanDegree * 2 + neighbors.size()) / 3;
updateHierarchyDepthsOfNeighbors(node, neighbors);
stats().stopWatch.stop();
return neighbors;
}
@Override
public void finishContraction() {
chBuilder.replaceSkippedEdges(prepareGraph::getShortcutForPrepareEdge);
}
@Override
public long getAddedShortcutsCount() {
return addedShortcutsCount;
}
@Override
public float getDijkstraSeconds() {
return dijkstraSW.getCurrentSeconds();
}
@Override
public String getStatisticsString() {
return String.format(Locale.ROOT, "degree_approx: %3.1f", meanDegree) + ", priority : " + countingStats + ", " + wpsStatsHeur + ", contraction: " + addingStats + ", " + wpsStatsContr;
}
/**
* This method performs witness searches between all nodes adjacent to the given node and calls the
* given handler for all required shortcuts.
*/
private void findAndHandlePrepareShortcuts(int node, PrepareShortcutHandler shortcutHandler, int maxPolls, EdgeBasedWitnessPathSearcher.Stats wpsStats) {
stats().nodes++;
addedShortcuts.clear();
sourceNodes.clear();
// traverse incoming edges/shortcuts to find all the source nodes
PrepareGraphEdgeIterator incomingEdges = inEdgeExplorer.setBaseNode(node);
while (incomingEdges.next()) {
final int sourceNode = incomingEdges.getAdjNode();
if (sourceNode == node)
continue;
// make sure we process each source node only once
if (!sourceNodes.add(sourceNode))
continue;
// for each source node we need to look at every incoming original edge and check which target edges are reachable
PrepareGraphOrigEdgeIterator origInIter = sourceNodeOrigInEdgeExplorer.setBaseNode(sourceNode);
while (origInIter.next()) {
int origInKey = reverseEdgeKey(origInIter.getOrigEdgeKeyLast());
// we search 'bridge paths' leading to the target edges
IntObjectMap<BridgePathFinder.BridePathEntry> bridgePaths = bridgePathFinder.find(origInKey, sourceNode, node);
if (bridgePaths.isEmpty())
continue;
witnessPathSearcher.initSearch(origInKey, sourceNode, node, wpsStats);
for (IntObjectCursor<BridgePathFinder.BridePathEntry> bridgePath : bridgePaths) {
if (!Double.isFinite(bridgePath.value.weight))
throw new IllegalStateException("Bridge entry weights should always be finite");
int targetEdgeKey = bridgePath.key;
dijkstraSW.start();
double weight = witnessPathSearcher.runSearch(bridgePath.value.chEntry.adjNode, targetEdgeKey, bridgePath.value.weight, maxPolls);
dijkstraSW.stop();
if (weight <= bridgePath.value.weight)
// we found a witness, nothing to do
continue;
PrepareCHEntry root = bridgePath.value.chEntry;
while (EdgeIterator.Edge.isValid(root.parent.prepareEdge))
root = root.getParent();
// we make sure to add each shortcut only once. when we are actually adding shortcuts we check for existing
// shortcuts anyway, but at least this is important when we *count* shortcuts.
long addedShortcutKey = BitUtil.LITTLE.combineIntsToLong(root.firstEdgeKey, bridgePath.value.chEntry.incEdgeKey);
if (!addedShortcuts.add(addedShortcutKey))
continue;
double initialTurnCost = prepareGraph.getTurnWeight(origInKey, sourceNode, root.firstEdgeKey);
bridgePath.value.chEntry.weight -= initialTurnCost;
LOGGER.trace("Adding shortcuts for target entry {}", bridgePath.value.chEntry);
// todo: re-implement loop-avoidance heuristic as it existed in GH 1.0? it did not work the
// way it was implemented so it was removed at some point
shortcutHandler.handleShortcut(root, bridgePath.value.chEntry, bridgePath.value.chEntry.origEdges);
}
witnessPathSearcher.finishSearch();
}
}
}
/**
* Calls the shortcut handler for all edges and shortcuts adjacent to the given node. After this method is called
* these edges and shortcuts will be removed from the prepare graph, so this method offers the last chance to deal
* with them.
*/
private void insertShortcuts(int node) {
insertOutShortcuts(node);
insertInShortcuts(node);
}
private void insertOutShortcuts(int node) {
PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScFwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void insertInShortcuts(int node) {
PrepareGraphEdgeIterator iter = inEdgeExplorer.setBaseNode(node);
while (iter.next()) {
if (!iter.isShortcut())
continue;
// we added loops already using the outEdgeExplorer
if (iter.getAdjNode() == node)
continue;
int shortcut = chBuilder.addShortcutEdgeBased(node, iter.getAdjNode(),
PrepareEncoder.getScBwdDir(), iter.getWeight(),
iter.getSkipped1(), iter.getSkipped2(),
iter.getOrigEdgeKeyFirst(),
iter.getOrigEdgeKeyLast());
prepareGraph.setShortcutForPrepareEdge(iter.getPrepareEdge(), prepareGraph.getOriginalEdges() + shortcut);
addedShortcutsCount++;
}
}
private void countPreviousEdges(int node) {
// todo: this edge counting can probably be simplified, but we might need to re-optimize heuristic parameters then
PrepareGraphEdgeIterator outIter = outEdgeExplorer.setBaseNode(node);
while (outIter.next()) {
numAllEdges++;
numPrevEdges++;
numPrevOrigEdges += outIter.getOrigEdgeCount();
}
PrepareGraphEdgeIterator inIter = inEdgeExplorer.setBaseNode(node);
while (inIter.next()) {
numAllEdges++;
// do not consider loop edges a second time
if (inIter.getBaseNode() == inIter.getAdjNode())
continue;
numPrevEdges++;
numPrevOrigEdges += inIter.getOrigEdgeCount();
}
}
private void updateHierarchyDepthsOfNeighbors(int node, IntContainer neighbors) {
int level = hierarchyDepths[node];
for (IntCursor n : neighbors) {
if (n.value == node)
continue;
hierarchyDepths[n.value] = Math.max(hierarchyDepths[n.value], level + 1);
}
}
private PrepareCHEntry addShortcutsToPrepareGraph(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
if (edgeTo.parent.prepareEdge != edgeFrom.prepareEdge) {
// counting origEdgeCount correctly is tricky with loop shortcuts and the recursion we use here. so we
// simply ignore this, it probably does not matter that much
PrepareCHEntry prev = addShortcutsToPrepareGraph(edgeFrom, edgeTo.getParent(), origEdgeCount);
return doAddShortcut(prev, edgeTo, origEdgeCount);
} else {
return doAddShortcut(edgeFrom, edgeTo, origEdgeCount);
}
}
private PrepareCHEntry doAddShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int from = edgeFrom.parent.adjNode;
int adjNode = edgeTo.adjNode;
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(from);
while (iter.next()) {
if (!isSameShortcut(iter, adjNode, edgeFrom.firstEdgeKey, edgeTo.incEdgeKey)) {
// this is some other (shortcut) edge -> we do not care
continue;
}
final double existingWeight = iter.getWeight();
if (existingWeight <= edgeTo.weight) {
// our shortcut already exists with lower weight --> do nothing
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, existingWeight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
} else {
// update weight
iter.setSkippedEdges(edgeFrom.prepareEdge, edgeTo.prepareEdge);
iter.setWeight(edgeTo.weight);
iter.setOrigEdgeCount(origEdgeCount);
PrepareCHEntry entry = new PrepareCHEntry(iter.getPrepareEdge(), iter.getOrigEdgeKeyFirst(), iter.getOrigEdgeKeyLast(), adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
}
// our shortcut is new --> add it
int origFirstKey = edgeFrom.firstEdgeKey;
LOGGER.trace("Adding shortcut from {} to {}, weight: {}, firstOrigEdgeKey: {}, lastOrigEdgeKey: {}",
from, adjNode, edgeTo.weight, origFirstKey, edgeTo.incEdgeKey);
int prepareEdge = prepareGraph.addShortcut(from, adjNode, origFirstKey, edgeTo.incEdgeKey, edgeFrom.prepareEdge, edgeTo.prepareEdge, edgeTo.weight, origEdgeCount);
// does not<SUF>
int incEdgeKey = -1;
PrepareCHEntry entry = new PrepareCHEntry(prepareEdge, origFirstKey, incEdgeKey, edgeTo.adjNode, edgeTo.weight, origEdgeCount);
entry.parent = edgeFrom.parent;
return entry;
}
private boolean isSameShortcut(PrepareGraphEdgeIterator iter, int adjNode, int firstOrigEdgeKey, int lastOrigEdgeKey) {
return iter.isShortcut()
&& (iter.getAdjNode() == adjNode)
&& (iter.getOrigEdgeKeyFirst() == firstOrigEdgeKey)
&& (iter.getOrigEdgeKeyLast() == lastOrigEdgeKey);
}
private void resetEdgeCounters() {
numShortcuts = 0;
numPrevEdges = 0;
numOrigEdges = 0;
numPrevOrigEdges = 0;
numAllEdges = 0;
}
@Override
public void close() {
prepareGraph.close();
inEdgeExplorer = null;
outEdgeExplorer = null;
existingShortcutExplorer = null;
sourceNodeOrigInEdgeExplorer = null;
chBuilder = null;
witnessPathSearcher.close();
sourceNodes.release();
targetNodes.release();
addedShortcuts.release();
hierarchyDepths = null;
}
private Stats stats() {
return activeStats;
}
@FunctionalInterface
private interface PrepareShortcutHandler {
void handleShortcut(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount);
}
private void countShortcuts(PrepareCHEntry edgeFrom, PrepareCHEntry edgeTo, int origEdgeCount) {
int fromNode = edgeFrom.parent.adjNode;
int toNode = edgeTo.adjNode;
int firstOrigEdgeKey = edgeFrom.firstEdgeKey;
int lastOrigEdgeKey = edgeTo.incEdgeKey;
// check if this shortcut already exists
final PrepareGraphEdgeIterator iter = existingShortcutExplorer.setBaseNode(fromNode);
while (iter.next()) {
if (isSameShortcut(iter, toNode, firstOrigEdgeKey, lastOrigEdgeKey)) {
// this shortcut exists already, maybe its weight will be updated but we should not count it as
// a new edge
return;
}
}
// this shortcut is new --> increase counts
while (edgeTo != edgeFrom) {
numShortcuts++;
edgeTo = edgeTo.parent;
}
numOrigEdges += origEdgeCount;
}
long getNumPolledEdges() {
return wpsStatsContr.numPolls + wpsStatsHeur.numPolls;
}
public static class Params {
private float edgeQuotientWeight = 100;
private float originalEdgeQuotientWeight = 100;
private float hierarchyDepthWeight = 20;
// Increasing these parameters (heuristic especially) will lead to a longer preparation time but also to fewer
// shortcuts and possibly (slightly) faster queries.
private double maxPollFactorHeuristic = 5;
private double maxPollFactorContraction = 200;
}
private static class Stats {
int nodes;
StopWatch stopWatch = new StopWatch();
@Override
public String toString() {
return String.format(Locale.ROOT,
"time: %7.2fs, nodes: %10s", stopWatch.getCurrentSeconds(), nf(nodes));
}
}
}
|
134854_1 |
package jdd.util;
/**
* This class contains the various configuration parameters used in the package
*
*/
public class Configuration {
// ---- [ dont change the defualt values here ] --------------------------------
/**
* number of garbage collection we will wait before giving up an unused partial cache.
* @see jdd.bdd.OptimizedCache
*/
public static final int MAX_KEEP_UNUSED_PARTIAL_CACHE = 5;
/**
* the smallest node-table we will allow
* @see jdd.bdd.NodeTable
*/
public static final int MIN_NODETABLE_SIZE = 100;
/**
* the smallest we will allow
* @see jdd.bdd.SimpleCache
*/
public static final int MIN_CACHE_SIZE = 32;
// --- [ default values for tweakable parameters ] ------------------------
// note-table
public static int DEFAULT_NODETABLE_SIMPLE_DEADCOUNT_THRESHOLD = 20000; /** see #nodetableSimpleDeadcountThreshold */
public static final int DEFAULT_NODETABLE_SMALL_SIZE = 200000; /** @see #nodetableSmallSize*/
public static final int DEFAULT_NODETABLE_LARGE_SIZE = 4000000; /** @see #nodetableLargeSize */
public static final int DEFAULT_NODETABLE_GROW_MIN = 50000; /** @see #nodetableGrowMin */
public static final int DEFAULT_NODETABLE_GROW_MAX = 300000; /** @see #nodetableGrowMax */
// bdd
public final static int DEFAULT_BDD_OPCACHE_DIV = 1; /** see #bddOpcacheDiv */
public final static int DEFAULT_BDD_NEGCACHE_DIV = 2; /** see #bddNegcacheDiv */
public final static int DEFAULT_BDD_ITECACHE_DIV = 4; /** see #bddItecacheDiv */
public final static int DEFAULT_BDD_QUANTCACHE_DIV = 3; /** see #bddOpcacheDiv */
public final static int DEFAULT_BDD_RELPRODCACHE_DIV = 2; /** see #bddRelprodcacheDiv */
public final static int DEFAULT_BDD_REPLACECACHE_DIV = 3; /** see #bddReplacecheDiv */
public final static int DEFAULT_BDD_SATCOUNT_DIV = 8; /** see #bddSatcountDiv */
public final static int DEFAULT_MAX_NODE_INCREASE = 100000; /** see #maxNodeIncrease */
public final static int DEFAULT_MIN_FREE_NODES_PROCENT = 20; /** see #minFreeNodesProcent */
public final static int DEFAULT_MAX_NODE_FREE = DEFAULT_MAX_NODE_INCREASE; /** see #maxNodeFree */
public final static int DEFAULT_MAX_SIMPLECACHE_GROWS = 5; /** see #maxSimplecacheGrows */
public final static int DEFAULT_MIN_SIMPLECACHE_HITRATE_TO_GROW = 40; /** see #minSimplecacheHitrateToGrow */
public final static int DEFAULT_MIN_SIMPLECACHE_ACCESS_TO_GROW = 15; /** see #minSimplecacheAccessToGrow */
public final static byte DEFAULT_CACHEENTRY_STICKY_HITS = 16; /** see #cacheentryStickyHits */
public final static int DEFAULT_MAX_CACHE_GROWS = 3; /** see #maxCacheGrows */
public final static int DEFAULT_MIN_CACHE_LOADFACTOR_TO_GROW = 95; /** see #minCacheLoadfactorToGrow */
// -------- node table
/** the threshold below which a simpler deadnode counter is used */
public static int nodetableSimpleDeadcountThreshold = DEFAULT_NODETABLE_SIMPLE_DEADCOUNT_THRESHOLD;
/** if node-table is smaller than this, we grow table with nodetableGrowMax nodes at a time */
public static int nodetableSmallSize = DEFAULT_NODETABLE_SMALL_SIZE;
/** if node-table is larger than this, we grow table with nodetableGrowMin nodes at a time */
public static int nodetableLargeSize = DEFAULT_NODETABLE_LARGE_SIZE;
/** the smallest node-table grow we recommend */
public static int nodetableGrowMin = DEFAULT_NODETABLE_GROW_MIN;
/** the largest node-table grow we allow */
public static int nodetableGrowMax = DEFAULT_NODETABLE_GROW_MAX;
// --- BDD node/hashtbale
// -- BDD.java
/** default size of the BDD cache range: 100-10k */
public final static int DEFAULT_BDD_CACHE_SIZE = 1000;
/** how little of the BDD cache is used for operations ?, range: 1-8 */
public static int bddOpcacheDiv = DEFAULT_BDD_OPCACHE_DIV;
/** how little of the BDD cache is used for negation?, range: 1-8 */
public static int bddNegcacheDiv = DEFAULT_BDD_NEGCACHE_DIV;
/** how little of the BDD cache is used for ITE?, range: 1-8 */
public static int bddItecacheDiv = DEFAULT_BDD_ITECACHE_DIV;
/** how little of the BDD cache is used for quantification?, range: 1-8 */
public static int bddQuantcacheDiv = DEFAULT_BDD_QUANTCACHE_DIV;
/** cache for relProd */
public final static int bddRelprodcacheDiv = DEFAULT_BDD_RELPRODCACHE_DIV;
/** how little the replace cache is, range: 2-8 */
public final static int bddReplacecacheDiv = DEFAULT_BDD_REPLACECACHE_DIV;
/** how little the satcount cache is, range: 4-32 */
public final static int bddSatcountDiv = DEFAULT_BDD_SATCOUNT_DIV;
// -- ZDD.java
/**
* default size of the ZDD cache range:
* @see #DEFAULT_BDD_CACHE_SIZE
*/
public final static int DEFAULT_ZDD_CACHE_SIZE = DEFAULT_BDD_CACHE_SIZE;
public final static int ZDD_UNARY_CACHE_DIV = 2; /** see #zddUnaryCacheDiv */
public final static int ZDD_BINARY_CACHE_DIV = 2; /** see #zddBinaryCacheDiv */
public final static int ZDD_UNATE_CACHE_DIV = 2; /** see #zddUnateCacheDiv */
public final static int ZDD_CSP_CACHE_DIV = 2; /** see #zddCSPCacheDiv */
public final static int ZDD_GRAPH_CACHE_DIV = 2; /** see #zddGraphCacheDiv */
/** how small the unary (subset/change) cache is, range: 2-8 */
public static int zddUnaryCacheDiv = ZDD_UNARY_CACHE_DIV;
/** how small the binary (set operations) cache is, range: 2-8 */
public static int zddBinaryCacheDiv = ZDD_BINARY_CACHE_DIV;
/** how small the unate (mul/div) cache is, range: 2-8 */
public static int zddUnateCacheDiv = ZDD_UNATE_CACHE_DIV;
/** how small the CSP (restrict/exclude) cache is, range: 2-8 */
public static int zddCSPCacheDiv = ZDD_CSP_CACHE_DIV;
/** how small the Graph cache is, range: 2-8 */
public static int zddGraphCacheDiv = ZDD_GRAPH_CACHE_DIV;
// --------- NodeTable.java
/** we wont grow the table with more than this amount, range: 10k-200k */
public static int maxNodeIncrease = DEFAULT_MAX_NODE_INCREASE;
/**
* if less than this precent nodes are free, we will garbage collect,
* or grow the nodetable, range: 5-40. [this constant is tested against MAX_NODE_FREE ]
*/
public static int minFreeNodesProcent = DEFAULT_MIN_FREE_NODES_PROCENT;
/** maximum number of nodes we that must be free, range: same as MAX_NODE_INCREASE?? */
public static int maxNodeFree = DEFAULT_MAX_NODE_FREE;
// -- SimpleCache.java
/** max number of cache grows allowed, rang: 0-15 */
public static int maxSimplecacheGrows = DEFAULT_MAX_SIMPLECACHE_GROWS;
/** min hitrate needed to grow cache (in %), range: 10-99 */
public static int minSimplecacheHitrateToGrow = DEFAULT_MIN_SIMPLECACHE_HITRATE_TO_GROW;
/** min access load before we consider the hitrate above valid, range: 1-99 */
public static int minSimplecacheAccessToGrow = DEFAULT_MIN_SIMPLECACHE_ACCESS_TO_GROW;
// -- Cache.java
/** max number of grows for the Cache, range: 0-10 */
public final static int maxCacheGrows = DEFAULT_MAX_CACHE_GROWS;
/** loadfactor required for Cache to grow, rang: 50-99 */
public final static int minCacheLoadfactorToGrow = DEFAULT_MIN_CACHE_LOADFACTOR_TO_GROW;
// -- CacheEntry.java
/** above this number of hits, a cached value cannot be overwritten, range: 8-32 */
public static byte cacheentryStickyHits = DEFAULT_CACHEENTRY_STICKY_HITS;
}
| utopia-group/SmartPulseTool | trunk/source/Library-JavaBDD/src/jdd/util/Configuration.java | 2,578 | // ---- [ dont change the defualt values here ] -------------------------------- | line_comment | nl |
package jdd.util;
/**
* This class contains the various configuration parameters used in the package
*
*/
public class Configuration {
// ---- [<SUF>
/**
* number of garbage collection we will wait before giving up an unused partial cache.
* @see jdd.bdd.OptimizedCache
*/
public static final int MAX_KEEP_UNUSED_PARTIAL_CACHE = 5;
/**
* the smallest node-table we will allow
* @see jdd.bdd.NodeTable
*/
public static final int MIN_NODETABLE_SIZE = 100;
/**
* the smallest we will allow
* @see jdd.bdd.SimpleCache
*/
public static final int MIN_CACHE_SIZE = 32;
// --- [ default values for tweakable parameters ] ------------------------
// note-table
public static int DEFAULT_NODETABLE_SIMPLE_DEADCOUNT_THRESHOLD = 20000; /** see #nodetableSimpleDeadcountThreshold */
public static final int DEFAULT_NODETABLE_SMALL_SIZE = 200000; /** @see #nodetableSmallSize*/
public static final int DEFAULT_NODETABLE_LARGE_SIZE = 4000000; /** @see #nodetableLargeSize */
public static final int DEFAULT_NODETABLE_GROW_MIN = 50000; /** @see #nodetableGrowMin */
public static final int DEFAULT_NODETABLE_GROW_MAX = 300000; /** @see #nodetableGrowMax */
// bdd
public final static int DEFAULT_BDD_OPCACHE_DIV = 1; /** see #bddOpcacheDiv */
public final static int DEFAULT_BDD_NEGCACHE_DIV = 2; /** see #bddNegcacheDiv */
public final static int DEFAULT_BDD_ITECACHE_DIV = 4; /** see #bddItecacheDiv */
public final static int DEFAULT_BDD_QUANTCACHE_DIV = 3; /** see #bddOpcacheDiv */
public final static int DEFAULT_BDD_RELPRODCACHE_DIV = 2; /** see #bddRelprodcacheDiv */
public final static int DEFAULT_BDD_REPLACECACHE_DIV = 3; /** see #bddReplacecheDiv */
public final static int DEFAULT_BDD_SATCOUNT_DIV = 8; /** see #bddSatcountDiv */
public final static int DEFAULT_MAX_NODE_INCREASE = 100000; /** see #maxNodeIncrease */
public final static int DEFAULT_MIN_FREE_NODES_PROCENT = 20; /** see #minFreeNodesProcent */
public final static int DEFAULT_MAX_NODE_FREE = DEFAULT_MAX_NODE_INCREASE; /** see #maxNodeFree */
public final static int DEFAULT_MAX_SIMPLECACHE_GROWS = 5; /** see #maxSimplecacheGrows */
public final static int DEFAULT_MIN_SIMPLECACHE_HITRATE_TO_GROW = 40; /** see #minSimplecacheHitrateToGrow */
public final static int DEFAULT_MIN_SIMPLECACHE_ACCESS_TO_GROW = 15; /** see #minSimplecacheAccessToGrow */
public final static byte DEFAULT_CACHEENTRY_STICKY_HITS = 16; /** see #cacheentryStickyHits */
public final static int DEFAULT_MAX_CACHE_GROWS = 3; /** see #maxCacheGrows */
public final static int DEFAULT_MIN_CACHE_LOADFACTOR_TO_GROW = 95; /** see #minCacheLoadfactorToGrow */
// -------- node table
/** the threshold below which a simpler deadnode counter is used */
public static int nodetableSimpleDeadcountThreshold = DEFAULT_NODETABLE_SIMPLE_DEADCOUNT_THRESHOLD;
/** if node-table is smaller than this, we grow table with nodetableGrowMax nodes at a time */
public static int nodetableSmallSize = DEFAULT_NODETABLE_SMALL_SIZE;
/** if node-table is larger than this, we grow table with nodetableGrowMin nodes at a time */
public static int nodetableLargeSize = DEFAULT_NODETABLE_LARGE_SIZE;
/** the smallest node-table grow we recommend */
public static int nodetableGrowMin = DEFAULT_NODETABLE_GROW_MIN;
/** the largest node-table grow we allow */
public static int nodetableGrowMax = DEFAULT_NODETABLE_GROW_MAX;
// --- BDD node/hashtbale
// -- BDD.java
/** default size of the BDD cache range: 100-10k */
public final static int DEFAULT_BDD_CACHE_SIZE = 1000;
/** how little of the BDD cache is used for operations ?, range: 1-8 */
public static int bddOpcacheDiv = DEFAULT_BDD_OPCACHE_DIV;
/** how little of the BDD cache is used for negation?, range: 1-8 */
public static int bddNegcacheDiv = DEFAULT_BDD_NEGCACHE_DIV;
/** how little of the BDD cache is used for ITE?, range: 1-8 */
public static int bddItecacheDiv = DEFAULT_BDD_ITECACHE_DIV;
/** how little of the BDD cache is used for quantification?, range: 1-8 */
public static int bddQuantcacheDiv = DEFAULT_BDD_QUANTCACHE_DIV;
/** cache for relProd */
public final static int bddRelprodcacheDiv = DEFAULT_BDD_RELPRODCACHE_DIV;
/** how little the replace cache is, range: 2-8 */
public final static int bddReplacecacheDiv = DEFAULT_BDD_REPLACECACHE_DIV;
/** how little the satcount cache is, range: 4-32 */
public final static int bddSatcountDiv = DEFAULT_BDD_SATCOUNT_DIV;
// -- ZDD.java
/**
* default size of the ZDD cache range:
* @see #DEFAULT_BDD_CACHE_SIZE
*/
public final static int DEFAULT_ZDD_CACHE_SIZE = DEFAULT_BDD_CACHE_SIZE;
public final static int ZDD_UNARY_CACHE_DIV = 2; /** see #zddUnaryCacheDiv */
public final static int ZDD_BINARY_CACHE_DIV = 2; /** see #zddBinaryCacheDiv */
public final static int ZDD_UNATE_CACHE_DIV = 2; /** see #zddUnateCacheDiv */
public final static int ZDD_CSP_CACHE_DIV = 2; /** see #zddCSPCacheDiv */
public final static int ZDD_GRAPH_CACHE_DIV = 2; /** see #zddGraphCacheDiv */
/** how small the unary (subset/change) cache is, range: 2-8 */
public static int zddUnaryCacheDiv = ZDD_UNARY_CACHE_DIV;
/** how small the binary (set operations) cache is, range: 2-8 */
public static int zddBinaryCacheDiv = ZDD_BINARY_CACHE_DIV;
/** how small the unate (mul/div) cache is, range: 2-8 */
public static int zddUnateCacheDiv = ZDD_UNATE_CACHE_DIV;
/** how small the CSP (restrict/exclude) cache is, range: 2-8 */
public static int zddCSPCacheDiv = ZDD_CSP_CACHE_DIV;
/** how small the Graph cache is, range: 2-8 */
public static int zddGraphCacheDiv = ZDD_GRAPH_CACHE_DIV;
// --------- NodeTable.java
/** we wont grow the table with more than this amount, range: 10k-200k */
public static int maxNodeIncrease = DEFAULT_MAX_NODE_INCREASE;
/**
* if less than this precent nodes are free, we will garbage collect,
* or grow the nodetable, range: 5-40. [this constant is tested against MAX_NODE_FREE ]
*/
public static int minFreeNodesProcent = DEFAULT_MIN_FREE_NODES_PROCENT;
/** maximum number of nodes we that must be free, range: same as MAX_NODE_INCREASE?? */
public static int maxNodeFree = DEFAULT_MAX_NODE_FREE;
// -- SimpleCache.java
/** max number of cache grows allowed, rang: 0-15 */
public static int maxSimplecacheGrows = DEFAULT_MAX_SIMPLECACHE_GROWS;
/** min hitrate needed to grow cache (in %), range: 10-99 */
public static int minSimplecacheHitrateToGrow = DEFAULT_MIN_SIMPLECACHE_HITRATE_TO_GROW;
/** min access load before we consider the hitrate above valid, range: 1-99 */
public static int minSimplecacheAccessToGrow = DEFAULT_MIN_SIMPLECACHE_ACCESS_TO_GROW;
// -- Cache.java
/** max number of grows for the Cache, range: 0-10 */
public final static int maxCacheGrows = DEFAULT_MAX_CACHE_GROWS;
/** loadfactor required for Cache to grow, rang: 50-99 */
public final static int minCacheLoadfactorToGrow = DEFAULT_MIN_CACHE_LOADFACTOR_TO_GROW;
// -- CacheEntry.java
/** above this number of hits, a cached value cannot be overwritten, range: 8-32 */
public static byte cacheentryStickyHits = DEFAULT_CACHEENTRY_STICKY_HITS;
}
|
40040_7 | package nl.utwente.db.named_entity_recog;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import nl.utwente.db.neogeo.utils.WebUtils;
public class TomTom {
private GeoNameEntityTable entityDB = null;
private static final boolean storeInDB = false; // set to true when running real scraper
public TomTom(Connection c) throws SQLException {
this.entityDB = new GeoNameEntityTable( GeoNamesDB.geoNameDBConnection() );
}
public void runTEST() throws IOException, SQLException {
if ( true ) {
// read small chunk of VRT Twente restaurants from file
handleReadPlacesRequest( new BufferedReader(new FileReader("/Users/flokstra/tomtom/Restaurants50/vrt-rest-0000_0050.json")) );
}
if ( false ) {
// read all CRT Twente places
readAllPlaces("&sw=52.0,6.2&ne=52.5,7.2","&what=Restaurants"); // VRT rest
}
if ( false ) {
// read the Groningen area, places
double lat = 53.2;
double lon = 6.5;
double delta = 0.4;
readAllPlaces("&sw="+(lat-delta)+","+(lon-delta)+"&ne="+(lat+delta)+","+(lon+delta),"");
}
}
public void readAllPlaces(String bbox, String what) throws IOException, SQLException {
int count = 0;
boolean cont = true;
while ( cont ) {
int nRead = readPlacesSlice(bbox,what,count,50);
if ( nRead == 0 )
cont = false;
else
count += nRead;
// cont = false;
}
}
public int readPlacesSlice(String bbox, String what, int places2start, int places2read) throws IOException, SQLException {
String url_str="http://api.tomtom.com/places/search/1/place?key=aadnffgkrxfkbrhbp4mgvguz"+bbox+what+"&results="+places2read+"&start="+places2start+"&format=json&searchId=249cfb70-f2ef-11e3-8ce6-ea75e91104fd";
URL url = new URL(url_str);
// System.out.println("URL="+url_str);
return handleReadPlacesRequest( new BufferedReader(new InputStreamReader(url.openStream())) );
}
//
private int handleReadPlacesRequest(BufferedReader br) throws IOException, SQLException {
int placesRead = 0;
JsonReader jsonReader = Json.createReader(br);
JsonObject jo = jsonReader.readObject(); // incomplete, check errors
jsonReader.close();
//
JsonObject response = jo.getJsonObject("response");
JsonObject data = response.getJsonObject("data");
System.out.println("data="+data);
JsonObject data_main = data.getJsonObject("main");
System.out.println("Total #requests="+data_main.getInt("totalNumberOfResults"));
int results = data_main.getInt("numberOfResults");
System.out.println("Total #results="+results);
if ( results == 0 )
return 0;
JsonArray places = data.getJsonObject("places").getJsonArray("place");
for (int i=0; i<places.size(); i++) {
JsonObject place = places.getJsonObject(i);
//
JsonObject name = place.getJsonObject("name");
String name_str = name.getString("$");
System.out.println("Name: "+name_str);
//
int first_category_nr = 0;
String category_str = null;
if ( true ) {
JsonArray categories = place.getJsonObject("categories").getJsonArray("category");
for (int j=0; j<categories.size(); j++) {
JsonObject category = categories.getJsonObject(j);
String newcat = category.getString("name");
int newcat_id = new Integer(category.getString("@id")).intValue();
System.out.println("Categorie: "+newcat);
if ( first_category_nr == 0 ) {
first_category_nr = newcat_id;
category_str = newcat;
} else {
category_str += (","+newcat);
}
entityDB.defineCategory(newcat_id, newcat);
System.out.println("Cat#: "+first_category_nr);
}
// INCOMPLETE: als laatste, voor elke category 1 record genereren.
// INCOMPLETE: id klopt niet met lijst op website, ????, make auto tabel, alles lc
// tabel: tt_poi_category [name,id]
}
//
JsonObject city = place.getJsonObject("city");
String city_str = city.getString("$");
// System.out.println("City: "+city_str);
JsonObject province = place.getJsonObject("province");
String province_str = province.getString("$");
// System.out.println("Province: "+province_str);
String fmaddr_str = place.getString("formattedAddress");
// String fmaddr_str = city.getString("$");
System.out.println("Full Adres: "+fmaddr_str);
//
JsonNumber lat = place.getJsonNumber("latitude");
JsonNumber lon = place.getJsonNumber("longitude");
System.out.println("lat/lon="+lat+"/"+lon);
//
if ( storeInDB ) {
entityDB.insertEntity(name_str, new Integer(first_category_nr).intValue(), category_str, city_str, province_str, fmaddr_str, 1/*count_nl*/, lon.doubleValue(), lat.doubleValue());
}
placesRead++;
}
if ( true )
System.out.println("#! read "+placesRead + " Places!");
return placesRead;
}
private static int step = 50;
private static int limit = 1750; // 1750 rest / 58350 voor all
public static final String restaurantDir = "/Users/flokstra/tomtom/Restaurants_RAW/";
public static final String allplaceDir = "/Users/flokstra/tomtom/VrtAll_RAW/";
public static final String baseDir = restaurantDir;
public String restFileName(String base, String pfx, String kind, int from, int step) {
return base+pfx+"-"+kind+"-"+(from)+"_"+(from+step)+".json";
}
public void test2() throws IOException {
String what = "&what=Restaurants";
int count = 0;
while ( count < limit ) {
String url="http://api.tomtom.com/places/search/1/place?key=aadnffgkrxfkbrhbp4mgvguz&sw=52.0,6.2&ne=52.5,7.2"+what+"&results="+step+"&start="+count+"&format=json&searchId=249cfb70-f2ef-11e3-8ce6-ea75e91104fd";
System.out.println("- "+count+"-"+(count+step));
System.out.println(url);
url2file(url, restFileName(baseDir,"vrt","rest",count,step));
count += step;
}
}
public void test2all() throws IOException {
String what = "";
int count = 0;
while ( count < 58350 ) {
String url="http://api.tomtom.com/places/search/1/place?key=aadnffgkrxfkbrhbp4mgvguz&sw=52.0,6.2&ne=52.5,7.2"+what+"&results="+step+"&start="+count+"&format=json&searchId=249cfb70-f2ef-11e3-8ce6-ea75e91104fd";
System.out.println("- "+count+"-"+(count+step));
System.out.println(url);
url2file(url, restFileName(allplaceDir,"vrt","all",count,step));
count += step;
}
}
public static void url2file(String url, String fileName) throws IOException {
String doc = WebUtils.getContent(url);
if ( doc == null )
throw new FileNotFoundException("URL not found: "+url);
PrintWriter out = new PrintWriter(fileName);
out.print(doc);
out.close();
}
public static void main(String[] args) {
try {
TomTom tomtom = new TomTom( GeoNamesDB.geoNameDBConnection() );
tomtom.runTEST();
} catch (Exception e) {
System.out.println("CAUGHT: "+e);
e.printStackTrace();
}
}
} | utwente-db/neogeo | named-entity-recog/src/main/java/nl/utwente/db/named_entity_recog/TomTom.java | 2,595 | // INCOMPLETE: id klopt niet met lijst op website, ????, make auto tabel, alles lc | line_comment | nl | package nl.utwente.db.named_entity_recog;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import nl.utwente.db.neogeo.utils.WebUtils;
public class TomTom {
private GeoNameEntityTable entityDB = null;
private static final boolean storeInDB = false; // set to true when running real scraper
public TomTom(Connection c) throws SQLException {
this.entityDB = new GeoNameEntityTable( GeoNamesDB.geoNameDBConnection() );
}
public void runTEST() throws IOException, SQLException {
if ( true ) {
// read small chunk of VRT Twente restaurants from file
handleReadPlacesRequest( new BufferedReader(new FileReader("/Users/flokstra/tomtom/Restaurants50/vrt-rest-0000_0050.json")) );
}
if ( false ) {
// read all CRT Twente places
readAllPlaces("&sw=52.0,6.2&ne=52.5,7.2","&what=Restaurants"); // VRT rest
}
if ( false ) {
// read the Groningen area, places
double lat = 53.2;
double lon = 6.5;
double delta = 0.4;
readAllPlaces("&sw="+(lat-delta)+","+(lon-delta)+"&ne="+(lat+delta)+","+(lon+delta),"");
}
}
public void readAllPlaces(String bbox, String what) throws IOException, SQLException {
int count = 0;
boolean cont = true;
while ( cont ) {
int nRead = readPlacesSlice(bbox,what,count,50);
if ( nRead == 0 )
cont = false;
else
count += nRead;
// cont = false;
}
}
public int readPlacesSlice(String bbox, String what, int places2start, int places2read) throws IOException, SQLException {
String url_str="http://api.tomtom.com/places/search/1/place?key=aadnffgkrxfkbrhbp4mgvguz"+bbox+what+"&results="+places2read+"&start="+places2start+"&format=json&searchId=249cfb70-f2ef-11e3-8ce6-ea75e91104fd";
URL url = new URL(url_str);
// System.out.println("URL="+url_str);
return handleReadPlacesRequest( new BufferedReader(new InputStreamReader(url.openStream())) );
}
//
private int handleReadPlacesRequest(BufferedReader br) throws IOException, SQLException {
int placesRead = 0;
JsonReader jsonReader = Json.createReader(br);
JsonObject jo = jsonReader.readObject(); // incomplete, check errors
jsonReader.close();
//
JsonObject response = jo.getJsonObject("response");
JsonObject data = response.getJsonObject("data");
System.out.println("data="+data);
JsonObject data_main = data.getJsonObject("main");
System.out.println("Total #requests="+data_main.getInt("totalNumberOfResults"));
int results = data_main.getInt("numberOfResults");
System.out.println("Total #results="+results);
if ( results == 0 )
return 0;
JsonArray places = data.getJsonObject("places").getJsonArray("place");
for (int i=0; i<places.size(); i++) {
JsonObject place = places.getJsonObject(i);
//
JsonObject name = place.getJsonObject("name");
String name_str = name.getString("$");
System.out.println("Name: "+name_str);
//
int first_category_nr = 0;
String category_str = null;
if ( true ) {
JsonArray categories = place.getJsonObject("categories").getJsonArray("category");
for (int j=0; j<categories.size(); j++) {
JsonObject category = categories.getJsonObject(j);
String newcat = category.getString("name");
int newcat_id = new Integer(category.getString("@id")).intValue();
System.out.println("Categorie: "+newcat);
if ( first_category_nr == 0 ) {
first_category_nr = newcat_id;
category_str = newcat;
} else {
category_str += (","+newcat);
}
entityDB.defineCategory(newcat_id, newcat);
System.out.println("Cat#: "+first_category_nr);
}
// INCOMPLETE: als laatste, voor elke category 1 record genereren.
// INCOMPLETE: id<SUF>
// tabel: tt_poi_category [name,id]
}
//
JsonObject city = place.getJsonObject("city");
String city_str = city.getString("$");
// System.out.println("City: "+city_str);
JsonObject province = place.getJsonObject("province");
String province_str = province.getString("$");
// System.out.println("Province: "+province_str);
String fmaddr_str = place.getString("formattedAddress");
// String fmaddr_str = city.getString("$");
System.out.println("Full Adres: "+fmaddr_str);
//
JsonNumber lat = place.getJsonNumber("latitude");
JsonNumber lon = place.getJsonNumber("longitude");
System.out.println("lat/lon="+lat+"/"+lon);
//
if ( storeInDB ) {
entityDB.insertEntity(name_str, new Integer(first_category_nr).intValue(), category_str, city_str, province_str, fmaddr_str, 1/*count_nl*/, lon.doubleValue(), lat.doubleValue());
}
placesRead++;
}
if ( true )
System.out.println("#! read "+placesRead + " Places!");
return placesRead;
}
private static int step = 50;
private static int limit = 1750; // 1750 rest / 58350 voor all
public static final String restaurantDir = "/Users/flokstra/tomtom/Restaurants_RAW/";
public static final String allplaceDir = "/Users/flokstra/tomtom/VrtAll_RAW/";
public static final String baseDir = restaurantDir;
public String restFileName(String base, String pfx, String kind, int from, int step) {
return base+pfx+"-"+kind+"-"+(from)+"_"+(from+step)+".json";
}
public void test2() throws IOException {
String what = "&what=Restaurants";
int count = 0;
while ( count < limit ) {
String url="http://api.tomtom.com/places/search/1/place?key=aadnffgkrxfkbrhbp4mgvguz&sw=52.0,6.2&ne=52.5,7.2"+what+"&results="+step+"&start="+count+"&format=json&searchId=249cfb70-f2ef-11e3-8ce6-ea75e91104fd";
System.out.println("- "+count+"-"+(count+step));
System.out.println(url);
url2file(url, restFileName(baseDir,"vrt","rest",count,step));
count += step;
}
}
public void test2all() throws IOException {
String what = "";
int count = 0;
while ( count < 58350 ) {
String url="http://api.tomtom.com/places/search/1/place?key=aadnffgkrxfkbrhbp4mgvguz&sw=52.0,6.2&ne=52.5,7.2"+what+"&results="+step+"&start="+count+"&format=json&searchId=249cfb70-f2ef-11e3-8ce6-ea75e91104fd";
System.out.println("- "+count+"-"+(count+step));
System.out.println(url);
url2file(url, restFileName(allplaceDir,"vrt","all",count,step));
count += step;
}
}
public static void url2file(String url, String fileName) throws IOException {
String doc = WebUtils.getContent(url);
if ( doc == null )
throw new FileNotFoundException("URL not found: "+url);
PrintWriter out = new PrintWriter(fileName);
out.print(doc);
out.close();
}
public static void main(String[] args) {
try {
TomTom tomtom = new TomTom( GeoNamesDB.geoNameDBConnection() );
tomtom.runTEST();
} catch (Exception e) {
System.out.println("CAUGHT: "+e);
e.printStackTrace();
}
}
} |
33164_40 | package nl.utwente.di.gradeManager.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import nl.utwente.di.gradeManager.db.GradesDB;
import nl.utwente.di.gradeManager.model.Assignment;
import nl.utwente.di.gradeManager.model.AssignmentOccasion;
import nl.utwente.di.gradeManager.model.AssignmentResult;
import nl.utwente.di.gradeManager.model.Course;
import nl.utwente.di.gradeManager.model.Module;
import nl.utwente.di.gradeManager.model.ModuleResult;
import nl.utwente.di.gradeManager.model.Student;
import nl.utwente.di.gradeManager.db.LoginDB;
public class Resulttable extends HttpServlet {
//Alle benodiggde variablen aanmaken
private final String jsp_address = "Student.jsp";
private List<Course> courses;
private List<Assignment> assignments;
private List<AssignmentResult> occasions;
private List<Module> studentmodules;
private Module module;
private ModuleResult moduleResult;
private Student student;
private StudentModules modules;
//Alle informatie uit de database halen en in de locale variablen zetten zodat ze doorgestuurd kunnen worden
protected void setInfo(int personID, int moduleID, int moduleYear){
//Database connectie opzetten
GradesDB gradesDB = new GradesDB();
//Alle database operaties uitvoeren in try-finally zodat de connectie ook wordt afgesloten mocht er iets fout gaan in de queries
try{
//Als de module niet gespecificeerd zijn in de URL, wordt in de 'DoGet' alvast alle modules van de student opgezocht, dus hoeft dat hier niet meer
if(studentmodules == null){
//Alle modules van de student opzoeken
studentmodules = gradesDB.getModulesForStudent(personID);
}
//Alle studentinformatie van de huidig ingelogde student opvragen
student = gradesDB.getStudent(personID);
//Alle modules die de ingelogde student volgt opzoeken
modules = new StudentModules(personID, studentmodules);
//De module opzoeken die op het scherm moet verschijnen
module = gradesDB.getModule(moduleID, moduleYear);
//Alle vakken van de module opzoeken
courses = gradesDB.getCoursesForModule(moduleID);
//Het resultaat van de gehele module opzoeken
moduleResult = gradesDB.getModuleResult(personID, module.getModulecode(), module.getYear());
/**Tijdelijke Assingment lijst aanmaken.
*Moet een arraylist zijn zodat we assignments aan de lijst kunnen toevoegen.
*De variable 'assignments' is een List<Assignment>, hier kunnen we geen extra assignments aan toevoegen nadat we de database-query
*voor 1 vak hebben uitgevoerd
*Daarom hebben de assignmemtList, we lopen elk vak van de module door, en voegen alle assignments van die vakken toe aan de lijst.
*/
List<Assignment> assignmentList = new ArrayList<Assignment>();
//For-loop voor alle vakken van de module
for(int i = 0; i < courses.size(); i++){
//Vraagt alle assignments van 1 vak op
assignments = gradesDB.getAssignmentsForCourse(courses.get(i).getCourseCode(), courses.get(i).getYear());
//Als er assignments zijn, toevoegen aan assignmentlist
if (assignments != null){
//For-loop voor alle assignments in de lijst
for (int j = 0; j < assignments.size(); j++) {
//Assignment toevoegen aan de tijdelijke lijst
if(assignments.get(j) != null){
assignmentList.add(assignments.get(j));
}
}
}
}
//Tijdelijke assignmentlist omzetten naar de uiteindelijke 'assignment' lijst
assignments = assignmentList;
/**
* Tijdelijke AssignmentResult lijst aanmaken
* 'resultList' is een arraylist zodat er element aan toegevoegd kunnen worden
* Dan alle resultaten van alle assignments toevoegen aan de tijdelijke lijst
* Daarna weer tijdelijke lijst terugzetten naar de officiele 'occasions' AssignmentResult lijst
*/
List<AssignmentResult> resultList = new ArrayList<AssignmentResult>();
//Alle assignments doorlopen
//Alle assignments van alle vakken staan al in de lijst, dus hoeven geen vak te specificeren
for(int i = 0; i < assignments.size(); i++){
//Alle resultaten van een assignment opvragen
occasions = gradesDB.getResultsForAssignmentAndStudent(personID, assignments.get(i).getAssignmentID());
//Als er resultaten zijn, deze toevoegen aan de 'resultList'
if (occasions != null){
//Alle resultaten doorlopen
for (int j = 0; j < occasions.size(); j++) {
//Resultaat toevoegen aan de tijdelijke lijst
if(occasions.get(j) != null){
resultList.add(occasions.get(j));
}
}
}
}
//Tijdelijke lijst weer omzetten naar de definitieve lijst
occasions = resultList;
}finally{
//Database connectie afsluiten
gradesDB.closeConnection();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Alle variabelen aanmaken die nodig zijn om de 'setInfo' methode aan te roepen
Integer moduleid;
Integer moduleyear;
Integer SID;
//De sessie van de gebruiker opvragen. Als er geen sessie bestaat, deze niet aanmaken
HttpSession session = request.getSession(false);
//Het ID van de sessie opvragen
if(session != null){
String sessionid = session.getId();
//Database connectie aanmaken
LoginDB logindb = new LoginDB();
try{
//Het studentnummer verbonden aan de huidige sessie in de variabele 'SID' zetten
SID = Integer.parseInt(logindb.getLoggedInPersonid(sessionid).substring(1));
}finally{
//Database connectie afsluiten
logindb.closeConnection();
}
//Als er geen moduleid en moduleyear in de URL wordt gespecificeerd, de meest recente module van de student opzoeken en die tonen
if (request.getParameter("moduleid") == null || request.getParameter("moduleyear") == null){
//Database connectie aanmaken
GradesDB gradesDB = new GradesDB();
try{
//Alle modules van de gebruiker opvragen
studentmodules = gradesDB.getModulesForStudent(SID);
//getModulecode sorteert automatisch op de meest recente module, dus eerste resultaat is de module die getoont moet worden
moduleid = studentmodules.get(0).getModulecode();
moduleyear = studentmodules.get(0).getYear();
}finally{
//Database connectie afsluiten
gradesDB.closeConnection();
}
}else{
//Als er wel een module-id&jaar wordt gespecificeerd, deze uit de URL halen en de locale variabelen stoppen
moduleid = Integer.parseInt(request.getParameter("moduleid"));
moduleyear = Integer.parseInt(request.getParameter("moduleyear"));
}
//Alle informatie is nu bekend, dus nu kan 'setInfo' aangeroepen worden.
setInfo(SID, moduleid, moduleyear);
if(student!= null && modules != null && module != null && moduleResult != null && courses != null && assignments != null && occasions != null){
//De informatie van de student meegeven aan de JSP pagina
request.setAttribute("student", student);
//De lijst van alle modules meegeven aan de JSP pagina
request.setAttribute("studentModules", modules);
//De informatie van de module meegeveen aan de JSP pagina
request.setAttribute("moduletoShow", module);
//Het uiteindelijke moduleresulaat meegeven aan de JSP pagina
request.setAttribute("moduleresulttoShow", moduleResult);
//Bean aanmaken met de lijst van vakken die de student volgt
StudentCourses beanSC = new StudentCourses(SID, courses);
//De bean meegeven aan de JSP pagina
request.setAttribute("coursestoShow", beanSC);
//Bean aanmaken met de lijst van alle assignments van alle vakken van de module
CourseAssignments beanCA = new CourseAssignments("Dit is een vak", assignments);
//De bean meegeven voor de JSP pagina
request.setAttribute("assignmentstoShow", beanCA);
//Bean aanmaken van alle behaalde resultaten van de student
StudentAssignments beanSA = new StudentAssignments("Dit is een resultaat", occasions);
//Bean meegeven aan de JSP pagina
request.setAttribute("resultstoShow", beanSA);
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher(jsp_address);
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
} else {
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}else{
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}
}
| utwente-di/di19 | gradeManager/src/main/java/nl/utwente/di/gradeManager/servlets/Resulttable.java | 2,820 | //De informatie van de student meegeven aan de JSP pagina | line_comment | nl | package nl.utwente.di.gradeManager.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import nl.utwente.di.gradeManager.db.GradesDB;
import nl.utwente.di.gradeManager.model.Assignment;
import nl.utwente.di.gradeManager.model.AssignmentOccasion;
import nl.utwente.di.gradeManager.model.AssignmentResult;
import nl.utwente.di.gradeManager.model.Course;
import nl.utwente.di.gradeManager.model.Module;
import nl.utwente.di.gradeManager.model.ModuleResult;
import nl.utwente.di.gradeManager.model.Student;
import nl.utwente.di.gradeManager.db.LoginDB;
public class Resulttable extends HttpServlet {
//Alle benodiggde variablen aanmaken
private final String jsp_address = "Student.jsp";
private List<Course> courses;
private List<Assignment> assignments;
private List<AssignmentResult> occasions;
private List<Module> studentmodules;
private Module module;
private ModuleResult moduleResult;
private Student student;
private StudentModules modules;
//Alle informatie uit de database halen en in de locale variablen zetten zodat ze doorgestuurd kunnen worden
protected void setInfo(int personID, int moduleID, int moduleYear){
//Database connectie opzetten
GradesDB gradesDB = new GradesDB();
//Alle database operaties uitvoeren in try-finally zodat de connectie ook wordt afgesloten mocht er iets fout gaan in de queries
try{
//Als de module niet gespecificeerd zijn in de URL, wordt in de 'DoGet' alvast alle modules van de student opgezocht, dus hoeft dat hier niet meer
if(studentmodules == null){
//Alle modules van de student opzoeken
studentmodules = gradesDB.getModulesForStudent(personID);
}
//Alle studentinformatie van de huidig ingelogde student opvragen
student = gradesDB.getStudent(personID);
//Alle modules die de ingelogde student volgt opzoeken
modules = new StudentModules(personID, studentmodules);
//De module opzoeken die op het scherm moet verschijnen
module = gradesDB.getModule(moduleID, moduleYear);
//Alle vakken van de module opzoeken
courses = gradesDB.getCoursesForModule(moduleID);
//Het resultaat van de gehele module opzoeken
moduleResult = gradesDB.getModuleResult(personID, module.getModulecode(), module.getYear());
/**Tijdelijke Assingment lijst aanmaken.
*Moet een arraylist zijn zodat we assignments aan de lijst kunnen toevoegen.
*De variable 'assignments' is een List<Assignment>, hier kunnen we geen extra assignments aan toevoegen nadat we de database-query
*voor 1 vak hebben uitgevoerd
*Daarom hebben de assignmemtList, we lopen elk vak van de module door, en voegen alle assignments van die vakken toe aan de lijst.
*/
List<Assignment> assignmentList = new ArrayList<Assignment>();
//For-loop voor alle vakken van de module
for(int i = 0; i < courses.size(); i++){
//Vraagt alle assignments van 1 vak op
assignments = gradesDB.getAssignmentsForCourse(courses.get(i).getCourseCode(), courses.get(i).getYear());
//Als er assignments zijn, toevoegen aan assignmentlist
if (assignments != null){
//For-loop voor alle assignments in de lijst
for (int j = 0; j < assignments.size(); j++) {
//Assignment toevoegen aan de tijdelijke lijst
if(assignments.get(j) != null){
assignmentList.add(assignments.get(j));
}
}
}
}
//Tijdelijke assignmentlist omzetten naar de uiteindelijke 'assignment' lijst
assignments = assignmentList;
/**
* Tijdelijke AssignmentResult lijst aanmaken
* 'resultList' is een arraylist zodat er element aan toegevoegd kunnen worden
* Dan alle resultaten van alle assignments toevoegen aan de tijdelijke lijst
* Daarna weer tijdelijke lijst terugzetten naar de officiele 'occasions' AssignmentResult lijst
*/
List<AssignmentResult> resultList = new ArrayList<AssignmentResult>();
//Alle assignments doorlopen
//Alle assignments van alle vakken staan al in de lijst, dus hoeven geen vak te specificeren
for(int i = 0; i < assignments.size(); i++){
//Alle resultaten van een assignment opvragen
occasions = gradesDB.getResultsForAssignmentAndStudent(personID, assignments.get(i).getAssignmentID());
//Als er resultaten zijn, deze toevoegen aan de 'resultList'
if (occasions != null){
//Alle resultaten doorlopen
for (int j = 0; j < occasions.size(); j++) {
//Resultaat toevoegen aan de tijdelijke lijst
if(occasions.get(j) != null){
resultList.add(occasions.get(j));
}
}
}
}
//Tijdelijke lijst weer omzetten naar de definitieve lijst
occasions = resultList;
}finally{
//Database connectie afsluiten
gradesDB.closeConnection();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Alle variabelen aanmaken die nodig zijn om de 'setInfo' methode aan te roepen
Integer moduleid;
Integer moduleyear;
Integer SID;
//De sessie van de gebruiker opvragen. Als er geen sessie bestaat, deze niet aanmaken
HttpSession session = request.getSession(false);
//Het ID van de sessie opvragen
if(session != null){
String sessionid = session.getId();
//Database connectie aanmaken
LoginDB logindb = new LoginDB();
try{
//Het studentnummer verbonden aan de huidige sessie in de variabele 'SID' zetten
SID = Integer.parseInt(logindb.getLoggedInPersonid(sessionid).substring(1));
}finally{
//Database connectie afsluiten
logindb.closeConnection();
}
//Als er geen moduleid en moduleyear in de URL wordt gespecificeerd, de meest recente module van de student opzoeken en die tonen
if (request.getParameter("moduleid") == null || request.getParameter("moduleyear") == null){
//Database connectie aanmaken
GradesDB gradesDB = new GradesDB();
try{
//Alle modules van de gebruiker opvragen
studentmodules = gradesDB.getModulesForStudent(SID);
//getModulecode sorteert automatisch op de meest recente module, dus eerste resultaat is de module die getoont moet worden
moduleid = studentmodules.get(0).getModulecode();
moduleyear = studentmodules.get(0).getYear();
}finally{
//Database connectie afsluiten
gradesDB.closeConnection();
}
}else{
//Als er wel een module-id&jaar wordt gespecificeerd, deze uit de URL halen en de locale variabelen stoppen
moduleid = Integer.parseInt(request.getParameter("moduleid"));
moduleyear = Integer.parseInt(request.getParameter("moduleyear"));
}
//Alle informatie is nu bekend, dus nu kan 'setInfo' aangeroepen worden.
setInfo(SID, moduleid, moduleyear);
if(student!= null && modules != null && module != null && moduleResult != null && courses != null && assignments != null && occasions != null){
//De informatie<SUF>
request.setAttribute("student", student);
//De lijst van alle modules meegeven aan de JSP pagina
request.setAttribute("studentModules", modules);
//De informatie van de module meegeveen aan de JSP pagina
request.setAttribute("moduletoShow", module);
//Het uiteindelijke moduleresulaat meegeven aan de JSP pagina
request.setAttribute("moduleresulttoShow", moduleResult);
//Bean aanmaken met de lijst van vakken die de student volgt
StudentCourses beanSC = new StudentCourses(SID, courses);
//De bean meegeven aan de JSP pagina
request.setAttribute("coursestoShow", beanSC);
//Bean aanmaken met de lijst van alle assignments van alle vakken van de module
CourseAssignments beanCA = new CourseAssignments("Dit is een vak", assignments);
//De bean meegeven voor de JSP pagina
request.setAttribute("assignmentstoShow", beanCA);
//Bean aanmaken van alle behaalde resultaten van de student
StudentAssignments beanSA = new StudentAssignments("Dit is een resultaat", occasions);
//Bean meegeven aan de JSP pagina
request.setAttribute("resultstoShow", beanSA);
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher(jsp_address);
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
} else {
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}else{
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}
}
|
100073_10 | /*
* Copyright 2010, 2015 Julian de Hoog ([email protected]), Victor Spirin ([email protected])
*
* This file is part of MRESim 2.2, a simulator for testing the behaviour
* of multiple robots exploring unknown environments.
*
* If you use MRESim, I would appreciate an acknowledgement and/or a citation
* of our papers:
*
* @inproceedings{deHoog2009,
* title = "Role-Based Autonomous Multi-Robot Exploration",
* author = "Julian de Hoog, Stephen Cameron and Arnoud Visser",
* year = "2009",
* booktitle = "International Conference on Advanced Cognitive Technologies and Applications (COGNITIVE)",
* location = "Athens, Greece",
* month = "November",
* }
*
* @incollection{spirin2015mresim,
* title={MRESim, a Multi-robot Exploration Simulator for the Rescue Simulation League},
* author={Spirin, Victor and de Hoog, Julian and Visser, Arnoud and Cameron, Stephen},
* booktitle={RoboCup 2014: Robot World Cup XVIII},
* pages={106--117},
* year={2015},
* publisher={Springer}
* }
*
* MRESim 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.
*
* MRESim 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 MRESim.
* If not, see <http://www.gnu.org/licenses/>.
*/
package config;
import java.awt.Color;
/**
*
* @author julh
*/
public class Constants {
// Max number of rows in environment
public static final int MAX_ROWS = 600;
// Max number of columns in enviroment
public static final int MAX_COLS = 800;
// Random seed for random walk (set to a constant for testing, otherwise to System.currentTimeMillis())
public static final int RANDOM_SEED = (int)System.currentTimeMillis();
// Max time to search for a path, in ms
public static final int MAX_PATH_SEARCH_TIME = 500;
// Size of relay in image
public static final int AGENT_RADIUS = 4; // default 4;
// Distance that the grid is partitioned into for A* path planning
public static final int STEP_SIZE = 1; // default 3;
// Target ratio of info known at base to total info known at agents
//public static final double TARGET_INFO_RATIO = 1;
// default agent speed
public static final int DEFAULT_SPEED = 10;
// Safe distance for each relay's Safe Range, percentage of Free Space Range
public static final int SAFE_RANGE = 10;
// How thick should the agent mark the obstacles/walls in the OccGrid
public static final int WALL_THICKNESS = 3; //was 3
// How often should we calculate area known by all the agents? (Takes around 200ms)
public static final int RECALC_JOINT_AREA = 10;
// Initial delay of timer
public static final int INIT_DELAY = 500;
// Replan every ... steps
public static final int REPLAN_INTERVAL = 15;
// Min time between RV replan
public static final int RV_REPLAN_INTERVAL = REPLAN_INTERVAL;
// Difference in milliseconds between increments in simulation rate slider bar
public static final int TIME_INCREMENT = 111;
// Maximum proximity an relay may have to a wall, in pixels, when planning paths
// (May cause bugs if less than step size)
public static final int WALL_DISTANCE = 3; // default 3;
// How many neighbours are added to the queue for AStar search when planning paths
public static final int PATH_SEARCH_RESOLUTION = 12;
// Maximum number of nodes to examine for path planner
public static final int MAX_PATH_PLANNER_ITERATIONS = Integer.MAX_VALUE;
// Number of frontiers (closest ones and biggest) to be evaluated when choosing a frontier
public static final int MAX_NUM_FRONTIERS = 6; //was 6
// Minimum size a frontier must have to be considered as part of exploration
public static final int MIN_FRONTIER_SIZE = 3; // default 20; was 3
// How long should we assume that the teammate is exploring the frontier that he last told us he was to explore?
public static final int REMEMBER_TEAMMATE_FRONTIER_PERIOD = 500;
// Minimum wait time until attempting to communicate with the Base Station again. This is to ensure when in range
// with the base station we do not try to transfer big maps every step, resulting in slowdown.
public static final int MIN_COMM_WITH_CS_PERIOD = 10;
// Probability of going out of service at any given time
public static final double PROB_OUT_OF_SERVICE = 0.002;
// Maximum possible time (for divisions by zero speed)
public static final int MAX_TIME = 10000;
// Percent of a territory that must be explored
public static final double TERRITORY_PERCENT_EXPLORED_GOAL = 0.95;
// Probability of new debris at each time step
public static final double NEW_DEBRIS_LIKELIHOOD = 0.5;
// Maximum size of new debris
public static final int NEW_DEBRIS_MAX_SIZE = 50;
// How often agents should recalculate how much they know, how much they are relaying etc.
public static final int UPDATE_AGENT_KNOWLEDGE_INTERVAL = 1;
// Unexplored topological space ID
public static final int UNEXPLORED_NODE_ID = Integer.MAX_VALUE;
// Time an agent needs to be in a state, before he starts communicating with the parent for RoleBasedExploration
public static final int MIN_TIME_IN_EXPLORE_STATE = 15;
public static final int BASE_STATION_TEAMMATE_ID = 1;
public static final int BASE_STATION_AGENT_ID = 0;
// How often should we check if it's time to RV?
public static final int CHECK_INTERVAL_TIME_TO_RV = 2;
// How often should we recalculate path to parent
public static final int PATH_RECALC_PARENT_INTERVAL = 8;
public static final int PATH_RECALC_CHILD_INTERVAL = 8;
// How long should we wait at RV, before we make alternative arrangements
public static final int WAIT_AT_RV_BEFORE_REPLAN = 60;
// Minimal time an explorer should explore a frontier before delivering the information back
public static final int FRONTIER_MIN_EXPLORE_TIME = 75;
//In role-based exploration try not to go to frontiers if we will have to turn back to RV before we can even reach the frontier.
public static final boolean AVOID_FRONTIERS_WE_CANNOT_REACH_IN_TIME = true;
// How often should we check if we need to rebuild topological path?
public static final int REBUILD_TOPOLOGICAL_MAP_INTERVAL = REPLAN_INTERVAL;
// How often MUST we rebuild topological map?
public static final int MUST_REBUILD_TOPOLOGICAL_MAP_INTERVAL = REPLAN_INTERVAL*10;
// How many cells in the occupancy grid need to change for us to rebuild topological map
public static final int MAP_CHANGED_THRESHOLD = 100;
// How many steps should we initialize for
public static final int INIT_CYCLES = 3;
// How much better should RV through a Wall be, compared to RV from the same spot not through a wall, to be accepted
public static final double MIN_RV_THROUGH_WALL_ACCEPT_RATIO = 0.8;
// Maximum time we're allowed to search for distance by skeleton, in ms
public static final long MAX_TIME_DISTANCE_BY_SKELETON = 100;
public static final boolean OUTPUT_PATH_ERROR = false;
public static final String DEFAULT_PATH_LOG_DIRECTORY = "C:\\Users\\Victor\\Sources\\University\\MRESim\\GIT\\MRESim\\patherror\\";//System.getProperty("user.dir") + "\\patherror\\";
// Colors to be used on map
public static class MapColor {
public static final Color background() {return Color.LIGHT_GRAY;}
public static final Color explored() {return Color.WHITE;}
public static final Color explored_base() {return Color.YELLOW;}
public static final Color safe() {return Color.GREEN;}
public static final Color unexplored() {return Color.LIGHT_GRAY;}
public static final Color relay() {return Color.RED;}
public static final Color explorer() {return Color.BLUE;} //{return new Color(238,118,33);}
public static final Color comStation() {return Color.BLACK;}
public static final Color sensed() {return Color.CYAN;}
public static final Color comm() {return Color.BLUE;}
public static final Color obstacle() {return Color.BLACK;}
public static final Color wall() {return Color.BLACK;}
public static final Color text() {return Color.BLACK;}
public static final Color link() {return Color.GREEN;}
public static final Color frontier() {return Color.MAGENTA;}
public static final Color test() {return Color.GREEN;}
public static final Color skeleton() {return Color.BLACK;}
public static final Color keyPoints() {return Color.LIGHT_GRAY;}
public static final Color rvPoints() {return Color.RED;}
public static final Color childRV() {return Color.ORANGE;}
public static final Color parentRV() {return Color.GREEN;}
public static final Color hierarchy() {return Color.MAGENTA;}
}
// Indent in console information
public static final String INDENT = " - ";
}
| v-spirin/MRESim | src/config/Constants.java | 2,812 | // default agent speed | line_comment | nl | /*
* Copyright 2010, 2015 Julian de Hoog ([email protected]), Victor Spirin ([email protected])
*
* This file is part of MRESim 2.2, a simulator for testing the behaviour
* of multiple robots exploring unknown environments.
*
* If you use MRESim, I would appreciate an acknowledgement and/or a citation
* of our papers:
*
* @inproceedings{deHoog2009,
* title = "Role-Based Autonomous Multi-Robot Exploration",
* author = "Julian de Hoog, Stephen Cameron and Arnoud Visser",
* year = "2009",
* booktitle = "International Conference on Advanced Cognitive Technologies and Applications (COGNITIVE)",
* location = "Athens, Greece",
* month = "November",
* }
*
* @incollection{spirin2015mresim,
* title={MRESim, a Multi-robot Exploration Simulator for the Rescue Simulation League},
* author={Spirin, Victor and de Hoog, Julian and Visser, Arnoud and Cameron, Stephen},
* booktitle={RoboCup 2014: Robot World Cup XVIII},
* pages={106--117},
* year={2015},
* publisher={Springer}
* }
*
* MRESim 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.
*
* MRESim 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 MRESim.
* If not, see <http://www.gnu.org/licenses/>.
*/
package config;
import java.awt.Color;
/**
*
* @author julh
*/
public class Constants {
// Max number of rows in environment
public static final int MAX_ROWS = 600;
// Max number of columns in enviroment
public static final int MAX_COLS = 800;
// Random seed for random walk (set to a constant for testing, otherwise to System.currentTimeMillis())
public static final int RANDOM_SEED = (int)System.currentTimeMillis();
// Max time to search for a path, in ms
public static final int MAX_PATH_SEARCH_TIME = 500;
// Size of relay in image
public static final int AGENT_RADIUS = 4; // default 4;
// Distance that the grid is partitioned into for A* path planning
public static final int STEP_SIZE = 1; // default 3;
// Target ratio of info known at base to total info known at agents
//public static final double TARGET_INFO_RATIO = 1;
// default agent<SUF>
public static final int DEFAULT_SPEED = 10;
// Safe distance for each relay's Safe Range, percentage of Free Space Range
public static final int SAFE_RANGE = 10;
// How thick should the agent mark the obstacles/walls in the OccGrid
public static final int WALL_THICKNESS = 3; //was 3
// How often should we calculate area known by all the agents? (Takes around 200ms)
public static final int RECALC_JOINT_AREA = 10;
// Initial delay of timer
public static final int INIT_DELAY = 500;
// Replan every ... steps
public static final int REPLAN_INTERVAL = 15;
// Min time between RV replan
public static final int RV_REPLAN_INTERVAL = REPLAN_INTERVAL;
// Difference in milliseconds between increments in simulation rate slider bar
public static final int TIME_INCREMENT = 111;
// Maximum proximity an relay may have to a wall, in pixels, when planning paths
// (May cause bugs if less than step size)
public static final int WALL_DISTANCE = 3; // default 3;
// How many neighbours are added to the queue for AStar search when planning paths
public static final int PATH_SEARCH_RESOLUTION = 12;
// Maximum number of nodes to examine for path planner
public static final int MAX_PATH_PLANNER_ITERATIONS = Integer.MAX_VALUE;
// Number of frontiers (closest ones and biggest) to be evaluated when choosing a frontier
public static final int MAX_NUM_FRONTIERS = 6; //was 6
// Minimum size a frontier must have to be considered as part of exploration
public static final int MIN_FRONTIER_SIZE = 3; // default 20; was 3
// How long should we assume that the teammate is exploring the frontier that he last told us he was to explore?
public static final int REMEMBER_TEAMMATE_FRONTIER_PERIOD = 500;
// Minimum wait time until attempting to communicate with the Base Station again. This is to ensure when in range
// with the base station we do not try to transfer big maps every step, resulting in slowdown.
public static final int MIN_COMM_WITH_CS_PERIOD = 10;
// Probability of going out of service at any given time
public static final double PROB_OUT_OF_SERVICE = 0.002;
// Maximum possible time (for divisions by zero speed)
public static final int MAX_TIME = 10000;
// Percent of a territory that must be explored
public static final double TERRITORY_PERCENT_EXPLORED_GOAL = 0.95;
// Probability of new debris at each time step
public static final double NEW_DEBRIS_LIKELIHOOD = 0.5;
// Maximum size of new debris
public static final int NEW_DEBRIS_MAX_SIZE = 50;
// How often agents should recalculate how much they know, how much they are relaying etc.
public static final int UPDATE_AGENT_KNOWLEDGE_INTERVAL = 1;
// Unexplored topological space ID
public static final int UNEXPLORED_NODE_ID = Integer.MAX_VALUE;
// Time an agent needs to be in a state, before he starts communicating with the parent for RoleBasedExploration
public static final int MIN_TIME_IN_EXPLORE_STATE = 15;
public static final int BASE_STATION_TEAMMATE_ID = 1;
public static final int BASE_STATION_AGENT_ID = 0;
// How often should we check if it's time to RV?
public static final int CHECK_INTERVAL_TIME_TO_RV = 2;
// How often should we recalculate path to parent
public static final int PATH_RECALC_PARENT_INTERVAL = 8;
public static final int PATH_RECALC_CHILD_INTERVAL = 8;
// How long should we wait at RV, before we make alternative arrangements
public static final int WAIT_AT_RV_BEFORE_REPLAN = 60;
// Minimal time an explorer should explore a frontier before delivering the information back
public static final int FRONTIER_MIN_EXPLORE_TIME = 75;
//In role-based exploration try not to go to frontiers if we will have to turn back to RV before we can even reach the frontier.
public static final boolean AVOID_FRONTIERS_WE_CANNOT_REACH_IN_TIME = true;
// How often should we check if we need to rebuild topological path?
public static final int REBUILD_TOPOLOGICAL_MAP_INTERVAL = REPLAN_INTERVAL;
// How often MUST we rebuild topological map?
public static final int MUST_REBUILD_TOPOLOGICAL_MAP_INTERVAL = REPLAN_INTERVAL*10;
// How many cells in the occupancy grid need to change for us to rebuild topological map
public static final int MAP_CHANGED_THRESHOLD = 100;
// How many steps should we initialize for
public static final int INIT_CYCLES = 3;
// How much better should RV through a Wall be, compared to RV from the same spot not through a wall, to be accepted
public static final double MIN_RV_THROUGH_WALL_ACCEPT_RATIO = 0.8;
// Maximum time we're allowed to search for distance by skeleton, in ms
public static final long MAX_TIME_DISTANCE_BY_SKELETON = 100;
public static final boolean OUTPUT_PATH_ERROR = false;
public static final String DEFAULT_PATH_LOG_DIRECTORY = "C:\\Users\\Victor\\Sources\\University\\MRESim\\GIT\\MRESim\\patherror\\";//System.getProperty("user.dir") + "\\patherror\\";
// Colors to be used on map
public static class MapColor {
public static final Color background() {return Color.LIGHT_GRAY;}
public static final Color explored() {return Color.WHITE;}
public static final Color explored_base() {return Color.YELLOW;}
public static final Color safe() {return Color.GREEN;}
public static final Color unexplored() {return Color.LIGHT_GRAY;}
public static final Color relay() {return Color.RED;}
public static final Color explorer() {return Color.BLUE;} //{return new Color(238,118,33);}
public static final Color comStation() {return Color.BLACK;}
public static final Color sensed() {return Color.CYAN;}
public static final Color comm() {return Color.BLUE;}
public static final Color obstacle() {return Color.BLACK;}
public static final Color wall() {return Color.BLACK;}
public static final Color text() {return Color.BLACK;}
public static final Color link() {return Color.GREEN;}
public static final Color frontier() {return Color.MAGENTA;}
public static final Color test() {return Color.GREEN;}
public static final Color skeleton() {return Color.BLACK;}
public static final Color keyPoints() {return Color.LIGHT_GRAY;}
public static final Color rvPoints() {return Color.RED;}
public static final Color childRV() {return Color.ORANGE;}
public static final Color parentRV() {return Color.GREEN;}
public static final Color hierarchy() {return Color.MAGENTA;}
}
// Indent in console information
public static final String INDENT = " - ";
}
|
173474_20 | // Copyright 2020 Gabor Kokeny and contributors
//
// 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.vaadin.addons.componentfactory.leaflet.layer.raster;
import org.vaadin.addons.componentfactory.leaflet.annotations.LeafletArgument;
import org.vaadin.addons.componentfactory.leaflet.layer.groups.GridLayer;
/**
* Used to load and display tile layers on the map. Note that most tile servers
* require attribution, which you can set under Layer. Extends GridLayer.
*
* @author <strong>Gabor Kokeny</strong> Email:
* <a href='[email protected]'>[email protected]</a>
* @since 2020-03-06
* @version 1.0
*/
public class TileLayer extends GridLayer {
/**
*
*/
private static final long serialVersionUID = 7333804905034746145L;
@LeafletArgument
private String urlTemplate;
private String[] subdomains = { "a", "b", "c" };
private String errorTileUrl;
private int zoomOffset = 0;
private boolean tms = false;
private boolean zoomReverse = false;
private boolean detectRetina = false;
private String crossOrigin;
/**
* Instantiates a tile layer object given a URL template and optionally an
* options object.
*
* @param urlTemplate the URL template of this tile layer
*/
public TileLayer(String urlTemplate) {
super();
this.urlTemplate = urlTemplate;
}
/**
* @return the subdomains
*/
public String[] getSubdomains() {
return subdomains;
}
/**
* Subdomains of the tile service. Can be passed in the form of one string
* (where each letter is a subdomain name) or an array of strings.
*
* @param subdomains the subdomains to set
*/
public void setSubdomains(String... subdomains) {
this.subdomains = subdomains;
}
/**
* @return the errorTileUrl
*/
public String getErrorTileUrl() {
return errorTileUrl;
}
/**
* URL to the tile image to show in place of the tile that failed to load.
*
* @param errorTileUrl the errorTileUrl to set
*/
public void setErrorTileUrl(String errorTileUrl) {
this.errorTileUrl = errorTileUrl;
}
/**
* @return the zoomOffset
*/
public int getZoomOffset() {
return zoomOffset;
}
/**
* The zoom number used in tile URLs will be offset with this value.
*
* @param zoomOffset the zoomOffset to set
*/
public void setZoomOffset(int zoomOffset) {
this.zoomOffset = zoomOffset;
}
/**
* @return the tms
*/
public boolean isTms() {
return tms;
}
/**
* If true, inverses Y axis numbering for tiles (turn this on for TMS services).
*
* @param tms the tms to set
*/
public void setTms(boolean tms) {
this.tms = tms;
}
/**
* @return the zoomReverse
*/
public boolean isZoomReverse() {
return zoomReverse;
}
/**
* If set to true, the zoom number used in tile URLs will be reversed (maxZoom -
* zoom instead of zoom)
*
* @param zoomReverse the zoomReverse to set
*/
public void setZoomReverse(boolean zoomReverse) {
this.zoomReverse = zoomReverse;
}
/**
* @return the detectRetina
*/
public boolean isDetectRetina() {
return detectRetina;
}
/**
* If true and user is on a retina display, it will request four tiles of half
* the specified size and a bigger zoom level in place of one to utilize the
* high resolution.
*
* @param detectRetina the detectRetina to set
*/
public void setDetectRetina(boolean detectRetina) {
this.detectRetina = detectRetina;
}
/**
* @return the crossOrigin
*/
public String getCrossOrigin() {
return crossOrigin;
}
/**
* Whether the crossOrigin attribute will be added to the tiles. If a String is
* provided, all tiles will have their crossOrigin attribute set to the String
* provided. This is needed if you want to access tile pixel data. Refer to CORS
* Settings for valid String values.
*
* @param crossOrigin the crossOrigin to set
*/
public void setCrossOrigin(String crossOrigin) {
this.crossOrigin = crossOrigin;
}
/**
* @return the urlTemplate
*/
public String getUrlTemplate() {
return urlTemplate;
}
}
| vaadin-component-factory/vcf-leaflet | src/main/java/org/vaadin/addons/componentfactory/leaflet/layer/raster/TileLayer.java | 1,438 | /**
* If set to true, the zoom number used in tile URLs will be reversed (maxZoom -
* zoom instead of zoom)
*
* @param zoomReverse the zoomReverse to set
*/ | block_comment | nl | // Copyright 2020 Gabor Kokeny and contributors
//
// 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.vaadin.addons.componentfactory.leaflet.layer.raster;
import org.vaadin.addons.componentfactory.leaflet.annotations.LeafletArgument;
import org.vaadin.addons.componentfactory.leaflet.layer.groups.GridLayer;
/**
* Used to load and display tile layers on the map. Note that most tile servers
* require attribution, which you can set under Layer. Extends GridLayer.
*
* @author <strong>Gabor Kokeny</strong> Email:
* <a href='[email protected]'>[email protected]</a>
* @since 2020-03-06
* @version 1.0
*/
public class TileLayer extends GridLayer {
/**
*
*/
private static final long serialVersionUID = 7333804905034746145L;
@LeafletArgument
private String urlTemplate;
private String[] subdomains = { "a", "b", "c" };
private String errorTileUrl;
private int zoomOffset = 0;
private boolean tms = false;
private boolean zoomReverse = false;
private boolean detectRetina = false;
private String crossOrigin;
/**
* Instantiates a tile layer object given a URL template and optionally an
* options object.
*
* @param urlTemplate the URL template of this tile layer
*/
public TileLayer(String urlTemplate) {
super();
this.urlTemplate = urlTemplate;
}
/**
* @return the subdomains
*/
public String[] getSubdomains() {
return subdomains;
}
/**
* Subdomains of the tile service. Can be passed in the form of one string
* (where each letter is a subdomain name) or an array of strings.
*
* @param subdomains the subdomains to set
*/
public void setSubdomains(String... subdomains) {
this.subdomains = subdomains;
}
/**
* @return the errorTileUrl
*/
public String getErrorTileUrl() {
return errorTileUrl;
}
/**
* URL to the tile image to show in place of the tile that failed to load.
*
* @param errorTileUrl the errorTileUrl to set
*/
public void setErrorTileUrl(String errorTileUrl) {
this.errorTileUrl = errorTileUrl;
}
/**
* @return the zoomOffset
*/
public int getZoomOffset() {
return zoomOffset;
}
/**
* The zoom number used in tile URLs will be offset with this value.
*
* @param zoomOffset the zoomOffset to set
*/
public void setZoomOffset(int zoomOffset) {
this.zoomOffset = zoomOffset;
}
/**
* @return the tms
*/
public boolean isTms() {
return tms;
}
/**
* If true, inverses Y axis numbering for tiles (turn this on for TMS services).
*
* @param tms the tms to set
*/
public void setTms(boolean tms) {
this.tms = tms;
}
/**
* @return the zoomReverse
*/
public boolean isZoomReverse() {
return zoomReverse;
}
/**
* If set to<SUF>*/
public void setZoomReverse(boolean zoomReverse) {
this.zoomReverse = zoomReverse;
}
/**
* @return the detectRetina
*/
public boolean isDetectRetina() {
return detectRetina;
}
/**
* If true and user is on a retina display, it will request four tiles of half
* the specified size and a bigger zoom level in place of one to utilize the
* high resolution.
*
* @param detectRetina the detectRetina to set
*/
public void setDetectRetina(boolean detectRetina) {
this.detectRetina = detectRetina;
}
/**
* @return the crossOrigin
*/
public String getCrossOrigin() {
return crossOrigin;
}
/**
* Whether the crossOrigin attribute will be added to the tiles. If a String is
* provided, all tiles will have their crossOrigin attribute set to the String
* provided. This is needed if you want to access tile pixel data. Refer to CORS
* Settings for valid String values.
*
* @param crossOrigin the crossOrigin to set
*/
public void setCrossOrigin(String crossOrigin) {
this.crossOrigin = crossOrigin;
}
/**
* @return the urlTemplate
*/
public String getUrlTemplate() {
return urlTemplate;
}
}
|
63155_18 | /*
* Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui;
import java.io.Serializable;
import com.vaadin.shared.ui.ui.UIState.TooltipConfigurationState;
/**
* Provides method for configuring the tooltip.
*
* @author Vaadin Ltd
* @since 7.1
*/
public interface TooltipConfiguration extends Serializable {
/**
* Returns the time (in ms) the tooltip should be displayed after an event
* that will cause it to be closed (e.g. mouse click outside the component,
* key down).
*
* @return The close timeout
*/
public int getCloseTimeout();
/**
* Sets the time (in ms) the tooltip should be displayed after an event that
* will cause it to be closed (e.g. mouse click outside the component, key
* down).
*
* @param closeTimeout
* The close timeout
*/
public void setCloseTimeout(int closeTimeout);
/**
* Returns the time (in ms) during which {@link #getQuickOpenDelay()} should
* be used instead of {@link #getOpenDelay()}. The quick open delay is used
* when the tooltip has very recently been shown, is currently hidden but
* about to be shown again.
*
* @return The quick open timeout
*/
public int getQuickOpenTimeout();
/**
* Sets the time (in ms) that determines when {@link #getQuickOpenDelay()}
* should be used instead of {@link #getOpenDelay()}. The quick open delay
* is used when the tooltip has very recently been shown, is currently
* hidden but about to be shown again.
*
* @param quickOpenTimeout
* The quick open timeout
*/
public void setQuickOpenTimeout(int quickOpenTimeout);
/**
* Returns the time (in ms) that should elapse before a tooltip will be
* shown, in the situation when a tooltip has very recently been shown
* (within {@link #getQuickOpenDelay()} ms).
*
* @return The quick open delay
*/
public int getQuickOpenDelay();
/**
* Sets the time (in ms) that should elapse before a tooltip will be shown,
* in the situation when a tooltip has very recently been shown (within
* {@link #getQuickOpenDelay()} ms).
*
* @param quickOpenDelay
* The quick open delay
*/
public void setQuickOpenDelay(int quickOpenDelay);
/**
* Returns the time (in ms) that should elapse after an event triggering
* tooltip showing has occurred (e.g. mouse over) before the tooltip is
* shown. If a tooltip has recently been shown, then
* {@link #getQuickOpenDelay()} is used instead of this.
*
* @return The open delay
*/
public int getOpenDelay();
/**
* Sets the time (in ms) that should elapse after an event triggering
* tooltip showing has occurred (e.g. mouse over) before the tooltip is
* shown. If a tooltip has recently been shown, then
* {@link #getQuickOpenDelay()} is used instead of this.
*
* @param openDelay
* The open delay
*/
public void setOpenDelay(int openDelay);
/**
* Returns the maximum width of the tooltip popup.
*
* @return The maximum width the tooltip popup
*/
public int getMaxWidth();
/**
* Sets the maximum width of the tooltip popup.
*
* @param maxWidth
* The maximum width the tooltip popup
*/
public void setMaxWidth(int maxWidth);
}
class TooltipConfigurationImpl implements TooltipConfiguration {
private final UI ui;
public TooltipConfigurationImpl(UI ui) {
this.ui = ui;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.UI.Tooltip#getCloseTimeout()
*/
@Override
public int getCloseTimeout() {
return getState(false).closeTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setCloseTimeout(int)
*/
@Override
public void setCloseTimeout(int closeTimeout) {
getState().closeTimeout = closeTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getQuickOpenTimeout()
*/
@Override
public int getQuickOpenTimeout() {
return getState(false).quickOpenTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setQuickOpenTimeout(int)
*/
@Override
public void setQuickOpenTimeout(int quickOpenTimeout) {
getState().quickOpenTimeout = quickOpenTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getQuickOpenDelay()
*/
@Override
public int getQuickOpenDelay() {
return getState(false).quickOpenDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setQuickOpenDelay(int)
*/
@Override
public void setQuickOpenDelay(int quickOpenDelay) {
getState().quickOpenDelay = quickOpenDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getOpenDelay()
*/
@Override
public int getOpenDelay() {
return getState(false).openDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setOpenDelay(int)
*/
@Override
public void setOpenDelay(int openDelay) {
getState().openDelay = openDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getMaxWidth()
*/
@Override
public int getMaxWidth() {
return getState(false).maxWidth;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setMaxWidth(int)
*/
@Override
public void setMaxWidth(int maxWidth) {
getState().maxWidth = maxWidth;
}
private TooltipConfigurationState getState() {
return ui.getState().tooltipConfiguration;
}
private TooltipConfigurationState getState(boolean markAsDirty) {
return ui.getState(markAsDirty).tooltipConfiguration;
}
}
| vaadin/framework | server/src/main/java/com/vaadin/ui/TooltipConfiguration.java | 1,953 | /*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getOpenDelay()
*/ | block_comment | nl | /*
* Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui;
import java.io.Serializable;
import com.vaadin.shared.ui.ui.UIState.TooltipConfigurationState;
/**
* Provides method for configuring the tooltip.
*
* @author Vaadin Ltd
* @since 7.1
*/
public interface TooltipConfiguration extends Serializable {
/**
* Returns the time (in ms) the tooltip should be displayed after an event
* that will cause it to be closed (e.g. mouse click outside the component,
* key down).
*
* @return The close timeout
*/
public int getCloseTimeout();
/**
* Sets the time (in ms) the tooltip should be displayed after an event that
* will cause it to be closed (e.g. mouse click outside the component, key
* down).
*
* @param closeTimeout
* The close timeout
*/
public void setCloseTimeout(int closeTimeout);
/**
* Returns the time (in ms) during which {@link #getQuickOpenDelay()} should
* be used instead of {@link #getOpenDelay()}. The quick open delay is used
* when the tooltip has very recently been shown, is currently hidden but
* about to be shown again.
*
* @return The quick open timeout
*/
public int getQuickOpenTimeout();
/**
* Sets the time (in ms) that determines when {@link #getQuickOpenDelay()}
* should be used instead of {@link #getOpenDelay()}. The quick open delay
* is used when the tooltip has very recently been shown, is currently
* hidden but about to be shown again.
*
* @param quickOpenTimeout
* The quick open timeout
*/
public void setQuickOpenTimeout(int quickOpenTimeout);
/**
* Returns the time (in ms) that should elapse before a tooltip will be
* shown, in the situation when a tooltip has very recently been shown
* (within {@link #getQuickOpenDelay()} ms).
*
* @return The quick open delay
*/
public int getQuickOpenDelay();
/**
* Sets the time (in ms) that should elapse before a tooltip will be shown,
* in the situation when a tooltip has very recently been shown (within
* {@link #getQuickOpenDelay()} ms).
*
* @param quickOpenDelay
* The quick open delay
*/
public void setQuickOpenDelay(int quickOpenDelay);
/**
* Returns the time (in ms) that should elapse after an event triggering
* tooltip showing has occurred (e.g. mouse over) before the tooltip is
* shown. If a tooltip has recently been shown, then
* {@link #getQuickOpenDelay()} is used instead of this.
*
* @return The open delay
*/
public int getOpenDelay();
/**
* Sets the time (in ms) that should elapse after an event triggering
* tooltip showing has occurred (e.g. mouse over) before the tooltip is
* shown. If a tooltip has recently been shown, then
* {@link #getQuickOpenDelay()} is used instead of this.
*
* @param openDelay
* The open delay
*/
public void setOpenDelay(int openDelay);
/**
* Returns the maximum width of the tooltip popup.
*
* @return The maximum width the tooltip popup
*/
public int getMaxWidth();
/**
* Sets the maximum width of the tooltip popup.
*
* @param maxWidth
* The maximum width the tooltip popup
*/
public void setMaxWidth(int maxWidth);
}
class TooltipConfigurationImpl implements TooltipConfiguration {
private final UI ui;
public TooltipConfigurationImpl(UI ui) {
this.ui = ui;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.UI.Tooltip#getCloseTimeout()
*/
@Override
public int getCloseTimeout() {
return getState(false).closeTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setCloseTimeout(int)
*/
@Override
public void setCloseTimeout(int closeTimeout) {
getState().closeTimeout = closeTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getQuickOpenTimeout()
*/
@Override
public int getQuickOpenTimeout() {
return getState(false).quickOpenTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setQuickOpenTimeout(int)
*/
@Override
public void setQuickOpenTimeout(int quickOpenTimeout) {
getState().quickOpenTimeout = quickOpenTimeout;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getQuickOpenDelay()
*/
@Override
public int getQuickOpenDelay() {
return getState(false).quickOpenDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setQuickOpenDelay(int)
*/
@Override
public void setQuickOpenDelay(int quickOpenDelay) {
getState().quickOpenDelay = quickOpenDelay;
}
/*
* (non-Javadoc)
<SUF>*/
@Override
public int getOpenDelay() {
return getState(false).openDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setOpenDelay(int)
*/
@Override
public void setOpenDelay(int openDelay) {
getState().openDelay = openDelay;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#getMaxWidth()
*/
@Override
public int getMaxWidth() {
return getState(false).maxWidth;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Tooltip#setMaxWidth(int)
*/
@Override
public void setMaxWidth(int maxWidth) {
getState().maxWidth = maxWidth;
}
private TooltipConfigurationState getState() {
return ui.getState().tooltipConfiguration;
}
private TooltipConfigurationState getState(boolean markAsDirty) {
return ui.getState(markAsDirty).tooltipConfiguration;
}
}
|
174793_2 | package com.example.watchtube;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.content.Intent;
import android.widget.Toast;
import com.example.watchtube.model.APIUtils.YouTubeAPIUtils;
import com.example.watchtube.UI.MainActivity;
import com.example.watchtube.model.DemandsChecker;
import com.example.watchtube.model.data.SubscriptionData;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.util.ExponentialBackOff;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;
/**
* Created by Nikita on 22.08.2018.
*/
public class MainPresenter implements Contract.Presenter {
private List<SubscriptionData> mSubscriptions;
private MainActivity mActivity;
//private ChannelFragment mChannelFragment;
//private VideoListFragment mTrendsVideoListFragment;
private CompositeDisposable mDisposables;
private YouTubeAPIUtils mYouTubeAPIUtils;
private GoogleAccountCredential mCredential;
private DemandsChecker mDemandsChecker;
//private VideoFragment mVideoFragment;
public MainPresenter(MainActivity mainActivity){
mActivity = mainActivity;
mCredential = GoogleAccountCredential.usingOAuth2(
mActivity.getApplicationContext(), Arrays.asList(MainActivity.SCOPES))
.setBackOff(new ExponentialBackOff());
mYouTubeAPIUtils = new YouTubeAPIUtils(mActivity.getApplicationContext(),
this);
mYouTubeAPIUtils.setupCredential(mCredential);
}
@Override
public void onStart() {
mDisposables = new CompositeDisposable();
}
public List<SubscriptionData> getSubscriptions() {
return mSubscriptions;
}
public GoogleAccountCredential getCredential() {
return mCredential;
}
public void checkDemands(){
mDemandsChecker = new DemandsChecker(mActivity, this);
if (!mDemandsChecker.isGooglePlayServicesAvailable()) {
mDemandsChecker.acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
chooseAccount();
} else if (!mDemandsChecker.isDeviceOnline()) {
Toast.makeText(mActivity.getApplicationContext(), "No network connection available.", Toast.LENGTH_SHORT).show();
//setText();
} else {
fetchSubscribesList();
//mActivity.setBottom("Exir40TV5Mw");
}
}
private void fetchSubscribesList() {
//setText("");
Disposable disposable = mYouTubeAPIUtils.getSubscriptionsInfo.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSingleObserver<ArrayList<SubscriptionData>>() {
@Override
public void onSuccess(ArrayList<SubscriptionData> subscriptions) {
//loadImageFromUrl(defaultObject.get(0).URL);
mActivity.setupNavigationDrawer(subscriptions);
mSubscriptions = subscriptions;
mActivity.hideProgress();
/*if(mYouTubeAPIUtils.pageToken != null){
fetchSubscribesList();
}*/
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
//setText("Error");
}
});
mDisposables.add(disposable);
}
/*public void fetchSelectedChannelData(int position){
mChannelFragment.setCredential(mCredential);
mChannelFragment.setChannelId(mSubscriptions.get(position).channelId);
mChannelFragment.fetchChannelData();
//mActivity.startActivity(intent);
//startActivity(Intent) channelActivity
}*/
/*public void chooseVideo(String videoId){
mVideoFragment.setVideoId(videoId);
mActivity.setPage();
}*/
public void checkAccountName(Intent data){
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
setSelectedAccountName(accountName);
}
}
public void setSelectedAccountName(String accountName){
mDemandsChecker.rememberSelectedAccountName(accountName);
mCredential.setSelectedAccountName(accountName);
checkDemands();
}
@AfterPermissionGranted(MainActivity.REQUEST_PERMISSION_GET_ACCOUNTS)
public void chooseAccount() {
String accountName = mDemandsChecker.getSelectedAccountName();
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
checkDemands();
} else {
mActivity.startActivityForResult(
mCredential.newChooseAccountIntent(),
MainActivity.REQUEST_ACCOUNT_PICKER);
}
}
public void makeGooglePlayServicesAvailabilityErrorDialog(GoogleApiAvailability apiAvailability,
final int connectionStatusCode) {
Dialog dialog = apiAvailability.getErrorDialog(
mActivity,
connectionStatusCode,
DemandsChecker.REQUEST_GOOGLE_PLAY_SERVICES);
mActivity.showDialog(dialog);
}
/*public void makePagerAdapter(){
ViewPagerAdapter adapter = new ViewPagerAdapter(mActivity.getSupportFragmentManager());
mTrendsVideoListFragment = new VideoListFragment();
mTrendsVideoListFragment.setCredentials(mCredential);
adapter.addFragment(mTrendsVideoListFragment, "Trending");
mChannelFragment = new ChannelFragment();
mChannelFragment.setMainPresenter(this);
adapter.addFragment(mChannelFragment, "Subscribe");
adapter.addFragment(new VideoListFragment(), "Settings");
mVideoFragment = new VideoFragment();
adapter.addFragment(mVideoFragment, "Video");
mActivity.setupPagerAdapter(adapter);
mActivity.setupTabIcons();
hideProgress();
}*/
/*public void setText(String text){
mActivity.mOutputText.setText(text);
}*/
@Override
public void onStop() {
mDisposables.clear();
}
} | vaginessa/WatchTube | app/src/main/java/com/example/watchtube/MainPresenter.java | 1,808 | //private VideoListFragment mTrendsVideoListFragment; | line_comment | nl | package com.example.watchtube;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.content.Intent;
import android.widget.Toast;
import com.example.watchtube.model.APIUtils.YouTubeAPIUtils;
import com.example.watchtube.UI.MainActivity;
import com.example.watchtube.model.DemandsChecker;
import com.example.watchtube.model.data.SubscriptionData;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.util.ExponentialBackOff;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;
/**
* Created by Nikita on 22.08.2018.
*/
public class MainPresenter implements Contract.Presenter {
private List<SubscriptionData> mSubscriptions;
private MainActivity mActivity;
//private ChannelFragment mChannelFragment;
//private VideoListFragment<SUF>
private CompositeDisposable mDisposables;
private YouTubeAPIUtils mYouTubeAPIUtils;
private GoogleAccountCredential mCredential;
private DemandsChecker mDemandsChecker;
//private VideoFragment mVideoFragment;
public MainPresenter(MainActivity mainActivity){
mActivity = mainActivity;
mCredential = GoogleAccountCredential.usingOAuth2(
mActivity.getApplicationContext(), Arrays.asList(MainActivity.SCOPES))
.setBackOff(new ExponentialBackOff());
mYouTubeAPIUtils = new YouTubeAPIUtils(mActivity.getApplicationContext(),
this);
mYouTubeAPIUtils.setupCredential(mCredential);
}
@Override
public void onStart() {
mDisposables = new CompositeDisposable();
}
public List<SubscriptionData> getSubscriptions() {
return mSubscriptions;
}
public GoogleAccountCredential getCredential() {
return mCredential;
}
public void checkDemands(){
mDemandsChecker = new DemandsChecker(mActivity, this);
if (!mDemandsChecker.isGooglePlayServicesAvailable()) {
mDemandsChecker.acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
chooseAccount();
} else if (!mDemandsChecker.isDeviceOnline()) {
Toast.makeText(mActivity.getApplicationContext(), "No network connection available.", Toast.LENGTH_SHORT).show();
//setText();
} else {
fetchSubscribesList();
//mActivity.setBottom("Exir40TV5Mw");
}
}
private void fetchSubscribesList() {
//setText("");
Disposable disposable = mYouTubeAPIUtils.getSubscriptionsInfo.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSingleObserver<ArrayList<SubscriptionData>>() {
@Override
public void onSuccess(ArrayList<SubscriptionData> subscriptions) {
//loadImageFromUrl(defaultObject.get(0).URL);
mActivity.setupNavigationDrawer(subscriptions);
mSubscriptions = subscriptions;
mActivity.hideProgress();
/*if(mYouTubeAPIUtils.pageToken != null){
fetchSubscribesList();
}*/
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
//setText("Error");
}
});
mDisposables.add(disposable);
}
/*public void fetchSelectedChannelData(int position){
mChannelFragment.setCredential(mCredential);
mChannelFragment.setChannelId(mSubscriptions.get(position).channelId);
mChannelFragment.fetchChannelData();
//mActivity.startActivity(intent);
//startActivity(Intent) channelActivity
}*/
/*public void chooseVideo(String videoId){
mVideoFragment.setVideoId(videoId);
mActivity.setPage();
}*/
public void checkAccountName(Intent data){
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
setSelectedAccountName(accountName);
}
}
public void setSelectedAccountName(String accountName){
mDemandsChecker.rememberSelectedAccountName(accountName);
mCredential.setSelectedAccountName(accountName);
checkDemands();
}
@AfterPermissionGranted(MainActivity.REQUEST_PERMISSION_GET_ACCOUNTS)
public void chooseAccount() {
String accountName = mDemandsChecker.getSelectedAccountName();
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
checkDemands();
} else {
mActivity.startActivityForResult(
mCredential.newChooseAccountIntent(),
MainActivity.REQUEST_ACCOUNT_PICKER);
}
}
public void makeGooglePlayServicesAvailabilityErrorDialog(GoogleApiAvailability apiAvailability,
final int connectionStatusCode) {
Dialog dialog = apiAvailability.getErrorDialog(
mActivity,
connectionStatusCode,
DemandsChecker.REQUEST_GOOGLE_PLAY_SERVICES);
mActivity.showDialog(dialog);
}
/*public void makePagerAdapter(){
ViewPagerAdapter adapter = new ViewPagerAdapter(mActivity.getSupportFragmentManager());
mTrendsVideoListFragment = new VideoListFragment();
mTrendsVideoListFragment.setCredentials(mCredential);
adapter.addFragment(mTrendsVideoListFragment, "Trending");
mChannelFragment = new ChannelFragment();
mChannelFragment.setMainPresenter(this);
adapter.addFragment(mChannelFragment, "Subscribe");
adapter.addFragment(new VideoListFragment(), "Settings");
mVideoFragment = new VideoFragment();
adapter.addFragment(mVideoFragment, "Video");
mActivity.setupPagerAdapter(adapter);
mActivity.setupTabIcons();
hideProgress();
}*/
/*public void setText(String text){
mActivity.mOutputText.setText(text);
}*/
@Override
public void onStop() {
mDisposables.clear();
}
} |
118804_4 | /*
* Copyright (c) 2007 Henri Sivonen
* Copyright (c) 2008-2017 Mozilla Foundation
*
* 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 nu.validator.htmlparser.xom;
import nu.validator.htmlparser.common.DocumentMode;
import nu.validator.htmlparser.impl.CoalescingTreeBuilder;
import nu.validator.htmlparser.impl.HtmlAttributes;
import nu.xom.Attribute;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.Nodes;
import nu.xom.ParentNode;
import nu.xom.Text;
import nu.xom.XMLException;
import org.xml.sax.SAXException;
class XOMTreeBuilder extends CoalescingTreeBuilder<Element> {
private final SimpleNodeFactory nodeFactory;
private Document document;
private int cachedTableIndex = -1;
private Element cachedTable = null;
protected XOMTreeBuilder(SimpleNodeFactory nodeFactory) {
super();
this.nodeFactory = nodeFactory;
}
@Override
protected void addAttributesToElement(Element element, HtmlAttributes attributes)
throws SAXException {
try {
for (int i = 0; i < attributes.getLength(); i++) {
String localName = attributes.getLocalNameNoBoundsCheck(i);
String uri = attributes.getURINoBoundsCheck(i);
if (element.getAttribute(localName, uri) == null) {
element.addAttribute(nodeFactory.makeAttribute(
localName,
uri,
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
}
} catch (XMLException e) {
fatal(e);
}
}
@Override protected void appendCharacters(Element parent, String text)
throws SAXException {
try {
int childCount = parent.getChildCount();
Node lastChild;
if (childCount != 0
&& ((lastChild = parent.getChild(childCount - 1)) instanceof Text)) {
Text lastAsText = (Text) lastChild;
lastAsText.setValue(lastAsText.getValue() + text);
return;
}
parent.appendChild(nodeFactory.makeText(text));
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendChildrenToNewParent(Element oldParent,
Element newParent) throws SAXException {
try {
Nodes children = oldParent.removeChildren();
for (int i = 0; i < children.size(); i++) {
newParent.appendChild(children.get(i));
}
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendComment(Element parent, String comment) throws SAXException {
try {
parent.appendChild(nodeFactory.makeComment(comment));
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendCommentToDocument(String comment)
throws SAXException {
try {
Element root = document.getRootElement();
if ("http://www.xom.nu/fakeRoot".equals(root.getNamespaceURI())) {
document.insertChild(nodeFactory.makeComment(comment), document.indexOf(root));
} else {
document.appendChild(nodeFactory.makeComment(comment));
}
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected Element createElement(String ns, String name,
HtmlAttributes attributes, Element intendedParent) throws SAXException {
try {
Element rv = nodeFactory.makeElement(name, ns);
for (int i = 0; i < attributes.getLength(); i++) {
rv.addAttribute(nodeFactory.makeAttribute(
attributes.getLocalNameNoBoundsCheck(i),
attributes.getURINoBoundsCheck(i),
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
return rv;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
@Override
protected Element createHtmlElementSetAsRoot(
HtmlAttributes attributes) throws SAXException {
try {
Element rv = nodeFactory.makeElement("html",
"http://www.w3.org/1999/xhtml");
for (int i = 0; i < attributes.getLength(); i++) {
rv.addAttribute(nodeFactory.makeAttribute(
attributes.getLocalNameNoBoundsCheck(i),
attributes.getURINoBoundsCheck(i),
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
document.setRootElement(rv);
return rv;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
@Override
protected void detachFromParent(Element element) throws SAXException {
try {
element.detach();
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendElement(Element child,
Element newParent) throws SAXException {
try {
child.detach();
newParent.appendChild(child);
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected boolean hasChildren(Element element) throws SAXException {
try {
return element.getChildCount() != 0;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
/**
* Returns the document.
*
* @return the document
*/
Document getDocument() {
Document rv = document;
document = null;
return rv;
}
Nodes getDocumentFragment() {
Element rootElt = document.getRootElement();
Nodes rv = rootElt.removeChildren();
document = null;
return rv;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#createElement(String,
* java.lang.String, org.xml.sax.Attributes, java.lang.Object)
*/
@Override
protected Element createElement(String ns, String name,
HtmlAttributes attributes, Element form, Element intendedParent) throws SAXException {
try {
Element rv = nodeFactory.makeElement(name,
ns, form);
for (int i = 0; i < attributes.getLength(); i++) {
rv.addAttribute(nodeFactory.makeAttribute(
attributes.getLocalName(i),
attributes.getURINoBoundsCheck(i),
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
return rv;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#start()
*/
@Override
protected void start(boolean fragment) throws SAXException {
document = nodeFactory.makeDocument();
cachedTableIndex = -1;
cachedTable = null;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#documentMode(nu.validator.htmlparser.common.DocumentMode,
* java.lang.String, java.lang.String, boolean)
*/
@Override
protected void documentMode(DocumentMode mode, String publicIdentifier,
String systemIdentifier)
throws SAXException {
if (document instanceof Mode) {
Mode modal = (Mode) document;
modal.setMode(mode);
}
}
@Override
protected Element createAndInsertFosterParentedElement(String ns, String name,
HtmlAttributes attributes, Element table, Element stackParent) throws SAXException {
try {
Node parent = table.getParent();
Element child = createElement(ns, name, attributes, parent != null ? (Element) parent : stackParent);
if (parent != null) { // always an element if not null
((ParentNode) parent).insertChild(child, indexOfTable(table, stackParent));
cachedTableIndex++;
} else {
stackParent.appendChild(child);
}
return child;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
@Override protected void insertFosterParentedCharacters(String text,
Element table, Element stackParent) throws SAXException {
try {
Node parent = table.getParent();
if (parent != null) { // always an element if not null
Element parentAsElt = (Element) parent;
int tableIndex = indexOfTable(table, parentAsElt);
Node prevSibling;
if (tableIndex != 0
&& ((prevSibling = parentAsElt.getChild(tableIndex - 1)) instanceof Text)) {
Text prevAsText = (Text) prevSibling;
prevAsText.setValue(prevAsText.getValue() + text);
return;
}
parentAsElt.insertChild(nodeFactory.makeText(text), tableIndex);
cachedTableIndex++;
return;
}
int childCount = stackParent.getChildCount();
Node lastChild;
if (childCount != 0
&& ((lastChild = stackParent.getChild(childCount - 1)) instanceof Text)) {
Text lastAsText = (Text) lastChild;
lastAsText.setValue(lastAsText.getValue() + text);
return;
}
stackParent.appendChild(nodeFactory.makeText(text));
} catch (XMLException e) {
fatal(e);
}
}
@Override protected void insertFosterParentedChild(Element child,
Element table, Element stackParent) throws SAXException {
try {
Node parent = table.getParent();
if (parent != null) { // always an element if not null
((ParentNode)parent).insertChild(child, indexOfTable(table, stackParent));
cachedTableIndex++;
} else {
stackParent.appendChild(child);
}
} catch (XMLException e) {
fatal(e);
}
}
private int indexOfTable(Element table, Element stackParent) {
if (table == cachedTable) {
return cachedTableIndex;
} else {
cachedTable = table;
return (cachedTableIndex = stackParent.indexOf(table));
}
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#end()
*/
@Override protected void end() throws SAXException {
cachedTableIndex = -1;
cachedTable = null;
}
}
| validator/htmlparser | src/nu/validator/htmlparser/xom/XOMTreeBuilder.java | 3,290 | /**
* @see nu.validator.htmlparser.impl.TreeBuilder#documentMode(nu.validator.htmlparser.common.DocumentMode,
* java.lang.String, java.lang.String, boolean)
*/ | block_comment | nl | /*
* Copyright (c) 2007 Henri Sivonen
* Copyright (c) 2008-2017 Mozilla Foundation
*
* 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 nu.validator.htmlparser.xom;
import nu.validator.htmlparser.common.DocumentMode;
import nu.validator.htmlparser.impl.CoalescingTreeBuilder;
import nu.validator.htmlparser.impl.HtmlAttributes;
import nu.xom.Attribute;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.Nodes;
import nu.xom.ParentNode;
import nu.xom.Text;
import nu.xom.XMLException;
import org.xml.sax.SAXException;
class XOMTreeBuilder extends CoalescingTreeBuilder<Element> {
private final SimpleNodeFactory nodeFactory;
private Document document;
private int cachedTableIndex = -1;
private Element cachedTable = null;
protected XOMTreeBuilder(SimpleNodeFactory nodeFactory) {
super();
this.nodeFactory = nodeFactory;
}
@Override
protected void addAttributesToElement(Element element, HtmlAttributes attributes)
throws SAXException {
try {
for (int i = 0; i < attributes.getLength(); i++) {
String localName = attributes.getLocalNameNoBoundsCheck(i);
String uri = attributes.getURINoBoundsCheck(i);
if (element.getAttribute(localName, uri) == null) {
element.addAttribute(nodeFactory.makeAttribute(
localName,
uri,
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
}
} catch (XMLException e) {
fatal(e);
}
}
@Override protected void appendCharacters(Element parent, String text)
throws SAXException {
try {
int childCount = parent.getChildCount();
Node lastChild;
if (childCount != 0
&& ((lastChild = parent.getChild(childCount - 1)) instanceof Text)) {
Text lastAsText = (Text) lastChild;
lastAsText.setValue(lastAsText.getValue() + text);
return;
}
parent.appendChild(nodeFactory.makeText(text));
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendChildrenToNewParent(Element oldParent,
Element newParent) throws SAXException {
try {
Nodes children = oldParent.removeChildren();
for (int i = 0; i < children.size(); i++) {
newParent.appendChild(children.get(i));
}
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendComment(Element parent, String comment) throws SAXException {
try {
parent.appendChild(nodeFactory.makeComment(comment));
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendCommentToDocument(String comment)
throws SAXException {
try {
Element root = document.getRootElement();
if ("http://www.xom.nu/fakeRoot".equals(root.getNamespaceURI())) {
document.insertChild(nodeFactory.makeComment(comment), document.indexOf(root));
} else {
document.appendChild(nodeFactory.makeComment(comment));
}
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected Element createElement(String ns, String name,
HtmlAttributes attributes, Element intendedParent) throws SAXException {
try {
Element rv = nodeFactory.makeElement(name, ns);
for (int i = 0; i < attributes.getLength(); i++) {
rv.addAttribute(nodeFactory.makeAttribute(
attributes.getLocalNameNoBoundsCheck(i),
attributes.getURINoBoundsCheck(i),
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
return rv;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
@Override
protected Element createHtmlElementSetAsRoot(
HtmlAttributes attributes) throws SAXException {
try {
Element rv = nodeFactory.makeElement("html",
"http://www.w3.org/1999/xhtml");
for (int i = 0; i < attributes.getLength(); i++) {
rv.addAttribute(nodeFactory.makeAttribute(
attributes.getLocalNameNoBoundsCheck(i),
attributes.getURINoBoundsCheck(i),
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
document.setRootElement(rv);
return rv;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
@Override
protected void detachFromParent(Element element) throws SAXException {
try {
element.detach();
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected void appendElement(Element child,
Element newParent) throws SAXException {
try {
child.detach();
newParent.appendChild(child);
} catch (XMLException e) {
fatal(e);
}
}
@Override
protected boolean hasChildren(Element element) throws SAXException {
try {
return element.getChildCount() != 0;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
/**
* Returns the document.
*
* @return the document
*/
Document getDocument() {
Document rv = document;
document = null;
return rv;
}
Nodes getDocumentFragment() {
Element rootElt = document.getRootElement();
Nodes rv = rootElt.removeChildren();
document = null;
return rv;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#createElement(String,
* java.lang.String, org.xml.sax.Attributes, java.lang.Object)
*/
@Override
protected Element createElement(String ns, String name,
HtmlAttributes attributes, Element form, Element intendedParent) throws SAXException {
try {
Element rv = nodeFactory.makeElement(name,
ns, form);
for (int i = 0; i < attributes.getLength(); i++) {
rv.addAttribute(nodeFactory.makeAttribute(
attributes.getLocalName(i),
attributes.getURINoBoundsCheck(i),
attributes.getValueNoBoundsCheck(i),
attributes.getTypeNoBoundsCheck(i) == "ID" ? Attribute.Type.ID
: Attribute.Type.CDATA));
}
return rv;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#start()
*/
@Override
protected void start(boolean fragment) throws SAXException {
document = nodeFactory.makeDocument();
cachedTableIndex = -1;
cachedTable = null;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#documentMode(nu.validator.htmlparser.common.DocumentMode,
<SUF>*/
@Override
protected void documentMode(DocumentMode mode, String publicIdentifier,
String systemIdentifier)
throws SAXException {
if (document instanceof Mode) {
Mode modal = (Mode) document;
modal.setMode(mode);
}
}
@Override
protected Element createAndInsertFosterParentedElement(String ns, String name,
HtmlAttributes attributes, Element table, Element stackParent) throws SAXException {
try {
Node parent = table.getParent();
Element child = createElement(ns, name, attributes, parent != null ? (Element) parent : stackParent);
if (parent != null) { // always an element if not null
((ParentNode) parent).insertChild(child, indexOfTable(table, stackParent));
cachedTableIndex++;
} else {
stackParent.appendChild(child);
}
return child;
} catch (XMLException e) {
fatal(e);
throw new RuntimeException("Unreachable");
}
}
@Override protected void insertFosterParentedCharacters(String text,
Element table, Element stackParent) throws SAXException {
try {
Node parent = table.getParent();
if (parent != null) { // always an element if not null
Element parentAsElt = (Element) parent;
int tableIndex = indexOfTable(table, parentAsElt);
Node prevSibling;
if (tableIndex != 0
&& ((prevSibling = parentAsElt.getChild(tableIndex - 1)) instanceof Text)) {
Text prevAsText = (Text) prevSibling;
prevAsText.setValue(prevAsText.getValue() + text);
return;
}
parentAsElt.insertChild(nodeFactory.makeText(text), tableIndex);
cachedTableIndex++;
return;
}
int childCount = stackParent.getChildCount();
Node lastChild;
if (childCount != 0
&& ((lastChild = stackParent.getChild(childCount - 1)) instanceof Text)) {
Text lastAsText = (Text) lastChild;
lastAsText.setValue(lastAsText.getValue() + text);
return;
}
stackParent.appendChild(nodeFactory.makeText(text));
} catch (XMLException e) {
fatal(e);
}
}
@Override protected void insertFosterParentedChild(Element child,
Element table, Element stackParent) throws SAXException {
try {
Node parent = table.getParent();
if (parent != null) { // always an element if not null
((ParentNode)parent).insertChild(child, indexOfTable(table, stackParent));
cachedTableIndex++;
} else {
stackParent.appendChild(child);
}
} catch (XMLException e) {
fatal(e);
}
}
private int indexOfTable(Element table, Element stackParent) {
if (table == cachedTable) {
return cachedTableIndex;
} else {
cachedTable = table;
return (cachedTableIndex = stackParent.indexOf(table));
}
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilder#end()
*/
@Override protected void end() throws SAXException {
cachedTableIndex = -1;
cachedTable = null;
}
}
|
50715_9 | import java.awt.*;
import javax.swing.*;
/**
* Miinakentästä huolehtiva paneeliluokka
*/
public class Pelipaneeli extends JPanel {
/** Swing-komponentit pitää voida serialisoida, joten tämä. */
private static final long serialVersionUID = -169273474225400220L;
/**
* Kaikki eri ruutunapit tallennetaan tähän 2D-taulukkoon. Ensimmäinen
* ulottuvuus on y-koordinaatti, toinen x-koordinaatti.
*/
private Ruutunappi[][] napit;
/**
* Pelipaneelin tieto siitä, mikä ruudukko hoitaa pelin logiikkaa.
*/
private Peliruudukko peliruudukko;
/** Tieto siitä, mihin peliin pelipaneeli kuuluu. */
private Miinapeli peli;
/** Onko ensimmäinen nappi jo avattu vai ei, eli onko peli aloitettu. */
private boolean onPeliAloitettu = false;
/** Luo uuden pelipaneelin ja asettaa sinne peliruudukon. */
public Pelipaneeli(Peliruudukko ruudukko, Miinapeli peli) {
// Sisältö menee taulukkopussileiskaan.
this.setLayout(new GridBagLayout());
// Luodaan sopivan kokoinen taulukko aivan aluksi.
int leveys = ruudukko.annaLeveys();
int korkeus = ruudukko.annaKorkeus();
this.napit = new Ruutunappi[korkeus][leveys];
// Tiedot talteen, tiedot talteen, paaarlevuu...
this.peliruudukko = ruudukko;
this.peli = peli;
// Luodaan uusi GridBagConstraints-olio, jonka gridx- ja
// gridy-attribuutteja asetellaan myöhemmin tarvittaessa.
// Oletusarvot kelpaavat meille, joten niistä ei huolestuta.
GridBagConstraints c = new GridBagConstraints();
// Luodaan nappulat sisäkkäisillä for-silmukoilla.
for (int x = 0; x < leveys; x++) {
c.gridx = x * 25;
for (int y = 0; y < korkeus; y++) {
c.gridy = y * 25;
// Luodaan se nappi.
Ruutunappi nappi = new Ruutunappi(x, y, ruudukko, this);
// Tallennetaan se
this.napit[y][x] = nappi;
this.add(nappi, c);
}
}
}
/**
* Päivittää miinapelin tilasta kertovan tekstin nykyistä pelitilannetta
* vastaavaksi.
*/
private void paivitaPelitilanneTeksti() {
String teksti = String.format(
"Miinoja jäljellä %d",
this.peliruudukko.annaMiinojenLkm()
- this.peliruudukko.annaLiputettujenRuutujenLkm());
this.peli.muutaTilaTeksti(teksti);
}
/** Hoitaa yhden Ruutunapin liputtamisen ja siihen liittyvän logiikan. */
public void liputa(int x, int y) {
if (!peliruudukko.miinojenPaikatArvottu()) {
String viesti = "Avaa ensin joku ruutu ennen liputtamista.";
this.peli.muutaTilaTeksti(viesti);
}
else {
Ruutunappi nappi = napit[y][x];
if (this.peliruudukko.onLiputettu(x, y)) {
if (this.peliruudukko.asetaLippu(x, y, false)) {
nappi.naytaLippu(false);
}
}
else {
if (this.peliruudukko.asetaLippu(x, y, true)) {
nappi.naytaLippu(true);
}
}
this.paivitaPelitilanneTeksti();
}
}
/**
* Hoitaa yhden Ruutunapin avaamisen ja siihen liittyvän logiikan.
*/
public void avaa(int x, int y) {
if (!this.onPeliAloitettu) {
// Aika.... alkaaa.... NYT!
this.peli.kaynnistaAjastin();
this.onPeliAloitettu = true;
}
int avausArvo = this.peliruudukko.avaa(x, y);
this.paivitaPelitilanneTeksti();
if (avausArvo == Peliruudukko.OLI_MIINA) {
Ruutunappi nappi = this.napit[y][x];
nappi.naytaRajahtanytMiina();
this.peli.peliPaattyi(false);
}
else if (avausArvo >= 0) {
// Avaa ruutunappi ja hoida logiikka.
this.avaaYksittainen(x, y, avausArvo);
if (avausArvo == 0) {
this.avaaNaapurit(x, y);
}
if (this.peliruudukko.peliVoitettu()) {
// Voitto kottiin!
this.peli.peliPaattyi(true);
}
}
}
/**
* Apumetodi, joka hoitaa vain yksittäisen napin avaamisen mutta ei
* mahdollisten naapurien availua.
*/
private void avaaYksittainen(int x, int y, int vihjenumero) {
Ruutunappi avattu = this.napit[y][x];
avattu.naytaVihje(vihjenumero);
}
/**
* Hoitaa yhden Ruutunapin kaikkien naapurien avaamisen.
*/
public void avaaNaapurit(int x, int y) {
java.util.List<Ruutunappi> naapurit = this.annaNaapurit(x, y);
// Pidetään tallessa kaikki uniikit naapurit, jotta ei lähdettäisi
// availemaan yksittäistä nappia useampaan kertaan.
java.util.Set<Ruutunappi> uniikit = new java.util.HashSet<Ruutunappi>();
for (int i = 0; i < naapurit.size(); i++) {
Ruutunappi tmpNaapuri = naapurit.get(i);
if (!uniikit.contains(tmpNaapuri)) {
uniikit.add(tmpNaapuri);
// Avataan se löydetty nappi
int tmpX = tmpNaapuri.annaX();
int tmpY = tmpNaapuri.annaY();
int avausArvo = this.peliruudukko.avaa(tmpX, tmpY);
if (avausArvo == Peliruudukko.OLI_MIINA) {
// Luultavasti käynyt niin, että oli liputettu väärä paikka
// ja nyt sen takia automaattiavaus epäonnistui.
// Sekin on GAME OVER! BUAHAHAHAA!
tmpNaapuri.naytaRajahtanytMiina();
this.peli.peliPaattyi(false);
return;
}
else if (avausArvo >= 0) {
this.avaaYksittainen(tmpX, tmpY, avausArvo);
if (avausArvo == 0) {
// Täytyy avata tämänkin napin naapurit, joten lisätään
// naapurit-listaan kaikki tämän napin naapurit.
naapurit.addAll(this.annaNaapurit(tmpX, tmpY));
}
// Swingi on jännä, tämän avulla toimii smoothisti
// nappuloiden avaus.
this.repaint();
}
}
}
}
/**
* Palauttaa listan kaikista annetuissa koordinaateissa sijaitsevan napin
* naapureista (enintään kahdeksan kappaletta). Käytetään vain tämän luokan
* sisällä apumetodina.
*
* @param x
* ruudun x-koordinaatti
* @param y
* ruudun y-koordinaatti
*/
private java.util.List<Ruutunappi> annaNaapurit(int x, int y) {
java.util.List<Peliruutu> naapuriRuudut =
this.peliruudukko.annaNaapurit(x, y);
java.util.List<Ruutunappi> naapuriNapit =
new java.util.ArrayList<Ruutunappi>(8);
for (Peliruutu ruutu : naapuriRuudut) {
Point p = ruutu.annaSijainti();
Ruutunappi nappi = this.napit[p.y][p.x];
naapuriNapit.add(nappi);
}
return naapuriNapit;
}
/**
* Hoitaa kaikkien loppujen ruutujen avaamisen.
*
* @param voitettu
* mikäli <code>true</code>, nappien ulkoasu on voitetun pelin
* mukainen, muutoin hävityn pelin mukainen.
*/
public void avaaKaikki(boolean voitettu) {
for (int x = 0; x < this.peliruudukko.annaLeveys(); x++) {
for (int y = 0; y < this.peliruudukko.annaKorkeus(); y++) {
Ruutunappi nappi = napit[y][x];
// Poistetaan heti hiirikuuntelija
nappi.poistaKuuntelijat();
int avausArvo = this.peliruudukko.avaa(x, y);
if (avausArvo >= 0) {
// Tyhjiä, avaamattomia paikkoja ei koskaan näytetä.
continue;
}
else if (avausArvo == Peliruudukko.OLI_MIINA) {
// Voitetun pelin miinat näytetään oikein liputettuna,
// hävityn pelin miinat näytetään ihan vain miinoina.
if (voitettu) {
nappi.naytaLippu(true);
}
else {
nappi.naytaMiina();
}
}
else if (avausArvo == Peliruudukko.OLI_LIPUTETTU) {
if (!this.peliruudukko.onMiina(x, y)) {
// Trollol, failasit!
nappi.naytaVirheellinenLiputus();
}
}
// Swingi on jännä, tämän avulla toimii smoothisti nappuloiden
// avaus.
this.repaint();
}
}
}
/**
* Avaa kaikki annetun ruudun ympäriltä olevat, lippujen määräämät varmat
* ruudut.
*
* @param x
* ruudun x-koordinaatti
* @param y
* ruudun y-koordinaatti
*/
public void avaaVarmat(int x, int y) {
java.util.List<Ruutunappi> naapurit = this.annaNaapurit(x, y);
// Käydään kaikki naapurit läpi ja avataan kaikki ruudut, joiden
// ympäriltä löytyvien liputettujen ruutujen määrä on vähintään yhtä
// suuri kuin ruudun vihjenumero.
int vihjenumero = this.peliruudukko.annaVihjenumero(x, y);
int liputettuja = this.peliruudukko.annaLiputettujenNaapurienLkm(x, y);
if (liputettuja >= vihjenumero) {
for (Ruutunappi naapuri : naapurit) {
this.avaa(naapuri.annaX(), naapuri.annaY());
}
}
}
}
| valscion/Miinapeli | src/Pelipaneeli.java | 3,777 | // Tiedot talteen, tiedot talteen, paaarlevuu...
| line_comment | nl | import java.awt.*;
import javax.swing.*;
/**
* Miinakentästä huolehtiva paneeliluokka
*/
public class Pelipaneeli extends JPanel {
/** Swing-komponentit pitää voida serialisoida, joten tämä. */
private static final long serialVersionUID = -169273474225400220L;
/**
* Kaikki eri ruutunapit tallennetaan tähän 2D-taulukkoon. Ensimmäinen
* ulottuvuus on y-koordinaatti, toinen x-koordinaatti.
*/
private Ruutunappi[][] napit;
/**
* Pelipaneelin tieto siitä, mikä ruudukko hoitaa pelin logiikkaa.
*/
private Peliruudukko peliruudukko;
/** Tieto siitä, mihin peliin pelipaneeli kuuluu. */
private Miinapeli peli;
/** Onko ensimmäinen nappi jo avattu vai ei, eli onko peli aloitettu. */
private boolean onPeliAloitettu = false;
/** Luo uuden pelipaneelin ja asettaa sinne peliruudukon. */
public Pelipaneeli(Peliruudukko ruudukko, Miinapeli peli) {
// Sisältö menee taulukkopussileiskaan.
this.setLayout(new GridBagLayout());
// Luodaan sopivan kokoinen taulukko aivan aluksi.
int leveys = ruudukko.annaLeveys();
int korkeus = ruudukko.annaKorkeus();
this.napit = new Ruutunappi[korkeus][leveys];
// Tiedot talteen,<SUF>
this.peliruudukko = ruudukko;
this.peli = peli;
// Luodaan uusi GridBagConstraints-olio, jonka gridx- ja
// gridy-attribuutteja asetellaan myöhemmin tarvittaessa.
// Oletusarvot kelpaavat meille, joten niistä ei huolestuta.
GridBagConstraints c = new GridBagConstraints();
// Luodaan nappulat sisäkkäisillä for-silmukoilla.
for (int x = 0; x < leveys; x++) {
c.gridx = x * 25;
for (int y = 0; y < korkeus; y++) {
c.gridy = y * 25;
// Luodaan se nappi.
Ruutunappi nappi = new Ruutunappi(x, y, ruudukko, this);
// Tallennetaan se
this.napit[y][x] = nappi;
this.add(nappi, c);
}
}
}
/**
* Päivittää miinapelin tilasta kertovan tekstin nykyistä pelitilannetta
* vastaavaksi.
*/
private void paivitaPelitilanneTeksti() {
String teksti = String.format(
"Miinoja jäljellä %d",
this.peliruudukko.annaMiinojenLkm()
- this.peliruudukko.annaLiputettujenRuutujenLkm());
this.peli.muutaTilaTeksti(teksti);
}
/** Hoitaa yhden Ruutunapin liputtamisen ja siihen liittyvän logiikan. */
public void liputa(int x, int y) {
if (!peliruudukko.miinojenPaikatArvottu()) {
String viesti = "Avaa ensin joku ruutu ennen liputtamista.";
this.peli.muutaTilaTeksti(viesti);
}
else {
Ruutunappi nappi = napit[y][x];
if (this.peliruudukko.onLiputettu(x, y)) {
if (this.peliruudukko.asetaLippu(x, y, false)) {
nappi.naytaLippu(false);
}
}
else {
if (this.peliruudukko.asetaLippu(x, y, true)) {
nappi.naytaLippu(true);
}
}
this.paivitaPelitilanneTeksti();
}
}
/**
* Hoitaa yhden Ruutunapin avaamisen ja siihen liittyvän logiikan.
*/
public void avaa(int x, int y) {
if (!this.onPeliAloitettu) {
// Aika.... alkaaa.... NYT!
this.peli.kaynnistaAjastin();
this.onPeliAloitettu = true;
}
int avausArvo = this.peliruudukko.avaa(x, y);
this.paivitaPelitilanneTeksti();
if (avausArvo == Peliruudukko.OLI_MIINA) {
Ruutunappi nappi = this.napit[y][x];
nappi.naytaRajahtanytMiina();
this.peli.peliPaattyi(false);
}
else if (avausArvo >= 0) {
// Avaa ruutunappi ja hoida logiikka.
this.avaaYksittainen(x, y, avausArvo);
if (avausArvo == 0) {
this.avaaNaapurit(x, y);
}
if (this.peliruudukko.peliVoitettu()) {
// Voitto kottiin!
this.peli.peliPaattyi(true);
}
}
}
/**
* Apumetodi, joka hoitaa vain yksittäisen napin avaamisen mutta ei
* mahdollisten naapurien availua.
*/
private void avaaYksittainen(int x, int y, int vihjenumero) {
Ruutunappi avattu = this.napit[y][x];
avattu.naytaVihje(vihjenumero);
}
/**
* Hoitaa yhden Ruutunapin kaikkien naapurien avaamisen.
*/
public void avaaNaapurit(int x, int y) {
java.util.List<Ruutunappi> naapurit = this.annaNaapurit(x, y);
// Pidetään tallessa kaikki uniikit naapurit, jotta ei lähdettäisi
// availemaan yksittäistä nappia useampaan kertaan.
java.util.Set<Ruutunappi> uniikit = new java.util.HashSet<Ruutunappi>();
for (int i = 0; i < naapurit.size(); i++) {
Ruutunappi tmpNaapuri = naapurit.get(i);
if (!uniikit.contains(tmpNaapuri)) {
uniikit.add(tmpNaapuri);
// Avataan se löydetty nappi
int tmpX = tmpNaapuri.annaX();
int tmpY = tmpNaapuri.annaY();
int avausArvo = this.peliruudukko.avaa(tmpX, tmpY);
if (avausArvo == Peliruudukko.OLI_MIINA) {
// Luultavasti käynyt niin, että oli liputettu väärä paikka
// ja nyt sen takia automaattiavaus epäonnistui.
// Sekin on GAME OVER! BUAHAHAHAA!
tmpNaapuri.naytaRajahtanytMiina();
this.peli.peliPaattyi(false);
return;
}
else if (avausArvo >= 0) {
this.avaaYksittainen(tmpX, tmpY, avausArvo);
if (avausArvo == 0) {
// Täytyy avata tämänkin napin naapurit, joten lisätään
// naapurit-listaan kaikki tämän napin naapurit.
naapurit.addAll(this.annaNaapurit(tmpX, tmpY));
}
// Swingi on jännä, tämän avulla toimii smoothisti
// nappuloiden avaus.
this.repaint();
}
}
}
}
/**
* Palauttaa listan kaikista annetuissa koordinaateissa sijaitsevan napin
* naapureista (enintään kahdeksan kappaletta). Käytetään vain tämän luokan
* sisällä apumetodina.
*
* @param x
* ruudun x-koordinaatti
* @param y
* ruudun y-koordinaatti
*/
private java.util.List<Ruutunappi> annaNaapurit(int x, int y) {
java.util.List<Peliruutu> naapuriRuudut =
this.peliruudukko.annaNaapurit(x, y);
java.util.List<Ruutunappi> naapuriNapit =
new java.util.ArrayList<Ruutunappi>(8);
for (Peliruutu ruutu : naapuriRuudut) {
Point p = ruutu.annaSijainti();
Ruutunappi nappi = this.napit[p.y][p.x];
naapuriNapit.add(nappi);
}
return naapuriNapit;
}
/**
* Hoitaa kaikkien loppujen ruutujen avaamisen.
*
* @param voitettu
* mikäli <code>true</code>, nappien ulkoasu on voitetun pelin
* mukainen, muutoin hävityn pelin mukainen.
*/
public void avaaKaikki(boolean voitettu) {
for (int x = 0; x < this.peliruudukko.annaLeveys(); x++) {
for (int y = 0; y < this.peliruudukko.annaKorkeus(); y++) {
Ruutunappi nappi = napit[y][x];
// Poistetaan heti hiirikuuntelija
nappi.poistaKuuntelijat();
int avausArvo = this.peliruudukko.avaa(x, y);
if (avausArvo >= 0) {
// Tyhjiä, avaamattomia paikkoja ei koskaan näytetä.
continue;
}
else if (avausArvo == Peliruudukko.OLI_MIINA) {
// Voitetun pelin miinat näytetään oikein liputettuna,
// hävityn pelin miinat näytetään ihan vain miinoina.
if (voitettu) {
nappi.naytaLippu(true);
}
else {
nappi.naytaMiina();
}
}
else if (avausArvo == Peliruudukko.OLI_LIPUTETTU) {
if (!this.peliruudukko.onMiina(x, y)) {
// Trollol, failasit!
nappi.naytaVirheellinenLiputus();
}
}
// Swingi on jännä, tämän avulla toimii smoothisti nappuloiden
// avaus.
this.repaint();
}
}
}
/**
* Avaa kaikki annetun ruudun ympäriltä olevat, lippujen määräämät varmat
* ruudut.
*
* @param x
* ruudun x-koordinaatti
* @param y
* ruudun y-koordinaatti
*/
public void avaaVarmat(int x, int y) {
java.util.List<Ruutunappi> naapurit = this.annaNaapurit(x, y);
// Käydään kaikki naapurit läpi ja avataan kaikki ruudut, joiden
// ympäriltä löytyvien liputettujen ruutujen määrä on vähintään yhtä
// suuri kuin ruudun vihjenumero.
int vihjenumero = this.peliruudukko.annaVihjenumero(x, y);
int liputettuja = this.peliruudukko.annaLiputettujenNaapurienLkm(x, y);
if (liputettuja >= vihjenumero) {
for (Ruutunappi naapuri : naapurit) {
this.avaa(naapuri.annaX(), naapuri.annaY());
}
}
}
}
|
14086_36 | /* Project Supermarkt - OOP & Software Ontwerp
* Supermarkt.java
* Hidde Westerhof | i2A
* In samenwerking met:
* Rik de Boer
* Tjipke van der Heide
* Yannick Strobl
*/
/* TODO LIST!!!!!!
* Overgang afdeling voordeelpad
* Operators op verschillende plekken
* Geenbijstand moet uitgewerkt worden
* Het pakken van producten uit schappen en of afdeling.
* Het afrekenen
* Hibernate
* JavaDOCS
* Astah
* Kan magazijn weg?
*/
package supermarkt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
*
* @author Driving Ghost
*/
public class Supermarkt {
static ArrayList<Werknemer> werkActief = new ArrayList<>(); //Werknemers die wat aan het doen zijn
static ArrayList<Werknemer> werkPauze = new ArrayList<>(); //Werknemers die niks aan het doen zijn! Arbeiten >:(!
static ArrayList<String> toDo = new ArrayList<>(); //een lijst van taken die werknemers nog moeten doen
static ArrayList<Kassa> kassas = new ArrayList<>(); //een lijst van mogelijke kassas
static ArrayList<Pad> paden = new ArrayList<>(); //een lijst van alle paden
static ArrayList<Afdeling> afdelingen = new ArrayList<>(); //een lijst van alle afdelingen
static ArrayList<Klant> klanten = new ArrayList<>(); //Lijst van alle klanten (static want hij wordt in static methoden aangeroepen)
static ArrayList<String> namen = new ArrayList<>(); //Lijst met alle namen van een .txt file. Gebruikt door Werknemers en Klanten.
static ArrayList<Artikel> inventaris = new ArrayList<>(); //Lijst met alle artikelen in de winkel.
//static Voordeelpad vdpad;
static Magazijn magazijn;
private static ArrayList<ArrayList<Klant>> klanten2;
/**
* Main methode, start het hele gebeuren op commando van de GUI.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
///Toont de GUI klasse.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GUI());
frame.pack();
frame.setVisible(true);
}
});
initPad(); // Vult de padenlijst
initAfd(); // Vult de afdelingenlijst
initNames(); // Vult de namenlijst
initJobs(); // Vult de todoList met inititele taken
initInventaris(); // Vult de Inventaris met mogelijke producten
initKassas(); // Vult kassalijst met kassas, zonder operators.
Random r = new Random(); // Maakt Random aan
boolean limitset = false; // Check of GUI de limit gezet heeft
double limit = 8.0; // Standaard limiet waaraan moet worden voldaan.
for (int i = 0; i < 4; i++) {
werkPauze.add(new Werknemer());
}
// paden.add();
while (true) {
if (limitset) {
try {
Thread.sleep(100); //voor debug redenen
Double timed = r.nextDouble(); //onze random kans
generateKlant(timed, limit, r); //maakt klanten aan
} catch (Exception e) {
System.out.println(e.getMessage());
break; //we stoppen met de simulatie.
}
updateGUI(paden, afdelingen); //update Graphical User Interface met klantinformatie.
geenBijstand(); //zet medewerkers aan het werk.
koopPaden(); //update klanten in paden
koopAfdelingen(); //update klanten in afdelingen
koopVoordeel(); //update klanten in voordeelpad.
betaalProducten();
} else {
System.out.print(""); //Dit is nodig voor de Thread.
limitset = GUI.limitset;
limit = GUI.limit;
}
}
}
public static void generateKlant(double timed, double limit, Random r) {
if (timed > limit) {
int itop = r.nextInt(10);
//Check of itop negatief is, kan namelijk niet een negatief aantal klanten toevoegen
if (itop < 0) {
itop *= -1;
}
//voegt een aantal klanten toe, afhangend van het nummer dat bij itop gemaakt is.
for (int i = 0; i < itop; i++) {
paden.get(0).klanten.add(Supermarkt.maakKlant());
}
//limitcheck.
if (limit <= GUI.limit) {
limit += 0.1;
}
} else { //geen klant is toeworden gevoegd.
limit -= 0.05;
}
}
/**
* updateGUI
*
* @param paden alle paden, artikelen, en voordeelpad
*/
public static void updateGUI(ArrayList<Pad> paden, ArrayList<Afdeling> afdelingen) {
GUI.addKlant(paden, afdelingen);
}
public static void koopPaden() {
for (Pad p : paden) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : p.klanten) {
k.winkelen(p);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
p.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Pad p : paden) {
klanten2.add(p.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//beweging van laatste pad naar afdeling.
if (!(paden.get(paden.size() - 1)).klanten.isEmpty()) { //if last pad !empty
paden.get(paden.size() - 1).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(0).klanten = klanten2.get(paden.size() - 1);
klanten2.set(paden.size() - 1, new ArrayList<Klant>());
}
//daadwerkelijke beweging tussen paden
for (int i = 0; i < paden.size(); i++) {
if (i == (0)) {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(paden.size() - 1);//
} else {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopAfdelingen() {
for (Afdeling a : afdelingen) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : a.klanten) {
k.winkelen(a);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
a.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Afdeling a : afdelingen) {
klanten2.add(a.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//daadwerkelijke beweging.
for (int i = 0; i < afdelingen.size(); i++) {
if (i == (0)) {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(afdelingen.size() - 1);//
} else {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopVoordeel() {
}
public static void betaalProducten(){
for(Kassa k : kassas){
k.scanArtikelen();
}
}
public static void gaKassa(Klant K) {
int beste = kassas.get(0).klanten.size();
int kassaIndex = 0;
for (int i = 0; i < kassas.size(); i++) {
if (kassas.get(i).klanten.size() < beste && kassas.get(i).operator != null) {
kassaIndex = i;
}
}
kassas.get(kassaIndex).klanten.add(K);
}
/**
* initNames voegt namen toe aan de static lijst Namen. Hieruit haalt de
* klasse Klant en Werknemer zijn naam.
*/
public static void initNames() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(Supermarkt.class.getResourceAsStream("randomnames.txt")));
String line;
while ((line = br.readLine()) != null) {
namen.add(line);
}
br.close();
} catch (IOException e) {
//System.out.println(e.getMessage());
}
}
/**
* *
* Initialiseert de inventaris van de winkel. Heeft effect op (nog niks)
* klant zijn wishlist, pad zijn inventaris, afdeling zijn inventaris.
*/
public static void initInventaris() {
for (int i = 0; i < Supermarkt.paden.size(); i++) {
for (int x = 0; x < paden.get(i).artikelen.size(); x += 10) {
inventaris.add(paden.get(i).artikelen.get(x));
}
}
for (int i = 0; i < Supermarkt.afdelingen.size(); i++) {
for (int x = 0; x < afdelingen.get(i).artikelen.size(); x += 5) {
inventaris.add(afdelingen.get(i).artikelen.get(x));
}
}
}
/**
*
*/
public static void initKassas(){
for(int i = 0; i < GUI.kassa; i++){
kassas.add(new Kassa());
}
}
/**
* *
* InitJobs vult de lijst toDo met dingen die nog gedaan moeten worden in de
* opstart van het programma.
*
*/
public static void initJobs() {
toDo.add("Brood");
toDo.add("Kaas");
toDo.add("Kassa");
}
/**
* initPad is het maken van alle paden vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een pad aangemaakt
*/
public static void initPad() {
ArrayList<String> vars = new ArrayList<>();
vars.add("koekjes");
vars.add("azie");
vars.add("drank");
vars.add("zuivel");
vars.add("snoep");
for (int i = 0; i < vars.size(); i++) {
paden.add(new Pad(vars.get(i), 2, 10));
}
//vdp = new Voordeelpad();
}
/**
* initAfd is het maken van alle afdelingen vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een afdelingstype aangemaakt
*/
public static void initAfd() {
ArrayList<String> vars = new ArrayList<>();
vars.add("deegwaar");
vars.add("fruit");
vars.add("vleeswaar");
vars.add("zuivel");
for (int i = 0; i < vars.size(); i++) {
afdelingen.add(new Afdeling(vars.get(i), 1, 5));
}
}
/**
*
* geenBijstand methode zorgt ervoor dat werknemers in de werkPauze in
* werkActief komen te staan met een functie.
*
* @param werkPauze Lijst met non-actieve werknemers
* @param toDo lijst met dingen die er gedaan moeten worden
*/
public static void geenBijstand() {
try {
if (!werkPauze.isEmpty()) {
if (!toDo.isEmpty()) {
werkPauze.get(0).taak = toDo.get(0);
werkActief.add(werkPauze.get(0));
// System.out.println(werkPauze.get(0).Naam + " is now going to do job: " + werkPauze.get(0).taak);
werkPauze.remove(0);
toDo.remove(0);
} else {
//System.out.println(werkPauze.get(0).Naam + " has no dedicated task. Checking stocks.");
werkPauze.get(0).taak = "bijvullen";
werkActief.add(werkPauze.get(0));
werkPauze.remove(0);
}
}
} catch (Exception e) {
}
}
/**
* *
* maakKlant methode voegt klanten toe aan de klanten lijst
*
* @return een nieuw aangemaakte klant
*/
public static Klant maakKlant() {
try {
Klant k = new Klant();
klanten.add(k);
return k;
} catch (Exception E) {
System.out.println(E.getMessage());
}
return null;
}
}
| vancha/Containing | JavaApplication2/src/supermarkt/Supermarkt.java | 4,495 | //geen klant is toeworden gevoegd.
| line_comment | nl | /* Project Supermarkt - OOP & Software Ontwerp
* Supermarkt.java
* Hidde Westerhof | i2A
* In samenwerking met:
* Rik de Boer
* Tjipke van der Heide
* Yannick Strobl
*/
/* TODO LIST!!!!!!
* Overgang afdeling voordeelpad
* Operators op verschillende plekken
* Geenbijstand moet uitgewerkt worden
* Het pakken van producten uit schappen en of afdeling.
* Het afrekenen
* Hibernate
* JavaDOCS
* Astah
* Kan magazijn weg?
*/
package supermarkt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
*
* @author Driving Ghost
*/
public class Supermarkt {
static ArrayList<Werknemer> werkActief = new ArrayList<>(); //Werknemers die wat aan het doen zijn
static ArrayList<Werknemer> werkPauze = new ArrayList<>(); //Werknemers die niks aan het doen zijn! Arbeiten >:(!
static ArrayList<String> toDo = new ArrayList<>(); //een lijst van taken die werknemers nog moeten doen
static ArrayList<Kassa> kassas = new ArrayList<>(); //een lijst van mogelijke kassas
static ArrayList<Pad> paden = new ArrayList<>(); //een lijst van alle paden
static ArrayList<Afdeling> afdelingen = new ArrayList<>(); //een lijst van alle afdelingen
static ArrayList<Klant> klanten = new ArrayList<>(); //Lijst van alle klanten (static want hij wordt in static methoden aangeroepen)
static ArrayList<String> namen = new ArrayList<>(); //Lijst met alle namen van een .txt file. Gebruikt door Werknemers en Klanten.
static ArrayList<Artikel> inventaris = new ArrayList<>(); //Lijst met alle artikelen in de winkel.
//static Voordeelpad vdpad;
static Magazijn magazijn;
private static ArrayList<ArrayList<Klant>> klanten2;
/**
* Main methode, start het hele gebeuren op commando van de GUI.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
///Toont de GUI klasse.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GUI());
frame.pack();
frame.setVisible(true);
}
});
initPad(); // Vult de padenlijst
initAfd(); // Vult de afdelingenlijst
initNames(); // Vult de namenlijst
initJobs(); // Vult de todoList met inititele taken
initInventaris(); // Vult de Inventaris met mogelijke producten
initKassas(); // Vult kassalijst met kassas, zonder operators.
Random r = new Random(); // Maakt Random aan
boolean limitset = false; // Check of GUI de limit gezet heeft
double limit = 8.0; // Standaard limiet waaraan moet worden voldaan.
for (int i = 0; i < 4; i++) {
werkPauze.add(new Werknemer());
}
// paden.add();
while (true) {
if (limitset) {
try {
Thread.sleep(100); //voor debug redenen
Double timed = r.nextDouble(); //onze random kans
generateKlant(timed, limit, r); //maakt klanten aan
} catch (Exception e) {
System.out.println(e.getMessage());
break; //we stoppen met de simulatie.
}
updateGUI(paden, afdelingen); //update Graphical User Interface met klantinformatie.
geenBijstand(); //zet medewerkers aan het werk.
koopPaden(); //update klanten in paden
koopAfdelingen(); //update klanten in afdelingen
koopVoordeel(); //update klanten in voordeelpad.
betaalProducten();
} else {
System.out.print(""); //Dit is nodig voor de Thread.
limitset = GUI.limitset;
limit = GUI.limit;
}
}
}
public static void generateKlant(double timed, double limit, Random r) {
if (timed > limit) {
int itop = r.nextInt(10);
//Check of itop negatief is, kan namelijk niet een negatief aantal klanten toevoegen
if (itop < 0) {
itop *= -1;
}
//voegt een aantal klanten toe, afhangend van het nummer dat bij itop gemaakt is.
for (int i = 0; i < itop; i++) {
paden.get(0).klanten.add(Supermarkt.maakKlant());
}
//limitcheck.
if (limit <= GUI.limit) {
limit += 0.1;
}
} else { //geen klant<SUF>
limit -= 0.05;
}
}
/**
* updateGUI
*
* @param paden alle paden, artikelen, en voordeelpad
*/
public static void updateGUI(ArrayList<Pad> paden, ArrayList<Afdeling> afdelingen) {
GUI.addKlant(paden, afdelingen);
}
public static void koopPaden() {
for (Pad p : paden) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : p.klanten) {
k.winkelen(p);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
p.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Pad p : paden) {
klanten2.add(p.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//beweging van laatste pad naar afdeling.
if (!(paden.get(paden.size() - 1)).klanten.isEmpty()) { //if last pad !empty
paden.get(paden.size() - 1).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(0).klanten = klanten2.get(paden.size() - 1);
klanten2.set(paden.size() - 1, new ArrayList<Klant>());
}
//daadwerkelijke beweging tussen paden
for (int i = 0; i < paden.size(); i++) {
if (i == (0)) {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(paden.size() - 1);//
} else {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopAfdelingen() {
for (Afdeling a : afdelingen) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : a.klanten) {
k.winkelen(a);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
a.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Afdeling a : afdelingen) {
klanten2.add(a.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//daadwerkelijke beweging.
for (int i = 0; i < afdelingen.size(); i++) {
if (i == (0)) {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(afdelingen.size() - 1);//
} else {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopVoordeel() {
}
public static void betaalProducten(){
for(Kassa k : kassas){
k.scanArtikelen();
}
}
public static void gaKassa(Klant K) {
int beste = kassas.get(0).klanten.size();
int kassaIndex = 0;
for (int i = 0; i < kassas.size(); i++) {
if (kassas.get(i).klanten.size() < beste && kassas.get(i).operator != null) {
kassaIndex = i;
}
}
kassas.get(kassaIndex).klanten.add(K);
}
/**
* initNames voegt namen toe aan de static lijst Namen. Hieruit haalt de
* klasse Klant en Werknemer zijn naam.
*/
public static void initNames() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(Supermarkt.class.getResourceAsStream("randomnames.txt")));
String line;
while ((line = br.readLine()) != null) {
namen.add(line);
}
br.close();
} catch (IOException e) {
//System.out.println(e.getMessage());
}
}
/**
* *
* Initialiseert de inventaris van de winkel. Heeft effect op (nog niks)
* klant zijn wishlist, pad zijn inventaris, afdeling zijn inventaris.
*/
public static void initInventaris() {
for (int i = 0; i < Supermarkt.paden.size(); i++) {
for (int x = 0; x < paden.get(i).artikelen.size(); x += 10) {
inventaris.add(paden.get(i).artikelen.get(x));
}
}
for (int i = 0; i < Supermarkt.afdelingen.size(); i++) {
for (int x = 0; x < afdelingen.get(i).artikelen.size(); x += 5) {
inventaris.add(afdelingen.get(i).artikelen.get(x));
}
}
}
/**
*
*/
public static void initKassas(){
for(int i = 0; i < GUI.kassa; i++){
kassas.add(new Kassa());
}
}
/**
* *
* InitJobs vult de lijst toDo met dingen die nog gedaan moeten worden in de
* opstart van het programma.
*
*/
public static void initJobs() {
toDo.add("Brood");
toDo.add("Kaas");
toDo.add("Kassa");
}
/**
* initPad is het maken van alle paden vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een pad aangemaakt
*/
public static void initPad() {
ArrayList<String> vars = new ArrayList<>();
vars.add("koekjes");
vars.add("azie");
vars.add("drank");
vars.add("zuivel");
vars.add("snoep");
for (int i = 0; i < vars.size(); i++) {
paden.add(new Pad(vars.get(i), 2, 10));
}
//vdp = new Voordeelpad();
}
/**
* initAfd is het maken van alle afdelingen vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een afdelingstype aangemaakt
*/
public static void initAfd() {
ArrayList<String> vars = new ArrayList<>();
vars.add("deegwaar");
vars.add("fruit");
vars.add("vleeswaar");
vars.add("zuivel");
for (int i = 0; i < vars.size(); i++) {
afdelingen.add(new Afdeling(vars.get(i), 1, 5));
}
}
/**
*
* geenBijstand methode zorgt ervoor dat werknemers in de werkPauze in
* werkActief komen te staan met een functie.
*
* @param werkPauze Lijst met non-actieve werknemers
* @param toDo lijst met dingen die er gedaan moeten worden
*/
public static void geenBijstand() {
try {
if (!werkPauze.isEmpty()) {
if (!toDo.isEmpty()) {
werkPauze.get(0).taak = toDo.get(0);
werkActief.add(werkPauze.get(0));
// System.out.println(werkPauze.get(0).Naam + " is now going to do job: " + werkPauze.get(0).taak);
werkPauze.remove(0);
toDo.remove(0);
} else {
//System.out.println(werkPauze.get(0).Naam + " has no dedicated task. Checking stocks.");
werkPauze.get(0).taak = "bijvullen";
werkActief.add(werkPauze.get(0));
werkPauze.remove(0);
}
}
} catch (Exception e) {
}
}
/**
* *
* maakKlant methode voegt klanten toe aan de klanten lijst
*
* @return een nieuw aangemaakte klant
*/
public static Klant maakKlant() {
try {
Klant k = new Klant();
klanten.add(k);
return k;
} catch (Exception E) {
System.out.println(E.getMessage());
}
return null;
}
}
|
13721_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.awt.Window;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author E alse
*/
public class Controller {
private boolean isPlaying = false;
private Timer simulatieTimer;
private Calendar cal;
private ControllerWindow controllerWindow;
private SocketServer socketServer;
private Boolean firstTime = true;
private List<Container> containers;
public Controller(ControllerWindow controllerWindow) {
this.controllerWindow = controllerWindow;
// Setting a default port number.
int portNumber = 9991;
// initializing the Socket Server
socketServer = new SocketServer(portNumber);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
socketServer.start();
} catch (IOException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
thread.start();
}
public void start() {
containers = controllerWindow.getContainerList();
if (!isPlaying) {
cal = Calendar.getInstance();
cal.setTime(controllerWindow.getTime());
isPlaying = true;
}
this.simulatieTimer = new Timer();
this.simulatieTimer.schedule(new TimerTask() {
@Override
public void run() {
timerExecuter();
}
}, 0, 100);
}
// voert onderstaande methode iedere seconde uit (om aan te passen kijk bij start())
public void timerExecuter() {
if (firstTime) {
for (int i = 0; i < 10; i++) {
socketServer.sendMessage(containers.get(i).toString());
}
firstTime = false;
}
cal.add(Calendar.SECOND, 1);
controllerWindow.setTime(cal);
}
}
| vancha/Controllertje | Controller/src/controller/Controller.java | 647 | // voert onderstaande methode iedere seconde uit (om aan te passen kijk bij start())
| line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.awt.Window;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author E alse
*/
public class Controller {
private boolean isPlaying = false;
private Timer simulatieTimer;
private Calendar cal;
private ControllerWindow controllerWindow;
private SocketServer socketServer;
private Boolean firstTime = true;
private List<Container> containers;
public Controller(ControllerWindow controllerWindow) {
this.controllerWindow = controllerWindow;
// Setting a default port number.
int portNumber = 9991;
// initializing the Socket Server
socketServer = new SocketServer(portNumber);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
socketServer.start();
} catch (IOException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
thread.start();
}
public void start() {
containers = controllerWindow.getContainerList();
if (!isPlaying) {
cal = Calendar.getInstance();
cal.setTime(controllerWindow.getTime());
isPlaying = true;
}
this.simulatieTimer = new Timer();
this.simulatieTimer.schedule(new TimerTask() {
@Override
public void run() {
timerExecuter();
}
}, 0, 100);
}
// voert onderstaande<SUF>
public void timerExecuter() {
if (firstTime) {
for (int i = 0; i < 10; i++) {
socketServer.sendMessage(containers.get(i).toString());
}
firstTime = false;
}
cal.add(Calendar.SECOND, 1);
controllerWindow.setTime(cal);
}
}
|
201888_0 | package be.vives.ti.dndweapons.controllers;
import be.vives.ti.dndweapons.domain.Weapon;
import be.vives.ti.dndweapons.domain.WeaponAttack;
import be.vives.ti.dndweapons.exceptions.ResourceNotFoundException;
import be.vives.ti.dndweapons.repository.WeaponAttackRepository;
import be.vives.ti.dndweapons.repository.WeaponRepository;
import be.vives.ti.dndweapons.requests.WeaponAttackRequest;
import be.vives.ti.dndweapons.requests.WeaponRequest;
import be.vives.ti.dndweapons.responses.WeaponListResponse;
import be.vives.ti.dndweapons.responses.WeaponResponse;
import be.vives.ti.dndweapons.responses.WeaponWithPropertiesResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/weapons")
@CrossOrigin("*")
public class WeaponController {
private final WeaponRepository weaponRepository;
private final WeaponAttackRepository weaponAttackRepository;
public WeaponController(WeaponRepository weaponRepository, WeaponAttackRepository weaponAttackRepository) {
this.weaponRepository = weaponRepository;
this.weaponAttackRepository = weaponAttackRepository;
}
@Operation(summary = "Get all weapons", description = "Returns a list with all weapons")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved the list of weapons",
content = { @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = WeaponListResponse.class))) })
})
@GetMapping
public List<WeaponListResponse> findAllWeapons(){
return weaponRepository.findAll().stream().map(WeaponListResponse::new).toList();
}
@Operation(summary = "Get all weapons containing query", description = "Returns a list with all weapons where the name contains the query")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved the list of weapons",
content = { @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = WeaponListResponse.class))) })
})
@GetMapping("/search")
public List<WeaponListResponse> findByNameContainingIgnoreCase(@RequestParam("query") String query) {
return weaponRepository.findByNameContainingIgnoreCase(query).stream().map(WeaponListResponse::new).toList();
}
@Operation(summary = "Find weapon by id", description = "Returns one weapon with all its details by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Found the weapon",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = WeaponResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid id",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@GetMapping("/{weaponId}")
public WeaponResponse retrieveWeaponById(@PathVariable(name = "weaponId") Long weaponId) {
return new WeaponResponse(
weaponRepository.findById(weaponId).orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon"))
);
}
@Operation(summary = "Find the properties of a weapon", description = "Returns the properties with description of one weapon by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Found the weapon",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = WeaponWithPropertiesResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid id",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@GetMapping("/{weaponId}/properties")
public WeaponWithPropertiesResponse retrieveWeaponByIdWithProperties(@PathVariable(name = "weaponId") Long weaponId) {
return new WeaponWithPropertiesResponse(weaponRepository.findById(weaponId).orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon")));
}
@Operation(summary = "Add new weapon", description = "Add new weapon")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Weapon created",
content = @Content),
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content)
})
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> createWeapon(@RequestBody @Valid WeaponRequest weaponRequest) {
Weapon newWeapon = new Weapon(
weaponRequest.getName(),
weaponRequest.getCost(),
weaponRequest.getRarity(),
weaponRequest.getDamageModifier(),
weaponRequest.getWeight(),
weaponRequest.getProperties(),
weaponRequest.getWeaponType(),
weaponRequest.isMartial()
);
Weapon weapon = weaponRepository.save(newWeapon);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(weapon.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@Operation(summary = "Update existing weapon", description = "Update existing weapon by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Weapon updated",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = WeaponResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@PutMapping("/{weaponId}")
public WeaponResponse putWeapon(@PathVariable(name = "weaponId") Long weaponId,
@RequestBody @Valid WeaponRequest weaponRequest) {
Weapon weapon = weaponRepository.findById(Long.parseLong(weaponId.toString())).orElseThrow(
() -> new ResourceNotFoundException(weaponId.toString(), "weapon")
);
weapon.setName(weaponRequest.getName());
weapon.setCost(weaponRequest.getCost());
weapon.setRarity(weaponRequest.getRarity());
weapon.setDamageModifier(weaponRequest.getDamageModifier());
weapon.setWeight(weaponRequest.getWeight());
weapon.setProperties(weaponRequest.getProperties());
weapon.setWeaponType(weaponRequest.getWeaponType());
weapon.setMartial(weaponRequest.isMartial());
return new WeaponResponse(weaponRepository.save(weapon));
}
@Operation(summary = "Delete weapon", description = "Delete weapon and its weapon-attacks by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Weapon deleted",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@DeleteMapping("/{weaponId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteWeapon(@PathVariable(name = "weaponId") Long weaponId) {
weaponRepository.findById(weaponId).orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon"));
try {
weaponRepository.deleteById(weaponId);
} catch (EmptyResultDataAccessException e) {
// als het niet bestaat dan hoefde het niet verwijderd te worden
}
}
@Operation(summary = "Add new weapon-attack", description = "Add new weapon-attack to existing weapon")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Weapon-attack created",
content = @Content),
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@PostMapping("/{weaponId}/weapon-attacks")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> addAttackToWeapon(@PathVariable(name = "weaponId") Long weaponId, @RequestBody @Valid WeaponAttackRequest weaponAttackRequest) {
WeaponAttack newWeaponAttack = new WeaponAttack(
weaponAttackRequest.getName(),
weaponAttackRequest.getDamageRolls(),
weaponAttackRequest.getRange()
);
WeaponAttack weaponAttack = weaponAttackRepository.save(newWeaponAttack);
Weapon weapon = weaponRepository.findById(weaponId)
.orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon"));
weapon.addAttack(weaponAttack);
weaponRepository.save(weapon);
URI location = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/weapons/{id}/weapon-attacks")
.buildAndExpand(weaponAttack.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@Operation(summary = "Delete weapon", description = "Delete weapon-attack by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Weapon attack deleted",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@DeleteMapping("/weapon-attacks/{weaponAttackId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteAttackOfWeapon(@PathVariable(name = "weaponAttackId") Long weaponAttackId) {
try {
weaponAttackRepository.deleteById(weaponAttackId);
} catch (EmptyResultDataAccessException e) {
// als het niet bestaat dan hoefde het niet verwijderd te worden
}
}
}
| vanhaverbekejitse/dnd-weapons | src/main/java/be/vives/ti/dndweapons/controllers/WeaponController.java | 2,949 | // als het niet bestaat dan hoefde het niet verwijderd te worden | line_comment | nl | package be.vives.ti.dndweapons.controllers;
import be.vives.ti.dndweapons.domain.Weapon;
import be.vives.ti.dndweapons.domain.WeaponAttack;
import be.vives.ti.dndweapons.exceptions.ResourceNotFoundException;
import be.vives.ti.dndweapons.repository.WeaponAttackRepository;
import be.vives.ti.dndweapons.repository.WeaponRepository;
import be.vives.ti.dndweapons.requests.WeaponAttackRequest;
import be.vives.ti.dndweapons.requests.WeaponRequest;
import be.vives.ti.dndweapons.responses.WeaponListResponse;
import be.vives.ti.dndweapons.responses.WeaponResponse;
import be.vives.ti.dndweapons.responses.WeaponWithPropertiesResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/weapons")
@CrossOrigin("*")
public class WeaponController {
private final WeaponRepository weaponRepository;
private final WeaponAttackRepository weaponAttackRepository;
public WeaponController(WeaponRepository weaponRepository, WeaponAttackRepository weaponAttackRepository) {
this.weaponRepository = weaponRepository;
this.weaponAttackRepository = weaponAttackRepository;
}
@Operation(summary = "Get all weapons", description = "Returns a list with all weapons")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved the list of weapons",
content = { @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = WeaponListResponse.class))) })
})
@GetMapping
public List<WeaponListResponse> findAllWeapons(){
return weaponRepository.findAll().stream().map(WeaponListResponse::new).toList();
}
@Operation(summary = "Get all weapons containing query", description = "Returns a list with all weapons where the name contains the query")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved the list of weapons",
content = { @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = WeaponListResponse.class))) })
})
@GetMapping("/search")
public List<WeaponListResponse> findByNameContainingIgnoreCase(@RequestParam("query") String query) {
return weaponRepository.findByNameContainingIgnoreCase(query).stream().map(WeaponListResponse::new).toList();
}
@Operation(summary = "Find weapon by id", description = "Returns one weapon with all its details by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Found the weapon",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = WeaponResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid id",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@GetMapping("/{weaponId}")
public WeaponResponse retrieveWeaponById(@PathVariable(name = "weaponId") Long weaponId) {
return new WeaponResponse(
weaponRepository.findById(weaponId).orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon"))
);
}
@Operation(summary = "Find the properties of a weapon", description = "Returns the properties with description of one weapon by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Found the weapon",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = WeaponWithPropertiesResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid id",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@GetMapping("/{weaponId}/properties")
public WeaponWithPropertiesResponse retrieveWeaponByIdWithProperties(@PathVariable(name = "weaponId") Long weaponId) {
return new WeaponWithPropertiesResponse(weaponRepository.findById(weaponId).orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon")));
}
@Operation(summary = "Add new weapon", description = "Add new weapon")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Weapon created",
content = @Content),
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content)
})
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> createWeapon(@RequestBody @Valid WeaponRequest weaponRequest) {
Weapon newWeapon = new Weapon(
weaponRequest.getName(),
weaponRequest.getCost(),
weaponRequest.getRarity(),
weaponRequest.getDamageModifier(),
weaponRequest.getWeight(),
weaponRequest.getProperties(),
weaponRequest.getWeaponType(),
weaponRequest.isMartial()
);
Weapon weapon = weaponRepository.save(newWeapon);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(weapon.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@Operation(summary = "Update existing weapon", description = "Update existing weapon by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Weapon updated",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = WeaponResponse.class)) }),
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@PutMapping("/{weaponId}")
public WeaponResponse putWeapon(@PathVariable(name = "weaponId") Long weaponId,
@RequestBody @Valid WeaponRequest weaponRequest) {
Weapon weapon = weaponRepository.findById(Long.parseLong(weaponId.toString())).orElseThrow(
() -> new ResourceNotFoundException(weaponId.toString(), "weapon")
);
weapon.setName(weaponRequest.getName());
weapon.setCost(weaponRequest.getCost());
weapon.setRarity(weaponRequest.getRarity());
weapon.setDamageModifier(weaponRequest.getDamageModifier());
weapon.setWeight(weaponRequest.getWeight());
weapon.setProperties(weaponRequest.getProperties());
weapon.setWeaponType(weaponRequest.getWeaponType());
weapon.setMartial(weaponRequest.isMartial());
return new WeaponResponse(weaponRepository.save(weapon));
}
@Operation(summary = "Delete weapon", description = "Delete weapon and its weapon-attacks by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Weapon deleted",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@DeleteMapping("/{weaponId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteWeapon(@PathVariable(name = "weaponId") Long weaponId) {
weaponRepository.findById(weaponId).orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon"));
try {
weaponRepository.deleteById(weaponId);
} catch (EmptyResultDataAccessException e) {
// als het<SUF>
}
}
@Operation(summary = "Add new weapon-attack", description = "Add new weapon-attack to existing weapon")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Weapon-attack created",
content = @Content),
@ApiResponse(responseCode = "400", description = "Invalid input",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@PostMapping("/{weaponId}/weapon-attacks")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> addAttackToWeapon(@PathVariable(name = "weaponId") Long weaponId, @RequestBody @Valid WeaponAttackRequest weaponAttackRequest) {
WeaponAttack newWeaponAttack = new WeaponAttack(
weaponAttackRequest.getName(),
weaponAttackRequest.getDamageRolls(),
weaponAttackRequest.getRange()
);
WeaponAttack weaponAttack = weaponAttackRepository.save(newWeaponAttack);
Weapon weapon = weaponRepository.findById(weaponId)
.orElseThrow(() -> new ResourceNotFoundException(weaponId.toString(), "weapon"));
weapon.addAttack(weaponAttack);
weaponRepository.save(weapon);
URI location = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/weapons/{id}/weapon-attacks")
.buildAndExpand(weaponAttack.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@Operation(summary = "Delete weapon", description = "Delete weapon-attack by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Weapon attack deleted",
content = @Content),
@ApiResponse(responseCode = "404", description = "Weapon not found",
content = @Content)
})
@DeleteMapping("/weapon-attacks/{weaponAttackId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteAttackOfWeapon(@PathVariable(name = "weaponAttackId") Long weaponAttackId) {
try {
weaponAttackRepository.deleteById(weaponAttackId);
} catch (EmptyResultDataAccessException e) {
// als het niet bestaat dan hoefde het niet verwijderd te worden
}
}
}
|
37944_4 | package org.cq2.delegator.internal;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.cq2.delegator.Component;
import org.cq2.delegator.Self;
import org.cq2.delegator.internal.MethodsCache.Tuple;
import org.cq2.delegator.method.MethodUtil;
public class ComposedClass {
private List classes;
private ComposedClass[] removeReferences;
private Map addMap;
private Map insertMap;
private ForwardingMethod[] implementingMethods;
private static ComposedClass emptyClass;
private int[] componentIndexes;
private ComposedClass() {
this(new ArrayList());
}
ComposedClass(List classes) {
this.classes = classes;
removeReferences = new ComposedClass[classes.size()];
addMap = new HashMap();
insertMap = new HashMap();
implementingMethods = new ForwardingMethod[0];
componentIndexes = new int[0];
}
public static ComposedClass getEmptyClass() {
if (emptyClass == null) {
emptyClass = ComposedClassCache.get(new ArrayList());
}
return emptyClass;
}
public ComposedClass remove(int i) {
ComposedClass result = removeReferences[i];
if (result == null) {
List smallerClasses = new ArrayList(classes);
smallerClasses.remove(i);
result = ComposedClassCache.get(smallerClasses);
removeReferences[i] = result;
}
return result;
}
public ComposedClass add(Class clazz) {
ComposedClass result = (ComposedClass) addMap.get(clazz);
if (result == null) {
List largerClasses = new ArrayList(classes);
largerClasses.add(clazz);
result = ComposedClassCache.get(largerClasses);
addMap.put(clazz, result);
}
return result;
}
public ComposedClass insert(Class clazz) {
ComposedClass result = (ComposedClass) insertMap.get(clazz);
if (result == null) {
List largerClasses = new ArrayList(classes);
largerClasses.add(0, clazz);
result = ComposedClassCache.get(largerClasses);
insertMap.put(clazz, result);
}
return result;
}
public int getComponentIndex(int methodIdentifier) {
if (methodIdentifier < componentIndexes.length) {
int result = componentIndexes[methodIdentifier];
if (result != -1)
return result;
} else enlargeArrays(methodIdentifier + 1);
setMethod(methodIdentifier);
return componentIndexes[methodIdentifier];
}
public ForwardingMethod getMethod(int methodIdentifier) {
if (methodIdentifier < implementingMethods.length) {
ForwardingMethod result = implementingMethods[methodIdentifier];
if (result != null)
return result;
} else enlargeArrays(methodIdentifier + 1);
return setMethod(methodIdentifier);
}
private Tuple resolve(int uniqueIdentifier) {
Method method = ForwardingMethodRegister.getInstance().getMethod(uniqueIdentifier);
//TODO synchronization noodzaak opnieuw checken.
if ("hashCode".equals(method.getName()) || "equals".equals(method.getName()))
return resolve(method, classes.size(), Self.class);
int i = 0;
for (; i < classes.size(); i++) {
Class clazz = (Class) classes.get(i);
Tuple result = resolve(method, i, clazz);
if (result != null) return result;
}
Tuple result = resolve(method, classes.size(), Self.class);
if (result != null) return result;
throw new NoSuchMethodError(method.toString());
}
private Tuple resolve(Method method, int i, Class clazz) {
Method delegateMethod;
boolean componentMethodIsProtected = false;
if (Component.class.isAssignableFrom(clazz)) {
delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName() + ClassGenerator.SUPERCALL_POSTFIX, method.getParameterTypes(),
method.getExceptionTypes());
//De superdelegatemethod is feitelijk de methode zoals
// ingetiept door de programmeur
//deze bestaat per definitie - als die niet gevonden wordt
// betekent dat hij protected of package is
Method superDelegateMethod = MethodUtil.getDeclaredMethod(
clazz.getSuperclass(), method.getName(),
method.getParameterTypes(), method.getExceptionTypes());
componentMethodIsProtected = (delegateMethod != null)
&& (superDelegateMethod == null);
} else {
delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName(), method.getParameterTypes(),
method.getExceptionTypes());
if (delegateMethod != null) componentMethodIsProtected = Modifier
.isProtected(delegateMethod.getModifiers());
}
if (delegateMethod != null
&& (!componentMethodIsProtected || Modifier
.isProtected(method.getModifiers()))
|| !Modifier.isPublic(method.getModifiers())) {
return new Tuple(i, delegateMethod);
}
return null;
}
private ForwardingMethod setMethod(int methodIdentifier) {
Tuple tuple = resolve(methodIdentifier);
int componentIndex = tuple.componentIndex;
Class componentClass;
if (componentIndex == classes.size()) componentClass = Self.class;
else componentClass = (Class) classes.get(componentIndex);
Method delegateMethod = tuple.method;
int componentClassIdentifier = ComponentClassRegister.getInstance().getIdentifier(componentClass);
Class clazz = null;
try {
clazz = ClassGenerator.getClassLoader().loadClass("org.cq2.delegator.ComponentMethod" + methodIdentifier + "_" + componentClassIdentifier);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
ForwardingMethod result = null;
try {
result = (ForwardingMethod) clazz.newInstance();
clazz.getField("componentIndex").set(result, new Integer(componentIndex));
} catch (Exception e) {
throw new RuntimeException(e);
}
implementingMethods[methodIdentifier] = result;
componentIndexes[methodIdentifier] = componentIndex;
return result;
}
private void enlargeArrays(int length) {
ForwardingMethod[] oldComponentMethods = implementingMethods;
implementingMethods = new ForwardingMethod[length];
System.arraycopy(oldComponentMethods, 0, implementingMethods, 0,
oldComponentMethods.length);
int[] oldComponentIndexes = componentIndexes;
componentIndexes = new int[length];
System.arraycopy(oldComponentIndexes, 0, componentIndexes, 0,
oldComponentIndexes.length);
Arrays.fill(componentIndexes, oldComponentIndexes.length, componentIndexes.length - 1, -1);
}
public String toString() {
return "ComposedClass: " + classes.toString();
}
public ComposedClass getSuffix(int i) {
if (i == 0) return this;
return remove(0).getSuffix(i - 1);
}
} | vanschelven/delegator | org/cq2/delegator/internal/ComposedClass.java | 1,951 | // betekent dat hij protected of package is | line_comment | nl | package org.cq2.delegator.internal;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.cq2.delegator.Component;
import org.cq2.delegator.Self;
import org.cq2.delegator.internal.MethodsCache.Tuple;
import org.cq2.delegator.method.MethodUtil;
public class ComposedClass {
private List classes;
private ComposedClass[] removeReferences;
private Map addMap;
private Map insertMap;
private ForwardingMethod[] implementingMethods;
private static ComposedClass emptyClass;
private int[] componentIndexes;
private ComposedClass() {
this(new ArrayList());
}
ComposedClass(List classes) {
this.classes = classes;
removeReferences = new ComposedClass[classes.size()];
addMap = new HashMap();
insertMap = new HashMap();
implementingMethods = new ForwardingMethod[0];
componentIndexes = new int[0];
}
public static ComposedClass getEmptyClass() {
if (emptyClass == null) {
emptyClass = ComposedClassCache.get(new ArrayList());
}
return emptyClass;
}
public ComposedClass remove(int i) {
ComposedClass result = removeReferences[i];
if (result == null) {
List smallerClasses = new ArrayList(classes);
smallerClasses.remove(i);
result = ComposedClassCache.get(smallerClasses);
removeReferences[i] = result;
}
return result;
}
public ComposedClass add(Class clazz) {
ComposedClass result = (ComposedClass) addMap.get(clazz);
if (result == null) {
List largerClasses = new ArrayList(classes);
largerClasses.add(clazz);
result = ComposedClassCache.get(largerClasses);
addMap.put(clazz, result);
}
return result;
}
public ComposedClass insert(Class clazz) {
ComposedClass result = (ComposedClass) insertMap.get(clazz);
if (result == null) {
List largerClasses = new ArrayList(classes);
largerClasses.add(0, clazz);
result = ComposedClassCache.get(largerClasses);
insertMap.put(clazz, result);
}
return result;
}
public int getComponentIndex(int methodIdentifier) {
if (methodIdentifier < componentIndexes.length) {
int result = componentIndexes[methodIdentifier];
if (result != -1)
return result;
} else enlargeArrays(methodIdentifier + 1);
setMethod(methodIdentifier);
return componentIndexes[methodIdentifier];
}
public ForwardingMethod getMethod(int methodIdentifier) {
if (methodIdentifier < implementingMethods.length) {
ForwardingMethod result = implementingMethods[methodIdentifier];
if (result != null)
return result;
} else enlargeArrays(methodIdentifier + 1);
return setMethod(methodIdentifier);
}
private Tuple resolve(int uniqueIdentifier) {
Method method = ForwardingMethodRegister.getInstance().getMethod(uniqueIdentifier);
//TODO synchronization noodzaak opnieuw checken.
if ("hashCode".equals(method.getName()) || "equals".equals(method.getName()))
return resolve(method, classes.size(), Self.class);
int i = 0;
for (; i < classes.size(); i++) {
Class clazz = (Class) classes.get(i);
Tuple result = resolve(method, i, clazz);
if (result != null) return result;
}
Tuple result = resolve(method, classes.size(), Self.class);
if (result != null) return result;
throw new NoSuchMethodError(method.toString());
}
private Tuple resolve(Method method, int i, Class clazz) {
Method delegateMethod;
boolean componentMethodIsProtected = false;
if (Component.class.isAssignableFrom(clazz)) {
delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName() + ClassGenerator.SUPERCALL_POSTFIX, method.getParameterTypes(),
method.getExceptionTypes());
//De superdelegatemethod is feitelijk de methode zoals
// ingetiept door de programmeur
//deze bestaat per definitie - als die niet gevonden wordt
// betekent dat<SUF>
Method superDelegateMethod = MethodUtil.getDeclaredMethod(
clazz.getSuperclass(), method.getName(),
method.getParameterTypes(), method.getExceptionTypes());
componentMethodIsProtected = (delegateMethod != null)
&& (superDelegateMethod == null);
} else {
delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName(), method.getParameterTypes(),
method.getExceptionTypes());
if (delegateMethod != null) componentMethodIsProtected = Modifier
.isProtected(delegateMethod.getModifiers());
}
if (delegateMethod != null
&& (!componentMethodIsProtected || Modifier
.isProtected(method.getModifiers()))
|| !Modifier.isPublic(method.getModifiers())) {
return new Tuple(i, delegateMethod);
}
return null;
}
private ForwardingMethod setMethod(int methodIdentifier) {
Tuple tuple = resolve(methodIdentifier);
int componentIndex = tuple.componentIndex;
Class componentClass;
if (componentIndex == classes.size()) componentClass = Self.class;
else componentClass = (Class) classes.get(componentIndex);
Method delegateMethod = tuple.method;
int componentClassIdentifier = ComponentClassRegister.getInstance().getIdentifier(componentClass);
Class clazz = null;
try {
clazz = ClassGenerator.getClassLoader().loadClass("org.cq2.delegator.ComponentMethod" + methodIdentifier + "_" + componentClassIdentifier);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
ForwardingMethod result = null;
try {
result = (ForwardingMethod) clazz.newInstance();
clazz.getField("componentIndex").set(result, new Integer(componentIndex));
} catch (Exception e) {
throw new RuntimeException(e);
}
implementingMethods[methodIdentifier] = result;
componentIndexes[methodIdentifier] = componentIndex;
return result;
}
private void enlargeArrays(int length) {
ForwardingMethod[] oldComponentMethods = implementingMethods;
implementingMethods = new ForwardingMethod[length];
System.arraycopy(oldComponentMethods, 0, implementingMethods, 0,
oldComponentMethods.length);
int[] oldComponentIndexes = componentIndexes;
componentIndexes = new int[length];
System.arraycopy(oldComponentIndexes, 0, componentIndexes, 0,
oldComponentIndexes.length);
Arrays.fill(componentIndexes, oldComponentIndexes.length, componentIndexes.length - 1, -1);
}
public String toString() {
return "ComposedClass: " + classes.toString();
}
public ComposedClass getSuffix(int i) {
if (i == 0) return this;
return remove(0).getSuffix(i - 1);
}
} |
12245_11 | package kulak_ogp_oz1.eigen;
import be.kuleuven.cs.som.annotate.*;
/**
* A class that represents an oil tank
* @version 1.1
* @author Vincent Van Schependom
*/
public class Oiltank {
private float capacity;
private float oil;
/**
* Een constructor voor de klasse co.vis.kulak_ogp.oz1.eigen.Oiltank met 1 argument.
* @param capacity
* @effect Na het uitvoeren van de constructor wordt een olietank aangemaakt inhoud van 0 en wordt de capaciteit
* ingesteld op de meegegeven waarde via setCapacity.
*/
public Oiltank(float capacity) {
this(capacity,0);
}
/**
* Een constructor voor de klasse co.vis.kulak_ogp.oz1.eigen.Oiltank met 2 argumenten.
* @param capacity De capaciteit van de nieuwe co.vis.kulak_ogp.oz1.eigen.Oiltank.
* @param oil De inhoud van de nieuwe olietank.
* @effect Er wordt een nieuwe olietank aangemaakt en de inhoud en de capaciteit worden ingesteld met respectievelijk
* de methodes setOil en setCapacity.
*/
public Oiltank(float capacity, float oil) {
this.setOil(oil);
this.setCapacity(capacity);
}
/**
* Een constructor voor de klasse co.vis.kulak_ogp.oz1.eigen.Oiltank zonder argumenten.
* @effect Na het aanroepen van deze constructor wordt een olietank aangemaakt met capaciteit 5000 en inhoud 0
* aan de hand van de constructor die zowel capaciteit als inhoud meekrijgt.
*/
public Oiltank() {
this(5000,0);
}
/**
* De getter voor de capaciteit op te halen.
* @return De capaciteit wordt teruggegeven.
*/
@Basic
public float getCapacity() {
return capacity;
}
/**
* De getter voor de hoeveelheid olie in de tank
* @return Deze getter returnt de hoeveelheid olie.
*/
@Basic
public float getOil() {
return oil;
}
/**
* Een methode om de capaciteit in te stellen
* @param capacity De capaciteit om in te stellen
* @post Als de capaciteit positief is, wordt de capaciteit ingesteld op de meegegeven waarde, anders
* wordt de capaciteit ingesteld op 0.
*/
private void setCapacity(float capacity) {
if (capacity >= 0) {
this.capacity = capacity;
} else {
this.capacity = 0;
}
}
/**
* Setter voor de hoeveelheid olie.
* @param oil De te setten hoeveelheid
* @post Na het uitvoeren van de setter zal de hoeveelheid olie in de tank gelijk zijn aan oil, als deze
* de capaciteit niet overschrijdt. (intertia: niks zeggen over de else -> ongewijzigd)
*/
@Basic
private void setOil(float oil) {
if (oil <= getCapacity())
this.oil = oil;
}
/**
* Methode om een hoeveelheid olie toe te voegen.
* @param amount De hoeveelheid die moet worden toegevoegd
* @post Als de huidige hoeveelheid olie, verhoogd met de toe te voegen hoeveelheid
* olie de capaciteit niet overschrijdt, wordt de hoeveelheid olie in de tank verhoogd.
*/
public void addOil(float amount) {
float current = getOil();
if (current + amount <= capacity) {
setOil(current + amount);
}
}
/**
* Methode om de tank volledig te vullen.
* @post Na het uitvoeren van de methode zal de inhoud gelijk zijn aan de capaciteit.
*/
public void fillTank() {
setOil(getCapacity());
}
/**
* Methode om de tank leeg te maken
* @post Na het uitvoeren is de inhoud 0.
*/
public void emptyTank() {
setOil(0);
}
/**
* Een methode om olie over te dragen naar een andere olietank.
* @param other De olietank om naar over te dragen
* @param amount De hoeveelheid die moet overgedragen worden
* @post Als de nieuwe hoeveelheid de capaciteit van de andere tank niet overschrijdt, en bovendien de hoeveelheid
* minder is of gelijk is aan de huidige hoeveelheid in de tank, wordt de hoeveelheid effectief overgedragen.
*/
public void transfer(Oiltank other, float amount) {
if (amount + other.getOil() <= other.getCapacity() && amount <= this.getCapacity()) {
other.addOil(amount);
}
}
/**
* Een methode om te kijken of de tank voller is dan een andere tank, procentueel gezien.
* @param other De andere olietank
* @return Er wordt true gereturnd als de tank voller is, anders false.
*/
public boolean isFullerThan(Oiltank other) {
float ownPercentage = this.getOil() / this.getCapacity();
float otherPercentage = other.getOil() / other.getCapacity();
return ownPercentage > otherPercentage;
}
/**
* Een methode om te kijken welke van 3 olietanken de grootste restcapaciteit heeft.
* @param t1 De eerste olietank.
* @param t2 De tweede olietank.
* @param t3 De derde olietank.
* @return Na het uitvoeren wordt de olietank met de grootste restcapaciteit gereturnd.
*/
public static Oiltank fullest(Oiltank t1, Oiltank t2, Oiltank t3) {
Oiltank[] tanks = { t1, t2, t3 };
float biggestRest = Float.MIN_VALUE;
Oiltank largest = null;
for(Oiltank tank : tanks) {
float rest = tank.getCapacity() - tank.getOil();
if (rest > biggestRest) {
biggestRest = rest;
largest = tank;
}
}
return largest;
}
/**
* Een methode om het object mooi uit te printen.
* @return Een string met een representatie van de capaciteit en de hoeveelheid olie.
*/
@Override
public String toString() {
return "Olietank " +
"met capaciteit" + capacity +
"en hoeveelheid olie" + oil;
}
/**
* A method for checking if an oiltank has the same capacity as another oil tank
* @param other The oiltank to compare this one with.
* @return Returns true if the capacities are the same, false otherwise.
*/
public boolean hasSameCapacity(Oiltank other) {
return this.getCapacity() == other.getCapacity();
}
/**
* A method for checking if an oiltank has the same amount of oil as another oil tank
* @param other The oiltank to compare this one with.
* @return Returns true if the amounts of oil are the same, false otherwise.
*/
public boolean hasSameOil(Oiltank other) {
return this.getOil() == other.getOil();
}
}
| vanschependom/KULAK_objectgericht-programmeren | Oefenzitting 1/src/kulak_ogp_oz1/eigen/Oiltank.java | 2,037 | /**
* Een methode om olie over te dragen naar een andere olietank.
* @param other De olietank om naar over te dragen
* @param amount De hoeveelheid die moet overgedragen worden
* @post Als de nieuwe hoeveelheid de capaciteit van de andere tank niet overschrijdt, en bovendien de hoeveelheid
* minder is of gelijk is aan de huidige hoeveelheid in de tank, wordt de hoeveelheid effectief overgedragen.
*/ | block_comment | nl | package kulak_ogp_oz1.eigen;
import be.kuleuven.cs.som.annotate.*;
/**
* A class that represents an oil tank
* @version 1.1
* @author Vincent Van Schependom
*/
public class Oiltank {
private float capacity;
private float oil;
/**
* Een constructor voor de klasse co.vis.kulak_ogp.oz1.eigen.Oiltank met 1 argument.
* @param capacity
* @effect Na het uitvoeren van de constructor wordt een olietank aangemaakt inhoud van 0 en wordt de capaciteit
* ingesteld op de meegegeven waarde via setCapacity.
*/
public Oiltank(float capacity) {
this(capacity,0);
}
/**
* Een constructor voor de klasse co.vis.kulak_ogp.oz1.eigen.Oiltank met 2 argumenten.
* @param capacity De capaciteit van de nieuwe co.vis.kulak_ogp.oz1.eigen.Oiltank.
* @param oil De inhoud van de nieuwe olietank.
* @effect Er wordt een nieuwe olietank aangemaakt en de inhoud en de capaciteit worden ingesteld met respectievelijk
* de methodes setOil en setCapacity.
*/
public Oiltank(float capacity, float oil) {
this.setOil(oil);
this.setCapacity(capacity);
}
/**
* Een constructor voor de klasse co.vis.kulak_ogp.oz1.eigen.Oiltank zonder argumenten.
* @effect Na het aanroepen van deze constructor wordt een olietank aangemaakt met capaciteit 5000 en inhoud 0
* aan de hand van de constructor die zowel capaciteit als inhoud meekrijgt.
*/
public Oiltank() {
this(5000,0);
}
/**
* De getter voor de capaciteit op te halen.
* @return De capaciteit wordt teruggegeven.
*/
@Basic
public float getCapacity() {
return capacity;
}
/**
* De getter voor de hoeveelheid olie in de tank
* @return Deze getter returnt de hoeveelheid olie.
*/
@Basic
public float getOil() {
return oil;
}
/**
* Een methode om de capaciteit in te stellen
* @param capacity De capaciteit om in te stellen
* @post Als de capaciteit positief is, wordt de capaciteit ingesteld op de meegegeven waarde, anders
* wordt de capaciteit ingesteld op 0.
*/
private void setCapacity(float capacity) {
if (capacity >= 0) {
this.capacity = capacity;
} else {
this.capacity = 0;
}
}
/**
* Setter voor de hoeveelheid olie.
* @param oil De te setten hoeveelheid
* @post Na het uitvoeren van de setter zal de hoeveelheid olie in de tank gelijk zijn aan oil, als deze
* de capaciteit niet overschrijdt. (intertia: niks zeggen over de else -> ongewijzigd)
*/
@Basic
private void setOil(float oil) {
if (oil <= getCapacity())
this.oil = oil;
}
/**
* Methode om een hoeveelheid olie toe te voegen.
* @param amount De hoeveelheid die moet worden toegevoegd
* @post Als de huidige hoeveelheid olie, verhoogd met de toe te voegen hoeveelheid
* olie de capaciteit niet overschrijdt, wordt de hoeveelheid olie in de tank verhoogd.
*/
public void addOil(float amount) {
float current = getOil();
if (current + amount <= capacity) {
setOil(current + amount);
}
}
/**
* Methode om de tank volledig te vullen.
* @post Na het uitvoeren van de methode zal de inhoud gelijk zijn aan de capaciteit.
*/
public void fillTank() {
setOil(getCapacity());
}
/**
* Methode om de tank leeg te maken
* @post Na het uitvoeren is de inhoud 0.
*/
public void emptyTank() {
setOil(0);
}
/**
* Een methode om<SUF>*/
public void transfer(Oiltank other, float amount) {
if (amount + other.getOil() <= other.getCapacity() && amount <= this.getCapacity()) {
other.addOil(amount);
}
}
/**
* Een methode om te kijken of de tank voller is dan een andere tank, procentueel gezien.
* @param other De andere olietank
* @return Er wordt true gereturnd als de tank voller is, anders false.
*/
public boolean isFullerThan(Oiltank other) {
float ownPercentage = this.getOil() / this.getCapacity();
float otherPercentage = other.getOil() / other.getCapacity();
return ownPercentage > otherPercentage;
}
/**
* Een methode om te kijken welke van 3 olietanken de grootste restcapaciteit heeft.
* @param t1 De eerste olietank.
* @param t2 De tweede olietank.
* @param t3 De derde olietank.
* @return Na het uitvoeren wordt de olietank met de grootste restcapaciteit gereturnd.
*/
public static Oiltank fullest(Oiltank t1, Oiltank t2, Oiltank t3) {
Oiltank[] tanks = { t1, t2, t3 };
float biggestRest = Float.MIN_VALUE;
Oiltank largest = null;
for(Oiltank tank : tanks) {
float rest = tank.getCapacity() - tank.getOil();
if (rest > biggestRest) {
biggestRest = rest;
largest = tank;
}
}
return largest;
}
/**
* Een methode om het object mooi uit te printen.
* @return Een string met een representatie van de capaciteit en de hoeveelheid olie.
*/
@Override
public String toString() {
return "Olietank " +
"met capaciteit" + capacity +
"en hoeveelheid olie" + oil;
}
/**
* A method for checking if an oiltank has the same capacity as another oil tank
* @param other The oiltank to compare this one with.
* @return Returns true if the capacities are the same, false otherwise.
*/
public boolean hasSameCapacity(Oiltank other) {
return this.getCapacity() == other.getCapacity();
}
/**
* A method for checking if an oiltank has the same amount of oil as another oil tank
* @param other The oiltank to compare this one with.
* @return Returns true if the amounts of oil are the same, false otherwise.
*/
public boolean hasSameOil(Oiltank other) {
return this.getOil() == other.getOil();
}
}
|
184977_2 | /**
*
*/
package net.varkhan.serv.p2p.message.transport;
import net.varkhan.base.management.report.JMXAverageMonitorReport;
import net.varkhan.serv.p2p.message.dispatch.MesgDispatcher;
import net.varkhan.serv.p2p.message.dispatch.MesgReceiver;
import net.varkhan.serv.p2p.message.dispatch.MesgSender;
import net.varkhan.serv.p2p.connect.PeerNode;
import net.varkhan.serv.p2p.message.PeerResolver;
import net.varkhan.serv.p2p.connect.PeerAddress;
import net.varkhan.serv.p2p.connect.transport.MTXAddress;
import net.varkhan.serv.p2p.message.*;
import net.varkhan.serv.p2p.message.protocol.BinaryEnvelope;
import net.varkhan.serv.p2p.message.protocol.BinaryPayload;
import net.varkhan.serv.p2p.connect.transport.UDPAddress;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.Enumeration;
/**
* <b>.</b>
* <p/>
* @author varkhan
* @date Nov 12, 2009
* @time 9:40:07 AM
*/
@SuppressWarnings( { "UnusedDeclaration" })
public class MTXTransport implements MesgTransport, MesgSender {
public static final Logger log=LogManager.getLogger(MTXTransport.class);
// Incoming packet queue size
public static final int QUEUE_SIZE =100;
// Default packet recv / send size
public static final int PACKET_SIZE =1024*16;
// Maximum data payload inside packets
public static final int MAX_DATA_SIZE=PACKET_SIZE-50;
// Maximum time spent waiting for message reception (5sec)
private static final int RECV_TIMEOUT =5000;
/** The MTX group address */
private InetAddress groupAddr;
/** The MTX group port */
private int groupPort;
private int timeout =RECV_TIMEOUT;
private int packetSize=PACKET_SIZE;
private int queueSize =QUEUE_SIZE;
private InetAddress localAddr;
protected MulticastSocket server=null;
protected PeerResolver resolver;
protected MesgDispatcher dispatcher;
protected PeerAddress local;
private JMXAverageMonitorReport stats;
private String name;
private volatile boolean run =false;
private volatile Thread thread=null;
/**
* Creates a Multicast PeerChannel, specifying incoming packet and queue size
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param queueSize the size of the packet queue
* @param packetSize the size of outgoing/incoming packets
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
int queueSize, int packetSize, JMXAverageMonitorReport stats) throws IOException {
this.resolver=resolver;
this.dispatcher=dispatcher;
this.local=localPoint;
this.stats=stats;
this.localAddr=localAddr;
this.groupAddr = groupAddr;
this.groupPort = groupPort;
if(log.isDebugEnabled()) log.debug("BIND MTX "+(localAddr==null?"0.0.0.0":localAddr.getHostAddress())+":"+groupPort);
server=new MulticastSocket(new InetSocketAddress(localAddr,groupPort));
server.setReuseAddress(true);
server.setSoTimeout(timeout);
// socket.joinGroup(groupAddr);
if(this.localAddr==null) {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
if(ifaces.hasMoreElements()) server.setNetworkInterface(ifaces.nextElement());
}
else {
// This fails because Java sucks at networking
// server.setInterface(this.localAddr);
NetworkInterface localIface = NetworkInterface.getByInetAddress(this.localAddr);
if(localIface!=null) {
server.setNetworkInterface(localIface);
}
}
setQueueSize(queueSize);
setPacketSize(packetSize);
this.name = ((server.getLocalAddress()==null)?"0.0.0.0": server.getLocalAddress().getHostAddress())+
":"+server.getLocalPort()+
"@"+localPoint.name();
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,localAddr,groupAddr,groupPort,QUEUE_SIZE,PACKET_SIZE,stats);
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,null,groupAddr,groupPort,QUEUE_SIZE, PACKET_SIZE,stats);
}
/**
* Get the size of datagram packets emitted from or received by this server
*
* @return the size of datagram packets emitted from or received by this server
*/
public int getPacketSize() {
return packetSize;
}
/**
* Set the size of datagram packets emitted from or received by this server
*
* @param size the size of datagram packets emitted from or received by this server
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setPacketSize(int size) throws SocketException {
packetSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the size of the message waiting queue
*
* @return the number of messages that can be queued in the reception buffer
*/
public int getQueueSize() {
return queueSize;
}
/**
* Set the size of the message waiting queue
*
* @param size the number of messages that can be queued in the reception buffer
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setQueueSize(int size) throws SocketException {
queueSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the message reception timeout
*
* @return the maximum number of milliseconds the exchange will wait for the reception of a single message
*/
public int getTimeout() {
return timeout;
}
/**
* Set the message reception timeout
*
* @param delay the maximum number of milliseconds the exchange will wait for the reception of a single message
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setTimeout(int delay) throws SocketException {
timeout = delay;
if(server!=null) server.setSoTimeout(timeout);
}
/**
* Gets the local listening address for this exchange
*
* @return the local address this exchange listens on
*/
public InetAddress getAddress() {
return server.getLocalAddress();
}
/**
* Gets the local listening port for this exchange
*
* @return the local port this exchange listens on
*/
public int getPort() {
return server.getLocalPort();
}
public InetAddress getGroupAddr() {
return groupAddr;
}
public int getGroupPort() {
return groupPort;
}
/**********************************************************************************
** Lifecycle management
**/
@Override
public PeerAddress endpoint() {
return new MTXAddress() {
@Override
public InetAddress addrMTXgroup() {
return groupAddr;
}
@Override
public int portMTXgroup() {
return groupPort;
}
@Override
public String name() {
return name;
}
@Override
@SuppressWarnings("unchecked")
public <T> T as(Class<T> c) {
if(c.isAssignableFrom(UDPAddress.class)) return (T) this;
return null;
}
};
}
/**
* Indicates whether the exchange is started and able to handle messages
*
* @return {@code true} if the exchange transport layer is ready to handle outgoing messages,
* and the listening thread is handling incoming messages
*/
public boolean isStarted() {
return run && thread!=null && thread.isAlive();
}
/**
* Start the exchange
*
* @throws java.io.IOException if the exchange could not bind to an address
*/
public synchronized void start() throws IOException {
if(run || (thread!=null && thread.isAlive())) return;
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": start "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
server.joinGroup(groupAddr);
thread = new Thread() {
public void run() { receive(); }
};
thread.setName(MTXTransport.class.getSimpleName()+"("+groupAddr.getHostAddress()+":"+ groupPort+")");
thread.setDaemon(true);
run = true;
thread.start();
}
/**
* Stop the exchange
*
* @throws java.io.IOException if the exchange could not free resources
*/
public synchronized void stop() throws IOException {
run = false;
Thread t=thread;
if(t==null) return;
server.leaveGroup(groupAddr);
thread = null;
t.interrupt();
try {
t.join(2*timeout);
}
catch(InterruptedException e) {
// ignore
}
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": stop "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
}
public void receive() {
DatagramPacket pakt = new DatagramPacket(new byte[packetSize], packetSize);
// Main message listening loop
while(run) {
// Waiting for reception of a message
try {
server.receive(pakt);
}
catch(SocketTimeoutException e) {
// Ignore this, as receive naturally times out because we set SO_TIMEOUT
continue;
}
catch(InterruptedIOException e) {
if(!run) return;
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" interrupted",e);
continue;
}
catch(SocketException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" protocol error",e);
continue;
}
catch(IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed", e);
continue;
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
continue;
}
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" receiving from "+pakt.getAddress().getHostAddress());
// Handle the message
try {
receive(pakt);
stats.inc(MTXTransport.class.getSimpleName()+".Recv.Success");
}
catch (IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed to read data", e);
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
}
}
}
private void receive(DatagramPacket pakt) throws IOException {// Building received message
BinaryEnvelope recv = new BinaryEnvelope(pakt.getData(), pakt.getOffset(), pakt.getLength());
String method=recv.method();
MesgPayload mesg = recv.message();
long sequence=recv.sequence();
// Passing message to the dispatcher
switch(recv.type()) {
case BinaryEnvelope.PING: {
PeerAddress remote = resolver.update(recv.srcId(),mesg);
if(sequence>=0){
// Reply immediately, with decremented ttl
ping(local, remote, method, resolver.info(), sequence-1);
}
}
break;
case BinaryEnvelope.CALL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
if(sequence<0) {
dispatcher.call(src, dst, method, mesg, null, -1, null);
}
else {
BinaryPayload repl = new BinaryPayload();
dispatcher.call(src, dst, method, mesg, repl, sequence, this);
}
}
break;
case BinaryEnvelope.REPL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
dispatcher.repl(src, dst, method, mesg, sequence);
}
break;
}
}
/**********************************************************************************
** Message transmission handling
**/
public boolean call(PeerAddress src, PeerAddress dst, String method, MesgPayload message, MesgReceiver handler) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Address.Unsupported");
return false;
}
long sequence = -1;
if(handler!=null) sequence = dispatcher.register(handler);
if(log.isDebugEnabled()) log.debug("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),"",dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Call.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Call.Success");
return true;
}
public boolean repl(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Address.Unsupported");
return false;
}
if(log.isDebugEnabled()) log.debug("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Repl.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Success");
return true;
}
public boolean ping(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotLocal");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not from local "+src.name());
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Oversize");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" oversize message "+message.getLength());
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Protocol.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to multicast "+dst.name());
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Address.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to group "+dst.name());
return false;
}
if(log.isDebugEnabled()) log.debug("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.PING, src.name(), method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Ping.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Success");
return true;
}
public void send(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
// Send reply
PeerNode node = (PeerNode)dst;
node.repl(method, message, sequence);
}
}
| varkhan/VCom4j | Serv/P2PConnect/src/net/varkhan/serv/p2p/message/transport/MTXTransport.java | 6,442 | // Default packet recv / send size | line_comment | nl | /**
*
*/
package net.varkhan.serv.p2p.message.transport;
import net.varkhan.base.management.report.JMXAverageMonitorReport;
import net.varkhan.serv.p2p.message.dispatch.MesgDispatcher;
import net.varkhan.serv.p2p.message.dispatch.MesgReceiver;
import net.varkhan.serv.p2p.message.dispatch.MesgSender;
import net.varkhan.serv.p2p.connect.PeerNode;
import net.varkhan.serv.p2p.message.PeerResolver;
import net.varkhan.serv.p2p.connect.PeerAddress;
import net.varkhan.serv.p2p.connect.transport.MTXAddress;
import net.varkhan.serv.p2p.message.*;
import net.varkhan.serv.p2p.message.protocol.BinaryEnvelope;
import net.varkhan.serv.p2p.message.protocol.BinaryPayload;
import net.varkhan.serv.p2p.connect.transport.UDPAddress;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.Enumeration;
/**
* <b>.</b>
* <p/>
* @author varkhan
* @date Nov 12, 2009
* @time 9:40:07 AM
*/
@SuppressWarnings( { "UnusedDeclaration" })
public class MTXTransport implements MesgTransport, MesgSender {
public static final Logger log=LogManager.getLogger(MTXTransport.class);
// Incoming packet queue size
public static final int QUEUE_SIZE =100;
// Default packet<SUF>
public static final int PACKET_SIZE =1024*16;
// Maximum data payload inside packets
public static final int MAX_DATA_SIZE=PACKET_SIZE-50;
// Maximum time spent waiting for message reception (5sec)
private static final int RECV_TIMEOUT =5000;
/** The MTX group address */
private InetAddress groupAddr;
/** The MTX group port */
private int groupPort;
private int timeout =RECV_TIMEOUT;
private int packetSize=PACKET_SIZE;
private int queueSize =QUEUE_SIZE;
private InetAddress localAddr;
protected MulticastSocket server=null;
protected PeerResolver resolver;
protected MesgDispatcher dispatcher;
protected PeerAddress local;
private JMXAverageMonitorReport stats;
private String name;
private volatile boolean run =false;
private volatile Thread thread=null;
/**
* Creates a Multicast PeerChannel, specifying incoming packet and queue size
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param queueSize the size of the packet queue
* @param packetSize the size of outgoing/incoming packets
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
int queueSize, int packetSize, JMXAverageMonitorReport stats) throws IOException {
this.resolver=resolver;
this.dispatcher=dispatcher;
this.local=localPoint;
this.stats=stats;
this.localAddr=localAddr;
this.groupAddr = groupAddr;
this.groupPort = groupPort;
if(log.isDebugEnabled()) log.debug("BIND MTX "+(localAddr==null?"0.0.0.0":localAddr.getHostAddress())+":"+groupPort);
server=new MulticastSocket(new InetSocketAddress(localAddr,groupPort));
server.setReuseAddress(true);
server.setSoTimeout(timeout);
// socket.joinGroup(groupAddr);
if(this.localAddr==null) {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
if(ifaces.hasMoreElements()) server.setNetworkInterface(ifaces.nextElement());
}
else {
// This fails because Java sucks at networking
// server.setInterface(this.localAddr);
NetworkInterface localIface = NetworkInterface.getByInetAddress(this.localAddr);
if(localIface!=null) {
server.setNetworkInterface(localIface);
}
}
setQueueSize(queueSize);
setPacketSize(packetSize);
this.name = ((server.getLocalAddress()==null)?"0.0.0.0": server.getLocalAddress().getHostAddress())+
":"+server.getLocalPort()+
"@"+localPoint.name();
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,localAddr,groupAddr,groupPort,QUEUE_SIZE,PACKET_SIZE,stats);
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,null,groupAddr,groupPort,QUEUE_SIZE, PACKET_SIZE,stats);
}
/**
* Get the size of datagram packets emitted from or received by this server
*
* @return the size of datagram packets emitted from or received by this server
*/
public int getPacketSize() {
return packetSize;
}
/**
* Set the size of datagram packets emitted from or received by this server
*
* @param size the size of datagram packets emitted from or received by this server
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setPacketSize(int size) throws SocketException {
packetSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the size of the message waiting queue
*
* @return the number of messages that can be queued in the reception buffer
*/
public int getQueueSize() {
return queueSize;
}
/**
* Set the size of the message waiting queue
*
* @param size the number of messages that can be queued in the reception buffer
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setQueueSize(int size) throws SocketException {
queueSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the message reception timeout
*
* @return the maximum number of milliseconds the exchange will wait for the reception of a single message
*/
public int getTimeout() {
return timeout;
}
/**
* Set the message reception timeout
*
* @param delay the maximum number of milliseconds the exchange will wait for the reception of a single message
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setTimeout(int delay) throws SocketException {
timeout = delay;
if(server!=null) server.setSoTimeout(timeout);
}
/**
* Gets the local listening address for this exchange
*
* @return the local address this exchange listens on
*/
public InetAddress getAddress() {
return server.getLocalAddress();
}
/**
* Gets the local listening port for this exchange
*
* @return the local port this exchange listens on
*/
public int getPort() {
return server.getLocalPort();
}
public InetAddress getGroupAddr() {
return groupAddr;
}
public int getGroupPort() {
return groupPort;
}
/**********************************************************************************
** Lifecycle management
**/
@Override
public PeerAddress endpoint() {
return new MTXAddress() {
@Override
public InetAddress addrMTXgroup() {
return groupAddr;
}
@Override
public int portMTXgroup() {
return groupPort;
}
@Override
public String name() {
return name;
}
@Override
@SuppressWarnings("unchecked")
public <T> T as(Class<T> c) {
if(c.isAssignableFrom(UDPAddress.class)) return (T) this;
return null;
}
};
}
/**
* Indicates whether the exchange is started and able to handle messages
*
* @return {@code true} if the exchange transport layer is ready to handle outgoing messages,
* and the listening thread is handling incoming messages
*/
public boolean isStarted() {
return run && thread!=null && thread.isAlive();
}
/**
* Start the exchange
*
* @throws java.io.IOException if the exchange could not bind to an address
*/
public synchronized void start() throws IOException {
if(run || (thread!=null && thread.isAlive())) return;
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": start "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
server.joinGroup(groupAddr);
thread = new Thread() {
public void run() { receive(); }
};
thread.setName(MTXTransport.class.getSimpleName()+"("+groupAddr.getHostAddress()+":"+ groupPort+")");
thread.setDaemon(true);
run = true;
thread.start();
}
/**
* Stop the exchange
*
* @throws java.io.IOException if the exchange could not free resources
*/
public synchronized void stop() throws IOException {
run = false;
Thread t=thread;
if(t==null) return;
server.leaveGroup(groupAddr);
thread = null;
t.interrupt();
try {
t.join(2*timeout);
}
catch(InterruptedException e) {
// ignore
}
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": stop "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
}
public void receive() {
DatagramPacket pakt = new DatagramPacket(new byte[packetSize], packetSize);
// Main message listening loop
while(run) {
// Waiting for reception of a message
try {
server.receive(pakt);
}
catch(SocketTimeoutException e) {
// Ignore this, as receive naturally times out because we set SO_TIMEOUT
continue;
}
catch(InterruptedIOException e) {
if(!run) return;
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" interrupted",e);
continue;
}
catch(SocketException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" protocol error",e);
continue;
}
catch(IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed", e);
continue;
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
continue;
}
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" receiving from "+pakt.getAddress().getHostAddress());
// Handle the message
try {
receive(pakt);
stats.inc(MTXTransport.class.getSimpleName()+".Recv.Success");
}
catch (IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed to read data", e);
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
}
}
}
private void receive(DatagramPacket pakt) throws IOException {// Building received message
BinaryEnvelope recv = new BinaryEnvelope(pakt.getData(), pakt.getOffset(), pakt.getLength());
String method=recv.method();
MesgPayload mesg = recv.message();
long sequence=recv.sequence();
// Passing message to the dispatcher
switch(recv.type()) {
case BinaryEnvelope.PING: {
PeerAddress remote = resolver.update(recv.srcId(),mesg);
if(sequence>=0){
// Reply immediately, with decremented ttl
ping(local, remote, method, resolver.info(), sequence-1);
}
}
break;
case BinaryEnvelope.CALL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
if(sequence<0) {
dispatcher.call(src, dst, method, mesg, null, -1, null);
}
else {
BinaryPayload repl = new BinaryPayload();
dispatcher.call(src, dst, method, mesg, repl, sequence, this);
}
}
break;
case BinaryEnvelope.REPL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
dispatcher.repl(src, dst, method, mesg, sequence);
}
break;
}
}
/**********************************************************************************
** Message transmission handling
**/
public boolean call(PeerAddress src, PeerAddress dst, String method, MesgPayload message, MesgReceiver handler) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Address.Unsupported");
return false;
}
long sequence = -1;
if(handler!=null) sequence = dispatcher.register(handler);
if(log.isDebugEnabled()) log.debug("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),"",dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Call.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Call.Success");
return true;
}
public boolean repl(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Address.Unsupported");
return false;
}
if(log.isDebugEnabled()) log.debug("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Repl.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Success");
return true;
}
public boolean ping(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotLocal");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not from local "+src.name());
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Oversize");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" oversize message "+message.getLength());
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Protocol.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to multicast "+dst.name());
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Address.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to group "+dst.name());
return false;
}
if(log.isDebugEnabled()) log.debug("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.PING, src.name(), method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Ping.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Success");
return true;
}
public void send(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
// Send reply
PeerNode node = (PeerNode)dst;
node.repl(method, message, sequence);
}
}
|
97669_11 | // Copyright 2011 Google Inc. All Rights Reserved.
// Author: [email protected] (Sreeni Viswanadha)
/* Copyright (c) 2005-2006, Kees Jan Koster [email protected]
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.javacc.jjtree;
import java.io.File;
import org.javacc.parser.JavaCCErrors;
import org.javacc.parser.Options;
/**
* The JJTree-specific options.
*
* @author Kees Jan Koster <[email protected]>
*/
class JJTreeOptions extends Options {
/**
* Limit subclassing to derived classes.
*/
protected JJTreeOptions() {
super();
}
/**
* Initialize the JJTree-specific options.
*/
public static void init() {
Options.init();
Options.optionValues.put("MULTI", Boolean.FALSE);
Options.optionValues.put("NODE_DEFAULT_VOID", Boolean.FALSE);
Options.optionValues.put("NODE_SCOPE_HOOK", Boolean.FALSE);
Options.optionValues.put("NODE_USES_PARSER", Boolean.FALSE);
Options.optionValues.put("BUILD_NODE_FILES", Boolean.TRUE);
Options.optionValues.put("VISITOR", Boolean.FALSE);
Options.optionValues.put("VISITOR_METHOD_NAME_INCLUDES_TYPE_NAME", Boolean.FALSE);
Options.optionValues.put("TRACK_TOKENS", Boolean.FALSE);
Options.optionValues.put("NODE_PREFIX", "AST");
Options.optionValues.put("NODE_PACKAGE", "");
Options.optionValues.put("NODE_EXTENDS", "");
Options.optionValues.put("NODE_CLASS", "");
Options.optionValues.put("NODE_FACTORY", "");
Options.optionValues.put("NODE_INCLUDES", "");
Options.optionValues.put("OUTPUT_FILE", "");
Options.optionValues.put("VISITOR_DATA_TYPE", "");
Options.optionValues.put("VISITOR_RETURN_TYPE", "Object");
Options.optionValues.put("VISITOR_EXCEPTION", "");
Options.optionValues.put("JJTREE_OUTPUT_DIRECTORY", "");
// TODO :: 2013/07/23 -- This appears to be a duplicate from the parent class
Options.optionValues.put(Options.USEROPTION__JDK_VERSION, "1.5");
// Also appears to be a duplicate
Options.optionValues.put(Options.USEROPTION__CPP_NAMESPACE, "");
// Also appears to be a duplicate
Options.optionValues.put(Options.USEROPTION__CPP_IGNORE_ACTIONS, Boolean.FALSE);
}
/**
* Check options for consistency
*/
public static void validate() {
if (!getVisitor()) {
if (getVisitorDataType().length() > 0) {
JavaCCErrors.warning("VISITOR_DATA_TYPE option will be ignored since VISITOR is false");
}
if (getVisitorReturnType().length() > 0 && !getVisitorReturnType().equals("Object")) {
JavaCCErrors.warning("VISITOR_RETURN_TYPE option will be ignored since VISITOR is false");
}
if (getVisitorException().length() > 0) {
JavaCCErrors.warning("VISITOR_EXCEPTION option will be ignored since VISITOR is false");
}
}
}
/**
* Find the multi value.
*
* @return The requested multi value.
*/
public static boolean getMulti() {
return booleanValue("MULTI");
}
/**
* Find the node default void value.
*
* @return The requested node default void value.
*/
public static boolean getNodeDefaultVoid() {
return booleanValue("NODE_DEFAULT_VOID");
}
/**
* Find the node scope hook value.
*
* @return The requested node scope hook value.
*/
public static boolean getNodeScopeHook() {
return booleanValue("NODE_SCOPE_HOOK");
}
/**
* Find the node factory value.
*
* @return The requested node factory value.
*/
public static String getNodeFactory() {
return stringValue("NODE_FACTORY");
}
/**
* Find the node uses parser value.
*
* @return The requested node uses parser value.
*/
public static boolean getNodeUsesParser() {
return booleanValue("NODE_USES_PARSER");
}
/**
* Find the build node files value.
*
* @return The requested build node files value.
*/
public static boolean getBuildNodeFiles() {
return booleanValue("BUILD_NODE_FILES");
}
/**
* Find the visitor value.
*
* @return The requested visitor value.
*/
public static boolean getVisitor() {
return booleanValue("VISITOR");
}
/**
* Find the trackTokens value.
*
* @return The requested trackTokens value.
*/
public static boolean getTrackTokens() {
return booleanValue("TRACK_TOKENS");
}
/**
* Find the node prefix value.
*
* @return The requested node prefix value.
*/
public static String getNodePrefix() {
return stringValue("NODE_PREFIX");
}
/**
* Find the node super class name.
*
* @return The requested node super class
*/
public static String getNodeExtends() {
return stringValue("NODE_EXTENDS");
}
/**
* Find the node class name.
*
* @return The requested node class
*/
public static String getNodeClass() {
return stringValue("NODE_CLASS");
}
/**
* Find the node package value.
*
* @return The requested node package value.
*/
public static String getNodePackage() {
return stringValue("NODE_PACKAGE");
}
/**
* Find the output file value.
*
* @return The requested output file value.
*/
public static String getOutputFile() {
return stringValue("OUTPUT_FILE");
}
/**
* Find the visitor exception value
*
* @return The requested visitor exception value.
*/
public static String getVisitorException() {
return stringValue("VISITOR_EXCEPTION");
}
/**
* Find the visitor data type value
*
* @return The requested visitor data type value.
*/
public static String getVisitorDataType() {
return stringValue("VISITOR_DATA_TYPE");
}
/**
* Find the visitor return type value
*
* @return The requested visitor return type value.
*/
public static String getVisitorReturnType() {
return stringValue("VISITOR_RETURN_TYPE");
}
/**
* Find the output directory to place the generated <code>.jj</code> files
* into. If none is configured, use the value of
* <code>getOutputDirectory()</code>.
*
* @return The requested JJTree output directory
*/
public static File getJJTreeOutputDirectory() {
final String dirName = stringValue("JJTREE_OUTPUT_DIRECTORY");
File dir = null;
if ("".equals(dirName)) {
dir = getOutputDirectory();
} else {
dir = new File(dirName);
}
return dir;
}
}
| vavrcc/vavrcc | src/main/java/org/javacc/jjtree/JJTreeOptions.java | 2,441 | /**
* Find the node default void value.
*
* @return The requested node default void value.
*/ | block_comment | nl | // Copyright 2011 Google Inc. All Rights Reserved.
// Author: [email protected] (Sreeni Viswanadha)
/* Copyright (c) 2005-2006, Kees Jan Koster [email protected]
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.javacc.jjtree;
import java.io.File;
import org.javacc.parser.JavaCCErrors;
import org.javacc.parser.Options;
/**
* The JJTree-specific options.
*
* @author Kees Jan Koster <[email protected]>
*/
class JJTreeOptions extends Options {
/**
* Limit subclassing to derived classes.
*/
protected JJTreeOptions() {
super();
}
/**
* Initialize the JJTree-specific options.
*/
public static void init() {
Options.init();
Options.optionValues.put("MULTI", Boolean.FALSE);
Options.optionValues.put("NODE_DEFAULT_VOID", Boolean.FALSE);
Options.optionValues.put("NODE_SCOPE_HOOK", Boolean.FALSE);
Options.optionValues.put("NODE_USES_PARSER", Boolean.FALSE);
Options.optionValues.put("BUILD_NODE_FILES", Boolean.TRUE);
Options.optionValues.put("VISITOR", Boolean.FALSE);
Options.optionValues.put("VISITOR_METHOD_NAME_INCLUDES_TYPE_NAME", Boolean.FALSE);
Options.optionValues.put("TRACK_TOKENS", Boolean.FALSE);
Options.optionValues.put("NODE_PREFIX", "AST");
Options.optionValues.put("NODE_PACKAGE", "");
Options.optionValues.put("NODE_EXTENDS", "");
Options.optionValues.put("NODE_CLASS", "");
Options.optionValues.put("NODE_FACTORY", "");
Options.optionValues.put("NODE_INCLUDES", "");
Options.optionValues.put("OUTPUT_FILE", "");
Options.optionValues.put("VISITOR_DATA_TYPE", "");
Options.optionValues.put("VISITOR_RETURN_TYPE", "Object");
Options.optionValues.put("VISITOR_EXCEPTION", "");
Options.optionValues.put("JJTREE_OUTPUT_DIRECTORY", "");
// TODO :: 2013/07/23 -- This appears to be a duplicate from the parent class
Options.optionValues.put(Options.USEROPTION__JDK_VERSION, "1.5");
// Also appears to be a duplicate
Options.optionValues.put(Options.USEROPTION__CPP_NAMESPACE, "");
// Also appears to be a duplicate
Options.optionValues.put(Options.USEROPTION__CPP_IGNORE_ACTIONS, Boolean.FALSE);
}
/**
* Check options for consistency
*/
public static void validate() {
if (!getVisitor()) {
if (getVisitorDataType().length() > 0) {
JavaCCErrors.warning("VISITOR_DATA_TYPE option will be ignored since VISITOR is false");
}
if (getVisitorReturnType().length() > 0 && !getVisitorReturnType().equals("Object")) {
JavaCCErrors.warning("VISITOR_RETURN_TYPE option will be ignored since VISITOR is false");
}
if (getVisitorException().length() > 0) {
JavaCCErrors.warning("VISITOR_EXCEPTION option will be ignored since VISITOR is false");
}
}
}
/**
* Find the multi value.
*
* @return The requested multi value.
*/
public static boolean getMulti() {
return booleanValue("MULTI");
}
/**
* Find the node<SUF>*/
public static boolean getNodeDefaultVoid() {
return booleanValue("NODE_DEFAULT_VOID");
}
/**
* Find the node scope hook value.
*
* @return The requested node scope hook value.
*/
public static boolean getNodeScopeHook() {
return booleanValue("NODE_SCOPE_HOOK");
}
/**
* Find the node factory value.
*
* @return The requested node factory value.
*/
public static String getNodeFactory() {
return stringValue("NODE_FACTORY");
}
/**
* Find the node uses parser value.
*
* @return The requested node uses parser value.
*/
public static boolean getNodeUsesParser() {
return booleanValue("NODE_USES_PARSER");
}
/**
* Find the build node files value.
*
* @return The requested build node files value.
*/
public static boolean getBuildNodeFiles() {
return booleanValue("BUILD_NODE_FILES");
}
/**
* Find the visitor value.
*
* @return The requested visitor value.
*/
public static boolean getVisitor() {
return booleanValue("VISITOR");
}
/**
* Find the trackTokens value.
*
* @return The requested trackTokens value.
*/
public static boolean getTrackTokens() {
return booleanValue("TRACK_TOKENS");
}
/**
* Find the node prefix value.
*
* @return The requested node prefix value.
*/
public static String getNodePrefix() {
return stringValue("NODE_PREFIX");
}
/**
* Find the node super class name.
*
* @return The requested node super class
*/
public static String getNodeExtends() {
return stringValue("NODE_EXTENDS");
}
/**
* Find the node class name.
*
* @return The requested node class
*/
public static String getNodeClass() {
return stringValue("NODE_CLASS");
}
/**
* Find the node package value.
*
* @return The requested node package value.
*/
public static String getNodePackage() {
return stringValue("NODE_PACKAGE");
}
/**
* Find the output file value.
*
* @return The requested output file value.
*/
public static String getOutputFile() {
return stringValue("OUTPUT_FILE");
}
/**
* Find the visitor exception value
*
* @return The requested visitor exception value.
*/
public static String getVisitorException() {
return stringValue("VISITOR_EXCEPTION");
}
/**
* Find the visitor data type value
*
* @return The requested visitor data type value.
*/
public static String getVisitorDataType() {
return stringValue("VISITOR_DATA_TYPE");
}
/**
* Find the visitor return type value
*
* @return The requested visitor return type value.
*/
public static String getVisitorReturnType() {
return stringValue("VISITOR_RETURN_TYPE");
}
/**
* Find the output directory to place the generated <code>.jj</code> files
* into. If none is configured, use the value of
* <code>getOutputDirectory()</code>.
*
* @return The requested JJTree output directory
*/
public static File getJJTreeOutputDirectory() {
final String dirName = stringValue("JJTREE_OUTPUT_DIRECTORY");
File dir = null;
if ("".equals(dirName)) {
dir = getOutputDirectory();
} else {
dir = new File(dirName);
}
return dir;
}
}
|
30724_2 | package be.vdab.academy.entities;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.Table;
import javax.persistence.Version;
import be.vdab.academy.enums.Gender;
@Entity
@Table(name="docenten")
/*
@NamedQuery(
name="Teacher.findWagesBetween",
query="SELECT d FROM Teacher d WHERE d.wages BETWEEN :from AND :to " +
"ORDER BY d.wages, d.id")
*/
@NamedEntityGraphs( {
@NamedEntityGraph(
name = Teacher.WITH_CAMPUS,
attributeNodes = @NamedAttributeNode("campus")),
@NamedEntityGraph(
name = "Teacher.withCampusAndResponsibilities",
attributeNodes = {
@NamedAttributeNode("campus"),
@NamedAttributeNode("responsibilities")
})/*,
@NamedEntityGraph(
name = "Teacher.withCampusAndManager",
attributeNodes =
@NamedAttributeNode(value = "campus", subgraph = "withManager"),
subgraphs = @NamedSubgraph(
name = "withManager",
attributeNodes = @NamedAttributeNode("manager")))*/
})
public class Teacher implements Serializable {
/** Implements Serializable. */
private static final long serialVersionUID = -2152663213264949852L;
public static final String WITH_CAMPUS = "Teacher.withCampus";
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private long id;
@Column(name = "voornaam")
private String firstName;
@Column(name = "familienaam")
private String lastName;
// @Column(name = "geslacht")
// private Gender gender;
// @Column(name="geslacht")
// @Enumerated(EnumType.STRING)
// private Gender gender;
@Column(name="geslacht")
private String gender;
@Column(name = "wedde")
private BigDecimal wages;
@Column(name = "emailAdres")
private String emailAddress;
@Version
@Column(name = "versie")
/*private long version;*/
private Timestamp version;
@ElementCollection
@CollectionTable(name = "docentenbijnamen",
joinColumns = @JoinColumn(name = "docentId"))
@Column(name = "bijnaam")
private Set<String> nicknames;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "campusId")
private Campus campus;
@ManyToMany(mappedBy = "teachers")
private Set<Responsibility> responsibilities = new LinkedHashSet<>();
protected Teacher() {}
/*
public Teacher(
final String firstName,
final String lastName,
final Gender gender,
final BigDecimal wages,
final String emailAddress) {
this(firstName, lastName, gender, wages, emailAddress, null);
}
*/
public Teacher(
final String firstName,
final String lastName,
final Gender gender,
final BigDecimal wages,
final String emailAddress,
final Campus campus) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender.toString();
this.wages = wages;
this.emailAddress = emailAddress;
setCampus(campus);
this.nicknames = new LinkedHashSet<>();
}
public long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Gender getGender() {
return Gender.parse(gender);
}
public BigDecimal getWages() {
return wages;
}
public String getEmailAddress() {
return emailAddress;
}
public void raise(final BigDecimal percentage) {
if (percentage.compareTo(BigDecimal.ZERO) <= 0)
throw new IllegalArgumentException(
"Raise percentage must be positive");
final BigDecimal factor
= BigDecimal.ONE.add(percentage.divide(BigDecimal.valueOf(100L)));
wages = wages.multiply(factor, new MathContext(2, RoundingMode.HALF_UP));
}
public Set<String> getNicknames() {
return Collections.unmodifiableSet(nicknames);
}
public boolean addNickname(final String nickname) {
if (nickname.trim().isEmpty())
throw new IllegalArgumentException("A nickname can't be empty");
return nicknames.add(nickname);
}
public boolean removeNickname(final String nickname) {
return nicknames.remove(nickname);
}
public void setCampus(final Campus campus) {
if (campus == null) throw new NullPointerException();
if (!campus.getTeachers().contains(this))
campus.addTeacher(this);
this.campus = campus;
}
public Campus getCampus() {
return campus;
}
@Override
public boolean equals(final Object object) {
if (object == null || !(object instanceof Teacher)) return false;
if (getEmailAddress() == null) return false;
final Teacher teacher = (Teacher)object;
/*
return getFirstName().equalsIgnoreCase(teacher.getFirstName()) &&
getLastName().equalsIgnoreCase(teacher.getLastName()) &&
getGender() == teacher.getGender() &&
getWages().equals(teacher.getWages()) &&
getEmailAddress().equalsIgnoreCase(teacher.getEmailAddress());
*/
return getEmailAddress().equalsIgnoreCase(teacher.getEmailAddress());
}
@Override
public int hashCode() {
/*
return 13 * (getFirstName().hashCode() +
getLastName().hashCode() +
getGender().hashCode() +
getWages().hashCode() +
getEmailAddress().hashCode());
*/
return getEmailAddress() == null ?
0 : getEmailAddress().toLowerCase().hashCode();
}
public boolean addResponsibility(final Responsibility responsibility) {
final boolean added = responsibilities.add(responsibility);
if (!responsibility.getTeachers().contains(this))
responsibility.addTeacher(this);
return added;
}
public boolean removeResponsibility(final Responsibility responsibility) {
final boolean removed = responsibilities.remove(responsibility);
if (responsibility.getTeachers().contains(this))
responsibility.removeTeacher(this);
return removed;
}
public Set<Responsibility> getResponsibilities() {
return Collections.unmodifiableSet(responsibilities);
}
}
| vdab-stijn/fietsacademy | src/main/java/be/vdab/academy/entities/Teacher.java | 2,089 | // @Column(name = "geslacht") | line_comment | nl | package be.vdab.academy.entities;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.Table;
import javax.persistence.Version;
import be.vdab.academy.enums.Gender;
@Entity
@Table(name="docenten")
/*
@NamedQuery(
name="Teacher.findWagesBetween",
query="SELECT d FROM Teacher d WHERE d.wages BETWEEN :from AND :to " +
"ORDER BY d.wages, d.id")
*/
@NamedEntityGraphs( {
@NamedEntityGraph(
name = Teacher.WITH_CAMPUS,
attributeNodes = @NamedAttributeNode("campus")),
@NamedEntityGraph(
name = "Teacher.withCampusAndResponsibilities",
attributeNodes = {
@NamedAttributeNode("campus"),
@NamedAttributeNode("responsibilities")
})/*,
@NamedEntityGraph(
name = "Teacher.withCampusAndManager",
attributeNodes =
@NamedAttributeNode(value = "campus", subgraph = "withManager"),
subgraphs = @NamedSubgraph(
name = "withManager",
attributeNodes = @NamedAttributeNode("manager")))*/
})
public class Teacher implements Serializable {
/** Implements Serializable. */
private static final long serialVersionUID = -2152663213264949852L;
public static final String WITH_CAMPUS = "Teacher.withCampus";
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private long id;
@Column(name = "voornaam")
private String firstName;
@Column(name = "familienaam")
private String lastName;
// @Column(name =<SUF>
// private Gender gender;
// @Column(name="geslacht")
// @Enumerated(EnumType.STRING)
// private Gender gender;
@Column(name="geslacht")
private String gender;
@Column(name = "wedde")
private BigDecimal wages;
@Column(name = "emailAdres")
private String emailAddress;
@Version
@Column(name = "versie")
/*private long version;*/
private Timestamp version;
@ElementCollection
@CollectionTable(name = "docentenbijnamen",
joinColumns = @JoinColumn(name = "docentId"))
@Column(name = "bijnaam")
private Set<String> nicknames;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "campusId")
private Campus campus;
@ManyToMany(mappedBy = "teachers")
private Set<Responsibility> responsibilities = new LinkedHashSet<>();
protected Teacher() {}
/*
public Teacher(
final String firstName,
final String lastName,
final Gender gender,
final BigDecimal wages,
final String emailAddress) {
this(firstName, lastName, gender, wages, emailAddress, null);
}
*/
public Teacher(
final String firstName,
final String lastName,
final Gender gender,
final BigDecimal wages,
final String emailAddress,
final Campus campus) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender.toString();
this.wages = wages;
this.emailAddress = emailAddress;
setCampus(campus);
this.nicknames = new LinkedHashSet<>();
}
public long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Gender getGender() {
return Gender.parse(gender);
}
public BigDecimal getWages() {
return wages;
}
public String getEmailAddress() {
return emailAddress;
}
public void raise(final BigDecimal percentage) {
if (percentage.compareTo(BigDecimal.ZERO) <= 0)
throw new IllegalArgumentException(
"Raise percentage must be positive");
final BigDecimal factor
= BigDecimal.ONE.add(percentage.divide(BigDecimal.valueOf(100L)));
wages = wages.multiply(factor, new MathContext(2, RoundingMode.HALF_UP));
}
public Set<String> getNicknames() {
return Collections.unmodifiableSet(nicknames);
}
public boolean addNickname(final String nickname) {
if (nickname.trim().isEmpty())
throw new IllegalArgumentException("A nickname can't be empty");
return nicknames.add(nickname);
}
public boolean removeNickname(final String nickname) {
return nicknames.remove(nickname);
}
public void setCampus(final Campus campus) {
if (campus == null) throw new NullPointerException();
if (!campus.getTeachers().contains(this))
campus.addTeacher(this);
this.campus = campus;
}
public Campus getCampus() {
return campus;
}
@Override
public boolean equals(final Object object) {
if (object == null || !(object instanceof Teacher)) return false;
if (getEmailAddress() == null) return false;
final Teacher teacher = (Teacher)object;
/*
return getFirstName().equalsIgnoreCase(teacher.getFirstName()) &&
getLastName().equalsIgnoreCase(teacher.getLastName()) &&
getGender() == teacher.getGender() &&
getWages().equals(teacher.getWages()) &&
getEmailAddress().equalsIgnoreCase(teacher.getEmailAddress());
*/
return getEmailAddress().equalsIgnoreCase(teacher.getEmailAddress());
}
@Override
public int hashCode() {
/*
return 13 * (getFirstName().hashCode() +
getLastName().hashCode() +
getGender().hashCode() +
getWages().hashCode() +
getEmailAddress().hashCode());
*/
return getEmailAddress() == null ?
0 : getEmailAddress().toLowerCase().hashCode();
}
public boolean addResponsibility(final Responsibility responsibility) {
final boolean added = responsibilities.add(responsibility);
if (!responsibility.getTeachers().contains(this))
responsibility.addTeacher(this);
return added;
}
public boolean removeResponsibility(final Responsibility responsibility) {
final boolean removed = responsibilities.remove(responsibility);
if (responsibility.getTeachers().contains(this))
responsibility.removeTeacher(this);
return removed;
}
public Set<Responsibility> getResponsibilities() {
return Collections.unmodifiableSet(responsibilities);
}
}
|
97352_0 | package be.vdab.goededoel.entities;
import java.math.BigDecimal;
/**
* Een <strong>goed doel</strong> waarvoor men cash inzamelt.
* TOMCAT DEPLOYMENT
* @author Stijn.Verholen
*
*/
public class GoedeDoel {
private final String naam;
private BigDecimal opgebracht = BigDecimal.ZERO;
/**
* Instantiates a GoedeDoel object.
* @param naam the charity's name.
*/
public GoedeDoel(String naam) {
this.naam = naam;
}
/**
* Returns the charity's name
* @return the charity's name
*/
public String getNaam() {
return naam;
}
/**
* Return the amount that was donated.
* @return the amount that was donated.
*/
public BigDecimal getOpgebracht() {
return opgebracht;
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof GoedeDoel))
return false;
return ((GoedeDoel)object).naam.equalsIgnoreCase(naam);
}
@Override
public int hashCode() {
return this.naam.toUpperCase().hashCode();
}
}
| vdab-stijn/goededoel | src/main/java/be/vdab/goededoel/entities/GoedeDoel.java | 343 | /**
* Een <strong>goed doel</strong> waarvoor men cash inzamelt.
* TOMCAT DEPLOYMENT
* @author Stijn.Verholen
*
*/ | block_comment | nl | package be.vdab.goededoel.entities;
import java.math.BigDecimal;
/**
* Een <strong>goed doel</strong><SUF>*/
public class GoedeDoel {
private final String naam;
private BigDecimal opgebracht = BigDecimal.ZERO;
/**
* Instantiates a GoedeDoel object.
* @param naam the charity's name.
*/
public GoedeDoel(String naam) {
this.naam = naam;
}
/**
* Returns the charity's name
* @return the charity's name
*/
public String getNaam() {
return naam;
}
/**
* Return the amount that was donated.
* @return the amount that was donated.
*/
public BigDecimal getOpgebracht() {
return opgebracht;
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof GoedeDoel))
return false;
return ((GoedeDoel)object).naam.equalsIgnoreCase(naam);
}
@Override
public int hashCode() {
return this.naam.toUpperCase().hashCode();
}
}
|
189762_1 | package be.vdab.groenetenen.mail;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import be.vdab.groenetenen.entities.Tender;
import be.vdab.groenetenen.exceptions.UnableToSendMailException;
@Component
public class MailSenderDefault implements MailSender {
private static final Logger LOGGER
= LoggerFactory.getLogger(MailSenderDefault.class);
private final JavaMailSender sender;
private final String emailAddressWebmaster;
public MailSenderDefault(
final JavaMailSender sender,
@Value("${emailAddressWebmaster}")
final String emailAddressWebmaster) {
this.sender = sender;
this.emailAddressWebmaster = emailAddressWebmaster;
}
@Override
@Async
public void newTender(final Tender tender, final String tenderURL) {
try {
// final SimpleMailMessage message = new SimpleMailMessage();
//
// message.setTo(tender.getEmailAdress());
// message.setSubject("Green toes - New Tender");
// message.setText("Your tender has number " + tender.getId());
//
// sender.send(message);
final MimeMessage message = sender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(tender.getEmailAddress());
helper.setSubject("New tender from Green Toes");
helper.setText("Your tender has number <strong>" + tender.getId() +
"</strong>. You can access your tender details " +
"<a href='" + tenderURL + tender.getId() + "'>here</a>.",
true);
sender.send(message);
}
catch (final MessagingException | MailException ex) {
final String error = "Can't send new tender mail";
LOGGER.error(error, ex);
throw new UnableToSendMailException(error, ex);
}
}
@Override
public void countTendersMail(final long count) {
try {
final MimeMessage message = sender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(emailAddressWebmaster);
helper.setSubject("Tender count");
helper.setText("Number of tenders:<strong>" + count + "</strong",
true);
sender.send(message);
}
catch (final MessagingException | MailException ex) {
final String error = "Can't send tender count mail";
LOGGER.error(error, ex);
throw new UnableToSendMailException(error, ex);
}
}
}
| vdab-stijn/groenetenen | src/main/java/be/vdab/groenetenen/mail/MailSenderDefault.java | 823 | // message.setSubject("Green toes - New Tender"); | line_comment | nl | package be.vdab.groenetenen.mail;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import be.vdab.groenetenen.entities.Tender;
import be.vdab.groenetenen.exceptions.UnableToSendMailException;
@Component
public class MailSenderDefault implements MailSender {
private static final Logger LOGGER
= LoggerFactory.getLogger(MailSenderDefault.class);
private final JavaMailSender sender;
private final String emailAddressWebmaster;
public MailSenderDefault(
final JavaMailSender sender,
@Value("${emailAddressWebmaster}")
final String emailAddressWebmaster) {
this.sender = sender;
this.emailAddressWebmaster = emailAddressWebmaster;
}
@Override
@Async
public void newTender(final Tender tender, final String tenderURL) {
try {
// final SimpleMailMessage message = new SimpleMailMessage();
//
// message.setTo(tender.getEmailAdress());
// message.setSubject("Green toes<SUF>
// message.setText("Your tender has number " + tender.getId());
//
// sender.send(message);
final MimeMessage message = sender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(tender.getEmailAddress());
helper.setSubject("New tender from Green Toes");
helper.setText("Your tender has number <strong>" + tender.getId() +
"</strong>. You can access your tender details " +
"<a href='" + tenderURL + tender.getId() + "'>here</a>.",
true);
sender.send(message);
}
catch (final MessagingException | MailException ex) {
final String error = "Can't send new tender mail";
LOGGER.error(error, ex);
throw new UnableToSendMailException(error, ex);
}
}
@Override
public void countTendersMail(final long count) {
try {
final MimeMessage message = sender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(emailAddressWebmaster);
helper.setSubject("Tender count");
helper.setText("Number of tenders:<strong>" + count + "</strong",
true);
sender.send(message);
}
catch (final MessagingException | MailException ex) {
final String error = "Can't send tender count mail";
LOGGER.error(error, ex);
throw new UnableToSendMailException(error, ex);
}
}
}
|
34512_1 | package GameNationBackEnd.Repositories;
import GameNationBackEnd.Documents.User;
import GameNationBackEnd.Documents.Game;
import GameNationBackEnd.Documents.UserGame;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserGameRepository extends MongoRepository<UserGame, String> {
List<UserGame> findByUser(User user);
List<UserGame> findAll();
List<UserGame> findByGame(Game game);
// da dingske werkt hier precies nie echt kweenie, steeds NullPointerExceptions
// misschiend door die dbrefs? kweenie
List<Game> findGameByUser(User user);
UserGame findByUserAndGame(User user, Game game);
}
| vdhwouter/GameNation | src/main/java/GameNationBackEnd/Repositories/UserGameRepository.java | 220 | // misschiend door die dbrefs? kweenie | line_comment | nl | package GameNationBackEnd.Repositories;
import GameNationBackEnd.Documents.User;
import GameNationBackEnd.Documents.Game;
import GameNationBackEnd.Documents.UserGame;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserGameRepository extends MongoRepository<UserGame, String> {
List<UserGame> findByUser(User user);
List<UserGame> findAll();
List<UserGame> findByGame(Game game);
// da dingske werkt hier precies nie echt kweenie, steeds NullPointerExceptions
// misschiend door<SUF>
List<Game> findGameByUser(User user);
UserGame findByUserAndGame(User user, Game game);
}
|
91707_3 | /**
* @author Christian Visintin <[email protected]>
* @version 0.1.0
*
* MIT License
*
* Copyright (c) 2020 Christian Visintin
*
* 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 it.deskichup.robespierre.core;
import java.util.ArrayList;
import java.util.Collections;
import it.deskichup.robespierre.utils.Uuidv4;
/**
* This class gives name to Feed Workers. Yes.
*/
public class FeedWorkerGodfather {
private final ArrayList<String> names;
public FeedWorkerGodfather(boolean useGeekNames) {
// Initialize names
names = new ArrayList<>();
if (useGeekNames) {
// Put names (> 96)
// Tech geek stuff
addName("Bash");
addName("C++");
addName("Python");
addName("Java");
addName("Rust");
addName("GCC");
addName("Yocto");
addName("Balena");
addName("Docker");
addName("Maria");
addName("EOF");
addName("Kernel Panic");
addName("Debian");
addName("Github");
addName("React");
addName("NodeJS");
addName("Segfault");
addName("SIGABRT");
addName("Kill-9");
addName("psaux");
addName("Redis");
addName("Mongo");
addName("pip");
addName("CMake");
addName("Gitignore");
addName("Linux");
addName("Fedora");
addName("Redux");
addName("Systemd");
addName("Qwerty");
addName("Regex");
addName("Manjaro");
addName("apt-get");
addName("sudo");
addName("-fpedantic");
// Geek stuff
// Sonic
addName("Amy Rose");
addName("Sonic");
addName("Mr Eggman");
// TF2
addName("Pootis Spencer");
addName("The G-Man");
addName("Red Engineer");
addName("Rancho Relaxo");
addName("Herr Doktor");
// Mario
addName("Mario");
addName("Luigi");
addName("Toad");
addName("Peach");
addName("Daisy");
// Zelda
addName("Link");
addName("Zelda");
addName("Ganondorf");
// Memes
addName("Rest in pepperoni");
addName("Moon Emoji");
addName("Master Hand");
addName("Crazy Hand");
addName("Konty");
addName("Mickey");
addName("Omar");
addName("Globglogabgalab");
addName("Shrek");
addName("Caramelldansen");
addName("Doge Shibe");
addName("Harambe");
addName("Pingu");
addName("Gabe");
addName("Doggo");
addName("Big Shaq");
addName("Poppy");
addName("Aimbot");
addName("Wallhack");
addName("Paintexe");
addName("Animoji");
addName("Nyan Cat");
addName("Mr Sandman");
// minecraft
addName("Steve");
addName("Herobrine");
addName("Noteblock");
addName("Pink Sheep");
// TV Series
addName("Bojack");
addName("Diane Nguyen");
addName("Mr Peanutbutter");
addName("Princess Carolyn");
addName("Piper Chapman");
addName("Rick");
addName("Morty");
addName("Mr Meeseeks");
addName("Abed Nadir");
// Pokemon
addName("Ditto");
addName("Pikachu");
addName("Clefairy");
addName("Sylveon");
addName("Latias");
addName("Latios");
addName("Mew");
addName("Mewtwo");
// Animal Crossing
addName("Tom Nook");
addName("Isabelle");
addName("Tortimer");
addName("KK Slider");
// Subnautica
addName("Reaper Leviathan");
addName("Mesmer");
addName("Warper");
addName("Peeper");
// Overwatch
addName("Winston");
addName("DVa");
addName("Tracer");
addName("Genji");
// Other stuff
addName("Barbie Girl");
addName("Pizza");
addName("Coconut");
addName("Seitan");
addName("Tofu");
addName("Curry");
addName("Pineapple");
addName("Long Island");
addName("Midori");
addName("Pina Colada");
addName("PYT");
// It's me
addName("Veeso");
}
// Then shuffle list
Collections.shuffle(names);
}
/**
* <p>
* Baptize worker
* </p>
*
* @return String
*/
public String baptize() {
// If names has length 0, return 'UUID'
if (names.size() == 0) {
return new Uuidv4().toString();
}
// Get first element in list and remove it from the list
return names.remove(0);
}
/**
* <p>
* Add name to names
* </p>
*
* @param name
*/
private void addName(String name) {
this.names.add(name);
}
}
| veeso/Robespierre | src/main/java/it/deskichup/robespierre/core/FeedWorkerGodfather.java | 1,959 | // Tech geek stuff | line_comment | nl | /**
* @author Christian Visintin <[email protected]>
* @version 0.1.0
*
* MIT License
*
* Copyright (c) 2020 Christian Visintin
*
* 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 it.deskichup.robespierre.core;
import java.util.ArrayList;
import java.util.Collections;
import it.deskichup.robespierre.utils.Uuidv4;
/**
* This class gives name to Feed Workers. Yes.
*/
public class FeedWorkerGodfather {
private final ArrayList<String> names;
public FeedWorkerGodfather(boolean useGeekNames) {
// Initialize names
names = new ArrayList<>();
if (useGeekNames) {
// Put names (> 96)
// Tech geek<SUF>
addName("Bash");
addName("C++");
addName("Python");
addName("Java");
addName("Rust");
addName("GCC");
addName("Yocto");
addName("Balena");
addName("Docker");
addName("Maria");
addName("EOF");
addName("Kernel Panic");
addName("Debian");
addName("Github");
addName("React");
addName("NodeJS");
addName("Segfault");
addName("SIGABRT");
addName("Kill-9");
addName("psaux");
addName("Redis");
addName("Mongo");
addName("pip");
addName("CMake");
addName("Gitignore");
addName("Linux");
addName("Fedora");
addName("Redux");
addName("Systemd");
addName("Qwerty");
addName("Regex");
addName("Manjaro");
addName("apt-get");
addName("sudo");
addName("-fpedantic");
// Geek stuff
// Sonic
addName("Amy Rose");
addName("Sonic");
addName("Mr Eggman");
// TF2
addName("Pootis Spencer");
addName("The G-Man");
addName("Red Engineer");
addName("Rancho Relaxo");
addName("Herr Doktor");
// Mario
addName("Mario");
addName("Luigi");
addName("Toad");
addName("Peach");
addName("Daisy");
// Zelda
addName("Link");
addName("Zelda");
addName("Ganondorf");
// Memes
addName("Rest in pepperoni");
addName("Moon Emoji");
addName("Master Hand");
addName("Crazy Hand");
addName("Konty");
addName("Mickey");
addName("Omar");
addName("Globglogabgalab");
addName("Shrek");
addName("Caramelldansen");
addName("Doge Shibe");
addName("Harambe");
addName("Pingu");
addName("Gabe");
addName("Doggo");
addName("Big Shaq");
addName("Poppy");
addName("Aimbot");
addName("Wallhack");
addName("Paintexe");
addName("Animoji");
addName("Nyan Cat");
addName("Mr Sandman");
// minecraft
addName("Steve");
addName("Herobrine");
addName("Noteblock");
addName("Pink Sheep");
// TV Series
addName("Bojack");
addName("Diane Nguyen");
addName("Mr Peanutbutter");
addName("Princess Carolyn");
addName("Piper Chapman");
addName("Rick");
addName("Morty");
addName("Mr Meeseeks");
addName("Abed Nadir");
// Pokemon
addName("Ditto");
addName("Pikachu");
addName("Clefairy");
addName("Sylveon");
addName("Latias");
addName("Latios");
addName("Mew");
addName("Mewtwo");
// Animal Crossing
addName("Tom Nook");
addName("Isabelle");
addName("Tortimer");
addName("KK Slider");
// Subnautica
addName("Reaper Leviathan");
addName("Mesmer");
addName("Warper");
addName("Peeper");
// Overwatch
addName("Winston");
addName("DVa");
addName("Tracer");
addName("Genji");
// Other stuff
addName("Barbie Girl");
addName("Pizza");
addName("Coconut");
addName("Seitan");
addName("Tofu");
addName("Curry");
addName("Pineapple");
addName("Long Island");
addName("Midori");
addName("Pina Colada");
addName("PYT");
// It's me
addName("Veeso");
}
// Then shuffle list
Collections.shuffle(names);
}
/**
* <p>
* Baptize worker
* </p>
*
* @return String
*/
public String baptize() {
// If names has length 0, return 'UUID'
if (names.size() == 0) {
return new Uuidv4().toString();
}
// Get first element in list and remove it from the list
return names.remove(0);
}
/**
* <p>
* Add name to names
* </p>
*
* @param name
*/
private void addName(String name) {
this.names.add(name);
}
}
|
194980_35 | /**
* Copyright 2016, RadiantBlue Technologies, 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 access.deploy;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import com.amazonaws.AmazonClientException;
import access.database.Accessor;
import access.util.AccessUtilities;
import exception.GeoServerException;
import exception.InvalidInputException;
import model.data.DataResource;
import model.data.deployment.Deployment;
import model.data.type.GeoJsonDataType;
import model.data.type.PostGISDataType;
import model.data.type.RasterDataType;
import model.data.type.ShapefileDataType;
import model.logger.AuditElement;
import model.logger.Severity;
import util.PiazzaLogger;
import util.UUIDFactory;
/**
* Class that manages the GeoServer Deployments held by this component. This is done by managing the Deployments via a
* MongoDB collection.
*
* A deployment is, in this current context, a GeoServer layer being stood up. In the future, this may be expanded to
* other deployment solutions, as requested by users in the Access Job.
*
* @author Patrick.Doody
*
*/
@Component
public class Deployer {
@Autowired
private PiazzaLogger pzLogger;
@Autowired
private UUIDFactory uuidFactory;
@Autowired
private AccessUtilities accessUtilities;
@Autowired
private Accessor accessor;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.hostname}")
private String geoserverHost;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.port}")
private String geoserverPort;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.username}")
private String geoserverUsername;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.password}")
private String geoserverPassword;
@Autowired
private RestTemplate restTemplate;
private static final String HOST_ADDRESS = "http://%s:%s%s";
private static final String ADD_LAYER_ENDPOINT = "/geoserver/rest/workspaces/piazza/datastores/piazza/featuretypes/";
private static final String CAPABILITIES_URL = "/geoserver/piazza/wfs?service=wfs&version=2.0.0&request=GetCapabilities";
private static final Logger LOGGER = LoggerFactory.getLogger(Deployer.class);
/**
* Creates a new deployment from the dataResource object.
*
* @param dataResource
* The resource metadata, describing the object to be deployed.
* @return A deployment for the object.
* @throws GeoServerException
*/
public Deployment createDeployment(DataResource dataResource) throws GeoServerException {
// Create the GeoServer Deployment based on the Data Type
Deployment deployment;
try {
if ((dataResource.getDataType() instanceof ShapefileDataType) || (dataResource.getDataType() instanceof PostGISDataType)
|| (dataResource.getDataType() instanceof GeoJsonDataType)) {
// GeoJSON allows for empty feature sets. If a GeoJSON with no features, then do not deploy.
if (dataResource.getDataType() instanceof GeoJsonDataType) {
if ((dataResource.getSpatialMetadata().getNumFeatures() != null)
&& (dataResource.getSpatialMetadata().getNumFeatures() == 0)) {
// If no GeoJSON features, then do not deploy.
throw new GeoServerException(
String.format("Could not create deployment for %s. This Data contains no features or feature schema.",
dataResource.getDataId()));
}
}
// Deploy from an existing PostGIS Table
deployment = deployPostGisTable(dataResource);
} else if (dataResource.getDataType() instanceof RasterDataType) {
// Deploy a GeoTIFF to GeoServer
deployment = deployRaster(dataResource);
} else {
// Unsupported Data type has been specified.
throw new UnsupportedOperationException(
"Cannot deploy the following Data Type to GeoServer: " + dataResource.getDataType().getClass().getSimpleName());
}
} catch (Exception exception) {
String error = String.format("There was an error deploying the to GeoServer instance: %s", exception.getMessage());
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
// Insert the Deployment into the Database
deployment.createdOn = new DateTime();
accessor.insertDeployment(deployment);
// Log information
pzLogger.log(
String.format("Created Deployment %s for Data %s on host %s", deployment.getDeploymentId(), deployment.getDataId(),
deployment.getHost()),
Severity.INFORMATIONAL, new AuditElement("access", "createNewDeployment", deployment.getDeploymentId()));
// Return Deployment reference
return deployment;
}
/**
* Deploys a PostGIS Table resource to GeoServer. This will create a new GeoServer layer that will reference the
* PostGIS table.
*
* PostGIS tables can be created via the Ingest process by, for instance, ingesting a Shapefile or a WFS into the
* Database.
*
* @param dataResource
* The DataResource to deploy.
* @return The Deployment
* @throws GeoServerException
* @throws IOException
*/
private Deployment deployPostGisTable(DataResource dataResource) throws GeoServerException, IOException {
// Create the JSON Payload for the Layer request to GeoServer
ClassLoader classLoader = getClass().getClassLoader();
InputStream templateStream = null;
String featureTypeRequestBody = null;
try {
templateStream = classLoader.getResourceAsStream("templates" + File.separator + "featureTypeRequest.xml");
featureTypeRequestBody = IOUtils.toString(templateStream);
} catch (Exception exception) {
LOGGER.error("Error reading GeoServer Template.", exception);
} finally {
try {
templateStream.close();
} catch (Exception exception) {
LOGGER.error("Error closing GeoServer Template Stream.", exception);
}
}
// Get the appropriate Table Name from the DataResource
String tableName = null;
if (dataResource.getDataType() instanceof ShapefileDataType) {
tableName = ((ShapefileDataType) dataResource.getDataType()).getDatabaseTableName();
} else if (dataResource.getDataType() instanceof PostGISDataType) {
tableName = ((PostGISDataType) dataResource.getDataType()).getTable();
} else if (dataResource.getDataType() instanceof GeoJsonDataType) {
tableName = ((GeoJsonDataType) dataResource.getDataType()).databaseTableName;
}
// Inject the Metadata from the Data Resource into the Payload
String requestBody = String.format(featureTypeRequestBody, tableName, tableName, tableName,
dataResource.getSpatialMetadata().getEpsgString(), "EPSG:4326");
// Execute the POST to GeoServer to add the FeatureType
HttpStatus statusCode = postGeoServerFeatureType(ADD_LAYER_ENDPOINT, requestBody);
// Ensure the Status Code is OK
if (statusCode != HttpStatus.CREATED) {
pzLogger.log(
String.format("Failed to Deploy PostGIS Table name %s for Resource %s to GeoServer. HTTP Code: %s", tableName,
dataResource.getDataId(), statusCode),
Severity.ERROR, new AuditElement("access", "failedToCreatePostGisTable", dataResource.getDataId()));
throw new GeoServerException("Failed to Deploy to GeoServer; the Status returned a non-OK response code: " + statusCode);
}
// Create a new Deployment for this Resource
String deploymentId = uuidFactory.getUUID();
String capabilitiesUrl = String.format(HOST_ADDRESS, geoserverHost, geoserverPort, CAPABILITIES_URL);
pzLogger.log(String.format("Created PostGIS Table for Resource %s", dataResource.getDataId()), Severity.INFORMATIONAL,
new AuditElement("access", "createPostGisTable", dataResource.getDataId()));
return new Deployment(deploymentId, dataResource.getDataId(), geoserverHost, geoserverPort, tableName, capabilitiesUrl);
}
/**
* Deploys a GeoTIFF resource to GeoServer. This will create a new GeoServer data store and layer. This will upload
* the file directly to GeoServer using the GeoServer REST API.
*
* @param dataResource
* The DataResource to deploy.
* @return The Deployment
* @throws InvalidInputException
* @throws IOException
* @throws AmazonClientException
*/
private Deployment deployRaster(DataResource dataResource) throws GeoServerException, IOException, InvalidInputException {
// Get the File Bytes of the Raster to be uploaded
byte[] fileBytes = accessUtilities.getBytesForDataResource(dataResource);
// Create the Request that will upload the File
HttpHeaders headers = getGeoServerHeaders();
headers.add("Content-type", "image/tiff");
HttpEntity<byte[]> request = new HttpEntity<>(fileBytes, headers);
// Send the Request
String url = String.format("http://%s:%s/geoserver/rest/workspaces/piazza/coveragestores/%s/file.geotiff", geoserverHost,
geoserverPort, dataResource.getDataId());
try {
pzLogger.log(String.format("Creating new Raster Deployment to %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "deployGeoServerRasterLayer", dataResource.getDataId()));
restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
if (exception.getStatusCode() == HttpStatus.METHOD_NOT_ALLOWED) {
// If 405 NOT ALLOWED is encountered, then the layer may already exist on the GeoServer. Check if it
// exists already. If it does, then use this layer for the Deployment.
if (!doesGeoServerLayerExist(dataResource.getDataId())) {
// If it doesn't exist, throw an error. Something went wrong.
String error = String.format(
"GeoServer would not allow for layer creation, despite an existing layer not being present: url: %s, statusCode: %s, exceptionBody: %s",
url, exception.getStatusCode().toString(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR);
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
} else if ((exception.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR)
&& (exception.getResponseBodyAsString().contains("Error persisting"))) {
// If a 500 is received, then it's possible that GeoServer is processing this layer already via a
// simultaneous POST, and there is a collision. Add this information to the response.
// TODO: In the future, we should persist a lookup table where only one Data ID is persisted at a time
// to GeoServer, to avoid this collision.
String error = String.format(
"Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s. This may be the result of GeoServer processing this Data Id simultaneously by another request. Please try again.",
url, exception.getStatusCode().toString(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToDeployRaster", dataResource.getDataId()));
LOGGER.error(error, exception);
throw new GeoServerException(error);
} else {
// For any other errors, report back this error to the user and fail the job.
String error = String.format("Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s", url,
exception.getStatusCode().toString(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToDeployRaster", dataResource.getDataId()));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
// Create a Deployment for this Resource
String deploymentId = uuidFactory.getUUID();
String capabilitiesUrl = String.format(HOST_ADDRESS, geoserverHost, geoserverPort, CAPABILITIES_URL);
String deploymentLayerName = dataResource.getDataId();
return new Deployment(deploymentId, dataResource.getDataId(), geoserverHost, geoserverPort, deploymentLayerName, capabilitiesUrl);
}
/**
* Deletes a deployment, as specified by its Id. This will remove the Deployment from GeoServer, delete the lease
* and the deployment from the Database.
*
* @param deploymentId
* The Id of the deployment.
* @throws GeoServerException
* @throws InvalidInputException
*/
public void undeploy(String deploymentId) throws GeoServerException, InvalidInputException {
// Get the Deployment from the Database to delete. If the Deployment had
// a lease, then the lease is automatically removed when the deployment
// is deleted.
Deployment deployment = accessor.getDeployment(deploymentId);
if (deployment == null) {
throw new InvalidInputException("Deployment does not exist matching Id " + deploymentId);
}
// Delete the Deployment Layer from GeoServer
HttpHeaders headers = getGeoServerHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(headers);
String url = String.format("http://%s:%s/geoserver/rest/layers/%s", geoserverHost, geoserverPort, deployment.getLayer());
try {
pzLogger.log(String.format("Deleting Deployment from Resource %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "undeployGeoServerLayer", deploymentId));
restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
// Check the status code. If it's a 404, then the layer has likely
// already been deleted by some other means.
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
String warning = String.format(
"Attempted to undeploy GeoServer layer %s while deleting the Deployment Id %s, but the layer was already deleted from GeoServer. This layer may have been removed by some other means. If this was a Vector Source, then this message can be safely ignored.",
deployment.getLayer(), deploymentId);
pzLogger.log(warning, Severity.WARNING);
} else {
// Some other exception occurred. Bubble it up.
String error = String.format("Error deleting GeoServer Layer for Deployment %s via request %s: Code %s with Error %s",
deploymentId, url, exception.getStatusCode(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToDeleteGeoServerLayer", deploymentId));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
// If this was a Raster dataset that contained its own unique data store, then delete that Coverage Store.
url = String.format("http://%s:%s/geoserver/rest/workspaces/piazza/coveragestores/%s?purge=all&recurse=true", geoserverHost,
geoserverPort, deployment.getDataId());
try {
pzLogger.log(String.format("Deleting Coverage Store from Resource %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "deleteGeoServerCoverageStore", deployment.getDataId()));
restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
// Check the status code. If it's a 404, then the layer has likely
// already been deleted by some other means.
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
String warning = String.format(
"Attempted to delete Coverage Store for GeoServer %s while deleting the Deployment Id %s, but the Coverage Store was already deleted from GeoServer. This Store may have been removed by some other means.",
deployment.getLayer(), deploymentId);
pzLogger.log(warning, Severity.WARNING);
} else {
// Some other exception occurred. Bubble it up.
String error = String.format(
"Error deleting GeoServer Coverage Store for Deployment %s via request %s: Code %s with Error: %s", deploymentId,
url, exception.getStatusCode(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToUndeployLayer", deploymentId));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
// Remove the Deployment from the Database
accessor.deleteDeployment(deployment);
}
/**
* Executes the POST request to GeoServer to create the FeatureType as a Layer.
*
* @param featureType
* The JSON Payload of the POST request
* @return The HTTP Status code of the request to GeoServer for adding the layer. GeoServer will typically not
* return any payload in the response, so the HTTP Status is the best we can do in order to check for
* success.
* @throws GeoServerException
*/
private HttpStatus postGeoServerFeatureType(String restURL, String featureType) throws GeoServerException {
// Construct the URL for the Service
String url = String.format(HOST_ADDRESS, geoserverHost, geoserverPort, restURL);
LOGGER.info(String.format("Attempting to push a GeoServer Featuretype %s to URL %s", featureType, url));
// Create the Request template and execute
HttpHeaders headers = getGeoServerHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<String> request = new HttpEntity<>(featureType, headers);
ResponseEntity<String> response = null;
try {
pzLogger.log(String.format("Creating GeoServer Feature Type for Resource %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "createGeoServerFeatureType", url));
response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
} catch (Exception exception) {
String error = String.format("There was an error creating the Coverage Layer to URL %s with errors %s", url,
exception.getMessage());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToCreateGeoServerFeatureType", url));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
// Return the HTTP Status
return response.getStatusCode();
}
/**
* Checks GeoServer to determine if a Layer exists.
*
* @param layerId
* The ID of the layer. Corresponds with the Data ID.
* @return True if the layer exists on GeoServer, false if not.
* @throws GeoServerException
*/
public boolean doesGeoServerLayerExist(String layerId) throws GeoServerException {
HttpHeaders headers = getGeoServerHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(headers);
String url = String.format("http://%s:%s/geoserver/rest/layers/%s.json", geoserverHost, geoserverPort, layerId);
try {
pzLogger.log(String.format("Checking GeoServer if Layer Exists %s", layerId), Severity.INFORMATIONAL,
new AuditElement("access", "checkGeoServerLayerExists", url));
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
return response.getStatusCode().equals(HttpStatus.OK);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
// Check the status code. If it's a 404, then the layer does not exist.
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
return false;
} else {
// Some other exception occurred. Bubble it up as an exception.
String error = String.format("Error while checking status of Layer %s. GeoServer returned with Code %s and error %s: ",
layerId, exception.getStatusCode(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToCheckGeoServerLayerStatus", layerId));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
}
/**
* Gets the headers for a typical GeoServer request. This include the "application/XML" content, and the encoded
* basic credentials.
*
* @return
*/
public HttpHeaders getGeoServerHeaders() {
// Get the Basic authentication Headers for GeoServer
String plainCredentials = String.format("%s:%s", geoserverUsername, geoserverPassword);
byte[] credentialBytes = plainCredentials.getBytes();
byte[] encodedCredentials = Base64.encodeBase64(credentialBytes);
String credentials = new String(encodedCredentials);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + credentials);
return headers;
}
/**
* Checks to see if the DataResource currently has a deployment in the system or not.
*
* @param dataId
* The Data Id to check for Deployment.
* @return True if a deployment exists for the Data Id, false if not.
*/
public boolean doesDeploymentExist(String dataId) {
return accessor.getDeploymentByDataId(dataId) != null ? true : false;
}
}
| venicegeo/dg-pz-access | src/main/java/access/deploy/Deployer.java | 6,221 | //%s:%s/geoserver/rest/layers/%s", geoserverHost, geoserverPort, deployment.getLayer()); | line_comment | nl | /**
* Copyright 2016, RadiantBlue Technologies, 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 access.deploy;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import com.amazonaws.AmazonClientException;
import access.database.Accessor;
import access.util.AccessUtilities;
import exception.GeoServerException;
import exception.InvalidInputException;
import model.data.DataResource;
import model.data.deployment.Deployment;
import model.data.type.GeoJsonDataType;
import model.data.type.PostGISDataType;
import model.data.type.RasterDataType;
import model.data.type.ShapefileDataType;
import model.logger.AuditElement;
import model.logger.Severity;
import util.PiazzaLogger;
import util.UUIDFactory;
/**
* Class that manages the GeoServer Deployments held by this component. This is done by managing the Deployments via a
* MongoDB collection.
*
* A deployment is, in this current context, a GeoServer layer being stood up. In the future, this may be expanded to
* other deployment solutions, as requested by users in the Access Job.
*
* @author Patrick.Doody
*
*/
@Component
public class Deployer {
@Autowired
private PiazzaLogger pzLogger;
@Autowired
private UUIDFactory uuidFactory;
@Autowired
private AccessUtilities accessUtilities;
@Autowired
private Accessor accessor;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.hostname}")
private String geoserverHost;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.port}")
private String geoserverPort;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.username}")
private String geoserverUsername;
@Value("${vcap.services.pz-geoserver-efs.credentials.geoserver.password}")
private String geoserverPassword;
@Autowired
private RestTemplate restTemplate;
private static final String HOST_ADDRESS = "http://%s:%s%s";
private static final String ADD_LAYER_ENDPOINT = "/geoserver/rest/workspaces/piazza/datastores/piazza/featuretypes/";
private static final String CAPABILITIES_URL = "/geoserver/piazza/wfs?service=wfs&version=2.0.0&request=GetCapabilities";
private static final Logger LOGGER = LoggerFactory.getLogger(Deployer.class);
/**
* Creates a new deployment from the dataResource object.
*
* @param dataResource
* The resource metadata, describing the object to be deployed.
* @return A deployment for the object.
* @throws GeoServerException
*/
public Deployment createDeployment(DataResource dataResource) throws GeoServerException {
// Create the GeoServer Deployment based on the Data Type
Deployment deployment;
try {
if ((dataResource.getDataType() instanceof ShapefileDataType) || (dataResource.getDataType() instanceof PostGISDataType)
|| (dataResource.getDataType() instanceof GeoJsonDataType)) {
// GeoJSON allows for empty feature sets. If a GeoJSON with no features, then do not deploy.
if (dataResource.getDataType() instanceof GeoJsonDataType) {
if ((dataResource.getSpatialMetadata().getNumFeatures() != null)
&& (dataResource.getSpatialMetadata().getNumFeatures() == 0)) {
// If no GeoJSON features, then do not deploy.
throw new GeoServerException(
String.format("Could not create deployment for %s. This Data contains no features or feature schema.",
dataResource.getDataId()));
}
}
// Deploy from an existing PostGIS Table
deployment = deployPostGisTable(dataResource);
} else if (dataResource.getDataType() instanceof RasterDataType) {
// Deploy a GeoTIFF to GeoServer
deployment = deployRaster(dataResource);
} else {
// Unsupported Data type has been specified.
throw new UnsupportedOperationException(
"Cannot deploy the following Data Type to GeoServer: " + dataResource.getDataType().getClass().getSimpleName());
}
} catch (Exception exception) {
String error = String.format("There was an error deploying the to GeoServer instance: %s", exception.getMessage());
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
// Insert the Deployment into the Database
deployment.createdOn = new DateTime();
accessor.insertDeployment(deployment);
// Log information
pzLogger.log(
String.format("Created Deployment %s for Data %s on host %s", deployment.getDeploymentId(), deployment.getDataId(),
deployment.getHost()),
Severity.INFORMATIONAL, new AuditElement("access", "createNewDeployment", deployment.getDeploymentId()));
// Return Deployment reference
return deployment;
}
/**
* Deploys a PostGIS Table resource to GeoServer. This will create a new GeoServer layer that will reference the
* PostGIS table.
*
* PostGIS tables can be created via the Ingest process by, for instance, ingesting a Shapefile or a WFS into the
* Database.
*
* @param dataResource
* The DataResource to deploy.
* @return The Deployment
* @throws GeoServerException
* @throws IOException
*/
private Deployment deployPostGisTable(DataResource dataResource) throws GeoServerException, IOException {
// Create the JSON Payload for the Layer request to GeoServer
ClassLoader classLoader = getClass().getClassLoader();
InputStream templateStream = null;
String featureTypeRequestBody = null;
try {
templateStream = classLoader.getResourceAsStream("templates" + File.separator + "featureTypeRequest.xml");
featureTypeRequestBody = IOUtils.toString(templateStream);
} catch (Exception exception) {
LOGGER.error("Error reading GeoServer Template.", exception);
} finally {
try {
templateStream.close();
} catch (Exception exception) {
LOGGER.error("Error closing GeoServer Template Stream.", exception);
}
}
// Get the appropriate Table Name from the DataResource
String tableName = null;
if (dataResource.getDataType() instanceof ShapefileDataType) {
tableName = ((ShapefileDataType) dataResource.getDataType()).getDatabaseTableName();
} else if (dataResource.getDataType() instanceof PostGISDataType) {
tableName = ((PostGISDataType) dataResource.getDataType()).getTable();
} else if (dataResource.getDataType() instanceof GeoJsonDataType) {
tableName = ((GeoJsonDataType) dataResource.getDataType()).databaseTableName;
}
// Inject the Metadata from the Data Resource into the Payload
String requestBody = String.format(featureTypeRequestBody, tableName, tableName, tableName,
dataResource.getSpatialMetadata().getEpsgString(), "EPSG:4326");
// Execute the POST to GeoServer to add the FeatureType
HttpStatus statusCode = postGeoServerFeatureType(ADD_LAYER_ENDPOINT, requestBody);
// Ensure the Status Code is OK
if (statusCode != HttpStatus.CREATED) {
pzLogger.log(
String.format("Failed to Deploy PostGIS Table name %s for Resource %s to GeoServer. HTTP Code: %s", tableName,
dataResource.getDataId(), statusCode),
Severity.ERROR, new AuditElement("access", "failedToCreatePostGisTable", dataResource.getDataId()));
throw new GeoServerException("Failed to Deploy to GeoServer; the Status returned a non-OK response code: " + statusCode);
}
// Create a new Deployment for this Resource
String deploymentId = uuidFactory.getUUID();
String capabilitiesUrl = String.format(HOST_ADDRESS, geoserverHost, geoserverPort, CAPABILITIES_URL);
pzLogger.log(String.format("Created PostGIS Table for Resource %s", dataResource.getDataId()), Severity.INFORMATIONAL,
new AuditElement("access", "createPostGisTable", dataResource.getDataId()));
return new Deployment(deploymentId, dataResource.getDataId(), geoserverHost, geoserverPort, tableName, capabilitiesUrl);
}
/**
* Deploys a GeoTIFF resource to GeoServer. This will create a new GeoServer data store and layer. This will upload
* the file directly to GeoServer using the GeoServer REST API.
*
* @param dataResource
* The DataResource to deploy.
* @return The Deployment
* @throws InvalidInputException
* @throws IOException
* @throws AmazonClientException
*/
private Deployment deployRaster(DataResource dataResource) throws GeoServerException, IOException, InvalidInputException {
// Get the File Bytes of the Raster to be uploaded
byte[] fileBytes = accessUtilities.getBytesForDataResource(dataResource);
// Create the Request that will upload the File
HttpHeaders headers = getGeoServerHeaders();
headers.add("Content-type", "image/tiff");
HttpEntity<byte[]> request = new HttpEntity<>(fileBytes, headers);
// Send the Request
String url = String.format("http://%s:%s/geoserver/rest/workspaces/piazza/coveragestores/%s/file.geotiff", geoserverHost,
geoserverPort, dataResource.getDataId());
try {
pzLogger.log(String.format("Creating new Raster Deployment to %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "deployGeoServerRasterLayer", dataResource.getDataId()));
restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
if (exception.getStatusCode() == HttpStatus.METHOD_NOT_ALLOWED) {
// If 405 NOT ALLOWED is encountered, then the layer may already exist on the GeoServer. Check if it
// exists already. If it does, then use this layer for the Deployment.
if (!doesGeoServerLayerExist(dataResource.getDataId())) {
// If it doesn't exist, throw an error. Something went wrong.
String error = String.format(
"GeoServer would not allow for layer creation, despite an existing layer not being present: url: %s, statusCode: %s, exceptionBody: %s",
url, exception.getStatusCode().toString(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR);
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
} else if ((exception.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR)
&& (exception.getResponseBodyAsString().contains("Error persisting"))) {
// If a 500 is received, then it's possible that GeoServer is processing this layer already via a
// simultaneous POST, and there is a collision. Add this information to the response.
// TODO: In the future, we should persist a lookup table where only one Data ID is persisted at a time
// to GeoServer, to avoid this collision.
String error = String.format(
"Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s. This may be the result of GeoServer processing this Data Id simultaneously by another request. Please try again.",
url, exception.getStatusCode().toString(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToDeployRaster", dataResource.getDataId()));
LOGGER.error(error, exception);
throw new GeoServerException(error);
} else {
// For any other errors, report back this error to the user and fail the job.
String error = String.format("Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s", url,
exception.getStatusCode().toString(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToDeployRaster", dataResource.getDataId()));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
// Create a Deployment for this Resource
String deploymentId = uuidFactory.getUUID();
String capabilitiesUrl = String.format(HOST_ADDRESS, geoserverHost, geoserverPort, CAPABILITIES_URL);
String deploymentLayerName = dataResource.getDataId();
return new Deployment(deploymentId, dataResource.getDataId(), geoserverHost, geoserverPort, deploymentLayerName, capabilitiesUrl);
}
/**
* Deletes a deployment, as specified by its Id. This will remove the Deployment from GeoServer, delete the lease
* and the deployment from the Database.
*
* @param deploymentId
* The Id of the deployment.
* @throws GeoServerException
* @throws InvalidInputException
*/
public void undeploy(String deploymentId) throws GeoServerException, InvalidInputException {
// Get the Deployment from the Database to delete. If the Deployment had
// a lease, then the lease is automatically removed when the deployment
// is deleted.
Deployment deployment = accessor.getDeployment(deploymentId);
if (deployment == null) {
throw new InvalidInputException("Deployment does not exist matching Id " + deploymentId);
}
// Delete the Deployment Layer from GeoServer
HttpHeaders headers = getGeoServerHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(headers);
String url = String.format("http://%s:%s/geoserver/rest/layers/%s", geoserverHost,<SUF>
try {
pzLogger.log(String.format("Deleting Deployment from Resource %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "undeployGeoServerLayer", deploymentId));
restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
// Check the status code. If it's a 404, then the layer has likely
// already been deleted by some other means.
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
String warning = String.format(
"Attempted to undeploy GeoServer layer %s while deleting the Deployment Id %s, but the layer was already deleted from GeoServer. This layer may have been removed by some other means. If this was a Vector Source, then this message can be safely ignored.",
deployment.getLayer(), deploymentId);
pzLogger.log(warning, Severity.WARNING);
} else {
// Some other exception occurred. Bubble it up.
String error = String.format("Error deleting GeoServer Layer for Deployment %s via request %s: Code %s with Error %s",
deploymentId, url, exception.getStatusCode(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToDeleteGeoServerLayer", deploymentId));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
// If this was a Raster dataset that contained its own unique data store, then delete that Coverage Store.
url = String.format("http://%s:%s/geoserver/rest/workspaces/piazza/coveragestores/%s?purge=all&recurse=true", geoserverHost,
geoserverPort, deployment.getDataId());
try {
pzLogger.log(String.format("Deleting Coverage Store from Resource %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "deleteGeoServerCoverageStore", deployment.getDataId()));
restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
// Check the status code. If it's a 404, then the layer has likely
// already been deleted by some other means.
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
String warning = String.format(
"Attempted to delete Coverage Store for GeoServer %s while deleting the Deployment Id %s, but the Coverage Store was already deleted from GeoServer. This Store may have been removed by some other means.",
deployment.getLayer(), deploymentId);
pzLogger.log(warning, Severity.WARNING);
} else {
// Some other exception occurred. Bubble it up.
String error = String.format(
"Error deleting GeoServer Coverage Store for Deployment %s via request %s: Code %s with Error: %s", deploymentId,
url, exception.getStatusCode(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToUndeployLayer", deploymentId));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
// Remove the Deployment from the Database
accessor.deleteDeployment(deployment);
}
/**
* Executes the POST request to GeoServer to create the FeatureType as a Layer.
*
* @param featureType
* The JSON Payload of the POST request
* @return The HTTP Status code of the request to GeoServer for adding the layer. GeoServer will typically not
* return any payload in the response, so the HTTP Status is the best we can do in order to check for
* success.
* @throws GeoServerException
*/
private HttpStatus postGeoServerFeatureType(String restURL, String featureType) throws GeoServerException {
// Construct the URL for the Service
String url = String.format(HOST_ADDRESS, geoserverHost, geoserverPort, restURL);
LOGGER.info(String.format("Attempting to push a GeoServer Featuretype %s to URL %s", featureType, url));
// Create the Request template and execute
HttpHeaders headers = getGeoServerHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<String> request = new HttpEntity<>(featureType, headers);
ResponseEntity<String> response = null;
try {
pzLogger.log(String.format("Creating GeoServer Feature Type for Resource %s", url), Severity.INFORMATIONAL,
new AuditElement("access", "createGeoServerFeatureType", url));
response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
} catch (Exception exception) {
String error = String.format("There was an error creating the Coverage Layer to URL %s with errors %s", url,
exception.getMessage());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToCreateGeoServerFeatureType", url));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
// Return the HTTP Status
return response.getStatusCode();
}
/**
* Checks GeoServer to determine if a Layer exists.
*
* @param layerId
* The ID of the layer. Corresponds with the Data ID.
* @return True if the layer exists on GeoServer, false if not.
* @throws GeoServerException
*/
public boolean doesGeoServerLayerExist(String layerId) throws GeoServerException {
HttpHeaders headers = getGeoServerHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(headers);
String url = String.format("http://%s:%s/geoserver/rest/layers/%s.json", geoserverHost, geoserverPort, layerId);
try {
pzLogger.log(String.format("Checking GeoServer if Layer Exists %s", layerId), Severity.INFORMATIONAL,
new AuditElement("access", "checkGeoServerLayerExists", url));
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
return response.getStatusCode().equals(HttpStatus.OK);
} catch (HttpClientErrorException | HttpServerErrorException exception) {
// Check the status code. If it's a 404, then the layer does not exist.
if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
return false;
} else {
// Some other exception occurred. Bubble it up as an exception.
String error = String.format("Error while checking status of Layer %s. GeoServer returned with Code %s and error %s: ",
layerId, exception.getStatusCode(), exception.getResponseBodyAsString());
pzLogger.log(error, Severity.ERROR, new AuditElement("access", "failedToCheckGeoServerLayerStatus", layerId));
LOGGER.error(error, exception);
throw new GeoServerException(error);
}
}
}
/**
* Gets the headers for a typical GeoServer request. This include the "application/XML" content, and the encoded
* basic credentials.
*
* @return
*/
public HttpHeaders getGeoServerHeaders() {
// Get the Basic authentication Headers for GeoServer
String plainCredentials = String.format("%s:%s", geoserverUsername, geoserverPassword);
byte[] credentialBytes = plainCredentials.getBytes();
byte[] encodedCredentials = Base64.encodeBase64(credentialBytes);
String credentials = new String(encodedCredentials);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + credentials);
return headers;
}
/**
* Checks to see if the DataResource currently has a deployment in the system or not.
*
* @param dataId
* The Data Id to check for Deployment.
* @return True if a deployment exists for the Data Id, false if not.
*/
public boolean doesDeploymentExist(String dataId) {
return accessor.getDeploymentByDataId(dataId) != null ? true : false;
}
}
|
189156_12 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package vista;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import modelo.ConfiguracionUsuario;
import modelo.Usuario;
import servicios.ServicioUsuario;
import sesion.Sesion;
import utils.UtileriaVista;
import utils.constantes.Constantes;
import utils.constantes.RespuestaGeneral;
/**
*
* @author vacev
*/
public class vReestablecer extends javax.swing.JFrame {
/**
* Creates new form vReestablecer
*/
public char pass;
Sesion sesion;
Usuario usuario = new Usuario();
ServicioUsuario _usuario;
public vReestablecer(Usuario usuario) {
initComponents();
_usuario = new ServicioUsuario(Constantes.rutaConexion);
sesion = new Sesion(usuario, new ConfiguracionUsuario(), Constantes.rutaConexion);
this.usuario = usuario;
this.txtUsuario.setText(usuario.getNombre());
this.iniciarVista();
}
public void iniciarVista() {
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/utils/icon/user.png")));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
rSPanel1 = new necesario.RSPanel();
txtUsuario = new RSMaterialComponent.RSTextFieldMaterial();
rSButtonShapeIcon15 = new RSMaterialComponent.RSButtonShapeIcon();
rSButtonShapeIcon10 = new RSMaterialComponent.RSButtonShapeIcon();
jLabel1 = new javax.swing.JLabel();
txtClave = new RSMaterialComponent.RSPasswordMaterial();
checkBox = new rojerusan.RSCheckBox();
txtClave1 = new RSMaterialComponent.RSPasswordMaterial();
jLabel3 = new javax.swing.JLabel();
rSButtonShapeIcon9 = new RSMaterialComponent.RSButtonShapeIcon();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
rSPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
rSPanel1.setForeground(new java.awt.Color(255, 255, 255));
rSPanel1.setColorBackground(new java.awt.Color(255, 255, 255));
txtUsuario.setForeground(new java.awt.Color(0, 0, 0));
txtUsuario.setColorMaterial(new java.awt.Color(0, 0, 0));
txtUsuario.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
txtUsuario.setPhColor(new java.awt.Color(0, 0, 0));
txtUsuario.setPlaceholder("Digite el usuario..");
txtUsuario.setSelectionColor(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon15.setBackground(new java.awt.Color(33, 58, 86));
rSButtonShapeIcon15.setText("Restablecer");
rSButtonShapeIcon15.setBackgroundHover(new java.awt.Color(33, 68, 86));
rSButtonShapeIcon15.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
rSButtonShapeIcon15.setForma(RSMaterialComponent.RSButtonShapeIcon.FORMA.ROUND);
rSButtonShapeIcon15.setIcons(rojeru_san.efectos.ValoresEnum.ICONS.CACHED);
rSButtonShapeIcon15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rSButtonShapeIcon15ActionPerformed(evt);
}
});
rSButtonShapeIcon10.setBackground(new java.awt.Color(251, 205, 6));
rSButtonShapeIcon10.setText("Cancelar");
rSButtonShapeIcon10.setBackgroundHover(new java.awt.Color(251, 174, 6));
rSButtonShapeIcon10.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
rSButtonShapeIcon10.setForegroundHover(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForegroundIcon(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForegroundIconHover(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForegroundText(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForma(RSMaterialComponent.RSButtonShapeIcon.FORMA.ROUND);
rSButtonShapeIcon10.setIcons(rojeru_san.efectos.ValoresEnum.ICONS.CANCEL);
rSButtonShapeIcon10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rSButtonShapeIcon10ActionPerformed(evt);
}
});
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/utils/img/recuperacion.png"))); // NOI18N
jLabel1.setToolTipText("");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jLabel1.setIconTextGap(1);
txtClave.setForeground(new java.awt.Color(0, 0, 0));
txtClave.setActionCommand("<Not Set>");
txtClave.setColorMaterial(new java.awt.Color(0, 0, 0));
txtClave.setDropMode(javax.swing.DropMode.INSERT);
txtClave.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
txtClave.setPhColor(new java.awt.Color(0, 0, 0));
txtClave.setPlaceholder("Digite la nueva contraseña..");
txtClave.setSelectionColor(new java.awt.Color(0, 0, 0));
txtClave.setThemeTooltip(necesario.Global.THEMETOOLTIP.LIGHT);
checkBox.setForeground(new java.awt.Color(0, 0, 0));
checkBox.setText("Mostrar Contraseña");
checkBox.setColorCheck(new java.awt.Color(0, 0, 0));
checkBox.setColorUnCheck(new java.awt.Color(0, 0, 0));
checkBox.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
checkBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkBoxActionPerformed(evt);
}
});
txtClave1.setForeground(new java.awt.Color(0, 0, 0));
txtClave1.setActionCommand("<Not Set>");
txtClave1.setColorMaterial(new java.awt.Color(0, 0, 0));
txtClave1.setDropMode(javax.swing.DropMode.INSERT);
txtClave1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
txtClave1.setPhColor(new java.awt.Color(0, 0, 0));
txtClave1.setPlaceholder("Repetir la nueva contraseña..");
txtClave1.setSelectionColor(new java.awt.Color(0, 0, 0));
txtClave1.setThemeTooltip(necesario.Global.THEMETOOLTIP.LIGHT);
jLabel3.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("REESTABLECER");
jLabel3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
rSButtonShapeIcon9.setBackground(new java.awt.Color(33, 58, 86));
rSButtonShapeIcon9.setToolTipText("SALIR DE LA APLICACIÓN");
rSButtonShapeIcon9.setBackgroundHover(new java.awt.Color(33, 68, 86));
rSButtonShapeIcon9.setForma(RSMaterialComponent.RSButtonShapeIcon.FORMA.RECT);
rSButtonShapeIcon9.setHideActionText(true);
rSButtonShapeIcon9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
rSButtonShapeIcon9.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
rSButtonShapeIcon9.setIcons(rojeru_san.efectos.ValoresEnum.ICONS.CLOSE);
rSButtonShapeIcon9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rSButtonShapeIcon9ActionPerformed(evt);
}
});
javax.swing.GroupLayout rSPanel1Layout = new javax.swing.GroupLayout(rSPanel1);
rSPanel1.setLayout(rSPanel1Layout);
rSPanel1Layout.setHorizontalGroup(
rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rSPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rSPanel1Layout.createSequentialGroup()
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtClave1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(checkBox, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(83, 83, 83))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rSPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(107, 107, 107)
.addComponent(rSButtonShapeIcon9, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(rSPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 361, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(rSPanel1Layout.createSequentialGroup()
.addComponent(rSButtonShapeIcon10, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(rSButtonShapeIcon15, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(29, Short.MAX_VALUE))
);
rSPanel1Layout.setVerticalGroup(
rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(rSPanel1Layout.createSequentialGroup()
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(rSPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1))
.addComponent(rSButtonShapeIcon9, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtClave1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkBox, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rSButtonShapeIcon10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rSButtonShapeIcon15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rSPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(rSPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void rSButtonShapeIcon15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rSButtonShapeIcon15ActionPerformed
// ir a db a consultar si el usuario existe y si la pregunta hace mach con alguna respuesta configurada.
if (txtUsuario.getText().isEmpty() || txtClave.getText().isEmpty() || txtClave1.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Complete toda la información", "¡Alerta!", JOptionPane.WARNING_MESSAGE);
}
else {
if (txtClave.getText().equals(txtClave1.getText())) {
RespuestaGeneral rg = this._usuario.actualizarClaveRecuperacion(this.usuario, txtClave.getText().toCharArray());
if (rg.esExitosa()) {
JOptionPane.showMessageDialog(this, "Clave Reseteada Correctamente,\nPor Favor Inicie Sesion con la nueva contraseña", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
vLogin login = new vLogin(this.sesion);
login.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, rg.getMensaje(), "Mensaje", UtileriaVista.devolverCodigoMensaje(rg));
}
} else {
JOptionPane.showMessageDialog(this, "Las contraseñas no coinciden", "Mensaje", JOptionPane.WARNING_MESSAGE);
}
}
}//GEN-LAST:event_rSButtonShapeIcon15ActionPerformed
private void rSButtonShapeIcon10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rSButtonShapeIcon10ActionPerformed
vLogin login = new vLogin(null);
login.setVisible(true);
this.dispose();
}//GEN-LAST:event_rSButtonShapeIcon10ActionPerformed
private void checkBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxActionPerformed
char character = this.txtClave.getEchoChar();
if (this.checkBox.isSelected()) {
this.pass = character;
this.txtClave.setEchoChar((char) 0);
this.txtClave1.setEchoChar((char) 0);
} else {
this.txtClave.setEchoChar((char) this.pass);
this.txtClave1.setEchoChar((char) this.pass);
}
}//GEN-LAST:event_checkBoxActionPerformed
private void rSButtonShapeIcon9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rSButtonShapeIcon9ActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_rSButtonShapeIcon9ActionPerformed
/**
* @param args the command line arguments
*/
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new vReestablecer().setVisible(true);
// }
// });
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private rojerusan.RSCheckBox checkBox;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private RSMaterialComponent.RSButtonShapeIcon rSButtonShapeIcon10;
private RSMaterialComponent.RSButtonShapeIcon rSButtonShapeIcon15;
private RSMaterialComponent.RSButtonShapeIcon rSButtonShapeIcon9;
private necesario.RSPanel rSPanel1;
private RSMaterialComponent.RSPasswordMaterial txtClave;
private RSMaterialComponent.RSPasswordMaterial txtClave1;
private RSMaterialComponent.RSTextFieldMaterial txtUsuario;
// End of variables declaration//GEN-END:variables
}
| vernesto2/sistema_contable | src/vista/vReestablecer.java | 6,180 | // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html | line_comment | nl | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package vista;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import modelo.ConfiguracionUsuario;
import modelo.Usuario;
import servicios.ServicioUsuario;
import sesion.Sesion;
import utils.UtileriaVista;
import utils.constantes.Constantes;
import utils.constantes.RespuestaGeneral;
/**
*
* @author vacev
*/
public class vReestablecer extends javax.swing.JFrame {
/**
* Creates new form vReestablecer
*/
public char pass;
Sesion sesion;
Usuario usuario = new Usuario();
ServicioUsuario _usuario;
public vReestablecer(Usuario usuario) {
initComponents();
_usuario = new ServicioUsuario(Constantes.rutaConexion);
sesion = new Sesion(usuario, new ConfiguracionUsuario(), Constantes.rutaConexion);
this.usuario = usuario;
this.txtUsuario.setText(usuario.getNombre());
this.iniciarVista();
}
public void iniciarVista() {
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/utils/icon/user.png")));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
rSPanel1 = new necesario.RSPanel();
txtUsuario = new RSMaterialComponent.RSTextFieldMaterial();
rSButtonShapeIcon15 = new RSMaterialComponent.RSButtonShapeIcon();
rSButtonShapeIcon10 = new RSMaterialComponent.RSButtonShapeIcon();
jLabel1 = new javax.swing.JLabel();
txtClave = new RSMaterialComponent.RSPasswordMaterial();
checkBox = new rojerusan.RSCheckBox();
txtClave1 = new RSMaterialComponent.RSPasswordMaterial();
jLabel3 = new javax.swing.JLabel();
rSButtonShapeIcon9 = new RSMaterialComponent.RSButtonShapeIcon();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
rSPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
rSPanel1.setForeground(new java.awt.Color(255, 255, 255));
rSPanel1.setColorBackground(new java.awt.Color(255, 255, 255));
txtUsuario.setForeground(new java.awt.Color(0, 0, 0));
txtUsuario.setColorMaterial(new java.awt.Color(0, 0, 0));
txtUsuario.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
txtUsuario.setPhColor(new java.awt.Color(0, 0, 0));
txtUsuario.setPlaceholder("Digite el usuario..");
txtUsuario.setSelectionColor(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon15.setBackground(new java.awt.Color(33, 58, 86));
rSButtonShapeIcon15.setText("Restablecer");
rSButtonShapeIcon15.setBackgroundHover(new java.awt.Color(33, 68, 86));
rSButtonShapeIcon15.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
rSButtonShapeIcon15.setForma(RSMaterialComponent.RSButtonShapeIcon.FORMA.ROUND);
rSButtonShapeIcon15.setIcons(rojeru_san.efectos.ValoresEnum.ICONS.CACHED);
rSButtonShapeIcon15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rSButtonShapeIcon15ActionPerformed(evt);
}
});
rSButtonShapeIcon10.setBackground(new java.awt.Color(251, 205, 6));
rSButtonShapeIcon10.setText("Cancelar");
rSButtonShapeIcon10.setBackgroundHover(new java.awt.Color(251, 174, 6));
rSButtonShapeIcon10.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
rSButtonShapeIcon10.setForegroundHover(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForegroundIcon(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForegroundIconHover(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForegroundText(new java.awt.Color(0, 0, 0));
rSButtonShapeIcon10.setForma(RSMaterialComponent.RSButtonShapeIcon.FORMA.ROUND);
rSButtonShapeIcon10.setIcons(rojeru_san.efectos.ValoresEnum.ICONS.CANCEL);
rSButtonShapeIcon10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rSButtonShapeIcon10ActionPerformed(evt);
}
});
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/utils/img/recuperacion.png"))); // NOI18N
jLabel1.setToolTipText("");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jLabel1.setIconTextGap(1);
txtClave.setForeground(new java.awt.Color(0, 0, 0));
txtClave.setActionCommand("<Not Set>");
txtClave.setColorMaterial(new java.awt.Color(0, 0, 0));
txtClave.setDropMode(javax.swing.DropMode.INSERT);
txtClave.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
txtClave.setPhColor(new java.awt.Color(0, 0, 0));
txtClave.setPlaceholder("Digite la nueva contraseña..");
txtClave.setSelectionColor(new java.awt.Color(0, 0, 0));
txtClave.setThemeTooltip(necesario.Global.THEMETOOLTIP.LIGHT);
checkBox.setForeground(new java.awt.Color(0, 0, 0));
checkBox.setText("Mostrar Contraseña");
checkBox.setColorCheck(new java.awt.Color(0, 0, 0));
checkBox.setColorUnCheck(new java.awt.Color(0, 0, 0));
checkBox.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
checkBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkBoxActionPerformed(evt);
}
});
txtClave1.setForeground(new java.awt.Color(0, 0, 0));
txtClave1.setActionCommand("<Not Set>");
txtClave1.setColorMaterial(new java.awt.Color(0, 0, 0));
txtClave1.setDropMode(javax.swing.DropMode.INSERT);
txtClave1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
txtClave1.setPhColor(new java.awt.Color(0, 0, 0));
txtClave1.setPlaceholder("Repetir la nueva contraseña..");
txtClave1.setSelectionColor(new java.awt.Color(0, 0, 0));
txtClave1.setThemeTooltip(necesario.Global.THEMETOOLTIP.LIGHT);
jLabel3.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("REESTABLECER");
jLabel3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
rSButtonShapeIcon9.setBackground(new java.awt.Color(33, 58, 86));
rSButtonShapeIcon9.setToolTipText("SALIR DE LA APLICACIÓN");
rSButtonShapeIcon9.setBackgroundHover(new java.awt.Color(33, 68, 86));
rSButtonShapeIcon9.setForma(RSMaterialComponent.RSButtonShapeIcon.FORMA.RECT);
rSButtonShapeIcon9.setHideActionText(true);
rSButtonShapeIcon9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
rSButtonShapeIcon9.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
rSButtonShapeIcon9.setIcons(rojeru_san.efectos.ValoresEnum.ICONS.CLOSE);
rSButtonShapeIcon9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rSButtonShapeIcon9ActionPerformed(evt);
}
});
javax.swing.GroupLayout rSPanel1Layout = new javax.swing.GroupLayout(rSPanel1);
rSPanel1.setLayout(rSPanel1Layout);
rSPanel1Layout.setHorizontalGroup(
rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rSPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rSPanel1Layout.createSequentialGroup()
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtClave1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(checkBox, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(83, 83, 83))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rSPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(107, 107, 107)
.addComponent(rSButtonShapeIcon9, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(rSPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 361, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(rSPanel1Layout.createSequentialGroup()
.addComponent(rSButtonShapeIcon10, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(rSButtonShapeIcon15, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(29, Short.MAX_VALUE))
);
rSPanel1Layout.setVerticalGroup(
rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(rSPanel1Layout.createSequentialGroup()
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(rSPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1))
.addComponent(rSButtonShapeIcon9, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtClave1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkBox, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(rSPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rSButtonShapeIcon10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rSButtonShapeIcon15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rSPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(rSPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void rSButtonShapeIcon15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rSButtonShapeIcon15ActionPerformed
// ir a db a consultar si el usuario existe y si la pregunta hace mach con alguna respuesta configurada.
if (txtUsuario.getText().isEmpty() || txtClave.getText().isEmpty() || txtClave1.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Complete toda la información", "¡Alerta!", JOptionPane.WARNING_MESSAGE);
}
else {
if (txtClave.getText().equals(txtClave1.getText())) {
RespuestaGeneral rg = this._usuario.actualizarClaveRecuperacion(this.usuario, txtClave.getText().toCharArray());
if (rg.esExitosa()) {
JOptionPane.showMessageDialog(this, "Clave Reseteada Correctamente,\nPor Favor Inicie Sesion con la nueva contraseña", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
vLogin login = new vLogin(this.sesion);
login.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, rg.getMensaje(), "Mensaje", UtileriaVista.devolverCodigoMensaje(rg));
}
} else {
JOptionPane.showMessageDialog(this, "Las contraseñas no coinciden", "Mensaje", JOptionPane.WARNING_MESSAGE);
}
}
}//GEN-LAST:event_rSButtonShapeIcon15ActionPerformed
private void rSButtonShapeIcon10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rSButtonShapeIcon10ActionPerformed
vLogin login = new vLogin(null);
login.setVisible(true);
this.dispose();
}//GEN-LAST:event_rSButtonShapeIcon10ActionPerformed
private void checkBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxActionPerformed
char character = this.txtClave.getEchoChar();
if (this.checkBox.isSelected()) {
this.pass = character;
this.txtClave.setEchoChar((char) 0);
this.txtClave1.setEchoChar((char) 0);
} else {
this.txtClave.setEchoChar((char) this.pass);
this.txtClave1.setEchoChar((char) this.pass);
}
}//GEN-LAST:event_checkBoxActionPerformed
private void rSButtonShapeIcon9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rSButtonShapeIcon9ActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_rSButtonShapeIcon9ActionPerformed
/**
* @param args the command line arguments
*/
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details<SUF>
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(vReestablecer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new vReestablecer().setVisible(true);
// }
// });
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private rojerusan.RSCheckBox checkBox;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private RSMaterialComponent.RSButtonShapeIcon rSButtonShapeIcon10;
private RSMaterialComponent.RSButtonShapeIcon rSButtonShapeIcon15;
private RSMaterialComponent.RSButtonShapeIcon rSButtonShapeIcon9;
private necesario.RSPanel rSPanel1;
private RSMaterialComponent.RSPasswordMaterial txtClave;
private RSMaterialComponent.RSPasswordMaterial txtClave1;
private RSMaterialComponent.RSTextFieldMaterial txtUsuario;
// End of variables declaration//GEN-END:variables
}
|
97297_10 | package org.icpc.tools.contest.util.floor;
import org.icpc.tools.contest.Trace;
import org.icpc.tools.contest.model.FloorMap;
import org.icpc.tools.contest.model.IPrinter;
import org.icpc.tools.contest.model.ITeam;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* @author verwoerd
* @since 18-10-2022
*/
public class FloorGeneratorNWERC2022 extends FloorGenerator {
// table width (in meters). ICPC standard is 1.8
private static final float tw = 1.8f;
// table depth (in meters). ICPC standard is 0.8
private static final float td = 0.8f;
// team area width (in meters). ICPC standard is 3.0
private static final float taw = 2.0f;
// team area depth (in meters). ICPC standard is 2.2
private static final float tad = 2.0f;
private static final int numRooms = 8;
private static final int firstRoom = 9;
private static final int numRows = 40;
private static final int numCols = 40;
private static final int numProblems = 13;
private static final float innerRoomSpace = 1f;
private static final float magicXDiff = .6f;
private static final float magicXDiff2 = 1.6f;
// private static final boolean showTeams = false;
private static final boolean showTeams = true;
// If > 0, use balloons with these numbers
private static final int useIntegerBalloons = -1;
private static List<Integer> skippedTeams = new ArrayList<>();
private static HashMap<Integer, Integer> teamsPerRoom = new HashMap<>();
private static final FloorMap floor = new FloorMap(taw - .2f, tad - .2f, tw, td);
private static final String balloon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
protected static void createAdjacentTeam(int teamNumber, int newId, double dx, double dy) {
ITeam t = floor.getTeam(teamNumber);
floor.createTeam(newId, t.getX() + dx, t.getY() + dy, t.getRotation());
}
public static void main(String[] args) {
Trace.init("ICPC Floor Map Generator", "floorMap", args);
//
// skippedTeams.add(18);
// skippedTeams.add(52);
// skippedTeams.add(68);
// skippedTeams.add(80);
// skippedTeams.add(94);
// skippedTeams.add(105);
// skippedTeams.add(113);
// skippedTeams.add(126);
try {
float lastX = numRows * taw;
float lastY = numCols * tad;
float foyerStart = (float) (lastX - numCols * .4 * taw);
float foyerEnd = foyerStart + taw * 10;
for (int i = 0; i < numProblems; i++) {
float y = lastY + 1;
float x = (float) (.75*lastX + (i + 1) * 20f / 12f); //roomHeight + 20f * (i + 1) / 12f;
if (useIntegerBalloons > 0) {
floor.createBalloon((i + useIntegerBalloons) + "", x, y);
} else {
floor.createBalloon(balloon.charAt(i) + "", x, y);
}
}
IPrinter p = floor.createPrinter(lastX + 1, lastY + 1);
float foyerHeight = (float) (lastY - numCols / 2.0 * tad);
float vanHasseltEntranceX = lastX + 2 * taw;
float videXStart = taw * 5;
float videYEnd = lastY - 12 * tad;
float videYStart = 6 * tad;
int teamId = 1;
// van hasselt west bottom teams
floor.createTeam(teamId++, vanHasseltEntranceX - tad, foyerStart - 6 * taw, 135);
floor.createTeam(teamId++, vanHasseltEntranceX - 2 * tad, foyerStart - 7 * taw, 135);
floor.createTeam(teamId++, vanHasseltEntranceX - 3 * tad, foyerStart - 8 * taw, 135);
// van hasselt east bottom teams
for (int i = 0; i < 5; i++) {
floor.createTeam(teamId++, vanHasseltEntranceX + (i + 1) * tad, foyerStart - (5.7 + i * .25) * taw, 194);
}
// van hasselt west top teams
floor.createTeam(teamId++, vanHasseltEntranceX - 1.6 * tad, foyerStart - (12 - 3 * .5) * taw, 57);
floor.createTeam(teamId++, vanHasseltEntranceX - tad, foyerStart - (12 - .5) * taw, 57);
// van hasselt east top teams
for (int i = 0; i < 6; i++) {
floor.createTeam(teamId++, vanHasseltEntranceX + (i + 1) * tad, foyerStart - (12 - i * .5) * taw, 149);
}
// van hasselt center teams
for (int i = 0; i < 7; i++) {
floor.createTeam(teamId++, vanHasseltEntranceX - tad + (tad * i), foyerStart - 8.5 * taw, FloorMap.E);
}
float commissieKamerStartX = (float) (videXStart + 3.5 * taw);
// left column
floor.createTeam(teamId++, commissieKamerStartX, videYEnd + .5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX, videYEnd + 1.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX, videYEnd + 2.5 * tad, FloorMap.N);
// middle column
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + .5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + 1.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + 2.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + 3.5 * tad, FloorMap.N);
// right column
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + .5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + 1.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + 2.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + 3.5 * tad, FloorMap.N);
// senaatszaal teams
// north corner teams
floor.createTeam(teamId++, videXStart + 12 * tad, videYStart + 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 11 * tad, videYStart + 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 10 * tad, videYStart + 3.5 * taw, FloorMap.E);
// west wall teams
floor.createTeam(teamId++, videXStart + 14 * tad, videYStart + 8.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 13 * tad, videYStart + 9.75 * taw, FloorMap.S);
floor.createTeam(teamId++, videXStart + 13 * tad, videYStart + 12.25 * taw, FloorMap.N);
floor.createTeam(teamId++, videXStart + 14 * tad, videYStart + 13.5 * taw, FloorMap.E);
// east wall teams
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
floor.createTeam(teamId++, videXStart + (9.5 - j) * tad, videYStart + (8 + 2 * i) * taw, FloorMap.E);
}
}
// south corner teams
floor.createTeam(teamId++, videXStart + 12 * tad, videYEnd - 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 11 * tad, videYEnd - 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 10 * tad, videYEnd - 3.5 * taw, FloorMap.E);
// left column left room
for (int i = 0; i < 4; i++) {
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - .5 * tad, FloorMap.S);
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - 1.5 * tad, FloorMap.S);
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - 2.5 * tad, FloorMap.S);
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - 3.5 * tad, FloorMap.S);
}
floor.createAisle(lastX+1, lastY+1, lastX, lastY);
// Foyer bounding box
floor.createAisle(foyerEnd, lastY, lastX, lastY);
floor.createAisle(foyerStart - 1, lastY, foyerEnd, lastY);
floor.createAisle(foyerStart - 1, lastY, foyerStart - 1, foyerHeight);
floor.createAisle(foyerEnd, foyerHeight, foyerStart - 1, foyerHeight);
floor.createAisle(foyerEnd, foyerHeight, foyerEnd, lastY);
// Big room
List<Integer> bigRoomNumbers = Arrays.asList(5, 7, 7, 6, 6, 6, 6, 6, 7, 7, 7);
for (int row = 0; row < bigRoomNumbers.size(); row++) {
float y = lastY - (2 * tad) * row;
floor.createAisle(foyerStart - 1, y, foyerEnd, y);
for (int times = 0; times < bigRoomNumbers.get(row); times++) {
floor.createTeam(teamId++, foyerStart + 1 + taw * times * 1.5, y - 1.5 * tad, FloorMap.E);
}
}
// stairs 2 second floor
floor.createAisle(foyerStart - 1, lastY - tad, taw, lastY - tad);
floor.createAisle(taw, lastY - tad, taw, videYEnd - 5 * tad);
floor.createAisle(taw, videYEnd - 5 * tad, videXStart, videYEnd - 5 * tad);
// hallway before senaatszaal
floor.createAisle(videXStart, videYStart, videXStart, videYEnd);
// commissie kamer south
floor.createAisle(videXStart, videYEnd, commissieKamerStartX + 3.5 * taw, videYEnd);
floor.createAisle(commissieKamerStartX + .75*taw, videYEnd, commissieKamerStartX + .75*taw, videYEnd + 4 * tad);
floor.createAisle(commissieKamerStartX + 3.75*taw, videYEnd, commissieKamerStartX + 3.75*taw, videYEnd + 4 * tad);
// commissie kamers North
floor.createAisle(videXStart, videYStart, commissieKamerStartX + 5 * taw, videYStart);
floor.createAisle(commissieKamerStartX + .75*taw, videYStart, commissieKamerStartX + .75*taw, videYStart - 4 * tad);
floor.createAisle(commissieKamerStartX + 3.75*taw, videYStart, commissieKamerStartX + 3.75*taw, videYStart - 4 * tad);
// Senaatszaal
floor.createAisle(videXStart, videYStart + 4 * taw, videXStart + 12 * tad, videYStart + 4 * taw);
floor.createAisle(videXStart, videYEnd - 4 * taw, videXStart + 12 * tad, videYEnd - 4 * taw);
floor.createAisle(videXStart + 10 * tad, videYStart + 4 * taw, videXStart + 10 * tad, videYEnd - 4 * taw);
floor.createAisle(videXStart + 12 * tad, videYStart + 4 * taw, videXStart + 12 * tad, videYEnd - 4 * taw);
// aisles to east wall
floor.createAisle(videXStart + 10 * tad, videYStart + 9 * taw, videXStart + 3 * tad, videYStart + 9 * taw);
floor.createAisle(videXStart + 10 * tad, videYStart + 11 * taw, videXStart + 3 * tad, videYStart + 11 * taw);
floor.createAisle(videXStart + 10 * tad, videYStart + 13 * taw, videXStart + 3 * tad, videYStart + 13 * taw);
// aisles to west wall
floor.createAisle(videXStart + 12 * tad, videYStart + 9 * taw, videXStart + 14 * tad, videYStart + 9 * taw);
floor.createAisle(videXStart + 12 * tad, videYStart + 13* taw, videXStart + 14 * tad, videYStart + 13 * taw);
// Path Senaatszaal to van hasselt (not in scale)
floor.createAisle(videXStart + 12 * tad, videYStart + 6 * taw, videXStart + 20 * tad, videYStart + 6 * taw);
floor.createAisle(videXStart + 20 * tad, videYStart + 6 * taw, videXStart + 20 * tad, videYStart + 9 * taw);
floor.createAisle(videXStart + 20 * tad, videYStart + 9 * taw, videXStart + 35 * tad, videYStart + 9 * taw);
// comment next line to avoid all paths to the third floor going through van hasselt
// floor.createAisle(videXStart + 35 * tad, videYStart + 9 * taw, videXStart + 35 * tad, videYStart + 10 * taw);
// route to van hasselt
floor.createAisle(lastX, lastY, vanHasseltEntranceX, lastY);
floor.createAisle(vanHasseltEntranceX, lastY, vanHasseltEntranceX, foyerStart - 6 * taw);
// aisles in van hasselt
floor.createAisle(vanHasseltEntranceX, foyerStart - 6 * taw, vanHasseltEntranceX - 2 * tad, foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX - 2 * tad, foyerStart - 8 * taw, vanHasseltEntranceX + 8 * tad,
foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX, foyerStart - 6 * taw, vanHasseltEntranceX + 8 * tad, foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX, foyerStart - 12 * taw, vanHasseltEntranceX + 8 * tad,
foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX - 2 * tad, foyerStart - 9 * taw, vanHasseltEntranceX, foyerStart - 12 * taw);
floor.write(Paths.get("tmp").toFile());
Trace.trace(Trace.USER, "------------------");
long time = System.currentTimeMillis();
FloorMap.Path path1 = floor.getPath(p, floor.getTeam(6));
FloorMap.Path path2 = floor.getPath(p, floor.getTeam(155));
FloorMap.Path path3 = floor.getPath(p, floor.getTeam(72));
FloorMap.Path path4 = floor.getPath(p, floor.getTeam(55));
Trace.trace(Trace.USER, "Time: " + (System.currentTimeMillis() - time));
show(floor, -1, true);
show(floor, 6, true, path1);
show(floor, 155, true, path2);
show(floor, 72, true, path3);
show(floor, 55, true, path4);
} catch (Exception e) {
Trace.trace(Trace.ERROR, "Error generating floor map", e);
}
}
}
| verwoerd/icpctools | ContestUtil/src/org/icpc/tools/contest/util/floor/FloorGeneratorNWERC2022.java | 5,029 | // van hasselt west top teams | line_comment | nl | package org.icpc.tools.contest.util.floor;
import org.icpc.tools.contest.Trace;
import org.icpc.tools.contest.model.FloorMap;
import org.icpc.tools.contest.model.IPrinter;
import org.icpc.tools.contest.model.ITeam;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* @author verwoerd
* @since 18-10-2022
*/
public class FloorGeneratorNWERC2022 extends FloorGenerator {
// table width (in meters). ICPC standard is 1.8
private static final float tw = 1.8f;
// table depth (in meters). ICPC standard is 0.8
private static final float td = 0.8f;
// team area width (in meters). ICPC standard is 3.0
private static final float taw = 2.0f;
// team area depth (in meters). ICPC standard is 2.2
private static final float tad = 2.0f;
private static final int numRooms = 8;
private static final int firstRoom = 9;
private static final int numRows = 40;
private static final int numCols = 40;
private static final int numProblems = 13;
private static final float innerRoomSpace = 1f;
private static final float magicXDiff = .6f;
private static final float magicXDiff2 = 1.6f;
// private static final boolean showTeams = false;
private static final boolean showTeams = true;
// If > 0, use balloons with these numbers
private static final int useIntegerBalloons = -1;
private static List<Integer> skippedTeams = new ArrayList<>();
private static HashMap<Integer, Integer> teamsPerRoom = new HashMap<>();
private static final FloorMap floor = new FloorMap(taw - .2f, tad - .2f, tw, td);
private static final String balloon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
protected static void createAdjacentTeam(int teamNumber, int newId, double dx, double dy) {
ITeam t = floor.getTeam(teamNumber);
floor.createTeam(newId, t.getX() + dx, t.getY() + dy, t.getRotation());
}
public static void main(String[] args) {
Trace.init("ICPC Floor Map Generator", "floorMap", args);
//
// skippedTeams.add(18);
// skippedTeams.add(52);
// skippedTeams.add(68);
// skippedTeams.add(80);
// skippedTeams.add(94);
// skippedTeams.add(105);
// skippedTeams.add(113);
// skippedTeams.add(126);
try {
float lastX = numRows * taw;
float lastY = numCols * tad;
float foyerStart = (float) (lastX - numCols * .4 * taw);
float foyerEnd = foyerStart + taw * 10;
for (int i = 0; i < numProblems; i++) {
float y = lastY + 1;
float x = (float) (.75*lastX + (i + 1) * 20f / 12f); //roomHeight + 20f * (i + 1) / 12f;
if (useIntegerBalloons > 0) {
floor.createBalloon((i + useIntegerBalloons) + "", x, y);
} else {
floor.createBalloon(balloon.charAt(i) + "", x, y);
}
}
IPrinter p = floor.createPrinter(lastX + 1, lastY + 1);
float foyerHeight = (float) (lastY - numCols / 2.0 * tad);
float vanHasseltEntranceX = lastX + 2 * taw;
float videXStart = taw * 5;
float videYEnd = lastY - 12 * tad;
float videYStart = 6 * tad;
int teamId = 1;
// van hasselt west bottom teams
floor.createTeam(teamId++, vanHasseltEntranceX - tad, foyerStart - 6 * taw, 135);
floor.createTeam(teamId++, vanHasseltEntranceX - 2 * tad, foyerStart - 7 * taw, 135);
floor.createTeam(teamId++, vanHasseltEntranceX - 3 * tad, foyerStart - 8 * taw, 135);
// van hasselt east bottom teams
for (int i = 0; i < 5; i++) {
floor.createTeam(teamId++, vanHasseltEntranceX + (i + 1) * tad, foyerStart - (5.7 + i * .25) * taw, 194);
}
// van hasselt<SUF>
floor.createTeam(teamId++, vanHasseltEntranceX - 1.6 * tad, foyerStart - (12 - 3 * .5) * taw, 57);
floor.createTeam(teamId++, vanHasseltEntranceX - tad, foyerStart - (12 - .5) * taw, 57);
// van hasselt east top teams
for (int i = 0; i < 6; i++) {
floor.createTeam(teamId++, vanHasseltEntranceX + (i + 1) * tad, foyerStart - (12 - i * .5) * taw, 149);
}
// van hasselt center teams
for (int i = 0; i < 7; i++) {
floor.createTeam(teamId++, vanHasseltEntranceX - tad + (tad * i), foyerStart - 8.5 * taw, FloorMap.E);
}
float commissieKamerStartX = (float) (videXStart + 3.5 * taw);
// left column
floor.createTeam(teamId++, commissieKamerStartX, videYEnd + .5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX, videYEnd + 1.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX, videYEnd + 2.5 * tad, FloorMap.N);
// middle column
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + .5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + 1.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + 2.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 1.5 * taw, videYEnd + 3.5 * tad, FloorMap.N);
// right column
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + .5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + 1.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + 2.5 * tad, FloorMap.N);
floor.createTeam(teamId++, commissieKamerStartX + 3 * taw, videYEnd + 3.5 * tad, FloorMap.N);
// senaatszaal teams
// north corner teams
floor.createTeam(teamId++, videXStart + 12 * tad, videYStart + 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 11 * tad, videYStart + 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 10 * tad, videYStart + 3.5 * taw, FloorMap.E);
// west wall teams
floor.createTeam(teamId++, videXStart + 14 * tad, videYStart + 8.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 13 * tad, videYStart + 9.75 * taw, FloorMap.S);
floor.createTeam(teamId++, videXStart + 13 * tad, videYStart + 12.25 * taw, FloorMap.N);
floor.createTeam(teamId++, videXStart + 14 * tad, videYStart + 13.5 * taw, FloorMap.E);
// east wall teams
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
floor.createTeam(teamId++, videXStart + (9.5 - j) * tad, videYStart + (8 + 2 * i) * taw, FloorMap.E);
}
}
// south corner teams
floor.createTeam(teamId++, videXStart + 12 * tad, videYEnd - 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 11 * tad, videYEnd - 3.5 * taw, FloorMap.E);
floor.createTeam(teamId++, videXStart + 10 * tad, videYEnd - 3.5 * taw, FloorMap.E);
// left column left room
for (int i = 0; i < 4; i++) {
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - .5 * tad, FloorMap.S);
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - 1.5 * tad, FloorMap.S);
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - 2.5 * tad, FloorMap.S);
floor.createTeam(teamId++, commissieKamerStartX + (i * 1.5) * taw, videYStart - 3.5 * tad, FloorMap.S);
}
floor.createAisle(lastX+1, lastY+1, lastX, lastY);
// Foyer bounding box
floor.createAisle(foyerEnd, lastY, lastX, lastY);
floor.createAisle(foyerStart - 1, lastY, foyerEnd, lastY);
floor.createAisle(foyerStart - 1, lastY, foyerStart - 1, foyerHeight);
floor.createAisle(foyerEnd, foyerHeight, foyerStart - 1, foyerHeight);
floor.createAisle(foyerEnd, foyerHeight, foyerEnd, lastY);
// Big room
List<Integer> bigRoomNumbers = Arrays.asList(5, 7, 7, 6, 6, 6, 6, 6, 7, 7, 7);
for (int row = 0; row < bigRoomNumbers.size(); row++) {
float y = lastY - (2 * tad) * row;
floor.createAisle(foyerStart - 1, y, foyerEnd, y);
for (int times = 0; times < bigRoomNumbers.get(row); times++) {
floor.createTeam(teamId++, foyerStart + 1 + taw * times * 1.5, y - 1.5 * tad, FloorMap.E);
}
}
// stairs 2 second floor
floor.createAisle(foyerStart - 1, lastY - tad, taw, lastY - tad);
floor.createAisle(taw, lastY - tad, taw, videYEnd - 5 * tad);
floor.createAisle(taw, videYEnd - 5 * tad, videXStart, videYEnd - 5 * tad);
// hallway before senaatszaal
floor.createAisle(videXStart, videYStart, videXStart, videYEnd);
// commissie kamer south
floor.createAisle(videXStart, videYEnd, commissieKamerStartX + 3.5 * taw, videYEnd);
floor.createAisle(commissieKamerStartX + .75*taw, videYEnd, commissieKamerStartX + .75*taw, videYEnd + 4 * tad);
floor.createAisle(commissieKamerStartX + 3.75*taw, videYEnd, commissieKamerStartX + 3.75*taw, videYEnd + 4 * tad);
// commissie kamers North
floor.createAisle(videXStart, videYStart, commissieKamerStartX + 5 * taw, videYStart);
floor.createAisle(commissieKamerStartX + .75*taw, videYStart, commissieKamerStartX + .75*taw, videYStart - 4 * tad);
floor.createAisle(commissieKamerStartX + 3.75*taw, videYStart, commissieKamerStartX + 3.75*taw, videYStart - 4 * tad);
// Senaatszaal
floor.createAisle(videXStart, videYStart + 4 * taw, videXStart + 12 * tad, videYStart + 4 * taw);
floor.createAisle(videXStart, videYEnd - 4 * taw, videXStart + 12 * tad, videYEnd - 4 * taw);
floor.createAisle(videXStart + 10 * tad, videYStart + 4 * taw, videXStart + 10 * tad, videYEnd - 4 * taw);
floor.createAisle(videXStart + 12 * tad, videYStart + 4 * taw, videXStart + 12 * tad, videYEnd - 4 * taw);
// aisles to east wall
floor.createAisle(videXStart + 10 * tad, videYStart + 9 * taw, videXStart + 3 * tad, videYStart + 9 * taw);
floor.createAisle(videXStart + 10 * tad, videYStart + 11 * taw, videXStart + 3 * tad, videYStart + 11 * taw);
floor.createAisle(videXStart + 10 * tad, videYStart + 13 * taw, videXStart + 3 * tad, videYStart + 13 * taw);
// aisles to west wall
floor.createAisle(videXStart + 12 * tad, videYStart + 9 * taw, videXStart + 14 * tad, videYStart + 9 * taw);
floor.createAisle(videXStart + 12 * tad, videYStart + 13* taw, videXStart + 14 * tad, videYStart + 13 * taw);
// Path Senaatszaal to van hasselt (not in scale)
floor.createAisle(videXStart + 12 * tad, videYStart + 6 * taw, videXStart + 20 * tad, videYStart + 6 * taw);
floor.createAisle(videXStart + 20 * tad, videYStart + 6 * taw, videXStart + 20 * tad, videYStart + 9 * taw);
floor.createAisle(videXStart + 20 * tad, videYStart + 9 * taw, videXStart + 35 * tad, videYStart + 9 * taw);
// comment next line to avoid all paths to the third floor going through van hasselt
// floor.createAisle(videXStart + 35 * tad, videYStart + 9 * taw, videXStart + 35 * tad, videYStart + 10 * taw);
// route to van hasselt
floor.createAisle(lastX, lastY, vanHasseltEntranceX, lastY);
floor.createAisle(vanHasseltEntranceX, lastY, vanHasseltEntranceX, foyerStart - 6 * taw);
// aisles in van hasselt
floor.createAisle(vanHasseltEntranceX, foyerStart - 6 * taw, vanHasseltEntranceX - 2 * tad, foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX - 2 * tad, foyerStart - 8 * taw, vanHasseltEntranceX + 8 * tad,
foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX, foyerStart - 6 * taw, vanHasseltEntranceX + 8 * tad, foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX, foyerStart - 12 * taw, vanHasseltEntranceX + 8 * tad,
foyerStart - 8 * taw);
floor.createAisle(vanHasseltEntranceX - 2 * tad, foyerStart - 9 * taw, vanHasseltEntranceX, foyerStart - 12 * taw);
floor.write(Paths.get("tmp").toFile());
Trace.trace(Trace.USER, "------------------");
long time = System.currentTimeMillis();
FloorMap.Path path1 = floor.getPath(p, floor.getTeam(6));
FloorMap.Path path2 = floor.getPath(p, floor.getTeam(155));
FloorMap.Path path3 = floor.getPath(p, floor.getTeam(72));
FloorMap.Path path4 = floor.getPath(p, floor.getTeam(55));
Trace.trace(Trace.USER, "Time: " + (System.currentTimeMillis() - time));
show(floor, -1, true);
show(floor, 6, true, path1);
show(floor, 155, true, path2);
show(floor, 72, true, path3);
show(floor, 55, true, path4);
} catch (Exception e) {
Trace.trace(Trace.ERROR, "Error generating floor map", e);
}
}
}
|
183963_17 | // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.net.URI;
import java.nio.file.Path;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
/**
* Builder for creating a {@link FeedClient} instance.
*
* @author bjorncs
* @author jonmv
*/
public interface FeedClientBuilder {
String PREFERRED_IMPLEMENTATION_PROPERTY = "vespa.feed.client.builder.implementation";
/**
* Creates a builder for a single feed container endpoint.
* This is for feeding against a container cluster with a load balancer in front of it.
**/
static FeedClientBuilder create(URI endpoint) { return create(List.of(endpoint)); }
/**
* Creates a builder which <em>distributes</em> the feed across the given feed container endpoints.
* This is for feeding directly against container nodes, i.e., when no load balancer sits in front of these.
* Each feed operation is sent to <em>one</em> of the endpoints, <strong>not all of them</strong>!
*/
static FeedClientBuilder create(List<URI> endpoints) {
return Helper.getFeedClientBuilderSupplier().get().setEndpointUris(endpoints);
}
/** Override FeedClientBuilder. This will be preferred in {@link #create} */
static void setFeedClientBuilderSupplier(Supplier<FeedClientBuilder> supplier) {
Helper.setFeedClientBuilderSupplier(supplier);
}
/**
* Sets the number of connections this client will use per endpoint.
*
* A reasonable value here is a value that lets all feed clients (if more than one)
* collectively have a number of connections which is a small multiple of the numbers
* of containers in the cluster to feed, so load can be balanced across these containers.
* In general, this value should be kept as low as possible, but poor connectivity
* between feeder and cluster may also warrant a higher number of connections.
*/
FeedClientBuilder setConnectionsPerEndpoint(int max);
/**
* Sets the maximum number of streams per HTTP/2 connection for this client.
*
* This determines the maximum number of concurrent, inflight requests for this client,
* which is {@code maxConnections * maxStreamsPerConnection}. Prefer more streams over
* more connections, when possible.
* The feed client automatically throttles load to achieve the best throughput, and the
* actual number of streams per connection is usually lower than the maximum.
*/
FeedClientBuilder setMaxStreamPerConnection(int max);
/** Sets a duration after which this client will recycle active connections. This is off ({@code Duration.ZERO}) by default. */
FeedClientBuilder setConnectionTimeToLive(Duration ttl);
/** Sets {@link SSLContext} instance. */
FeedClientBuilder setSslContext(SSLContext context);
/** Sets {@link HostnameVerifier} instance (e.g for disabling default SSL hostname verification). */
FeedClientBuilder setHostnameVerifier(HostnameVerifier verifier);
/** Sets {@link HostnameVerifier} instance for proxy (e.g for disabling default SSL hostname verification). */
FeedClientBuilder setProxyHostnameVerifier(HostnameVerifier verifier);
/** Turns off benchmarking. Attempting to get {@link FeedClient#stats()} will result in an exception. */
FeedClientBuilder noBenchmarking();
/** Adds HTTP request header to all client requests. */
FeedClientBuilder addRequestHeader(String name, String value);
/**
* Adds HTTP request header to all client requests. Value {@link Supplier} is invoked for each HTTP request,
* i.e. value can be dynamically updated during a feed.
*/
FeedClientBuilder addRequestHeader(String name, Supplier<String> valueSupplier);
/** Adds HTTP request header to all proxy requests. */
FeedClientBuilder addProxyRequestHeader(String name, String value);
/**
* Adds HTTP request header to all proxy requests. Value {@link Supplier} is invoked for each HTTP request,
* i.e. value can be dynamically updated for each new proxy connection.
*/
FeedClientBuilder addProxyRequestHeader(String name, Supplier<String> valueSupplier);
/**
* Overrides default retry strategy.
* @see FeedClient.RetryStrategy
*/
FeedClientBuilder setRetryStrategy(FeedClient.RetryStrategy strategy);
/**
* Overrides default circuit breaker.
* @see FeedClient.CircuitBreaker
*/
FeedClientBuilder setCircuitBreaker(FeedClient.CircuitBreaker breaker);
/** Sets path to client SSL certificate/key PEM files */
FeedClientBuilder setCertificate(Path certificatePemFile, Path privateKeyPemFile);
/** Sets client SSL certificates/key */
FeedClientBuilder setCertificate(Collection<X509Certificate> certificate, PrivateKey privateKey);
/** Sets client SSL certificate/key */
FeedClientBuilder setCertificate(X509Certificate certificate, PrivateKey privateKey);
/** Turns on dryrun mode, where each operation succeeds after a given delay, rather than being sent across the network. */
FeedClientBuilder setDryrun(boolean enabled);
/** Turns on speed test mode, where all feed operations are immediately acknowledged by the server. */
FeedClientBuilder setSpeedTest(boolean enabled);
/**
* Overrides JVM default SSL truststore
* @param caCertificatesFile Path to PEM encoded file containing trusted certificates
*/
FeedClientBuilder setCaCertificatesFile(Path caCertificatesFile);
/**
* Overrides JVM default SSL truststore for proxy
* @param caCertificatesFile Path to PEM encoded file containing trusted certificates
*/
FeedClientBuilder setProxyCaCertificatesFile(Path caCertificatesFile);
/** Overrides JVM default SSL truststore */
FeedClientBuilder setCaCertificates(Collection<X509Certificate> caCertificates);
/** Overrides JVM default SSL truststore for proxy */
FeedClientBuilder setProxyCaCertificates(Collection<X509Certificate> caCertificates);
/** Overrides endpoint URIs for this client */
FeedClientBuilder setEndpointUris(List<URI> endpoints);
/** Specify HTTP(S) proxy for all endpoints */
FeedClientBuilder setProxy(URI uri);
/** What compression to use for request bodies; default {@code auto}. */
FeedClientBuilder setCompression(Compression compression);
enum Compression { auto, none, gzip }
/** Constructs instance of {@link FeedClient} from builder configuration */
FeedClient build();
}
| vespa-engine/vespa | vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java | 1,720 | /**
* Overrides default circuit breaker.
* @see FeedClient.CircuitBreaker
*/ | block_comment | nl | // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.net.URI;
import java.nio.file.Path;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
/**
* Builder for creating a {@link FeedClient} instance.
*
* @author bjorncs
* @author jonmv
*/
public interface FeedClientBuilder {
String PREFERRED_IMPLEMENTATION_PROPERTY = "vespa.feed.client.builder.implementation";
/**
* Creates a builder for a single feed container endpoint.
* This is for feeding against a container cluster with a load balancer in front of it.
**/
static FeedClientBuilder create(URI endpoint) { return create(List.of(endpoint)); }
/**
* Creates a builder which <em>distributes</em> the feed across the given feed container endpoints.
* This is for feeding directly against container nodes, i.e., when no load balancer sits in front of these.
* Each feed operation is sent to <em>one</em> of the endpoints, <strong>not all of them</strong>!
*/
static FeedClientBuilder create(List<URI> endpoints) {
return Helper.getFeedClientBuilderSupplier().get().setEndpointUris(endpoints);
}
/** Override FeedClientBuilder. This will be preferred in {@link #create} */
static void setFeedClientBuilderSupplier(Supplier<FeedClientBuilder> supplier) {
Helper.setFeedClientBuilderSupplier(supplier);
}
/**
* Sets the number of connections this client will use per endpoint.
*
* A reasonable value here is a value that lets all feed clients (if more than one)
* collectively have a number of connections which is a small multiple of the numbers
* of containers in the cluster to feed, so load can be balanced across these containers.
* In general, this value should be kept as low as possible, but poor connectivity
* between feeder and cluster may also warrant a higher number of connections.
*/
FeedClientBuilder setConnectionsPerEndpoint(int max);
/**
* Sets the maximum number of streams per HTTP/2 connection for this client.
*
* This determines the maximum number of concurrent, inflight requests for this client,
* which is {@code maxConnections * maxStreamsPerConnection}. Prefer more streams over
* more connections, when possible.
* The feed client automatically throttles load to achieve the best throughput, and the
* actual number of streams per connection is usually lower than the maximum.
*/
FeedClientBuilder setMaxStreamPerConnection(int max);
/** Sets a duration after which this client will recycle active connections. This is off ({@code Duration.ZERO}) by default. */
FeedClientBuilder setConnectionTimeToLive(Duration ttl);
/** Sets {@link SSLContext} instance. */
FeedClientBuilder setSslContext(SSLContext context);
/** Sets {@link HostnameVerifier} instance (e.g for disabling default SSL hostname verification). */
FeedClientBuilder setHostnameVerifier(HostnameVerifier verifier);
/** Sets {@link HostnameVerifier} instance for proxy (e.g for disabling default SSL hostname verification). */
FeedClientBuilder setProxyHostnameVerifier(HostnameVerifier verifier);
/** Turns off benchmarking. Attempting to get {@link FeedClient#stats()} will result in an exception. */
FeedClientBuilder noBenchmarking();
/** Adds HTTP request header to all client requests. */
FeedClientBuilder addRequestHeader(String name, String value);
/**
* Adds HTTP request header to all client requests. Value {@link Supplier} is invoked for each HTTP request,
* i.e. value can be dynamically updated during a feed.
*/
FeedClientBuilder addRequestHeader(String name, Supplier<String> valueSupplier);
/** Adds HTTP request header to all proxy requests. */
FeedClientBuilder addProxyRequestHeader(String name, String value);
/**
* Adds HTTP request header to all proxy requests. Value {@link Supplier} is invoked for each HTTP request,
* i.e. value can be dynamically updated for each new proxy connection.
*/
FeedClientBuilder addProxyRequestHeader(String name, Supplier<String> valueSupplier);
/**
* Overrides default retry strategy.
* @see FeedClient.RetryStrategy
*/
FeedClientBuilder setRetryStrategy(FeedClient.RetryStrategy strategy);
/**
* Overrides default circuit<SUF>*/
FeedClientBuilder setCircuitBreaker(FeedClient.CircuitBreaker breaker);
/** Sets path to client SSL certificate/key PEM files */
FeedClientBuilder setCertificate(Path certificatePemFile, Path privateKeyPemFile);
/** Sets client SSL certificates/key */
FeedClientBuilder setCertificate(Collection<X509Certificate> certificate, PrivateKey privateKey);
/** Sets client SSL certificate/key */
FeedClientBuilder setCertificate(X509Certificate certificate, PrivateKey privateKey);
/** Turns on dryrun mode, where each operation succeeds after a given delay, rather than being sent across the network. */
FeedClientBuilder setDryrun(boolean enabled);
/** Turns on speed test mode, where all feed operations are immediately acknowledged by the server. */
FeedClientBuilder setSpeedTest(boolean enabled);
/**
* Overrides JVM default SSL truststore
* @param caCertificatesFile Path to PEM encoded file containing trusted certificates
*/
FeedClientBuilder setCaCertificatesFile(Path caCertificatesFile);
/**
* Overrides JVM default SSL truststore for proxy
* @param caCertificatesFile Path to PEM encoded file containing trusted certificates
*/
FeedClientBuilder setProxyCaCertificatesFile(Path caCertificatesFile);
/** Overrides JVM default SSL truststore */
FeedClientBuilder setCaCertificates(Collection<X509Certificate> caCertificates);
/** Overrides JVM default SSL truststore for proxy */
FeedClientBuilder setProxyCaCertificates(Collection<X509Certificate> caCertificates);
/** Overrides endpoint URIs for this client */
FeedClientBuilder setEndpointUris(List<URI> endpoints);
/** Specify HTTP(S) proxy for all endpoints */
FeedClientBuilder setProxy(URI uri);
/** What compression to use for request bodies; default {@code auto}. */
FeedClientBuilder setCompression(Compression compression);
enum Compression { auto, none, gzip }
/** Constructs instance of {@link FeedClient} from builder configuration */
FeedClient build();
}
|
139804_14 | /**
*/
package satellite;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Transceiver Band</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see satellite.SatellitePackage#getTransceiverBand()
* @model
* @generated
*/
public enum TransceiverBand implements Enumerator {
/**
* The '<em><b>UHF</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #UHF_VALUE
* @generated
* @ordered
*/
UHF(0, "UHF", "UHF"),
/**
* The '<em><b>X</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #X_VALUE
* @generated
* @ordered
*/
X(1, "X", "X"),
/**
* The '<em><b>Ka</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #KA_VALUE
* @generated
* @ordered
*/
KA(2, "Ka", "Ka");
/**
* The '<em><b>UHF</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #UHF
* @model
* @generated
* @ordered
*/
public static final int UHF_VALUE = 0;
/**
* The '<em><b>X</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #X
* @model
* @generated
* @ordered
*/
public static final int X_VALUE = 1;
/**
* The '<em><b>Ka</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #KA
* @model name="Ka"
* @generated
* @ordered
*/
public static final int KA_VALUE = 2;
/**
* An array of all the '<em><b>Transceiver Band</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final TransceiverBand[] VALUES_ARRAY = new TransceiverBand[] { UHF, X, KA, };
/**
* A public read-only list of all the '<em><b>Transceiver Band</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<TransceiverBand> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Transceiver Band</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static TransceiverBand get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
TransceiverBand result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Transceiver Band</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static TransceiverBand getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
TransceiverBand result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Transceiver Band</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static TransceiverBand get(int value) {
switch (value) {
case UHF_VALUE:
return UHF;
case X_VALUE:
return X;
case KA_VALUE:
return KA;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private TransceiverBand(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //TransceiverBand
| viatra/VIATRA-Generator | Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/TransceiverBand.java | 1,747 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
*/
package satellite;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Transceiver Band</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see satellite.SatellitePackage#getTransceiverBand()
* @model
* @generated
*/
public enum TransceiverBand implements Enumerator {
/**
* The '<em><b>UHF</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #UHF_VALUE
* @generated
* @ordered
*/
UHF(0, "UHF", "UHF"),
/**
* The '<em><b>X</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #X_VALUE
* @generated
* @ordered
*/
X(1, "X", "X"),
/**
* The '<em><b>Ka</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #KA_VALUE
* @generated
* @ordered
*/
KA(2, "Ka", "Ka");
/**
* The '<em><b>UHF</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #UHF
* @model
* @generated
* @ordered
*/
public static final int UHF_VALUE = 0;
/**
* The '<em><b>X</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #X
* @model
* @generated
* @ordered
*/
public static final int X_VALUE = 1;
/**
* The '<em><b>Ka</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #KA
* @model name="Ka"
* @generated
* @ordered
*/
public static final int KA_VALUE = 2;
/**
* An array of all the '<em><b>Transceiver Band</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final TransceiverBand[] VALUES_ARRAY = new TransceiverBand[] { UHF, X, KA, };
/**
* A public read-only list of all the '<em><b>Transceiver Band</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<TransceiverBand> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Transceiver Band</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static TransceiverBand get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
TransceiverBand result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Transceiver Band</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static TransceiverBand getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
TransceiverBand result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Transceiver Band</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static TransceiverBand get(int value) {
switch (value) {
case UHF_VALUE:
return UHF;
case X_VALUE:
return X;
case KA_VALUE:
return KA;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc --><SUF>*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private TransceiverBand(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //TransceiverBand
|
80482_3 | package utils;
import java.util.Locale;
/**
* Die Klasse Vector2D stellt eine Hilfsklasse zur Berechnung von Koordinaten dar. In erster Linie ist die Klasse zur
* Nutzung als Ortsvektor gedacht, eine Nutzung als Richtungsvektor ist aber ebenfalls möglich.
* Alle Methoden arbeiten nicht-destruktiv, um Fehlern bei der Nutzung vorzubeugen.
* @author Viktor Winkelmann
*
*/
public class Vector2D {
private static final double MAX_DEVIATION = 0.00001; // Maximale Koordinaten Abweichung für Objektgleichheit
private double x,y;
public Vector2D(double x, double y) {
this.x = x;
this.y = y;
}
public Vector2D() {
this(0,0);
}
/**
* Liefert den X-Koordinaten Anteil.
* @return X-Koordinate
*/
public double getX() {
return x;
}
/**
* Liefert den Y-Koordinaten Anteil.
* @return Y-Koordinate
*/
public double getY() {
return y;
}
/**
* Addiert einen Vektor.
* @param other Zu addierender Vektor
* @return Neuer Vektor
*/
public Vector2D add(Vector2D other) {
return new Vector2D(x + other.x, y + other.y);
}
/**
* Subtrahiert einen Vektor.
* @param other Zu subtrahierender Vektor
* @return Neuer Vektor
*/
public Vector2D subtract(Vector2D other) {
return new Vector2D(x - other.x, y - other.y);
}
/**
* Multipliziert den Vektor mit einem Skalar.
* @param scalar Skalar
* @return Neuer Vektor
*/
public Vector2D multiply(double scalar) {
return new Vector2D(x * scalar, y * scalar);
}
/**
* Dividiert den Vektor durch einen Skalar.
* @param scalar Skalar
* @return Neuer Vektor
*/
public Vector2D divide(double scalar) {
return new Vector2D(x / scalar, y / scalar);
}
/**
* Berechnet die Länge des Vektors.
* @return Vektorlänge
*/
public double length(){
return Math.sqrt(x*x + y*y);
}
/**
* Berechnet die Distanz zu einem anderen Vektor.
* @param other Anderer Vektor
* @return Distanz
*/
public double distanceTo(Vector2D other) {
return other.subtract(this).length();
}
/**
* Berechnet den Winkel zu einem anderen Vektor im Bereich
* von -180 bis 180 Grad. Ist der andere Vektor im Uhrzeigesinn
* gedreht, ist der Winkel postiv, sonst negativ.
*
* @param other Anderer Vektor
* @return Winkel
*/
public double angleTo(Vector2D other) {
return other.getNormalHeading() - getNormalHeading();
}
/**
* Liefert die Richtung eines Vektors im Bereich von 0 bis 360 Grad.
* 0 = Norden, 90 = Osten, 180 = Süden, 270 = Westen
* @return Richtung in Grad
*/
public double getHeading() {
double mathAngle = Utils.radToDeg(Math.acos(x / length()));
if (y >= 0) {
if (x < 0) {
return 450 - mathAngle;
} else {
return 90 - mathAngle;
}
} else {
return mathAngle + 90;
}
}
/**
* Liefert die normalisierte Richtung eines Vektors im Bereich von -180 bis 180 Grad.
* -180 = Westen, -90 = Norden, 0 = Osten, 90 = Süden
* @return Normalisierte Richtung in Grad
*/
public double getNormalHeading() {
double mathAngle = Utils.radToDeg(Math.acos(x / length()));
return (y >= 0) ? -1 * mathAngle : mathAngle;
}
/**
* Dreht den Vektor um einen Winkel in Grad.
* Die Drehung erfolgt um den Vektorursprung im mathematisch
* negativer Richtung (im Uhrzeigesinn).
* @param angleDegrees Winkel in Grad
* @return Neuer Vektor
*/
public Vector2D rotate(double angleDegrees) {
return rotateRad(Utils.degToRad(angleDegrees));
}
/**
* Dreht den Vektor um einen Winkel im Bogenmaß.
* Die Drehung erfolgt um den Vektorursprung im mathematisch
* negativer Richtung (im Uhrzeigesinn).
* @param angleRadians Winkel in Rad
* @return Neuer Vektor
*/
public Vector2D rotateRad(double angleRadians) {
angleRadians = angleRadians * -1;
return new Vector2D(x * Math.cos(angleRadians) - y * Math.sin(angleRadians), x * Math.sin(angleRadians) + y * Math.cos(angleRadians));
}
/**
* Prüf ob der Vector in einem Rechteck liegt.
* @param x
* @param y
* @param width
* @param height
* @return
*/
public boolean inRectangle(double x, double y, double width, double height) {
return !(this.x < x || this.y < y || this.x > x + width || this.y > y + height);
}
/**
* Liefert eine String Darstellung der Vektorkoordinaten.
*/
@Override
public String toString() {
return String.format(Locale.ENGLISH, "X: %1$,.3f, Y: %2$,.3f", x, y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2D other = (Vector2D) obj;
if (Math.abs(x - other.x) > MAX_DEVIATION)
return false;
if (Math.abs(y - other.y) > MAX_DEVIATION)
return false;
return true;
}
}
| vikwin/HAW-LernendeAgenten_RC | LARCbot_OliViktor/LARC/src/utils/Vector2D.java | 1,907 | /**
* Liefert den Y-Koordinaten Anteil.
* @return Y-Koordinate
*/ | block_comment | nl | package utils;
import java.util.Locale;
/**
* Die Klasse Vector2D stellt eine Hilfsklasse zur Berechnung von Koordinaten dar. In erster Linie ist die Klasse zur
* Nutzung als Ortsvektor gedacht, eine Nutzung als Richtungsvektor ist aber ebenfalls möglich.
* Alle Methoden arbeiten nicht-destruktiv, um Fehlern bei der Nutzung vorzubeugen.
* @author Viktor Winkelmann
*
*/
public class Vector2D {
private static final double MAX_DEVIATION = 0.00001; // Maximale Koordinaten Abweichung für Objektgleichheit
private double x,y;
public Vector2D(double x, double y) {
this.x = x;
this.y = y;
}
public Vector2D() {
this(0,0);
}
/**
* Liefert den X-Koordinaten Anteil.
* @return X-Koordinate
*/
public double getX() {
return x;
}
/**
* Liefert den Y-Koordinaten<SUF>*/
public double getY() {
return y;
}
/**
* Addiert einen Vektor.
* @param other Zu addierender Vektor
* @return Neuer Vektor
*/
public Vector2D add(Vector2D other) {
return new Vector2D(x + other.x, y + other.y);
}
/**
* Subtrahiert einen Vektor.
* @param other Zu subtrahierender Vektor
* @return Neuer Vektor
*/
public Vector2D subtract(Vector2D other) {
return new Vector2D(x - other.x, y - other.y);
}
/**
* Multipliziert den Vektor mit einem Skalar.
* @param scalar Skalar
* @return Neuer Vektor
*/
public Vector2D multiply(double scalar) {
return new Vector2D(x * scalar, y * scalar);
}
/**
* Dividiert den Vektor durch einen Skalar.
* @param scalar Skalar
* @return Neuer Vektor
*/
public Vector2D divide(double scalar) {
return new Vector2D(x / scalar, y / scalar);
}
/**
* Berechnet die Länge des Vektors.
* @return Vektorlänge
*/
public double length(){
return Math.sqrt(x*x + y*y);
}
/**
* Berechnet die Distanz zu einem anderen Vektor.
* @param other Anderer Vektor
* @return Distanz
*/
public double distanceTo(Vector2D other) {
return other.subtract(this).length();
}
/**
* Berechnet den Winkel zu einem anderen Vektor im Bereich
* von -180 bis 180 Grad. Ist der andere Vektor im Uhrzeigesinn
* gedreht, ist der Winkel postiv, sonst negativ.
*
* @param other Anderer Vektor
* @return Winkel
*/
public double angleTo(Vector2D other) {
return other.getNormalHeading() - getNormalHeading();
}
/**
* Liefert die Richtung eines Vektors im Bereich von 0 bis 360 Grad.
* 0 = Norden, 90 = Osten, 180 = Süden, 270 = Westen
* @return Richtung in Grad
*/
public double getHeading() {
double mathAngle = Utils.radToDeg(Math.acos(x / length()));
if (y >= 0) {
if (x < 0) {
return 450 - mathAngle;
} else {
return 90 - mathAngle;
}
} else {
return mathAngle + 90;
}
}
/**
* Liefert die normalisierte Richtung eines Vektors im Bereich von -180 bis 180 Grad.
* -180 = Westen, -90 = Norden, 0 = Osten, 90 = Süden
* @return Normalisierte Richtung in Grad
*/
public double getNormalHeading() {
double mathAngle = Utils.radToDeg(Math.acos(x / length()));
return (y >= 0) ? -1 * mathAngle : mathAngle;
}
/**
* Dreht den Vektor um einen Winkel in Grad.
* Die Drehung erfolgt um den Vektorursprung im mathematisch
* negativer Richtung (im Uhrzeigesinn).
* @param angleDegrees Winkel in Grad
* @return Neuer Vektor
*/
public Vector2D rotate(double angleDegrees) {
return rotateRad(Utils.degToRad(angleDegrees));
}
/**
* Dreht den Vektor um einen Winkel im Bogenmaß.
* Die Drehung erfolgt um den Vektorursprung im mathematisch
* negativer Richtung (im Uhrzeigesinn).
* @param angleRadians Winkel in Rad
* @return Neuer Vektor
*/
public Vector2D rotateRad(double angleRadians) {
angleRadians = angleRadians * -1;
return new Vector2D(x * Math.cos(angleRadians) - y * Math.sin(angleRadians), x * Math.sin(angleRadians) + y * Math.cos(angleRadians));
}
/**
* Prüf ob der Vector in einem Rechteck liegt.
* @param x
* @param y
* @param width
* @param height
* @return
*/
public boolean inRectangle(double x, double y, double width, double height) {
return !(this.x < x || this.y < y || this.x > x + width || this.y > y + height);
}
/**
* Liefert eine String Darstellung der Vektorkoordinaten.
*/
@Override
public String toString() {
return String.format(Locale.ENGLISH, "X: %1$,.3f, Y: %2$,.3f", x, y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2D other = (Vector2D) obj;
if (Math.abs(x - other.x) > MAX_DEVIATION)
return false;
if (Math.abs(y - other.y) > MAX_DEVIATION)
return false;
return true;
}
}
|
190667_9 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Paa forhand beklager jeg det du er i ferd med aa bla gjennom
// men har vaert og kommer til aa vaere sinnssykt opptatt med alt annet
// i livet naa saa dette ble fort og gaeli.
// Veldig gaeli.
public class GomOfLof {
// Lager vinduer og paneler slik at vi har noe aa jobbe med
static JFrame vindu = new JFrame("Game of Life");
static JPanel panel = new JPanel();
// Hoerer at Stein gikk gjennom noe enklere i andre forelesning om GUI.
// Naa faar vi alle lide.
// Deklarerer rakkelet statisk slik at oppdateringsmetoden jeg ogsaa gjorde
// statisk av en eller annen grunn (jeg ville ikke skrive den to ganger)
// og lager et skikkelig rot.
static JPanel knappenett = new JPanel();
static JPanel rutenett = new JPanel();
static Verden v;
static boolean ogre = true; // It's ogre
static boolean pause = false; // For aa "pause" traaden senere
static JButton levPanel = new JButton(); // Litt penere representasjon
static JButton genPanel = new JButton(); // av generasjon og ant levende celler
static int genNr, antLev;
// GAMMEL KOMMENTAR:
// Kjoett og poteter av hva som foregaar her, men det er noe veldig rart.
// Knappene virker bare paa partallsgenerasjoner, og jeg har ikke en fjerneste
// ide om hvorfor det kan vaere.
private static void oppdaterVindu() {
// Gaar gjennom hele rutenettet av celler
for (int i = 0; i < v.rutenett.antRader; i++) {
for (int j = 0; j < v.rutenett.antKolonner; j++) {
// Henter frem cellen
Celle c = v.rutenett.hentCelle(i, j);
// Lager en knapp av den
c.initGUI();
c.setPreferredSize(new Dimension(20, 20));
// Setter den hvit hvis levende, svart hvis doed
if (c.levende){
c.setBackground(Color.white);
} else {
c.setBackground(Color.black);
}
// Og legger til i rutenettet.
rutenett.add(c);
}
}
// Oppdaterer knappene med generasjonsnummer og antall levende
genNr = v.genNr;
antLev = v.rutenett.antallLevende();
genPanel.setText("Generasjon: " + genNr);
levPanel.setText("Antall levende: " + antLev);
}
//NY METODE SOM FIKSER PROBLEMET - Tydeligvis ble det troebbel da
// gui ble initialisert paa nytt, naa bare blar den gjennom og oppdaterer
// status. Igjen beklager rotet. Men den funker, og jeg orker ikke rydde akkurat naa.
private static void oppdaterVindu2() {
for (int i = 0; i < v.rutenett.antRader; i++) {
for (int j = 0; j < v.rutenett.antKolonner; j++) {
Celle c = v.rutenett.hentCelle(i, j);
if (c.levende){
c.setBackground(Color.white);
} else {
c.setBackground(Color.black);
}
rutenett.add(c);
}
}
genNr = v.genNr;
antLev = v.rutenett.antallLevende();
genPanel.setText("Generasjon: " + genNr);
levPanel.setText("Antall levende: " + antLev);
}
public static void main(String[] args){
// Kunne sikkert laget denne statisk ogsaa bare for aa vaere tverr.
// men nei. Denne brukes til aa oppdatere det du ser i vinduet .
class oppdater extends Thread {
@Override
public void run() {
try {
// Mens traaden er i live
while (!ogre) {
// Og pauset
if (pause) {
// Skal bare vinduet vises, og ingenting oppdateres
vindu.setVisible(true);
} else {
// Ellers skal alt oppdateres annethvert sekund
// gjorde det slik saann at pausingen oppleves
// litt smothere
sleep(1000);
// Ny oppdateringsmetode som ikke reinitaliserer cellene som knapper
v.oppdatering();
oppdaterVindu2();
sleep(1000);
}
}
} catch (InterruptedException e) {
}
}
}
// Lager oppdateringstraaden
oppdater o = new oppdater();
// Lager knapper for start/pause og avslutting
JButton pausKnapp = new JButton("Start/Pause");
JButton stoppKnapp = new JButton("Avslutt");
pausKnapp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Hvis traaden ikke er startet sparker vi den igang
if (ogre && !o.isAlive()) {
ogre = false;
o.start();
} else {
// Hvis den er startet pauser vi den
pause = !pause;
}
}
});
stoppKnapp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Kverker traaden og scriptet naar den trykkes
ogre = true;
System.exit(0);
}
});
// Maa gi de en verdi for aa kunne kompilere
int rad = 0;
int kol = 0;
try {
rad = Integer.parseInt(args[0]);
kol = Integer.parseInt(args[1]);
} catch (Exception e) {
System.out.println("Du maa oppgi rad og kolonner i argument");
System.out.println("Eks: java GomOfLof 10 10");
}
// genererer verden
v = new Verden(rad, kol);
// Mekker litt i vinduet
vindu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e){
System.out.println(" ");
}
vindu.add(panel);
// Proever at knappene ser litt ryddige ut i det minste
knappenett.setLayout(new GridLayout(2, 2));
knappenett.add(pausKnapp);
knappenett.add(stoppKnapp);
knappenett.add(levPanel);
knappenett.add(genPanel);
// Try catch for aa kunne gi feilmelding hvis bruker ikke oppga
// args for rader og kolonner
try {
rutenett.setLayout(new GridLayout(kol, rad));
} catch (Exception e) {
System.out.print("");
System.exit(1);
}
// Verden er generert, vi oppdaterer vinduet med
// den gamle metoden som tilegner knappen helt på nytt
oppdaterVindu();
// Slenger paa knappene og rutenetet av celler
panel.add(knappenett);
panel.add(rutenett);
// Maa til
vindu.pack();
vindu.setVisible(true);
}
}
// jeg savner python
| viljardh/IN1010 | Oblig6/GomOfLof.java | 2,353 | // For aa "pause" traaden senere
| line_comment | nl | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Paa forhand beklager jeg det du er i ferd med aa bla gjennom
// men har vaert og kommer til aa vaere sinnssykt opptatt med alt annet
// i livet naa saa dette ble fort og gaeli.
// Veldig gaeli.
public class GomOfLof {
// Lager vinduer og paneler slik at vi har noe aa jobbe med
static JFrame vindu = new JFrame("Game of Life");
static JPanel panel = new JPanel();
// Hoerer at Stein gikk gjennom noe enklere i andre forelesning om GUI.
// Naa faar vi alle lide.
// Deklarerer rakkelet statisk slik at oppdateringsmetoden jeg ogsaa gjorde
// statisk av en eller annen grunn (jeg ville ikke skrive den to ganger)
// og lager et skikkelig rot.
static JPanel knappenett = new JPanel();
static JPanel rutenett = new JPanel();
static Verden v;
static boolean ogre = true; // It's ogre
static boolean pause = false; // For aa<SUF>
static JButton levPanel = new JButton(); // Litt penere representasjon
static JButton genPanel = new JButton(); // av generasjon og ant levende celler
static int genNr, antLev;
// GAMMEL KOMMENTAR:
// Kjoett og poteter av hva som foregaar her, men det er noe veldig rart.
// Knappene virker bare paa partallsgenerasjoner, og jeg har ikke en fjerneste
// ide om hvorfor det kan vaere.
private static void oppdaterVindu() {
// Gaar gjennom hele rutenettet av celler
for (int i = 0; i < v.rutenett.antRader; i++) {
for (int j = 0; j < v.rutenett.antKolonner; j++) {
// Henter frem cellen
Celle c = v.rutenett.hentCelle(i, j);
// Lager en knapp av den
c.initGUI();
c.setPreferredSize(new Dimension(20, 20));
// Setter den hvit hvis levende, svart hvis doed
if (c.levende){
c.setBackground(Color.white);
} else {
c.setBackground(Color.black);
}
// Og legger til i rutenettet.
rutenett.add(c);
}
}
// Oppdaterer knappene med generasjonsnummer og antall levende
genNr = v.genNr;
antLev = v.rutenett.antallLevende();
genPanel.setText("Generasjon: " + genNr);
levPanel.setText("Antall levende: " + antLev);
}
//NY METODE SOM FIKSER PROBLEMET - Tydeligvis ble det troebbel da
// gui ble initialisert paa nytt, naa bare blar den gjennom og oppdaterer
// status. Igjen beklager rotet. Men den funker, og jeg orker ikke rydde akkurat naa.
private static void oppdaterVindu2() {
for (int i = 0; i < v.rutenett.antRader; i++) {
for (int j = 0; j < v.rutenett.antKolonner; j++) {
Celle c = v.rutenett.hentCelle(i, j);
if (c.levende){
c.setBackground(Color.white);
} else {
c.setBackground(Color.black);
}
rutenett.add(c);
}
}
genNr = v.genNr;
antLev = v.rutenett.antallLevende();
genPanel.setText("Generasjon: " + genNr);
levPanel.setText("Antall levende: " + antLev);
}
public static void main(String[] args){
// Kunne sikkert laget denne statisk ogsaa bare for aa vaere tverr.
// men nei. Denne brukes til aa oppdatere det du ser i vinduet .
class oppdater extends Thread {
@Override
public void run() {
try {
// Mens traaden er i live
while (!ogre) {
// Og pauset
if (pause) {
// Skal bare vinduet vises, og ingenting oppdateres
vindu.setVisible(true);
} else {
// Ellers skal alt oppdateres annethvert sekund
// gjorde det slik saann at pausingen oppleves
// litt smothere
sleep(1000);
// Ny oppdateringsmetode som ikke reinitaliserer cellene som knapper
v.oppdatering();
oppdaterVindu2();
sleep(1000);
}
}
} catch (InterruptedException e) {
}
}
}
// Lager oppdateringstraaden
oppdater o = new oppdater();
// Lager knapper for start/pause og avslutting
JButton pausKnapp = new JButton("Start/Pause");
JButton stoppKnapp = new JButton("Avslutt");
pausKnapp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Hvis traaden ikke er startet sparker vi den igang
if (ogre && !o.isAlive()) {
ogre = false;
o.start();
} else {
// Hvis den er startet pauser vi den
pause = !pause;
}
}
});
stoppKnapp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Kverker traaden og scriptet naar den trykkes
ogre = true;
System.exit(0);
}
});
// Maa gi de en verdi for aa kunne kompilere
int rad = 0;
int kol = 0;
try {
rad = Integer.parseInt(args[0]);
kol = Integer.parseInt(args[1]);
} catch (Exception e) {
System.out.println("Du maa oppgi rad og kolonner i argument");
System.out.println("Eks: java GomOfLof 10 10");
}
// genererer verden
v = new Verden(rad, kol);
// Mekker litt i vinduet
vindu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e){
System.out.println(" ");
}
vindu.add(panel);
// Proever at knappene ser litt ryddige ut i det minste
knappenett.setLayout(new GridLayout(2, 2));
knappenett.add(pausKnapp);
knappenett.add(stoppKnapp);
knappenett.add(levPanel);
knappenett.add(genPanel);
// Try catch for aa kunne gi feilmelding hvis bruker ikke oppga
// args for rader og kolonner
try {
rutenett.setLayout(new GridLayout(kol, rad));
} catch (Exception e) {
System.out.print("");
System.exit(1);
}
// Verden er generert, vi oppdaterer vinduet med
// den gamle metoden som tilegner knappen helt på nytt
oppdaterVindu();
// Slenger paa knappene og rutenetet av celler
panel.add(knappenett);
panel.add(rutenett);
// Maa til
vindu.pack();
vindu.setVisible(true);
}
}
// jeg savner python
|
29186_75 | // ----------------------------------------------------------------------------
// Copyright 2007-2013, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = 630;
public static final int ZONE_HEIGHT = 630; // 535;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_src[] = new String[] { "javascript.src" , "javascript.include" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
**/
public int getZoneWidth();
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
**/
public int getZoneHeight();
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinate)
**/
public long getAutoUpdateCount(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState,
int statusCodes[])
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState,
int statusCodes[])
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
| vimukthi-git/OpenGTS_2.4.9 | src/org/opengts/war/tools/MapProvider.java | 6,195 | // int (update interval seconds) | line_comment | nl | // ----------------------------------------------------------------------------
// Copyright 2007-2013, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = 630;
public static final int ZONE_HEIGHT = 630; // 535;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int <SUF>
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_src[] = new String[] { "javascript.src" , "javascript.include" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
**/
public int getZoneWidth();
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
**/
public int getZoneHeight();
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinate)
**/
public long getAutoUpdateCount(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState,
int statusCodes[])
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState,
int statusCodes[])
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
|
11571_0 | package be.kdg.groepi.security;
import be.kdg.groepi.model.User;
import be.kdg.groepi.service.UserService;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.gson.Gson;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Service;
@Service("authenticationSuccessHandler")
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Autowired
protected UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
User user = userService.getUserByEmail(authentication.getName());
Gson gson = new Gson();
HttpSession session = request.getSession();
session.setAttribute("userObject", user);
String jUser = gson.toJson(user);
response.addHeader("user", jUser);
// Check of er een redirect gebeurde omdat user nog niet ingelogd was
SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
RequestDispatcher dispatcher;
// Er is een redirect gebeurd, fetch de URI en zet die als bestemming
if (savedRequest != null) {
Pattern pattern = Pattern.compile("(https?://)([^:^/]*)(:\\d*)?(.*)?");
Matcher matcher = pattern.matcher(savedRequest.getRedirectUrl());
matcher.find();
String uri = matcher.group(4);
dispatcher = request.getRequestDispatcher(uri);
} // Geen redirect, dus gewoon profiel pagina tonen
else {
dispatcher = request.getRequestDispatcher("/profile/myprofile");
}
dispatcher.forward(request, response);
}
}
| vincentjanv/groepI | src/main/java/be/kdg/groepi/security/MyAuthenticationSuccessHandler.java | 633 | // Check of er een redirect gebeurde omdat user nog niet ingelogd was | line_comment | nl | package be.kdg.groepi.security;
import be.kdg.groepi.model.User;
import be.kdg.groepi.service.UserService;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.gson.Gson;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Service;
@Service("authenticationSuccessHandler")
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Autowired
protected UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
User user = userService.getUserByEmail(authentication.getName());
Gson gson = new Gson();
HttpSession session = request.getSession();
session.setAttribute("userObject", user);
String jUser = gson.toJson(user);
response.addHeader("user", jUser);
// Check of<SUF>
SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
RequestDispatcher dispatcher;
// Er is een redirect gebeurd, fetch de URI en zet die als bestemming
if (savedRequest != null) {
Pattern pattern = Pattern.compile("(https?://)([^:^/]*)(:\\d*)?(.*)?");
Matcher matcher = pattern.matcher(savedRequest.getRedirectUrl());
matcher.find();
String uri = matcher.group(4);
dispatcher = request.getRequestDispatcher(uri);
} // Geen redirect, dus gewoon profiel pagina tonen
else {
dispatcher = request.getRequestDispatcher("/profile/myprofile");
}
dispatcher.forward(request, response);
}
}
|
37160_0 | package nl.geslotenkingdom.postduif.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent.Action;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import nl.geslotenkingdom.postduif.main.Main;
import nl.geslotenkingdom.postduif.ui.GUI;
import nl.geslotenkingdom.postduif.utils.Utils;
public class PostDuif implements CommandExecutor {
private HashMap<Player, Integer> returnTime = new HashMap<Player, Integer>();
private HashMap<Player, Long> cooldown = new HashMap<Player, Long>();
public static HashMap<Player, List<ItemStack>> message = new HashMap<>();
private Map<Player, List<Player>> postduif = new HashMap<>();
private Main plugin;
public PostDuif(Main plugin) {
this.plugin = plugin;
plugin.getCommand("postduif").setExecutor(this);
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(Utils.chat("&cJe kan dit command niet uitvoeren!"));
return true;
}
Player p = (Player) sender;
//TODO: Bug fixen dat als je 2 boekjes stuurt (ontvanger heeft het niet gelezen) dat die dan boekje nog laat pakken
// CTRL + ALT + L (Instellingen veranderen)
if (p.hasPermission("postduif.use")) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("open")) {
if (args.length > 1) {
Player from = plugin.getServer().getPlayer(args[1]);
if (from != null) {
if (postduif.get(from).contains(p)) {
p.openInventory(GUI.GUI(from, p));
postduif.get(from).remove(p);
} else p.sendMessage(Utils.chat("&cJe hebt geen bericht ontvangen van &4" + args[1] + "&c!"));
} else p.sendMessage(Utils.chat("&cEen speler genaamd &4" + args[1] + " &cbestaat niet of is niet online!"));
} else p.sendMessage(Utils.chat("&cGeef alstjeblieft een speler op waarvan je het bericht wilt lezen als je die hebt ontvangen"));
} else {
if (cooldown.containsKey(p)) {
long secondsleft = ((cooldown.get(p) / 1000) + returnTime.get(p)) - (System.currentTimeMillis() / 1000);
if (secondsleft >= 0) { //Is meer dan of is 0
p.sendMessage(Utils.chat("&cJe postduif is nog niet teruggekeerd wacht nog &4" + secondsleft + " &cseconden"));
} else {
if (p.getInventory().getItemInMainHand().getType().equals(Material.WRITTEN_BOOK) || p.getInventory().getItemInMainHand().getType().equals(Material.BOOK_AND_QUILL)) {
Player target = plugin.getServer().getPlayer(args[0]);
if (target != null) {
if (!p.equals(target)) {
if(!(p.getInventory().getItemInMainHand().getAmount() > 1)) {
// Pytagoras om de diagonale lengte uit te rekenen tussen de twee personen en
// dat gedeelt door 10 om de tijd uit te rekenen
int returnTimeNumber = (int) Math.round(Math.sqrt(Math.pow(target.getLocation().getX() - p.getLocation().getX(), 2) + Math.pow(target.getLocation().getZ() - p.getLocation().getZ(), 2)) / 50);
if (returnTimeNumber < 0) returnTimeNumber *= -1;
returnTime.put(p, returnTimeNumber * 2);
cooldown.put(p, System.currentTimeMillis());
p.sendMessage(Utils.chat("&aJe bericht is succesvol verzonden!"));
List<ItemStack> messages = new ArrayList<>();
if (message.get(p) != null && !message.get(p).isEmpty()) messages.addAll(message.get(p));
messages.add(p.getInventory().getItemInMainHand());
message.put(p, messages);
p.getInventory().setItemInHand(null);
sendArrival(p, target, returnTimeNumber);
}
} else p.sendMessage(Utils.chat("&cJe kan geen postduif naar jezelf sturen!"));
} else p.sendMessage(Utils.chat("&cEen speler genaamd '" + args[0] + "' bestaat niet of is niet online!"));
} else p.sendMessage(Utils.chat("&cJe hebt een gesigned book of een book and quill met het bericht in je hand nodig om het bericht te kunnen versturen"));
}
} else {
if (p.getInventory().getItemInMainHand().getType().equals(Material.WRITTEN_BOOK) || p.getInventory().getItemInMainHand().getType().equals(Material.BOOK_AND_QUILL)) {
Player target = plugin.getServer().getPlayer(args[0]);
if (target != null) {
if (!p.equals(target)) {
// Pytagoras om de diagonale lengte uit te rekenen tussen de twee personen en
// dat gedeelt door 10 om de tijd uit te rekenen
int returnTimeNumber = (int) Math.round(Math.sqrt(Math.pow(target.getLocation().getX() - p.getLocation().getX(), 2) + Math.pow(target.getLocation().getZ() - p.getLocation().getZ(), 2)) / 50);
if (returnTimeNumber < 0) returnTimeNumber *= -1;
returnTime.put(p, returnTimeNumber * 2);
cooldown.put(p, System.currentTimeMillis());
p.sendMessage(Utils.chat("&aJe bericht is succesvol verzonden!"));
List<ItemStack> messages = new ArrayList<>();
if(message.get(p) != null && !message.get(p).isEmpty()) messages.addAll(message.get(p));
messages.add(p.getInventory().getItemInMainHand());
message.put(p, messages);
p.getInventory().setItemInHand(null);
sendArrival(p, target, returnTimeNumber);
} else p.sendMessage(Utils.chat("&cJe kan geen postduif naar jezelf sturen!"));
} else p.sendMessage(Utils.chat("&cEen speler genaamd '" + args[0] + "' bestaat niet of is niet online!"));
} else p.sendMessage(Utils.chat("&cJe hebt een gesigned book of een book and quill met het bericht in je hand nodig om het bericht te kunnen versturen"));
}
}
} else p.sendMessage(Utils.chat("&cGeef alstjeblieft een speler op waar je het bericht naar wilt sturen of open een bericht met '/postduif open <naam>' als je een bericht hebt ontvangen"));
} else p.sendMessage(Utils.chat("&cJe kan dit command niet uitvoeren!"));
return false;
}
public void sendArrival(final Player from, final Player to, int timeInSeconds) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
List<Player> values = new ArrayList<>();
values.add(to);
if(postduif.get(from) != null && !postduif.get(from).isEmpty()) values.addAll(postduif.get(from));
postduif.put(from, values);
TextComponent tc = new TextComponent();
tc.setText(Utils.chat("&aJe hebt een bericht ontvangen van &2" + from.getName() + "&a! Klik op dit &abericht om het te lezen"));
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Utils.chat("&aKlik op dit bericht om het bericht van &2" + from.getName() + " &ate lezen")).create()));
tc.setClickEvent(new ClickEvent(Action.RUN_COMMAND, "/postduif open " + from.getName()));
to.spigot().sendMessage(tc);
to.sendActionBar(Utils.chat("&aJe hebt een bericht ontvangen van " + from.getName() + "!"));
}
}, timeInSeconds * 20);
}
}
| vincevd1/Postduif | src/main/java/nl/geslotenkingdom/postduif/commands/PostDuif.java | 2,566 | //TODO: Bug fixen dat als je 2 boekjes stuurt (ontvanger heeft het niet gelezen) dat die dan boekje nog laat pakken | line_comment | nl | package nl.geslotenkingdom.postduif.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent.Action;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import nl.geslotenkingdom.postduif.main.Main;
import nl.geslotenkingdom.postduif.ui.GUI;
import nl.geslotenkingdom.postduif.utils.Utils;
public class PostDuif implements CommandExecutor {
private HashMap<Player, Integer> returnTime = new HashMap<Player, Integer>();
private HashMap<Player, Long> cooldown = new HashMap<Player, Long>();
public static HashMap<Player, List<ItemStack>> message = new HashMap<>();
private Map<Player, List<Player>> postduif = new HashMap<>();
private Main plugin;
public PostDuif(Main plugin) {
this.plugin = plugin;
plugin.getCommand("postduif").setExecutor(this);
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(Utils.chat("&cJe kan dit command niet uitvoeren!"));
return true;
}
Player p = (Player) sender;
//TODO: Bug<SUF>
// CTRL + ALT + L (Instellingen veranderen)
if (p.hasPermission("postduif.use")) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("open")) {
if (args.length > 1) {
Player from = plugin.getServer().getPlayer(args[1]);
if (from != null) {
if (postduif.get(from).contains(p)) {
p.openInventory(GUI.GUI(from, p));
postduif.get(from).remove(p);
} else p.sendMessage(Utils.chat("&cJe hebt geen bericht ontvangen van &4" + args[1] + "&c!"));
} else p.sendMessage(Utils.chat("&cEen speler genaamd &4" + args[1] + " &cbestaat niet of is niet online!"));
} else p.sendMessage(Utils.chat("&cGeef alstjeblieft een speler op waarvan je het bericht wilt lezen als je die hebt ontvangen"));
} else {
if (cooldown.containsKey(p)) {
long secondsleft = ((cooldown.get(p) / 1000) + returnTime.get(p)) - (System.currentTimeMillis() / 1000);
if (secondsleft >= 0) { //Is meer dan of is 0
p.sendMessage(Utils.chat("&cJe postduif is nog niet teruggekeerd wacht nog &4" + secondsleft + " &cseconden"));
} else {
if (p.getInventory().getItemInMainHand().getType().equals(Material.WRITTEN_BOOK) || p.getInventory().getItemInMainHand().getType().equals(Material.BOOK_AND_QUILL)) {
Player target = plugin.getServer().getPlayer(args[0]);
if (target != null) {
if (!p.equals(target)) {
if(!(p.getInventory().getItemInMainHand().getAmount() > 1)) {
// Pytagoras om de diagonale lengte uit te rekenen tussen de twee personen en
// dat gedeelt door 10 om de tijd uit te rekenen
int returnTimeNumber = (int) Math.round(Math.sqrt(Math.pow(target.getLocation().getX() - p.getLocation().getX(), 2) + Math.pow(target.getLocation().getZ() - p.getLocation().getZ(), 2)) / 50);
if (returnTimeNumber < 0) returnTimeNumber *= -1;
returnTime.put(p, returnTimeNumber * 2);
cooldown.put(p, System.currentTimeMillis());
p.sendMessage(Utils.chat("&aJe bericht is succesvol verzonden!"));
List<ItemStack> messages = new ArrayList<>();
if (message.get(p) != null && !message.get(p).isEmpty()) messages.addAll(message.get(p));
messages.add(p.getInventory().getItemInMainHand());
message.put(p, messages);
p.getInventory().setItemInHand(null);
sendArrival(p, target, returnTimeNumber);
}
} else p.sendMessage(Utils.chat("&cJe kan geen postduif naar jezelf sturen!"));
} else p.sendMessage(Utils.chat("&cEen speler genaamd '" + args[0] + "' bestaat niet of is niet online!"));
} else p.sendMessage(Utils.chat("&cJe hebt een gesigned book of een book and quill met het bericht in je hand nodig om het bericht te kunnen versturen"));
}
} else {
if (p.getInventory().getItemInMainHand().getType().equals(Material.WRITTEN_BOOK) || p.getInventory().getItemInMainHand().getType().equals(Material.BOOK_AND_QUILL)) {
Player target = plugin.getServer().getPlayer(args[0]);
if (target != null) {
if (!p.equals(target)) {
// Pytagoras om de diagonale lengte uit te rekenen tussen de twee personen en
// dat gedeelt door 10 om de tijd uit te rekenen
int returnTimeNumber = (int) Math.round(Math.sqrt(Math.pow(target.getLocation().getX() - p.getLocation().getX(), 2) + Math.pow(target.getLocation().getZ() - p.getLocation().getZ(), 2)) / 50);
if (returnTimeNumber < 0) returnTimeNumber *= -1;
returnTime.put(p, returnTimeNumber * 2);
cooldown.put(p, System.currentTimeMillis());
p.sendMessage(Utils.chat("&aJe bericht is succesvol verzonden!"));
List<ItemStack> messages = new ArrayList<>();
if(message.get(p) != null && !message.get(p).isEmpty()) messages.addAll(message.get(p));
messages.add(p.getInventory().getItemInMainHand());
message.put(p, messages);
p.getInventory().setItemInHand(null);
sendArrival(p, target, returnTimeNumber);
} else p.sendMessage(Utils.chat("&cJe kan geen postduif naar jezelf sturen!"));
} else p.sendMessage(Utils.chat("&cEen speler genaamd '" + args[0] + "' bestaat niet of is niet online!"));
} else p.sendMessage(Utils.chat("&cJe hebt een gesigned book of een book and quill met het bericht in je hand nodig om het bericht te kunnen versturen"));
}
}
} else p.sendMessage(Utils.chat("&cGeef alstjeblieft een speler op waar je het bericht naar wilt sturen of open een bericht met '/postduif open <naam>' als je een bericht hebt ontvangen"));
} else p.sendMessage(Utils.chat("&cJe kan dit command niet uitvoeren!"));
return false;
}
public void sendArrival(final Player from, final Player to, int timeInSeconds) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
List<Player> values = new ArrayList<>();
values.add(to);
if(postduif.get(from) != null && !postduif.get(from).isEmpty()) values.addAll(postduif.get(from));
postduif.put(from, values);
TextComponent tc = new TextComponent();
tc.setText(Utils.chat("&aJe hebt een bericht ontvangen van &2" + from.getName() + "&a! Klik op dit &abericht om het te lezen"));
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Utils.chat("&aKlik op dit bericht om het bericht van &2" + from.getName() + " &ate lezen")).create()));
tc.setClickEvent(new ClickEvent(Action.RUN_COMMAND, "/postduif open " + from.getName()));
to.spigot().sendMessage(tc);
to.sendActionBar(Utils.chat("&aJe hebt een bericht ontvangen van " + from.getName() + "!"));
}
}, timeInSeconds * 20);
}
}
|
84288_8 | package org.osmdroid.bonuspack.overlays;
import android.graphics.Canvas;
import org.osmdroid.bonuspack.utils.BonusPackHelper;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* A Folder overlay implementing 2 advanced features:
*
* 1) Z-Index to all overlays that it contains.
* Like Google Maps Android API:
* "An overlay with a larger z-index is drawn over overlays with smaller z-indices.
* The order of overlays with the same z-index value is arbitrary.
* The default is 0."
* Unlike Google Maps Android API, this applies to all overlays, including Markers.
*
* 2) Drawing optimization based on Bounding Box culling.
*
* TODO - DO NOT USE YET. WORK IN PROGRESS.
*
* @author M.Kergall
*/
public class FolderZOverlay extends Overlay {
protected TreeSet<ZOverlay> mList;
protected String mName, mDescription;
protected class ZOverlay implements Comparator<ZOverlay> {
float mZIndex;
BoundingBox mBoundingBox;
boolean mBoundingBoxSet;
Overlay mOverlay;
public ZOverlay(Overlay o, float zIndex){
mOverlay = o;
mZIndex = zIndex;
mBoundingBoxSet = false;
}
@Override public int compare(ZOverlay o1, ZOverlay o2){
return (int)Math.signum(o1.mZIndex - o2.mZIndex);
}
public void setBoundingBox(BoundingBox bb){
mBoundingBox = bb.clone();
mBoundingBoxSet = true;
}
public void unsetBoundingBox(){
mBoundingBox = null;
mBoundingBoxSet = false;
}
/**
* @param mapBB bounding box of the map view
* @param mapOrientation orientation of the map view
* @return true if the overlay should be drawn.
*/
public boolean shouldBeDrawn(BoundingBox mapBB, float mapOrientation){
if (!mBoundingBoxSet)
return true;
if (mBoundingBox == null)
//null bounding box means overlay is empty, so nothing to draw:
return false;
if (mapOrientation != 0.0f)
//TODO - handle map rotation...
return true;
if (mBoundingBox.getLatSouth() > mapBB.getLatNorth()
|| mBoundingBox.getLatNorth() < mapBB.getLatSouth()
|| mBoundingBox.getLonWest() > mapBB.getLonEast()
|| mBoundingBox.getLonEast() < mapBB.getLonWest())
//completely outside the map view:
return false;
return true;
}
}
public FolderZOverlay(){
super();
mList = new TreeSet<>();
mName = "";
mDescription = "";
}
public void setName(String name){
mName = name;
}
public String getName(){
return mName;
}
public void setDescription(String description){
mDescription = description;
}
public String getDescription(){
return mDescription;
}
public boolean add(Overlay item, float zIndex){
return mList.add(new ZOverlay(item, zIndex));
}
public boolean add(Overlay item){
return add(item, 0);
}
protected ZOverlay get(Overlay overlay){
Iterator<ZOverlay> itr = mList.iterator();
while (itr.hasNext()) {
ZOverlay item = itr.next();
if (item.mOverlay == overlay) {
mList.remove(item);
return item;
}
}
return null;
}
public boolean remove(Overlay overlay) {
ZOverlay item = get(overlay);
if (item != null) {
mList.remove(item);
return true;
}
else
return false;
}
/**
* Change the Z-Index of an overlay.
* @param overlay overlay to change
* @param zIndex new Z-Index to set
*/
public void setZIndex(Overlay overlay, float zIndex){
ZOverlay item = get(overlay);
if (item == null)
return;
mList.remove(item);
item.mZIndex = zIndex; //TODO Check if removal/addition is really necessary.
mList.add(item);
}
/**
* Define the bounding box of this overlay.
* This may dramatically increase drawing performance when the overlay is completely outside the current view.
* @param overlay
* @param bb the bounding box of this overlay.
*/
public void setBoundingBox(Overlay overlay, BoundingBox bb){
ZOverlay item = get(overlay);
if (item == null)
return;
item.setBoundingBox(bb);
}
public void unsetBoundingBox(Overlay overlay){
ZOverlay item = get(overlay);
if (item == null)
return;
item.unsetBoundingBox();
}
//TODO:
//get highest z-index => getMaxZIndex
@Override public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (shadow)
return;
Iterator<ZOverlay> itr=mList.iterator();
while(itr.hasNext()){
ZOverlay item = itr.next();
Overlay overlay = item.mOverlay;
if (overlay!=null && overlay.isEnabled()) {
if (item.shouldBeDrawn(mapView.getBoundingBox(), mapView.getMapOrientation())) {
overlay.draw(canvas, mapView, false);
}
}
}
}
//TODO Implement events
}
| visfleet/osmbonuspack | OSMBonusPack/src/main/java/org/osmdroid/bonuspack/overlays/FolderZOverlay.java | 1,605 | //get highest z-index => getMaxZIndex | line_comment | nl | package org.osmdroid.bonuspack.overlays;
import android.graphics.Canvas;
import org.osmdroid.bonuspack.utils.BonusPackHelper;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* A Folder overlay implementing 2 advanced features:
*
* 1) Z-Index to all overlays that it contains.
* Like Google Maps Android API:
* "An overlay with a larger z-index is drawn over overlays with smaller z-indices.
* The order of overlays with the same z-index value is arbitrary.
* The default is 0."
* Unlike Google Maps Android API, this applies to all overlays, including Markers.
*
* 2) Drawing optimization based on Bounding Box culling.
*
* TODO - DO NOT USE YET. WORK IN PROGRESS.
*
* @author M.Kergall
*/
public class FolderZOverlay extends Overlay {
protected TreeSet<ZOverlay> mList;
protected String mName, mDescription;
protected class ZOverlay implements Comparator<ZOverlay> {
float mZIndex;
BoundingBox mBoundingBox;
boolean mBoundingBoxSet;
Overlay mOverlay;
public ZOverlay(Overlay o, float zIndex){
mOverlay = o;
mZIndex = zIndex;
mBoundingBoxSet = false;
}
@Override public int compare(ZOverlay o1, ZOverlay o2){
return (int)Math.signum(o1.mZIndex - o2.mZIndex);
}
public void setBoundingBox(BoundingBox bb){
mBoundingBox = bb.clone();
mBoundingBoxSet = true;
}
public void unsetBoundingBox(){
mBoundingBox = null;
mBoundingBoxSet = false;
}
/**
* @param mapBB bounding box of the map view
* @param mapOrientation orientation of the map view
* @return true if the overlay should be drawn.
*/
public boolean shouldBeDrawn(BoundingBox mapBB, float mapOrientation){
if (!mBoundingBoxSet)
return true;
if (mBoundingBox == null)
//null bounding box means overlay is empty, so nothing to draw:
return false;
if (mapOrientation != 0.0f)
//TODO - handle map rotation...
return true;
if (mBoundingBox.getLatSouth() > mapBB.getLatNorth()
|| mBoundingBox.getLatNorth() < mapBB.getLatSouth()
|| mBoundingBox.getLonWest() > mapBB.getLonEast()
|| mBoundingBox.getLonEast() < mapBB.getLonWest())
//completely outside the map view:
return false;
return true;
}
}
public FolderZOverlay(){
super();
mList = new TreeSet<>();
mName = "";
mDescription = "";
}
public void setName(String name){
mName = name;
}
public String getName(){
return mName;
}
public void setDescription(String description){
mDescription = description;
}
public String getDescription(){
return mDescription;
}
public boolean add(Overlay item, float zIndex){
return mList.add(new ZOverlay(item, zIndex));
}
public boolean add(Overlay item){
return add(item, 0);
}
protected ZOverlay get(Overlay overlay){
Iterator<ZOverlay> itr = mList.iterator();
while (itr.hasNext()) {
ZOverlay item = itr.next();
if (item.mOverlay == overlay) {
mList.remove(item);
return item;
}
}
return null;
}
public boolean remove(Overlay overlay) {
ZOverlay item = get(overlay);
if (item != null) {
mList.remove(item);
return true;
}
else
return false;
}
/**
* Change the Z-Index of an overlay.
* @param overlay overlay to change
* @param zIndex new Z-Index to set
*/
public void setZIndex(Overlay overlay, float zIndex){
ZOverlay item = get(overlay);
if (item == null)
return;
mList.remove(item);
item.mZIndex = zIndex; //TODO Check if removal/addition is really necessary.
mList.add(item);
}
/**
* Define the bounding box of this overlay.
* This may dramatically increase drawing performance when the overlay is completely outside the current view.
* @param overlay
* @param bb the bounding box of this overlay.
*/
public void setBoundingBox(Overlay overlay, BoundingBox bb){
ZOverlay item = get(overlay);
if (item == null)
return;
item.setBoundingBox(bb);
}
public void unsetBoundingBox(Overlay overlay){
ZOverlay item = get(overlay);
if (item == null)
return;
item.unsetBoundingBox();
}
//TODO:
//get highest<SUF>
@Override public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (shadow)
return;
Iterator<ZOverlay> itr=mList.iterator();
while(itr.hasNext()){
ZOverlay item = itr.next();
Overlay overlay = item.mOverlay;
if (overlay!=null && overlay.isEnabled()) {
if (item.shouldBeDrawn(mapView.getBoundingBox(), mapView.getMapOrientation())) {
overlay.draw(canvas, mapView, false);
}
}
}
}
//TODO Implement events
}
|
32108_30 | /*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 2.0 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
** Processing integration: Andres Colubri, February 2012
*/
package com.parabay.cinema.text.tess;
class Mesh {
private Mesh() {
}
/************************ Utility Routines ************************/
/* MakeEdge creates a new pair of half-edges which form their own loop.
* No vertex or face structures are allocated, but these must be assigned
* before the current edge operation is completed.
*/
static GLUhalfEdge MakeEdge(GLUhalfEdge eNext) {
GLUhalfEdge e;
GLUhalfEdge eSym;
GLUhalfEdge ePrev;
// EdgePair * pair = (EdgePair *)
// memAlloc(sizeof(EdgePair));
// if (pair == NULL) return NULL;
//
// e = &pair - > e;
e = new GLUhalfEdge(true);
// eSym = &pair - > eSym;
eSym = new GLUhalfEdge(false);
/* Make sure eNext points to the first edge of the edge pair */
if (!eNext.first) {
eNext = eNext.Sym;
}
/* Insert in circular doubly-linked list before eNext.
* Note that the prev pointer is stored in Sym->next.
*/
ePrev = eNext.Sym.next;
eSym.next = ePrev;
ePrev.Sym.next = e;
e.next = eNext;
eNext.Sym.next = eSym;
e.Sym = eSym;
e.Onext = e;
e.Lnext = eSym;
e.Org = null;
e.Lface = null;
e.winding = 0;
e.activeRegion = null;
eSym.Sym = e;
eSym.Onext = eSym;
eSym.Lnext = e;
eSym.Org = null;
eSym.Lface = null;
eSym.winding = 0;
eSym.activeRegion = null;
return e;
}
/* Splice( a, b ) is best described by the Guibas/Stolfi paper or the
* CS348a notes (see mesh.h). Basically it modifies the mesh so that
* a->Onext and b->Onext are exchanged. This can have various effects
* depending on whether a and b belong to different face or vertex rings.
* For more explanation see __gl_meshSplice() below.
*/
static void Splice(GLUhalfEdge a, GLUhalfEdge b) {
GLUhalfEdge aOnext = a.Onext;
GLUhalfEdge bOnext = b.Onext;
aOnext.Sym.Lnext = b;
bOnext.Sym.Lnext = a;
a.Onext = bOnext;
b.Onext = aOnext;
}
/* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the
* origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives
* a place to insert the new vertex in the global vertex list. We insert
* the new vertex *before* vNext so that algorithms which walk the vertex
* list will not see the newly created vertices.
*/
static void MakeVertex(GLUvertex newVertex,
GLUhalfEdge eOrig, GLUvertex vNext) {
GLUhalfEdge e;
GLUvertex vPrev;
GLUvertex vNew = newVertex;
assert (vNew != null);
/* insert in circular doubly-linked list before vNext */
vPrev = vNext.prev;
vNew.prev = vPrev;
vPrev.next = vNew;
vNew.next = vNext;
vNext.prev = vNew;
vNew.anEdge = eOrig;
vNew.data = null;
/* leave coords, s, t undefined */
/* fix other edges on this vertex loop */
e = eOrig;
do {
e.Org = vNew;
e = e.Onext;
} while (e != eOrig);
}
/* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left
* face of all edges in the face loop to which eOrig belongs. "fNext" gives
* a place to insert the new face in the global face list. We insert
* the new face *before* fNext so that algorithms which walk the face
* list will not see the newly created faces.
*/
static void MakeFace(GLUface newFace, GLUhalfEdge eOrig, GLUface fNext) {
GLUhalfEdge e;
GLUface fPrev;
GLUface fNew = newFace;
assert (fNew != null);
/* insert in circular doubly-linked list before fNext */
fPrev = fNext.prev;
fNew.prev = fPrev;
fPrev.next = fNew;
fNew.next = fNext;
fNext.prev = fNew;
fNew.anEdge = eOrig;
fNew.data = null;
fNew.trail = null;
fNew.marked = false;
/* The new face is marked "inside" if the old one was. This is a
* convenience for the common case where a face has been split in two.
*/
fNew.inside = fNext.inside;
/* fix other edges on this face loop */
e = eOrig;
do {
e.Lface = fNew;
e = e.Lnext;
} while (e != eOrig);
}
/* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym),
* and removes from the global edge list.
*/
static void KillEdge(GLUhalfEdge eDel) {
GLUhalfEdge ePrev, eNext;
/* Half-edges are allocated in pairs, see EdgePair above */
if (!eDel.first) {
eDel = eDel.Sym;
}
/* delete from circular doubly-linked list */
eNext = eDel.next;
ePrev = eDel.Sym.next;
eNext.Sym.next = ePrev;
ePrev.Sym.next = eNext;
}
/* KillVertex( vDel ) destroys a vertex and removes it from the global
* vertex list. It updates the vertex loop to point to a given new vertex.
*/
static void KillVertex(GLUvertex vDel, GLUvertex newOrg) {
GLUhalfEdge e, eStart = vDel.anEdge;
GLUvertex vPrev, vNext;
/* change the origin of all affected edges */
e = eStart;
do {
e.Org = newOrg;
e = e.Onext;
} while (e != eStart);
/* delete from circular doubly-linked list */
vPrev = vDel.prev;
vNext = vDel.next;
vNext.prev = vPrev;
vPrev.next = vNext;
}
/* KillFace( fDel ) destroys a face and removes it from the global face
* list. It updates the face loop to point to a given new face.
*/
static void KillFace(GLUface fDel, GLUface newLface) {
GLUhalfEdge e, eStart = fDel.anEdge;
GLUface fPrev, fNext;
/* change the left face of all affected edges */
e = eStart;
do {
e.Lface = newLface;
e = e.Lnext;
} while (e != eStart);
/* delete from circular doubly-linked list */
fPrev = fDel.prev;
fNext = fDel.next;
fNext.prev = fPrev;
fPrev.next = fNext;
}
/****************** Basic Edge Operations **********************/
/* __gl_meshMakeEdge creates one edge, two vertices, and a loop (face).
* The loop consists of the two new half-edges.
*/
public static GLUhalfEdge __gl_meshMakeEdge(GLUmesh mesh) {
GLUvertex newVertex1 = new GLUvertex();
GLUvertex newVertex2 = new GLUvertex();
GLUface newFace = new GLUface();
GLUhalfEdge e;
e = MakeEdge(mesh.eHead);
if (e == null) return null;
MakeVertex(newVertex1, e, mesh.vHead);
MakeVertex(newVertex2, e.Sym, mesh.vHead);
MakeFace(newFace, e, mesh.fHead);
return e;
}
/* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the
* mesh connectivity and topology. It changes the mesh so that
* eOrg->Onext <- OLD( eDst->Onext )
* eDst->Onext <- OLD( eOrg->Onext )
* where OLD(...) means the value before the meshSplice operation.
*
* This can have two effects on the vertex structure:
* - if eOrg->Org != eDst->Org, the two vertices are merged together
* - if eOrg->Org == eDst->Org, the origin is split into two vertices
* In both cases, eDst->Org is changed and eOrg->Org is untouched.
*
* Similarly (and independently) for the face structure,
* - if eOrg->Lface == eDst->Lface, one loop is split into two
* - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one
* In both cases, eDst->Lface is changed and eOrg->Lface is unaffected.
*
* Some special cases:
* If eDst == eOrg, the operation has no effect.
* If eDst == eOrg->Lnext, the new face will have a single edge.
* If eDst == eOrg->Lprev, the old face will have a single edge.
* If eDst == eOrg->Onext, the new vertex will have a single edge.
* If eDst == eOrg->Oprev, the old vertex will have a single edge.
*/
public static boolean __gl_meshSplice(GLUhalfEdge eOrg, GLUhalfEdge eDst) {
boolean joiningLoops = false;
boolean joiningVertices = false;
if (eOrg == eDst) return true;
if (eDst.Org != eOrg.Org) {
/* We are merging two disjoint vertices -- destroy eDst->Org */
joiningVertices = true;
KillVertex(eDst.Org, eOrg.Org);
}
if (eDst.Lface != eOrg.Lface) {
/* We are connecting two disjoint loops -- destroy eDst.Lface */
joiningLoops = true;
KillFace(eDst.Lface, eOrg.Lface);
}
/* Change the edge structure */
Splice(eDst, eOrg);
if (!joiningVertices) {
GLUvertex newVertex = new GLUvertex();
/* We split one vertex into two -- the new vertex is eDst.Org.
* Make sure the old vertex points to a valid half-edge.
*/
MakeVertex(newVertex, eDst, eOrg.Org);
eOrg.Org.anEdge = eOrg;
}
if (!joiningLoops) {
GLUface newFace = new GLUface();
/* We split one loop into two -- the new loop is eDst.Lface.
* Make sure the old face points to a valid half-edge.
*/
MakeFace(newFace, eDst, eOrg.Lface);
eOrg.Lface.anEdge = eOrg;
}
return true;
}
/* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases:
* if (eDel.Lface != eDel.Rface), we join two loops into one; the loop
* eDel.Lface is deleted. Otherwise, we are splitting one loop into two;
* the newly created loop will contain eDel.Dst. If the deletion of eDel
* would create isolated vertices, those are deleted as well.
*
* This function could be implemented as two calls to __gl_meshSplice
* plus a few calls to memFree, but this would allocate and delete
* unnecessary vertices and faces.
*/
static boolean __gl_meshDelete(GLUhalfEdge eDel) {
GLUhalfEdge eDelSym = eDel.Sym;
boolean joiningLoops = false;
/* First step: disconnect the origin vertex eDel.Org. We make all
* changes to get a consistent mesh in this "intermediate" state.
*/
if (eDel.Lface != eDel.Sym.Lface) {
/* We are joining two loops into one -- remove the left face */
joiningLoops = true;
KillFace(eDel.Lface, eDel.Sym.Lface);
}
if (eDel.Onext == eDel) {
KillVertex(eDel.Org, null);
} else {
/* Make sure that eDel.Org and eDel.Sym.Lface point to valid half-edges */
eDel.Sym.Lface.anEdge = eDel.Sym.Lnext;
eDel.Org.anEdge = eDel.Onext;
Splice(eDel, eDel.Sym.Lnext);
if (!joiningLoops) {
GLUface newFace = new GLUface();
/* We are splitting one loop into two -- create a new loop for eDel. */
MakeFace(newFace, eDel, eDel.Lface);
}
}
/* Claim: the mesh is now in a consistent state, except that eDel.Org
* may have been deleted. Now we disconnect eDel.Dst.
*/
if (eDelSym.Onext == eDelSym) {
KillVertex(eDelSym.Org, null);
KillFace(eDelSym.Lface, null);
} else {
/* Make sure that eDel.Dst and eDel.Lface point to valid half-edges */
eDel.Lface.anEdge = eDelSym.Sym.Lnext;
eDelSym.Org.anEdge = eDelSym.Onext;
Splice(eDelSym, eDelSym.Sym.Lnext);
}
/* Any isolated vertices or faces have already been freed. */
KillEdge(eDel);
return true;
}
/******************** Other Edge Operations **********************/
/* All these routines can be implemented with the basic edge
* operations above. They are provided for convenience and efficiency.
*/
/* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that
* eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex.
* eOrg and eNew will have the same left face.
*/
static GLUhalfEdge __gl_meshAddEdgeVertex(GLUhalfEdge eOrg) {
GLUhalfEdge eNewSym;
GLUhalfEdge eNew = MakeEdge(eOrg);
eNewSym = eNew.Sym;
/* Connect the new edge appropriately */
Splice(eNew, eOrg.Lnext);
/* Set the vertex and face information */
eNew.Org = eOrg.Sym.Org;
{
GLUvertex newVertex = new GLUvertex();
MakeVertex(newVertex, eNewSym, eNew.Org);
}
eNew.Lface = eNewSym.Lface = eOrg.Lface;
return eNew;
}
/* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew,
* such that eNew == eOrg.Lnext. The new vertex is eOrg.Sym.Org == eNew.Org.
* eOrg and eNew will have the same left face.
*/
public static GLUhalfEdge __gl_meshSplitEdge(GLUhalfEdge eOrg) {
GLUhalfEdge eNew;
GLUhalfEdge tempHalfEdge = __gl_meshAddEdgeVertex(eOrg);
eNew = tempHalfEdge.Sym;
/* Disconnect eOrg from eOrg.Sym.Org and connect it to eNew.Org */
Splice(eOrg.Sym, eOrg.Sym.Sym.Lnext);
Splice(eOrg.Sym, eNew);
/* Set the vertex and face information */
eOrg.Sym.Org = eNew.Org;
eNew.Sym.Org.anEdge = eNew.Sym; /* may have pointed to eOrg.Sym */
eNew.Sym.Lface = eOrg.Sym.Lface;
eNew.winding = eOrg.winding; /* copy old winding information */
eNew.Sym.winding = eOrg.Sym.winding;
return eNew;
}
/* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Sym.Org
* to eDst.Org, and returns the corresponding half-edge eNew.
* If eOrg.Lface == eDst.Lface, this splits one loop into two,
* and the newly created loop is eNew.Lface. Otherwise, two disjoint
* loops are merged into one, and the loop eDst.Lface is destroyed.
*
* If (eOrg == eDst), the new face will have only two edges.
* If (eOrg.Lnext == eDst), the old face is reduced to a single edge.
* If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges.
*/
static GLUhalfEdge __gl_meshConnect(GLUhalfEdge eOrg, GLUhalfEdge eDst) {
GLUhalfEdge eNewSym;
boolean joiningLoops = false;
GLUhalfEdge eNew = MakeEdge(eOrg);
eNewSym = eNew.Sym;
if (eDst.Lface != eOrg.Lface) {
/* We are connecting two disjoint loops -- destroy eDst.Lface */
joiningLoops = true;
KillFace(eDst.Lface, eOrg.Lface);
}
/* Connect the new edge appropriately */
Splice(eNew, eOrg.Lnext);
Splice(eNewSym, eDst);
/* Set the vertex and face information */
eNew.Org = eOrg.Sym.Org;
eNewSym.Org = eDst.Org;
eNew.Lface = eNewSym.Lface = eOrg.Lface;
/* Make sure the old face points to a valid half-edge */
eOrg.Lface.anEdge = eNewSym;
if (!joiningLoops) {
GLUface newFace = new GLUface();
/* We split one loop into two -- the new loop is eNew.Lface */
MakeFace(newFace, eNew, eOrg.Lface);
}
return eNew;
}
/******************** Other Operations **********************/
/* __gl_meshZapFace( fZap ) destroys a face and removes it from the
* global face list. All edges of fZap will have a null pointer as their
* left face. Any edges which also have a null pointer as their right face
* are deleted entirely (along with any isolated vertices this produces).
* An entire mesh can be deleted by zapping its faces, one at a time,
* in any order. Zapped faces cannot be used in further mesh operations!
*/
static void __gl_meshZapFace(GLUface fZap) {
GLUhalfEdge eStart = fZap.anEdge;
GLUhalfEdge e, eNext, eSym;
GLUface fPrev, fNext;
/* walk around face, deleting edges whose right face is also null */
eNext = eStart.Lnext;
do {
e = eNext;
eNext = e.Lnext;
e.Lface = null;
if (e.Sym.Lface == null) {
/* delete the edge -- see __gl_MeshDelete above */
if (e.Onext == e) {
KillVertex(e.Org, null);
} else {
/* Make sure that e.Org points to a valid half-edge */
e.Org.anEdge = e.Onext;
Splice(e, e.Sym.Lnext);
}
eSym = e.Sym;
if (eSym.Onext == eSym) {
KillVertex(eSym.Org, null);
} else {
/* Make sure that eSym.Org points to a valid half-edge */
eSym.Org.anEdge = eSym.Onext;
Splice(eSym, eSym.Sym.Lnext);
}
KillEdge(e);
}
} while (e != eStart);
/* delete from circular doubly-linked list */
fPrev = fZap.prev;
fNext = fZap.next;
fNext.prev = fPrev;
fPrev.next = fNext;
}
/* __gl_meshNewMesh() creates a new mesh with no edges, no vertices,
* and no loops (what we usually call a "face").
*/
public static GLUmesh __gl_meshNewMesh() {
GLUvertex v;
GLUface f;
GLUhalfEdge e;
GLUhalfEdge eSym;
GLUmesh mesh = new GLUmesh();
v = mesh.vHead;
f = mesh.fHead;
e = mesh.eHead;
eSym = mesh.eHeadSym;
v.next = v.prev = v;
v.anEdge = null;
v.data = null;
f.next = f.prev = f;
f.anEdge = null;
f.data = null;
f.trail = null;
f.marked = false;
f.inside = false;
e.next = e;
e.Sym = eSym;
e.Onext = null;
e.Lnext = null;
e.Org = null;
e.Lface = null;
e.winding = 0;
e.activeRegion = null;
eSym.next = eSym;
eSym.Sym = e;
eSym.Onext = null;
eSym.Lnext = null;
eSym.Org = null;
eSym.Lface = null;
eSym.winding = 0;
eSym.activeRegion = null;
return mesh;
}
/* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in
* both meshes, and returns the new mesh (the old meshes are destroyed).
*/
static GLUmesh __gl_meshUnion(GLUmesh mesh1, GLUmesh mesh2) {
GLUface f1 = mesh1.fHead;
GLUvertex v1 = mesh1.vHead;
GLUhalfEdge e1 = mesh1.eHead;
GLUface f2 = mesh2.fHead;
GLUvertex v2 = mesh2.vHead;
GLUhalfEdge e2 = mesh2.eHead;
/* Add the faces, vertices, and edges of mesh2 to those of mesh1 */
if (f2.next != f2) {
f1.prev.next = f2.next;
f2.next.prev = f1.prev;
f2.prev.next = f1;
f1.prev = f2.prev;
}
if (v2.next != v2) {
v1.prev.next = v2.next;
v2.next.prev = v1.prev;
v2.prev.next = v1;
v1.prev = v2.prev;
}
if (e2.next != e2) {
e1.Sym.next.Sym.next = e2.next;
e2.next.Sym.next = e1.Sym.next;
e2.Sym.next.Sym.next = e1;
e1.Sym.next = e2.Sym.next;
}
return mesh1;
}
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
static void __gl_meshDeleteMeshZap(GLUmesh mesh) {
GLUface fHead = mesh.fHead;
while (fHead.next != fHead) {
__gl_meshZapFace(fHead.next);
}
assert (mesh.vHead.next == mesh.vHead);
}
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
public static void __gl_meshDeleteMesh(GLUmesh mesh) {
GLUface f, fNext;
GLUvertex v, vNext;
GLUhalfEdge e, eNext;
for (f = mesh.fHead.next; f != mesh.fHead; f = fNext) {
fNext = f.next;
}
for (v = mesh.vHead.next; v != mesh.vHead; v = vNext) {
vNext = v.next;
}
for (e = mesh.eHead.next; e != mesh.eHead; e = eNext) {
/* One call frees both e and e.Sym (see EdgePair above) */
eNext = e.next;
}
}
/* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency.
*/
public static void __gl_meshCheckMesh(GLUmesh mesh) {
GLUface fHead = mesh.fHead;
GLUvertex vHead = mesh.vHead;
GLUhalfEdge eHead = mesh.eHead;
GLUface f, fPrev;
GLUvertex v, vPrev;
GLUhalfEdge e, ePrev;
fPrev = fHead;
for (fPrev = fHead; (f = fPrev.next) != fHead; fPrev = f) {
assert (f.prev == fPrev);
e = f.anEdge;
do {
assert (e.Sym != e);
assert (e.Sym.Sym == e);
assert (e.Lnext.Onext.Sym == e);
assert (e.Onext.Sym.Lnext == e);
assert (e.Lface == f);
e = e.Lnext;
} while (e != f.anEdge);
}
assert (f.prev == fPrev && f.anEdge == null && f.data == null);
vPrev = vHead;
for (vPrev = vHead; (v = vPrev.next) != vHead; vPrev = v) {
assert (v.prev == vPrev);
e = v.anEdge;
do {
assert (e.Sym != e);
assert (e.Sym.Sym == e);
assert (e.Lnext.Onext.Sym == e);
assert (e.Onext.Sym.Lnext == e);
assert (e.Org == v);
e = e.Onext;
} while (e != v.anEdge);
}
assert (v.prev == vPrev && v.anEdge == null && v.data == null);
ePrev = eHead;
for (ePrev = eHead; (e = ePrev.next) != eHead; ePrev = e) {
assert (e.Sym.next == ePrev.Sym);
assert (e.Sym != e);
assert (e.Sym.Sym == e);
assert (e.Org != null);
assert (e.Sym.Org != null);
assert (e.Lnext.Onext.Sym == e);
assert (e.Onext.Sym.Lnext == e);
}
assert (e.Sym.next == ePrev.Sym
&& e.Sym == mesh.eHeadSym
&& e.Sym.Sym == e
&& e.Org == null && e.Sym.Org == null
&& e.Lface == null && e.Sym.Lface == null);
}
}
| vishnuvaradaraj/android-opengl | ParabayLib/src/com/parabay/cinema/text/tess/Mesh.java | 8,174 | /* We are merging two disjoint vertices -- destroy eDst->Org */ | block_comment | nl | /*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 2.0 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
** Processing integration: Andres Colubri, February 2012
*/
package com.parabay.cinema.text.tess;
class Mesh {
private Mesh() {
}
/************************ Utility Routines ************************/
/* MakeEdge creates a new pair of half-edges which form their own loop.
* No vertex or face structures are allocated, but these must be assigned
* before the current edge operation is completed.
*/
static GLUhalfEdge MakeEdge(GLUhalfEdge eNext) {
GLUhalfEdge e;
GLUhalfEdge eSym;
GLUhalfEdge ePrev;
// EdgePair * pair = (EdgePair *)
// memAlloc(sizeof(EdgePair));
// if (pair == NULL) return NULL;
//
// e = &pair - > e;
e = new GLUhalfEdge(true);
// eSym = &pair - > eSym;
eSym = new GLUhalfEdge(false);
/* Make sure eNext points to the first edge of the edge pair */
if (!eNext.first) {
eNext = eNext.Sym;
}
/* Insert in circular doubly-linked list before eNext.
* Note that the prev pointer is stored in Sym->next.
*/
ePrev = eNext.Sym.next;
eSym.next = ePrev;
ePrev.Sym.next = e;
e.next = eNext;
eNext.Sym.next = eSym;
e.Sym = eSym;
e.Onext = e;
e.Lnext = eSym;
e.Org = null;
e.Lface = null;
e.winding = 0;
e.activeRegion = null;
eSym.Sym = e;
eSym.Onext = eSym;
eSym.Lnext = e;
eSym.Org = null;
eSym.Lface = null;
eSym.winding = 0;
eSym.activeRegion = null;
return e;
}
/* Splice( a, b ) is best described by the Guibas/Stolfi paper or the
* CS348a notes (see mesh.h). Basically it modifies the mesh so that
* a->Onext and b->Onext are exchanged. This can have various effects
* depending on whether a and b belong to different face or vertex rings.
* For more explanation see __gl_meshSplice() below.
*/
static void Splice(GLUhalfEdge a, GLUhalfEdge b) {
GLUhalfEdge aOnext = a.Onext;
GLUhalfEdge bOnext = b.Onext;
aOnext.Sym.Lnext = b;
bOnext.Sym.Lnext = a;
a.Onext = bOnext;
b.Onext = aOnext;
}
/* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the
* origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives
* a place to insert the new vertex in the global vertex list. We insert
* the new vertex *before* vNext so that algorithms which walk the vertex
* list will not see the newly created vertices.
*/
static void MakeVertex(GLUvertex newVertex,
GLUhalfEdge eOrig, GLUvertex vNext) {
GLUhalfEdge e;
GLUvertex vPrev;
GLUvertex vNew = newVertex;
assert (vNew != null);
/* insert in circular doubly-linked list before vNext */
vPrev = vNext.prev;
vNew.prev = vPrev;
vPrev.next = vNew;
vNew.next = vNext;
vNext.prev = vNew;
vNew.anEdge = eOrig;
vNew.data = null;
/* leave coords, s, t undefined */
/* fix other edges on this vertex loop */
e = eOrig;
do {
e.Org = vNew;
e = e.Onext;
} while (e != eOrig);
}
/* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left
* face of all edges in the face loop to which eOrig belongs. "fNext" gives
* a place to insert the new face in the global face list. We insert
* the new face *before* fNext so that algorithms which walk the face
* list will not see the newly created faces.
*/
static void MakeFace(GLUface newFace, GLUhalfEdge eOrig, GLUface fNext) {
GLUhalfEdge e;
GLUface fPrev;
GLUface fNew = newFace;
assert (fNew != null);
/* insert in circular doubly-linked list before fNext */
fPrev = fNext.prev;
fNew.prev = fPrev;
fPrev.next = fNew;
fNew.next = fNext;
fNext.prev = fNew;
fNew.anEdge = eOrig;
fNew.data = null;
fNew.trail = null;
fNew.marked = false;
/* The new face is marked "inside" if the old one was. This is a
* convenience for the common case where a face has been split in two.
*/
fNew.inside = fNext.inside;
/* fix other edges on this face loop */
e = eOrig;
do {
e.Lface = fNew;
e = e.Lnext;
} while (e != eOrig);
}
/* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym),
* and removes from the global edge list.
*/
static void KillEdge(GLUhalfEdge eDel) {
GLUhalfEdge ePrev, eNext;
/* Half-edges are allocated in pairs, see EdgePair above */
if (!eDel.first) {
eDel = eDel.Sym;
}
/* delete from circular doubly-linked list */
eNext = eDel.next;
ePrev = eDel.Sym.next;
eNext.Sym.next = ePrev;
ePrev.Sym.next = eNext;
}
/* KillVertex( vDel ) destroys a vertex and removes it from the global
* vertex list. It updates the vertex loop to point to a given new vertex.
*/
static void KillVertex(GLUvertex vDel, GLUvertex newOrg) {
GLUhalfEdge e, eStart = vDel.anEdge;
GLUvertex vPrev, vNext;
/* change the origin of all affected edges */
e = eStart;
do {
e.Org = newOrg;
e = e.Onext;
} while (e != eStart);
/* delete from circular doubly-linked list */
vPrev = vDel.prev;
vNext = vDel.next;
vNext.prev = vPrev;
vPrev.next = vNext;
}
/* KillFace( fDel ) destroys a face and removes it from the global face
* list. It updates the face loop to point to a given new face.
*/
static void KillFace(GLUface fDel, GLUface newLface) {
GLUhalfEdge e, eStart = fDel.anEdge;
GLUface fPrev, fNext;
/* change the left face of all affected edges */
e = eStart;
do {
e.Lface = newLface;
e = e.Lnext;
} while (e != eStart);
/* delete from circular doubly-linked list */
fPrev = fDel.prev;
fNext = fDel.next;
fNext.prev = fPrev;
fPrev.next = fNext;
}
/****************** Basic Edge Operations **********************/
/* __gl_meshMakeEdge creates one edge, two vertices, and a loop (face).
* The loop consists of the two new half-edges.
*/
public static GLUhalfEdge __gl_meshMakeEdge(GLUmesh mesh) {
GLUvertex newVertex1 = new GLUvertex();
GLUvertex newVertex2 = new GLUvertex();
GLUface newFace = new GLUface();
GLUhalfEdge e;
e = MakeEdge(mesh.eHead);
if (e == null) return null;
MakeVertex(newVertex1, e, mesh.vHead);
MakeVertex(newVertex2, e.Sym, mesh.vHead);
MakeFace(newFace, e, mesh.fHead);
return e;
}
/* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the
* mesh connectivity and topology. It changes the mesh so that
* eOrg->Onext <- OLD( eDst->Onext )
* eDst->Onext <- OLD( eOrg->Onext )
* where OLD(...) means the value before the meshSplice operation.
*
* This can have two effects on the vertex structure:
* - if eOrg->Org != eDst->Org, the two vertices are merged together
* - if eOrg->Org == eDst->Org, the origin is split into two vertices
* In both cases, eDst->Org is changed and eOrg->Org is untouched.
*
* Similarly (and independently) for the face structure,
* - if eOrg->Lface == eDst->Lface, one loop is split into two
* - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one
* In both cases, eDst->Lface is changed and eOrg->Lface is unaffected.
*
* Some special cases:
* If eDst == eOrg, the operation has no effect.
* If eDst == eOrg->Lnext, the new face will have a single edge.
* If eDst == eOrg->Lprev, the old face will have a single edge.
* If eDst == eOrg->Onext, the new vertex will have a single edge.
* If eDst == eOrg->Oprev, the old vertex will have a single edge.
*/
public static boolean __gl_meshSplice(GLUhalfEdge eOrg, GLUhalfEdge eDst) {
boolean joiningLoops = false;
boolean joiningVertices = false;
if (eOrg == eDst) return true;
if (eDst.Org != eOrg.Org) {
/* We are merging<SUF>*/
joiningVertices = true;
KillVertex(eDst.Org, eOrg.Org);
}
if (eDst.Lface != eOrg.Lface) {
/* We are connecting two disjoint loops -- destroy eDst.Lface */
joiningLoops = true;
KillFace(eDst.Lface, eOrg.Lface);
}
/* Change the edge structure */
Splice(eDst, eOrg);
if (!joiningVertices) {
GLUvertex newVertex = new GLUvertex();
/* We split one vertex into two -- the new vertex is eDst.Org.
* Make sure the old vertex points to a valid half-edge.
*/
MakeVertex(newVertex, eDst, eOrg.Org);
eOrg.Org.anEdge = eOrg;
}
if (!joiningLoops) {
GLUface newFace = new GLUface();
/* We split one loop into two -- the new loop is eDst.Lface.
* Make sure the old face points to a valid half-edge.
*/
MakeFace(newFace, eDst, eOrg.Lface);
eOrg.Lface.anEdge = eOrg;
}
return true;
}
/* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases:
* if (eDel.Lface != eDel.Rface), we join two loops into one; the loop
* eDel.Lface is deleted. Otherwise, we are splitting one loop into two;
* the newly created loop will contain eDel.Dst. If the deletion of eDel
* would create isolated vertices, those are deleted as well.
*
* This function could be implemented as two calls to __gl_meshSplice
* plus a few calls to memFree, but this would allocate and delete
* unnecessary vertices and faces.
*/
static boolean __gl_meshDelete(GLUhalfEdge eDel) {
GLUhalfEdge eDelSym = eDel.Sym;
boolean joiningLoops = false;
/* First step: disconnect the origin vertex eDel.Org. We make all
* changes to get a consistent mesh in this "intermediate" state.
*/
if (eDel.Lface != eDel.Sym.Lface) {
/* We are joining two loops into one -- remove the left face */
joiningLoops = true;
KillFace(eDel.Lface, eDel.Sym.Lface);
}
if (eDel.Onext == eDel) {
KillVertex(eDel.Org, null);
} else {
/* Make sure that eDel.Org and eDel.Sym.Lface point to valid half-edges */
eDel.Sym.Lface.anEdge = eDel.Sym.Lnext;
eDel.Org.anEdge = eDel.Onext;
Splice(eDel, eDel.Sym.Lnext);
if (!joiningLoops) {
GLUface newFace = new GLUface();
/* We are splitting one loop into two -- create a new loop for eDel. */
MakeFace(newFace, eDel, eDel.Lface);
}
}
/* Claim: the mesh is now in a consistent state, except that eDel.Org
* may have been deleted. Now we disconnect eDel.Dst.
*/
if (eDelSym.Onext == eDelSym) {
KillVertex(eDelSym.Org, null);
KillFace(eDelSym.Lface, null);
} else {
/* Make sure that eDel.Dst and eDel.Lface point to valid half-edges */
eDel.Lface.anEdge = eDelSym.Sym.Lnext;
eDelSym.Org.anEdge = eDelSym.Onext;
Splice(eDelSym, eDelSym.Sym.Lnext);
}
/* Any isolated vertices or faces have already been freed. */
KillEdge(eDel);
return true;
}
/******************** Other Edge Operations **********************/
/* All these routines can be implemented with the basic edge
* operations above. They are provided for convenience and efficiency.
*/
/* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that
* eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex.
* eOrg and eNew will have the same left face.
*/
static GLUhalfEdge __gl_meshAddEdgeVertex(GLUhalfEdge eOrg) {
GLUhalfEdge eNewSym;
GLUhalfEdge eNew = MakeEdge(eOrg);
eNewSym = eNew.Sym;
/* Connect the new edge appropriately */
Splice(eNew, eOrg.Lnext);
/* Set the vertex and face information */
eNew.Org = eOrg.Sym.Org;
{
GLUvertex newVertex = new GLUvertex();
MakeVertex(newVertex, eNewSym, eNew.Org);
}
eNew.Lface = eNewSym.Lface = eOrg.Lface;
return eNew;
}
/* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew,
* such that eNew == eOrg.Lnext. The new vertex is eOrg.Sym.Org == eNew.Org.
* eOrg and eNew will have the same left face.
*/
public static GLUhalfEdge __gl_meshSplitEdge(GLUhalfEdge eOrg) {
GLUhalfEdge eNew;
GLUhalfEdge tempHalfEdge = __gl_meshAddEdgeVertex(eOrg);
eNew = tempHalfEdge.Sym;
/* Disconnect eOrg from eOrg.Sym.Org and connect it to eNew.Org */
Splice(eOrg.Sym, eOrg.Sym.Sym.Lnext);
Splice(eOrg.Sym, eNew);
/* Set the vertex and face information */
eOrg.Sym.Org = eNew.Org;
eNew.Sym.Org.anEdge = eNew.Sym; /* may have pointed to eOrg.Sym */
eNew.Sym.Lface = eOrg.Sym.Lface;
eNew.winding = eOrg.winding; /* copy old winding information */
eNew.Sym.winding = eOrg.Sym.winding;
return eNew;
}
/* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Sym.Org
* to eDst.Org, and returns the corresponding half-edge eNew.
* If eOrg.Lface == eDst.Lface, this splits one loop into two,
* and the newly created loop is eNew.Lface. Otherwise, two disjoint
* loops are merged into one, and the loop eDst.Lface is destroyed.
*
* If (eOrg == eDst), the new face will have only two edges.
* If (eOrg.Lnext == eDst), the old face is reduced to a single edge.
* If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges.
*/
static GLUhalfEdge __gl_meshConnect(GLUhalfEdge eOrg, GLUhalfEdge eDst) {
GLUhalfEdge eNewSym;
boolean joiningLoops = false;
GLUhalfEdge eNew = MakeEdge(eOrg);
eNewSym = eNew.Sym;
if (eDst.Lface != eOrg.Lface) {
/* We are connecting two disjoint loops -- destroy eDst.Lface */
joiningLoops = true;
KillFace(eDst.Lface, eOrg.Lface);
}
/* Connect the new edge appropriately */
Splice(eNew, eOrg.Lnext);
Splice(eNewSym, eDst);
/* Set the vertex and face information */
eNew.Org = eOrg.Sym.Org;
eNewSym.Org = eDst.Org;
eNew.Lface = eNewSym.Lface = eOrg.Lface;
/* Make sure the old face points to a valid half-edge */
eOrg.Lface.anEdge = eNewSym;
if (!joiningLoops) {
GLUface newFace = new GLUface();
/* We split one loop into two -- the new loop is eNew.Lface */
MakeFace(newFace, eNew, eOrg.Lface);
}
return eNew;
}
/******************** Other Operations **********************/
/* __gl_meshZapFace( fZap ) destroys a face and removes it from the
* global face list. All edges of fZap will have a null pointer as their
* left face. Any edges which also have a null pointer as their right face
* are deleted entirely (along with any isolated vertices this produces).
* An entire mesh can be deleted by zapping its faces, one at a time,
* in any order. Zapped faces cannot be used in further mesh operations!
*/
static void __gl_meshZapFace(GLUface fZap) {
GLUhalfEdge eStart = fZap.anEdge;
GLUhalfEdge e, eNext, eSym;
GLUface fPrev, fNext;
/* walk around face, deleting edges whose right face is also null */
eNext = eStart.Lnext;
do {
e = eNext;
eNext = e.Lnext;
e.Lface = null;
if (e.Sym.Lface == null) {
/* delete the edge -- see __gl_MeshDelete above */
if (e.Onext == e) {
KillVertex(e.Org, null);
} else {
/* Make sure that e.Org points to a valid half-edge */
e.Org.anEdge = e.Onext;
Splice(e, e.Sym.Lnext);
}
eSym = e.Sym;
if (eSym.Onext == eSym) {
KillVertex(eSym.Org, null);
} else {
/* Make sure that eSym.Org points to a valid half-edge */
eSym.Org.anEdge = eSym.Onext;
Splice(eSym, eSym.Sym.Lnext);
}
KillEdge(e);
}
} while (e != eStart);
/* delete from circular doubly-linked list */
fPrev = fZap.prev;
fNext = fZap.next;
fNext.prev = fPrev;
fPrev.next = fNext;
}
/* __gl_meshNewMesh() creates a new mesh with no edges, no vertices,
* and no loops (what we usually call a "face").
*/
public static GLUmesh __gl_meshNewMesh() {
GLUvertex v;
GLUface f;
GLUhalfEdge e;
GLUhalfEdge eSym;
GLUmesh mesh = new GLUmesh();
v = mesh.vHead;
f = mesh.fHead;
e = mesh.eHead;
eSym = mesh.eHeadSym;
v.next = v.prev = v;
v.anEdge = null;
v.data = null;
f.next = f.prev = f;
f.anEdge = null;
f.data = null;
f.trail = null;
f.marked = false;
f.inside = false;
e.next = e;
e.Sym = eSym;
e.Onext = null;
e.Lnext = null;
e.Org = null;
e.Lface = null;
e.winding = 0;
e.activeRegion = null;
eSym.next = eSym;
eSym.Sym = e;
eSym.Onext = null;
eSym.Lnext = null;
eSym.Org = null;
eSym.Lface = null;
eSym.winding = 0;
eSym.activeRegion = null;
return mesh;
}
/* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in
* both meshes, and returns the new mesh (the old meshes are destroyed).
*/
static GLUmesh __gl_meshUnion(GLUmesh mesh1, GLUmesh mesh2) {
GLUface f1 = mesh1.fHead;
GLUvertex v1 = mesh1.vHead;
GLUhalfEdge e1 = mesh1.eHead;
GLUface f2 = mesh2.fHead;
GLUvertex v2 = mesh2.vHead;
GLUhalfEdge e2 = mesh2.eHead;
/* Add the faces, vertices, and edges of mesh2 to those of mesh1 */
if (f2.next != f2) {
f1.prev.next = f2.next;
f2.next.prev = f1.prev;
f2.prev.next = f1;
f1.prev = f2.prev;
}
if (v2.next != v2) {
v1.prev.next = v2.next;
v2.next.prev = v1.prev;
v2.prev.next = v1;
v1.prev = v2.prev;
}
if (e2.next != e2) {
e1.Sym.next.Sym.next = e2.next;
e2.next.Sym.next = e1.Sym.next;
e2.Sym.next.Sym.next = e1;
e1.Sym.next = e2.Sym.next;
}
return mesh1;
}
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
static void __gl_meshDeleteMeshZap(GLUmesh mesh) {
GLUface fHead = mesh.fHead;
while (fHead.next != fHead) {
__gl_meshZapFace(fHead.next);
}
assert (mesh.vHead.next == mesh.vHead);
}
/* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*/
public static void __gl_meshDeleteMesh(GLUmesh mesh) {
GLUface f, fNext;
GLUvertex v, vNext;
GLUhalfEdge e, eNext;
for (f = mesh.fHead.next; f != mesh.fHead; f = fNext) {
fNext = f.next;
}
for (v = mesh.vHead.next; v != mesh.vHead; v = vNext) {
vNext = v.next;
}
for (e = mesh.eHead.next; e != mesh.eHead; e = eNext) {
/* One call frees both e and e.Sym (see EdgePair above) */
eNext = e.next;
}
}
/* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency.
*/
public static void __gl_meshCheckMesh(GLUmesh mesh) {
GLUface fHead = mesh.fHead;
GLUvertex vHead = mesh.vHead;
GLUhalfEdge eHead = mesh.eHead;
GLUface f, fPrev;
GLUvertex v, vPrev;
GLUhalfEdge e, ePrev;
fPrev = fHead;
for (fPrev = fHead; (f = fPrev.next) != fHead; fPrev = f) {
assert (f.prev == fPrev);
e = f.anEdge;
do {
assert (e.Sym != e);
assert (e.Sym.Sym == e);
assert (e.Lnext.Onext.Sym == e);
assert (e.Onext.Sym.Lnext == e);
assert (e.Lface == f);
e = e.Lnext;
} while (e != f.anEdge);
}
assert (f.prev == fPrev && f.anEdge == null && f.data == null);
vPrev = vHead;
for (vPrev = vHead; (v = vPrev.next) != vHead; vPrev = v) {
assert (v.prev == vPrev);
e = v.anEdge;
do {
assert (e.Sym != e);
assert (e.Sym.Sym == e);
assert (e.Lnext.Onext.Sym == e);
assert (e.Onext.Sym.Lnext == e);
assert (e.Org == v);
e = e.Onext;
} while (e != v.anEdge);
}
assert (v.prev == vPrev && v.anEdge == null && v.data == null);
ePrev = eHead;
for (ePrev = eHead; (e = ePrev.next) != eHead; ePrev = e) {
assert (e.Sym.next == ePrev.Sym);
assert (e.Sym != e);
assert (e.Sym.Sym == e);
assert (e.Org != null);
assert (e.Sym.Org != null);
assert (e.Lnext.Onext.Sym == e);
assert (e.Onext.Sym.Lnext == e);
}
assert (e.Sym.next == ePrev.Sym
&& e.Sym == mesh.eHeadSym
&& e.Sym.Sym == e
&& e.Org == null && e.Sym.Org == null
&& e.Lface == null && e.Sym.Lface == null);
}
}
|
71944_0 | package com.eomarker.storage;
import android.content.Context;
import android.widget.Toast;
import com.eomarker.device.Device;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class InternalStorage {
private File storageFile;
Context context;
public InternalStorage(Context _context) {
context = _context;
storageFile = new File(context.getFilesDir(), "devices.json");
if (!storageFile.exists()) {
try {
storageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONObject deviceObject = new JSONObject();
deviceObject.put("macAddress", device.macAddress);
deviceObject.put("name", device.name);
jsonArray.put(deviceObject);
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
public List<Device> getDevices() {
List<Device> devices = new ArrayList<>();
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String macAddress = deviceObject.getString("macAddress");
String name = deviceObject.getString("name");
devices.add(new Device(macAddress, name));
}
} catch (JSONException e) {
e.printStackTrace();
}
return devices;
}
public void updateDeviceName(String macAddress, String newName) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Controleer of het macAdres overeenkomt met het gezochte apparaat
if (deviceMacAddress.equals(macAddress)) {
// Wijzig de naam van het apparaat
deviceObject.put("name", newName);
// Sla de bijgewerkte array terug op
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
return; // Stop de loop omdat het apparaat is gevonden en bijgewerkt
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
private JSONArray readJsonArrayFromFile() {
JSONArray jsonArray = new JSONArray();
try {
BufferedReader reader = new BufferedReader(new FileReader(storageFile));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
jsonArray = new JSONArray(stringBuilder.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonArray;
}
public void deleteData() {
try{
storageFile = new File(context.getFilesDir(), "devices.json");
storageFile.delete();
Toast.makeText(context, "Data deleted!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Unable to delete data...", Toast.LENGTH_SHORT).show();
}
}
public void deleteDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONArray updatedArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Als het macAdres overeenkomt met het te verwijderen apparaat, sla het niet op in de bijgewerkte array
if (!deviceMacAddress.equals(device.macAddress)) {
updatedArray.put(deviceObject);
}
}
// Overschrijf het opslaan van de bijgewerkte array
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(updatedArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
} | vives-project-xp/EOMarkers | AndroidStudio/EOMarker/app/src/main/java/com/eomarker/storage/InternalStorage.java | 1,298 | // Controleer of het macAdres overeenkomt met het gezochte apparaat | line_comment | nl | package com.eomarker.storage;
import android.content.Context;
import android.widget.Toast;
import com.eomarker.device.Device;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class InternalStorage {
private File storageFile;
Context context;
public InternalStorage(Context _context) {
context = _context;
storageFile = new File(context.getFilesDir(), "devices.json");
if (!storageFile.exists()) {
try {
storageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONObject deviceObject = new JSONObject();
deviceObject.put("macAddress", device.macAddress);
deviceObject.put("name", device.name);
jsonArray.put(deviceObject);
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
public List<Device> getDevices() {
List<Device> devices = new ArrayList<>();
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String macAddress = deviceObject.getString("macAddress");
String name = deviceObject.getString("name");
devices.add(new Device(macAddress, name));
}
} catch (JSONException e) {
e.printStackTrace();
}
return devices;
}
public void updateDeviceName(String macAddress, String newName) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Controleer of<SUF>
if (deviceMacAddress.equals(macAddress)) {
// Wijzig de naam van het apparaat
deviceObject.put("name", newName);
// Sla de bijgewerkte array terug op
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(jsonArray.toString().getBytes());
fos.close();
return; // Stop de loop omdat het apparaat is gevonden en bijgewerkt
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
private JSONArray readJsonArrayFromFile() {
JSONArray jsonArray = new JSONArray();
try {
BufferedReader reader = new BufferedReader(new FileReader(storageFile));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
jsonArray = new JSONArray(stringBuilder.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonArray;
}
public void deleteData() {
try{
storageFile = new File(context.getFilesDir(), "devices.json");
storageFile.delete();
Toast.makeText(context, "Data deleted!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Unable to delete data...", Toast.LENGTH_SHORT).show();
}
}
public void deleteDevice(Device device) {
try {
JSONArray jsonArray = readJsonArrayFromFile();
JSONArray updatedArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject deviceObject = jsonArray.getJSONObject(i);
String deviceMacAddress = deviceObject.getString("macAddress");
// Als het macAdres overeenkomt met het te verwijderen apparaat, sla het niet op in de bijgewerkte array
if (!deviceMacAddress.equals(device.macAddress)) {
updatedArray.put(deviceObject);
}
}
// Overschrijf het opslaan van de bijgewerkte array
FileOutputStream fos = new FileOutputStream(storageFile);
fos.write(updatedArray.toString().getBytes());
fos.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
} |
78550_42 | //
// MessagePack for Java
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
//
// 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.msgpack;
import java.nio.ByteBuffer;
import java.math.BigInteger;
import org.msgpack.object.*;
public class UnpackerImpl {
static final int CS_HEADER = 0x00;
static final int CS_FLOAT = 0x0a;
static final int CS_DOUBLE = 0x0b;
static final int CS_UINT_8 = 0x0c;
static final int CS_UINT_16 = 0x0d;
static final int CS_UINT_32 = 0x0e;
static final int CS_UINT_64 = 0x0f;
static final int CS_INT_8 = 0x10;
static final int CS_INT_16 = 0x11;
static final int CS_INT_32 = 0x12;
static final int CS_INT_64 = 0x13;
static final int CS_RAW_16 = 0x1a;
static final int CS_RAW_32 = 0x1b;
static final int CS_ARRAY_16 = 0x1c;
static final int CS_ARRAY_32 = 0x1d;
static final int CS_MAP_16 = 0x1e;
static final int CS_MAP_32 = 0x1f;
static final int ACS_RAW_VALUE = 0x20;
static final int CS_VO_HEADER = 0x21;
static final int CS_VO_FIELDS = 0x22;
static final int CT_ARRAY_ITEM = 0x00;
static final int CT_MAP_KEY = 0x01;
static final int CT_MAP_VALUE = 0x02;
static final int CT_VO_VALUES = 0x03;
static final int MAX_STACK_SIZE = 32;
private int cs;
private int trail;
private int top;
private int[] stack_ct = new int[MAX_STACK_SIZE];
private int[] stack_count = new int[MAX_STACK_SIZE];
private Object[] stack_obj = new Object[MAX_STACK_SIZE];
private int top_ct;
private int top_count;
private Object top_obj;
private ByteBuffer castBuffer = ByteBuffer.allocate(8);
private boolean finished = false;
private MessagePackObject data = null;
private VOHelper voHelper = null;
public interface VOHelper {
VOInstance newObject();
}
static public abstract class VOInstance
{
int mixins = 0;
final boolean mixinDataRemains() {
return mixins != 0;
}
final void nextMixin() {
--mixins;
}
final void incrementMixinCount(int mixins) {
this.mixins += mixins;
}
// Custom value-type API
abstract protected int processValueType(int typeID);
abstract protected void putValue(byte[] bytes, int start);
// ValueObject builder API
abstract protected void prepareValueObject(int typeID);
abstract protected void prepareForNext8Fields(byte flags);
abstract protected void putValue(Object value);
abstract protected boolean fieldgroupRequiresMoreValues();
// Resulting object
abstract public MessagePackObject getData();
}
public UnpackerImpl()
{
reset();
}
public final void setVOHelper(VOHelper voHelper)
{
this.voHelper = voHelper;
}
public final MessagePackObject getData()
{
return data;
}
public final boolean isFinished()
{
return finished;
}
public final void resetState() {
cs = CS_HEADER;
top = -1;
top_ct = 0;
top_count = 0;
top_obj = null;
}
public final void reset()
{
resetState();
finished = false;
data = null;
}
@SuppressWarnings("unchecked")
public final int execute(byte[] src, int off, int length) throws UnpackException
{
if(off >= length) { return off; }
int limit = length;
int i = off;
int count;
Object obj = null;
_out: do {
_header_again_without_cs_reset: { _header_again: {
//System.out.println("while i:"+i+" limit:"+limit);
int b = src[i];
_push: {
_fixed_trail_again:
if(cs == CS_HEADER) {
if((b & 0x80) == 0) { // Positive Fixnum
//System.out.println("positive fixnum "+b);
obj = IntegerType.create((byte)b);
break _push;
}
if((b & 0xe0) == 0xe0) { // Negative Fixnum
//System.out.println("negative fixnum "+b);
obj = IntegerType.create((byte)b);
break _push;
}
if((b & 0xe0) == 0xa0) { // FixRaw
trail = b & 0x1f;
if(trail == 0) {
obj = RawType.create(new byte[0]);
break _push;
}
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
}
if((b & 0xf0) == 0x90) { // FixArray
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
count = b & 0x0f;
//System.out.println("fixarray count:"+count);
obj = new MessagePackObject[count];
if(count == 0) {
obj = ArrayType.create((MessagePackObject[])obj);
break _push;
}
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_ARRAY_ITEM;
top_count = count;
break _header_again;
}
if((b & 0xf0) == 0x80) { // FixMap
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
count = b & 0x0f;
obj = new MessagePackObject[count*2];
if(count == 0) {
obj = MapType.create((MessagePackObject[])obj);
break _push;
}
//System.out.println("fixmap count:"+count);
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_MAP_KEY;
top_count = count;
break _header_again;
}
switch(b & 0xff) { // FIXME
case 0xc0: // nil
obj = NilType.create();
break _push;
case 0xc2: // false
obj = BooleanType.create(false);
break _push;
case 0xc3: // true
obj = BooleanType.create(true);
break _push;
case 0xca: // float
case 0xcb: // double
case 0xcc: // unsigned int 8
case 0xcd: // unsigned int 16
case 0xce: // unsigned int 32
case 0xcf: // unsigned int 64
case 0xd0: // signed int 8
case 0xd1: // signed int 16
case 0xd2: // signed int 32
case 0xd3: // signed int 64
trail = 1 << (b & 0x03);
cs = b & 0x1f;
//System.out.println("a trail "+trail+" cs:"+cs);
break _fixed_trail_again;
case 0xda: // raw 16
case 0xdb: // raw 32
case 0xdc: // array 16
case 0xdd: // array 32
case 0xde: // map 16
case 0xdf: // map 32
trail = 2 << (b & 0x01);
cs = b & 0x1f;
//System.out.println("b trail "+trail+" cs:"+cs);
break _fixed_trail_again;
case 0xd7: // ValueObject
//System.out.println(top + " valueobject:start | (push top)");
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = voHelper.newObject();
top_ct = -1;
top_count = -1;
trail = 3; // of 2? header + typeID (max 2 bytes)
cs = CS_VO_HEADER;
break _fixed_trail_again;
default:
//System.out.println("unknown b "+(b&0xff));
throw new UnpackException("parse error");
}
} // _fixed_trail_again
do {
_fixed_trail_again: {
if(limit - i <= trail) { break _out; }
int n = i + 1;
i += trail;
switch(cs) {
case CS_FLOAT:
castBuffer.rewind();
castBuffer.put(src, n, 4);
obj = FloatType.create( castBuffer.getFloat(0) );
//System.out.println("float "+obj);
break _push;
case CS_DOUBLE:
castBuffer.rewind();
castBuffer.put(src, n, 8);
obj = FloatType.create( castBuffer.getDouble(0) );
//System.out.println("double "+obj);
break _push;
case CS_UINT_8:
//System.out.println(n);
//System.out.println(src[n]);
//System.out.println(src[n+1]);
//System.out.println(src[n-1]);
obj = IntegerType.create( (short)((src[n]) & 0xff) );
//System.out.println("uint8 "+obj);
break _push;
case CS_UINT_16:
//System.out.println(src[n]);
//System.out.println(src[n+1]);
castBuffer.rewind();
castBuffer.put(src, n, 2);
obj = IntegerType.create( ((int)castBuffer.getShort(0)) & 0xffff );
//System.out.println("uint 16 "+obj);
break _push;
case CS_UINT_32:
castBuffer.rewind();
castBuffer.put(src, n, 4);
obj = IntegerType.create( ((long)castBuffer.getInt(0)) & 0xffffffffL );
//System.out.println("uint 32 "+obj);
break _push;
case CS_UINT_64:
castBuffer.rewind();
castBuffer.put(src, n, 8);
{
long o = castBuffer.getLong(0);
if(o < 0) {
obj = IntegerType.create(new BigInteger(1, castBuffer.array()));
} else {
obj = IntegerType.create(o);
}
}
break _push;
case CS_INT_8:
obj = IntegerType.create( src[n] );
break _push;
case CS_INT_16:
castBuffer.rewind();
castBuffer.put(src, n, 2);
obj = IntegerType.create( castBuffer.getShort(0) );
break _push;
case CS_INT_32:
castBuffer.rewind();
castBuffer.put(src, n, 4);
obj = IntegerType.create( castBuffer.getInt(0) );
break _push;
case CS_INT_64:
castBuffer.rewind();
castBuffer.put(src, n, 8);
obj = IntegerType.create( castBuffer.getLong(0) );
break _push;
case CS_RAW_16:
castBuffer.rewind();
castBuffer.put(src, n, 2);
trail = ((int)castBuffer.getShort(0)) & 0xffff;
if(trail == 0) {
obj = RawType.create(new byte[0]);
break _push;
}
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
case CS_RAW_32:
castBuffer.rewind();
castBuffer.put(src, n, 4);
// FIXME overflow check
trail = castBuffer.getInt(0) & 0x7fffffff;
if(trail == 0) {
obj = RawType.create(new byte[0]);
break _push;
}
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
case ACS_RAW_VALUE: {
// TODO zero-copy buffer
byte[] raw = new byte[trail];
System.arraycopy(src, n, raw, 0, trail);
obj = RawType.create(raw);
}
break _push;
case CS_ARRAY_16:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 2);
count = ((int)castBuffer.getShort(0)) & 0xffff;
obj = new MessagePackObject[count];
if(count == 0) {
obj = ArrayType.create((MessagePackObject[])obj);
break _push;
}
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_ARRAY_ITEM;
top_count = count;
break _header_again;
case CS_ARRAY_32:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 4);
// FIXME overflow check
count = castBuffer.getInt(0) & 0x7fffffff;
obj = new MessagePackObject[count];
if(count == 0) {
obj = ArrayType.create((MessagePackObject[])obj);
break _push;
}
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_ARRAY_ITEM;
top_count = count;
break _header_again;
case CS_MAP_16:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 2);
count = ((int)castBuffer.getShort(0)) & 0xffff;
obj = new MessagePackObject[count*2];
if(count == 0) {
obj = MapType.create((MessagePackObject[])obj);
break _push;
}
//System.out.println("fixmap count:"+count);
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_MAP_KEY;
top_count = count;
break _header_again;
case CS_MAP_32:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 4);
// FIXME overflow check
count = castBuffer.getInt(0) & 0x7fffffff;
obj = new MessagePackObject[count*2];
if(count == 0) {
obj = MapType.create((MessagePackObject[])obj);
break _push;
}
//System.out.println("fixmap count:"+count);
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_MAP_KEY;
top_count = count;
break _header_again;
case CS_VO_HEADER: {
VOInstance vo = (VOInstance) top_obj;
int header = src[n];
if (header >= 0) // first (sign) bit not set
{
// Custom value type (not a value-object)
count = vo.processValueType(header);
if(limit - n <= count) {
trail = count + 1;
i = n - 1;
break _out; // try again later when sufficient data is available
}
i = n + count;
vo.putValue(src, n);
//System.out.println(top + " \\_ -> pop stack | custom value done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
count = header & 0x07; // property byte-flags count
int typeID;
if (0 == (header & 0x40)) { // single byte typeID
--i; // go back one, as trail was guessed as 3
typeID = ((src[n+1]) & 0xff);
} else {
castBuffer.rewind();
castBuffer.put(src, n+1, 2);
typeID = ((int)castBuffer.getShort(0)) & 0xffff;
}
/*System.out.println(top + " valueobject:header | firstbyte = "+ header +
", mixins = "+ mixinCount +
", property-sets = "+ count +
", typeID = "+ typeID);
*/
vo.prepareValueObject(typeID);
vo.incrementMixinCount((header & 0x38 /* 0b_0011_1000 */) >>> 3); // kan dus groter dan 7 worden (!) - dataRemains is true zolang mixinCount > 0
if ((top_count = count) > 0) {
trail = 1;
cs = CS_VO_FIELDS;
//System.out.println(top + " \\_ CS_VO_FIELDS | count = " + count);
break _fixed_trail_again;
}
// else if
if (vo.mixinDataRemains()) {
vo.nextMixin();
//System.out.println(top + " \\_ -> mixin | count = " + count + " trail = "+trail);
trail = 3; //bytes: 1 header, 2 type id (of 1 type id + iets aan data)
break _fixed_trail_again;
}
// else, object complete
//System.out.println(top + " \\_ -> pop stack | vo done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
case CS_VO_FIELDS: {
//System.out.println(top + " valueobject:fields");
// read 1 byte (field-group of max 8 values)
VOInstance vo = (VOInstance) top_obj;
vo.prepareForNext8Fields(src[i]);
if (src[i] != 0) {// && vo.fieldgroupRequiresMoreValues()) {
top_ct = CT_VO_VALUES;
break _header_again;
}
else if (--top_count == 0) // if 0: No more property groups for this type
{
//System.out.println(top + " \\_ -> no more field groups");
if (!vo.mixinDataRemains()) {
// else, object complete
//System.out.println(top + " \\_ -> pop stack | vo done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
// else
vo.nextMixin();
trail = 3;
cs = CS_VO_HEADER; // process next mixin
}
break _fixed_trail_again;
}
default:
throw new UnpackException("parse error");
}
} // _fixed_trail_again
} while(true);
} // _push
do {
_push: {
//System.out.println("push top:"+top);
if(top == -1) {
++i;
data = (MessagePackObject)obj;
finished = true;
break _out;
}
switch(top_ct) {
case CT_ARRAY_ITEM: {
//System.out.println("array item "+obj);
Object[] ar = (Object[])top_obj;
ar[ar.length - top_count] = obj;
if(--top_count == 0) {
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
obj = ArrayType.create((MessagePackObject[])ar);
stack_obj[top] = null;
--top;
break _push;
}
break _header_again;
}
case CT_MAP_KEY: {
//System.out.println("map key:"+top+" "+obj);
Object[] mp = (Object[])top_obj;
mp[mp.length - top_count*2] = obj;
top_ct = CT_MAP_VALUE;
break _header_again;
}
case CT_MAP_VALUE: {
//System.out.println("map value:"+top+" "+obj);
Object[] mp = (Object[])top_obj;
mp[mp.length - top_count*2 + 1] = obj;
if(--top_count == 0) {
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
obj = MapType.create((MessagePackObject[])mp);
stack_obj[top] = null;
--top;
break _push;
}
top_ct = CT_MAP_KEY;
break _header_again;
}
case CT_VO_VALUES: {
//System.out.println(top + " valueobject:values");
VOInstance vo = (VOInstance) top_obj;
vo.putValue(obj);
if (vo.fieldgroupRequiresMoreValues()) {
//System.out.println(top + " \\_ -> CT_VO_VALUES -> requires more values");
break _header_again;
}
// else
if (--top_count == 0)
{
//System.out.println(top + " \\_ -> no more field groups");
if (vo.mixinDataRemains()) {
vo.nextMixin();
trail = 3;
cs = CS_VO_HEADER; // process next mixin
break _header_again_without_cs_reset;
}
// else, value-object complete, POP stack
//System.out.println(top + " \\_ -> pop stack | vo done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
// else next set of properties
//System.out.println(top + " \\_ -> CT_VO_VALUES -> next set of properties");
trail = 1;
cs = CS_VO_FIELDS;
break _header_again_without_cs_reset;
}
default:
throw new UnpackException("parse error");
}
} // _push
} while(true);
} // _header_again
cs = CS_HEADER;
++i;
} // _header_again_without_cs_reset
} while(i < limit); // _out
return i;
}
}
| vizanto/msgpack | java/src/main/java/org/msgpack/UnpackerImpl.java | 7,447 | // kan dus groter dan 7 worden (!) - dataRemains is true zolang mixinCount > 0 | line_comment | nl | //
// MessagePack for Java
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
//
// 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.msgpack;
import java.nio.ByteBuffer;
import java.math.BigInteger;
import org.msgpack.object.*;
public class UnpackerImpl {
static final int CS_HEADER = 0x00;
static final int CS_FLOAT = 0x0a;
static final int CS_DOUBLE = 0x0b;
static final int CS_UINT_8 = 0x0c;
static final int CS_UINT_16 = 0x0d;
static final int CS_UINT_32 = 0x0e;
static final int CS_UINT_64 = 0x0f;
static final int CS_INT_8 = 0x10;
static final int CS_INT_16 = 0x11;
static final int CS_INT_32 = 0x12;
static final int CS_INT_64 = 0x13;
static final int CS_RAW_16 = 0x1a;
static final int CS_RAW_32 = 0x1b;
static final int CS_ARRAY_16 = 0x1c;
static final int CS_ARRAY_32 = 0x1d;
static final int CS_MAP_16 = 0x1e;
static final int CS_MAP_32 = 0x1f;
static final int ACS_RAW_VALUE = 0x20;
static final int CS_VO_HEADER = 0x21;
static final int CS_VO_FIELDS = 0x22;
static final int CT_ARRAY_ITEM = 0x00;
static final int CT_MAP_KEY = 0x01;
static final int CT_MAP_VALUE = 0x02;
static final int CT_VO_VALUES = 0x03;
static final int MAX_STACK_SIZE = 32;
private int cs;
private int trail;
private int top;
private int[] stack_ct = new int[MAX_STACK_SIZE];
private int[] stack_count = new int[MAX_STACK_SIZE];
private Object[] stack_obj = new Object[MAX_STACK_SIZE];
private int top_ct;
private int top_count;
private Object top_obj;
private ByteBuffer castBuffer = ByteBuffer.allocate(8);
private boolean finished = false;
private MessagePackObject data = null;
private VOHelper voHelper = null;
public interface VOHelper {
VOInstance newObject();
}
static public abstract class VOInstance
{
int mixins = 0;
final boolean mixinDataRemains() {
return mixins != 0;
}
final void nextMixin() {
--mixins;
}
final void incrementMixinCount(int mixins) {
this.mixins += mixins;
}
// Custom value-type API
abstract protected int processValueType(int typeID);
abstract protected void putValue(byte[] bytes, int start);
// ValueObject builder API
abstract protected void prepareValueObject(int typeID);
abstract protected void prepareForNext8Fields(byte flags);
abstract protected void putValue(Object value);
abstract protected boolean fieldgroupRequiresMoreValues();
// Resulting object
abstract public MessagePackObject getData();
}
public UnpackerImpl()
{
reset();
}
public final void setVOHelper(VOHelper voHelper)
{
this.voHelper = voHelper;
}
public final MessagePackObject getData()
{
return data;
}
public final boolean isFinished()
{
return finished;
}
public final void resetState() {
cs = CS_HEADER;
top = -1;
top_ct = 0;
top_count = 0;
top_obj = null;
}
public final void reset()
{
resetState();
finished = false;
data = null;
}
@SuppressWarnings("unchecked")
public final int execute(byte[] src, int off, int length) throws UnpackException
{
if(off >= length) { return off; }
int limit = length;
int i = off;
int count;
Object obj = null;
_out: do {
_header_again_without_cs_reset: { _header_again: {
//System.out.println("while i:"+i+" limit:"+limit);
int b = src[i];
_push: {
_fixed_trail_again:
if(cs == CS_HEADER) {
if((b & 0x80) == 0) { // Positive Fixnum
//System.out.println("positive fixnum "+b);
obj = IntegerType.create((byte)b);
break _push;
}
if((b & 0xe0) == 0xe0) { // Negative Fixnum
//System.out.println("negative fixnum "+b);
obj = IntegerType.create((byte)b);
break _push;
}
if((b & 0xe0) == 0xa0) { // FixRaw
trail = b & 0x1f;
if(trail == 0) {
obj = RawType.create(new byte[0]);
break _push;
}
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
}
if((b & 0xf0) == 0x90) { // FixArray
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
count = b & 0x0f;
//System.out.println("fixarray count:"+count);
obj = new MessagePackObject[count];
if(count == 0) {
obj = ArrayType.create((MessagePackObject[])obj);
break _push;
}
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_ARRAY_ITEM;
top_count = count;
break _header_again;
}
if((b & 0xf0) == 0x80) { // FixMap
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
count = b & 0x0f;
obj = new MessagePackObject[count*2];
if(count == 0) {
obj = MapType.create((MessagePackObject[])obj);
break _push;
}
//System.out.println("fixmap count:"+count);
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_MAP_KEY;
top_count = count;
break _header_again;
}
switch(b & 0xff) { // FIXME
case 0xc0: // nil
obj = NilType.create();
break _push;
case 0xc2: // false
obj = BooleanType.create(false);
break _push;
case 0xc3: // true
obj = BooleanType.create(true);
break _push;
case 0xca: // float
case 0xcb: // double
case 0xcc: // unsigned int 8
case 0xcd: // unsigned int 16
case 0xce: // unsigned int 32
case 0xcf: // unsigned int 64
case 0xd0: // signed int 8
case 0xd1: // signed int 16
case 0xd2: // signed int 32
case 0xd3: // signed int 64
trail = 1 << (b & 0x03);
cs = b & 0x1f;
//System.out.println("a trail "+trail+" cs:"+cs);
break _fixed_trail_again;
case 0xda: // raw 16
case 0xdb: // raw 32
case 0xdc: // array 16
case 0xdd: // array 32
case 0xde: // map 16
case 0xdf: // map 32
trail = 2 << (b & 0x01);
cs = b & 0x1f;
//System.out.println("b trail "+trail+" cs:"+cs);
break _fixed_trail_again;
case 0xd7: // ValueObject
//System.out.println(top + " valueobject:start | (push top)");
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = voHelper.newObject();
top_ct = -1;
top_count = -1;
trail = 3; // of 2? header + typeID (max 2 bytes)
cs = CS_VO_HEADER;
break _fixed_trail_again;
default:
//System.out.println("unknown b "+(b&0xff));
throw new UnpackException("parse error");
}
} // _fixed_trail_again
do {
_fixed_trail_again: {
if(limit - i <= trail) { break _out; }
int n = i + 1;
i += trail;
switch(cs) {
case CS_FLOAT:
castBuffer.rewind();
castBuffer.put(src, n, 4);
obj = FloatType.create( castBuffer.getFloat(0) );
//System.out.println("float "+obj);
break _push;
case CS_DOUBLE:
castBuffer.rewind();
castBuffer.put(src, n, 8);
obj = FloatType.create( castBuffer.getDouble(0) );
//System.out.println("double "+obj);
break _push;
case CS_UINT_8:
//System.out.println(n);
//System.out.println(src[n]);
//System.out.println(src[n+1]);
//System.out.println(src[n-1]);
obj = IntegerType.create( (short)((src[n]) & 0xff) );
//System.out.println("uint8 "+obj);
break _push;
case CS_UINT_16:
//System.out.println(src[n]);
//System.out.println(src[n+1]);
castBuffer.rewind();
castBuffer.put(src, n, 2);
obj = IntegerType.create( ((int)castBuffer.getShort(0)) & 0xffff );
//System.out.println("uint 16 "+obj);
break _push;
case CS_UINT_32:
castBuffer.rewind();
castBuffer.put(src, n, 4);
obj = IntegerType.create( ((long)castBuffer.getInt(0)) & 0xffffffffL );
//System.out.println("uint 32 "+obj);
break _push;
case CS_UINT_64:
castBuffer.rewind();
castBuffer.put(src, n, 8);
{
long o = castBuffer.getLong(0);
if(o < 0) {
obj = IntegerType.create(new BigInteger(1, castBuffer.array()));
} else {
obj = IntegerType.create(o);
}
}
break _push;
case CS_INT_8:
obj = IntegerType.create( src[n] );
break _push;
case CS_INT_16:
castBuffer.rewind();
castBuffer.put(src, n, 2);
obj = IntegerType.create( castBuffer.getShort(0) );
break _push;
case CS_INT_32:
castBuffer.rewind();
castBuffer.put(src, n, 4);
obj = IntegerType.create( castBuffer.getInt(0) );
break _push;
case CS_INT_64:
castBuffer.rewind();
castBuffer.put(src, n, 8);
obj = IntegerType.create( castBuffer.getLong(0) );
break _push;
case CS_RAW_16:
castBuffer.rewind();
castBuffer.put(src, n, 2);
trail = ((int)castBuffer.getShort(0)) & 0xffff;
if(trail == 0) {
obj = RawType.create(new byte[0]);
break _push;
}
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
case CS_RAW_32:
castBuffer.rewind();
castBuffer.put(src, n, 4);
// FIXME overflow check
trail = castBuffer.getInt(0) & 0x7fffffff;
if(trail == 0) {
obj = RawType.create(new byte[0]);
break _push;
}
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
case ACS_RAW_VALUE: {
// TODO zero-copy buffer
byte[] raw = new byte[trail];
System.arraycopy(src, n, raw, 0, trail);
obj = RawType.create(raw);
}
break _push;
case CS_ARRAY_16:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 2);
count = ((int)castBuffer.getShort(0)) & 0xffff;
obj = new MessagePackObject[count];
if(count == 0) {
obj = ArrayType.create((MessagePackObject[])obj);
break _push;
}
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_ARRAY_ITEM;
top_count = count;
break _header_again;
case CS_ARRAY_32:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 4);
// FIXME overflow check
count = castBuffer.getInt(0) & 0x7fffffff;
obj = new MessagePackObject[count];
if(count == 0) {
obj = ArrayType.create((MessagePackObject[])obj);
break _push;
}
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_ARRAY_ITEM;
top_count = count;
break _header_again;
case CS_MAP_16:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 2);
count = ((int)castBuffer.getShort(0)) & 0xffff;
obj = new MessagePackObject[count*2];
if(count == 0) {
obj = MapType.create((MessagePackObject[])obj);
break _push;
}
//System.out.println("fixmap count:"+count);
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_MAP_KEY;
top_count = count;
break _header_again;
case CS_MAP_32:
if(top >= MAX_STACK_SIZE) {
throw new UnpackException("parse error");
}
castBuffer.rewind();
castBuffer.put(src, n, 4);
// FIXME overflow check
count = castBuffer.getInt(0) & 0x7fffffff;
obj = new MessagePackObject[count*2];
if(count == 0) {
obj = MapType.create((MessagePackObject[])obj);
break _push;
}
//System.out.println("fixmap count:"+count);
++top;
stack_obj[top] = top_obj;
stack_ct[top] = top_ct;
stack_count[top] = top_count;
top_obj = obj;
top_ct = CT_MAP_KEY;
top_count = count;
break _header_again;
case CS_VO_HEADER: {
VOInstance vo = (VOInstance) top_obj;
int header = src[n];
if (header >= 0) // first (sign) bit not set
{
// Custom value type (not a value-object)
count = vo.processValueType(header);
if(limit - n <= count) {
trail = count + 1;
i = n - 1;
break _out; // try again later when sufficient data is available
}
i = n + count;
vo.putValue(src, n);
//System.out.println(top + " \\_ -> pop stack | custom value done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
count = header & 0x07; // property byte-flags count
int typeID;
if (0 == (header & 0x40)) { // single byte typeID
--i; // go back one, as trail was guessed as 3
typeID = ((src[n+1]) & 0xff);
} else {
castBuffer.rewind();
castBuffer.put(src, n+1, 2);
typeID = ((int)castBuffer.getShort(0)) & 0xffff;
}
/*System.out.println(top + " valueobject:header | firstbyte = "+ header +
", mixins = "+ mixinCount +
", property-sets = "+ count +
", typeID = "+ typeID);
*/
vo.prepareValueObject(typeID);
vo.incrementMixinCount((header & 0x38 /* 0b_0011_1000 */) >>> 3); // kan dus<SUF>
if ((top_count = count) > 0) {
trail = 1;
cs = CS_VO_FIELDS;
//System.out.println(top + " \\_ CS_VO_FIELDS | count = " + count);
break _fixed_trail_again;
}
// else if
if (vo.mixinDataRemains()) {
vo.nextMixin();
//System.out.println(top + " \\_ -> mixin | count = " + count + " trail = "+trail);
trail = 3; //bytes: 1 header, 2 type id (of 1 type id + iets aan data)
break _fixed_trail_again;
}
// else, object complete
//System.out.println(top + " \\_ -> pop stack | vo done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
case CS_VO_FIELDS: {
//System.out.println(top + " valueobject:fields");
// read 1 byte (field-group of max 8 values)
VOInstance vo = (VOInstance) top_obj;
vo.prepareForNext8Fields(src[i]);
if (src[i] != 0) {// && vo.fieldgroupRequiresMoreValues()) {
top_ct = CT_VO_VALUES;
break _header_again;
}
else if (--top_count == 0) // if 0: No more property groups for this type
{
//System.out.println(top + " \\_ -> no more field groups");
if (!vo.mixinDataRemains()) {
// else, object complete
//System.out.println(top + " \\_ -> pop stack | vo done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
// else
vo.nextMixin();
trail = 3;
cs = CS_VO_HEADER; // process next mixin
}
break _fixed_trail_again;
}
default:
throw new UnpackException("parse error");
}
} // _fixed_trail_again
} while(true);
} // _push
do {
_push: {
//System.out.println("push top:"+top);
if(top == -1) {
++i;
data = (MessagePackObject)obj;
finished = true;
break _out;
}
switch(top_ct) {
case CT_ARRAY_ITEM: {
//System.out.println("array item "+obj);
Object[] ar = (Object[])top_obj;
ar[ar.length - top_count] = obj;
if(--top_count == 0) {
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
obj = ArrayType.create((MessagePackObject[])ar);
stack_obj[top] = null;
--top;
break _push;
}
break _header_again;
}
case CT_MAP_KEY: {
//System.out.println("map key:"+top+" "+obj);
Object[] mp = (Object[])top_obj;
mp[mp.length - top_count*2] = obj;
top_ct = CT_MAP_VALUE;
break _header_again;
}
case CT_MAP_VALUE: {
//System.out.println("map value:"+top+" "+obj);
Object[] mp = (Object[])top_obj;
mp[mp.length - top_count*2 + 1] = obj;
if(--top_count == 0) {
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
obj = MapType.create((MessagePackObject[])mp);
stack_obj[top] = null;
--top;
break _push;
}
top_ct = CT_MAP_KEY;
break _header_again;
}
case CT_VO_VALUES: {
//System.out.println(top + " valueobject:values");
VOInstance vo = (VOInstance) top_obj;
vo.putValue(obj);
if (vo.fieldgroupRequiresMoreValues()) {
//System.out.println(top + " \\_ -> CT_VO_VALUES -> requires more values");
break _header_again;
}
// else
if (--top_count == 0)
{
//System.out.println(top + " \\_ -> no more field groups");
if (vo.mixinDataRemains()) {
vo.nextMixin();
trail = 3;
cs = CS_VO_HEADER; // process next mixin
break _header_again_without_cs_reset;
}
// else, value-object complete, POP stack
//System.out.println(top + " \\_ -> pop stack | vo done");
top_obj = stack_obj[top];
top_ct = stack_ct[top];
top_count = stack_count[top];
stack_obj[top] = null;
--top;
obj = vo.getData();
break _push;
}
// else next set of properties
//System.out.println(top + " \\_ -> CT_VO_VALUES -> next set of properties");
trail = 1;
cs = CS_VO_FIELDS;
break _header_again_without_cs_reset;
}
default:
throw new UnpackException("parse error");
}
} // _push
} while(true);
} // _header_again
cs = CS_HEADER;
++i;
} // _header_again_without_cs_reset
} while(i < limit); // _out
return i;
}
}
|
67131_3 | package KartoffelKanaalPlugin.plugin.kartoffelsystems.PulserSystem;
import KartoffelKanaalPlugin.plugin.AdvancedChat;
import KartoffelKanaalPlugin.plugin.AttribSystem;
import KartoffelKanaalPlugin.plugin.StoreTechnics;
import KartoffelKanaalPlugin.plugin.kartoffelsystems.PlayerSystem.Person;
import org.bukkit.command.CommandSender;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.logging.Logger;
public abstract class PNTechTextProvFormatted extends PNTechTextProv {
protected String[] parameters;
protected PNTechTextProvFormatted(byte[] src) {
super(src);
this.initialize(src);
}
protected PNTechTextProvFormatted(String[] parameters, boolean invisible, int ID, PulserNotifStandard base){
super(invisible, ID, base);
if(parameters == null)parameters = new String[0];
if(parameters.length > 100){
String[] newparams = new String[100];
System.arraycopy(parameters, 0, newparams, 0, 100);
}
this.parameters = parameters;
}
@Override
public String getTypeName(){
return super.getTypeName() + "Formatted";
}
public byte getTextProvType(){return 2;}
public abstract byte getFormattedType();
protected abstract byte getCorrectAmountParameters();
protected abstract boolean isSectionSignFormatAccepted(int index);
protected abstract int getNamedParameterIndex(String key);
protected boolean setParameter(int index, String value){
if(index < 0 || index >= this.parameters.length)return false;
parameters[index] = value;
this.notifyChange();
this.onParametersChanged();
return true;
}
protected boolean setNamedParameter(String key, String value){
int index = this.getNamedParameterIndex(key);
return this.setParameter(index, value);
}
protected abstract void onParametersChanged();
protected abstract byte getParameterViewAccessLevel();
protected abstract byte getParameterChangeAccessLevel(int paramID);
protected abstract String[] getPossibleKeys();
public String[] copyParameters(){
if(this.parameters == null)return new String[this.getCorrectAmountParameters()];
String[] s = new String[this.parameters.length];
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] != null)s[i] = new String(this.parameters[i]);
}
return s;
}
@Override
public int getEstimatedSize(){
if(this.parameters == null)return PNTechTextProvFormatted.generalInfoLength();
int l = this.parameters.length * 2;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)continue;
l += this.parameters[i].length();
}
return PNTechTextProvFormatted.generalInfoLength() + l;
}
protected static PNTechTextProvFormatted loadFromBytes(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return null;
byte t = src[PNTechTextProv.generalInfoLength()];//De hoogste bit hoeft er niet afgehaald te worden aangezien die geen functie heeft en dus niet gebruikt zo mogen worden. Als de hoogste bit dus voor verwarring zorgt, betekent dat dat er iets fout is.
if(t == 1){
return new PNTechTextProvFormattedVideo(src);
}
//System.out.println(" PNTechTextProvFormatted.loadFromBytes: PNTechTextProv geladen, onbekend TextProvType: " + t);
return null;
}
protected void initialize(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return;
byte[][] a = StoreTechnics.loadArrayShort(src, 100, (short) 5000, PNTechTextProvFormatted.generalInfoLength());
this.parameters = new String[a.length];
ByteArrayOutputStream b = new ByteArrayOutputStream();
for(int i = 0; i < a.length; i++){
if(a[i].length == 0)return;
try {
b.write(a[i]);
} catch (IOException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Een byte-array kon niet naar een ByteArrayOutputStream geschreven worden om het te converteren naar een String bij een PNTechTextProvFormatted: " + e.getMessage());
}
try {
this.parameters[i] = b.toString("UTF8");
} catch (UnsupportedEncodingException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] De Encoding \"UTF8\" wordt niet herkend (PNTechTextProvFormatted): " + e.getMessage());
}
b.reset();
}
try {
b.close();
} catch (IOException e) {}
}
@Override
protected byte[] saveTech(){//Dit is zonder de eerste byte van type
/*byte[] paramsarray;
{
int paramssize = 2 * parameters.length;
byte[][] params = new byte[this.parameters.length][];
int alength = 0;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)this.parameters[i] = "";
if(this.parameters[i].length() > 2500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is een parameters geskipt omdat die te lang was");
params[i] = new byte[0];
continue;
}
alength += this.parameters[i].length();
if(alength > 4500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er gestopt met bewaren vanwege een te lange totale lengte van parmaeters");
for(; i < this.parameters.length; i++){
params[i] = new byte[0];
}
break;
}
paramssize += this.parameters[i].length();
try {
params[i] = this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er een UnsuportedException opgedoken: " + e.getMessage());
}
}
paramsarray = new byte[paramssize];
int pos = 0;
for(int i = 0; i < params.length; i++){
paramsarray[pos++] = (byte) ((params[i].length >>> 8) & 0xFF);
paramsarray[pos++] = (byte) (params[i].length & 0xFF);
System.arraycopy(params[i], 0, paramsarray, pos, params[i].length);
pos += params[i].length;
}
}
byte[] array = new byte[6 + paramsarray.length];
array[0] = 1;
array[1] = format;
array[2] = (byte)((paramsarray.length >>> 24) & 0xFF);
array[3] = (byte)((paramsarray.length >>> 16) & 0xFF);
array[4] = (byte)((paramsarray.length >>> 8) & 0xFF);
array[5] = (byte)( paramsarray.length & 0xFF);
*/
byte[] params;
if(this.parameters == null){
params = new byte[0];
}else{
int l = this.parameters.length;
if(l > 100)l = 100;
byte[][] paramdata = new byte[l][];
for(int i = 0; i < l; i++){
try {
paramdata[i] = (this.parameters[i] == null)?new byte[0]:this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KKP] De Encoding \"UTF8\" is niet herkend bij een PNTechTextProvFormatted");;
paramdata[i] = new byte[0];
}
}
params = StoreTechnics.saveArrayShort(paramdata, 100);
}
byte[] ans = new byte[PNTechTextProvFormatted.generalInfoLength() + params.length];
System.arraycopy(params, 0, ans, PNTechTextProvFormatted.generalInfoLength(), params.length);
this.saveGeneralInfo(ans);
return ans;
}
//protected abstract void changeParameter(byte index, String value);//Hier hoort een validation bij betrokken te zijn of bepaalde parameters niet te lang zijn bv.
protected static int generalInfoLength(){return PNTechTextProv.generalInfoLength() + 1;}
protected boolean saveGeneralInfo(byte[] ans){
if(ans == null || ans.length < PNTechTextProv.generalInfoLength() + 1)return false;
super.saveGeneralInfo(ans);
ans[PNTechTextProv.generalInfoLength()] = this.getFormattedType();
return true;
}
@Override
public boolean handleObjectCommand(Person executor, CommandSender a, AttribSystem attribSys, String[] args) throws Exception {
if(super.handleObjectCommand(executor, a, attribSys, args))return true;
if(args.length < 1){
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §c<parameter> <...>");
return true;
}
if(executor.getSpelerOptions().getOpStatus() < 2){
a.sendMessage("§4Je hebt geen toegang tot dit commando");
return true;
}
args[0] = args[0].toLowerCase();
if(args[0].equals("parameter")){
if(this.notificationBase == null){
throw new Exception("ERROR: De notificationBase is null");
}
if(args.length == 2){
this.notificationBase.checkPermission(this, a, executor, this.getParameterViewAccessLevel());
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
a.sendMessage("§eDe parameter (#" + index + ") \"" + args[1] + "\" is " + ((this.parameters[index] == null || this.parameters[index].length() == 0)?("leeg"):("\"" + this.parameters[index] + "\"")));
}else if(args.length >= 3){
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
this.notificationBase.checkPermission(this, a, executor, this.getParameterChangeAccessLevel(index));
if(args.length == 3 && args[2].equals("leeg")){
if(this.setParameter(index, "")){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar een lege status");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar een lege status");
}
}else{
StringBuilder sb = new StringBuilder();
for(int i = 2; i < args.length - 1; i++){
sb.append(args[i]);
sb.append(' ');
}
sb.append(args[args.length - 1]);
String v = sb.toString();
if(attribSys.hasAttrib("verkleur")){
if(isSectionSignFormatAccepted(index)){
v = AdvancedChat.verkleurUitgebreid(v);
a.sendMessage("§eSectionSign-format is uitgevoerd");
}else{
a.sendMessage("§4SectionSign-format is niet geaccepteerd voor de parameter op index " + index);
}
}
if(this.setParameter(index, v)){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar \"§r§f" + v + "§r§e\"");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar \"§r§f" + v + "§r§4\"");
}
}
}else{
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §cparameter <parameterNaam> [nieuwe waarde]");
}
}else{
return false;
}
return true;
}
@Override
public ArrayList<String> autoCompleteObjectCommand(String[] args, ArrayList<String> a) throws Exception{
a = super.autoCompleteObjectCommand(args, a);
String label = args[0].toLowerCase();
if(args.length == 1){
if("parameter".startsWith(label))a.add("parameter");
}
return a;
}
}
| vkuhlmann/KartoffelKanaalPlugin | plugin/kartoffelsystems/PulserSystem/PNTechTextProvFormatted.java | 3,860 | //Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] De Encoding \"UTF8\" wordt niet herkend (PNTechTextProvFormatted): " + e.getMessage()); | line_comment | nl | package KartoffelKanaalPlugin.plugin.kartoffelsystems.PulserSystem;
import KartoffelKanaalPlugin.plugin.AdvancedChat;
import KartoffelKanaalPlugin.plugin.AttribSystem;
import KartoffelKanaalPlugin.plugin.StoreTechnics;
import KartoffelKanaalPlugin.plugin.kartoffelsystems.PlayerSystem.Person;
import org.bukkit.command.CommandSender;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.logging.Logger;
public abstract class PNTechTextProvFormatted extends PNTechTextProv {
protected String[] parameters;
protected PNTechTextProvFormatted(byte[] src) {
super(src);
this.initialize(src);
}
protected PNTechTextProvFormatted(String[] parameters, boolean invisible, int ID, PulserNotifStandard base){
super(invisible, ID, base);
if(parameters == null)parameters = new String[0];
if(parameters.length > 100){
String[] newparams = new String[100];
System.arraycopy(parameters, 0, newparams, 0, 100);
}
this.parameters = parameters;
}
@Override
public String getTypeName(){
return super.getTypeName() + "Formatted";
}
public byte getTextProvType(){return 2;}
public abstract byte getFormattedType();
protected abstract byte getCorrectAmountParameters();
protected abstract boolean isSectionSignFormatAccepted(int index);
protected abstract int getNamedParameterIndex(String key);
protected boolean setParameter(int index, String value){
if(index < 0 || index >= this.parameters.length)return false;
parameters[index] = value;
this.notifyChange();
this.onParametersChanged();
return true;
}
protected boolean setNamedParameter(String key, String value){
int index = this.getNamedParameterIndex(key);
return this.setParameter(index, value);
}
protected abstract void onParametersChanged();
protected abstract byte getParameterViewAccessLevel();
protected abstract byte getParameterChangeAccessLevel(int paramID);
protected abstract String[] getPossibleKeys();
public String[] copyParameters(){
if(this.parameters == null)return new String[this.getCorrectAmountParameters()];
String[] s = new String[this.parameters.length];
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] != null)s[i] = new String(this.parameters[i]);
}
return s;
}
@Override
public int getEstimatedSize(){
if(this.parameters == null)return PNTechTextProvFormatted.generalInfoLength();
int l = this.parameters.length * 2;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)continue;
l += this.parameters[i].length();
}
return PNTechTextProvFormatted.generalInfoLength() + l;
}
protected static PNTechTextProvFormatted loadFromBytes(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return null;
byte t = src[PNTechTextProv.generalInfoLength()];//De hoogste bit hoeft er niet afgehaald te worden aangezien die geen functie heeft en dus niet gebruikt zo mogen worden. Als de hoogste bit dus voor verwarring zorgt, betekent dat dat er iets fout is.
if(t == 1){
return new PNTechTextProvFormattedVideo(src);
}
//System.out.println(" PNTechTextProvFormatted.loadFromBytes: PNTechTextProv geladen, onbekend TextProvType: " + t);
return null;
}
protected void initialize(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return;
byte[][] a = StoreTechnics.loadArrayShort(src, 100, (short) 5000, PNTechTextProvFormatted.generalInfoLength());
this.parameters = new String[a.length];
ByteArrayOutputStream b = new ByteArrayOutputStream();
for(int i = 0; i < a.length; i++){
if(a[i].length == 0)return;
try {
b.write(a[i]);
} catch (IOException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Een byte-array kon niet naar een ByteArrayOutputStream geschreven worden om het te converteren naar een String bij een PNTechTextProvFormatted: " + e.getMessage());
}
try {
this.parameters[i] = b.toString("UTF8");
} catch (UnsupportedEncodingException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] De<SUF>
}
b.reset();
}
try {
b.close();
} catch (IOException e) {}
}
@Override
protected byte[] saveTech(){//Dit is zonder de eerste byte van type
/*byte[] paramsarray;
{
int paramssize = 2 * parameters.length;
byte[][] params = new byte[this.parameters.length][];
int alength = 0;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)this.parameters[i] = "";
if(this.parameters[i].length() > 2500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is een parameters geskipt omdat die te lang was");
params[i] = new byte[0];
continue;
}
alength += this.parameters[i].length();
if(alength > 4500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er gestopt met bewaren vanwege een te lange totale lengte van parmaeters");
for(; i < this.parameters.length; i++){
params[i] = new byte[0];
}
break;
}
paramssize += this.parameters[i].length();
try {
params[i] = this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er een UnsuportedException opgedoken: " + e.getMessage());
}
}
paramsarray = new byte[paramssize];
int pos = 0;
for(int i = 0; i < params.length; i++){
paramsarray[pos++] = (byte) ((params[i].length >>> 8) & 0xFF);
paramsarray[pos++] = (byte) (params[i].length & 0xFF);
System.arraycopy(params[i], 0, paramsarray, pos, params[i].length);
pos += params[i].length;
}
}
byte[] array = new byte[6 + paramsarray.length];
array[0] = 1;
array[1] = format;
array[2] = (byte)((paramsarray.length >>> 24) & 0xFF);
array[3] = (byte)((paramsarray.length >>> 16) & 0xFF);
array[4] = (byte)((paramsarray.length >>> 8) & 0xFF);
array[5] = (byte)( paramsarray.length & 0xFF);
*/
byte[] params;
if(this.parameters == null){
params = new byte[0];
}else{
int l = this.parameters.length;
if(l > 100)l = 100;
byte[][] paramdata = new byte[l][];
for(int i = 0; i < l; i++){
try {
paramdata[i] = (this.parameters[i] == null)?new byte[0]:this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KKP] De Encoding \"UTF8\" is niet herkend bij een PNTechTextProvFormatted");;
paramdata[i] = new byte[0];
}
}
params = StoreTechnics.saveArrayShort(paramdata, 100);
}
byte[] ans = new byte[PNTechTextProvFormatted.generalInfoLength() + params.length];
System.arraycopy(params, 0, ans, PNTechTextProvFormatted.generalInfoLength(), params.length);
this.saveGeneralInfo(ans);
return ans;
}
//protected abstract void changeParameter(byte index, String value);//Hier hoort een validation bij betrokken te zijn of bepaalde parameters niet te lang zijn bv.
protected static int generalInfoLength(){return PNTechTextProv.generalInfoLength() + 1;}
protected boolean saveGeneralInfo(byte[] ans){
if(ans == null || ans.length < PNTechTextProv.generalInfoLength() + 1)return false;
super.saveGeneralInfo(ans);
ans[PNTechTextProv.generalInfoLength()] = this.getFormattedType();
return true;
}
@Override
public boolean handleObjectCommand(Person executor, CommandSender a, AttribSystem attribSys, String[] args) throws Exception {
if(super.handleObjectCommand(executor, a, attribSys, args))return true;
if(args.length < 1){
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §c<parameter> <...>");
return true;
}
if(executor.getSpelerOptions().getOpStatus() < 2){
a.sendMessage("§4Je hebt geen toegang tot dit commando");
return true;
}
args[0] = args[0].toLowerCase();
if(args[0].equals("parameter")){
if(this.notificationBase == null){
throw new Exception("ERROR: De notificationBase is null");
}
if(args.length == 2){
this.notificationBase.checkPermission(this, a, executor, this.getParameterViewAccessLevel());
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
a.sendMessage("§eDe parameter (#" + index + ") \"" + args[1] + "\" is " + ((this.parameters[index] == null || this.parameters[index].length() == 0)?("leeg"):("\"" + this.parameters[index] + "\"")));
}else if(args.length >= 3){
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
this.notificationBase.checkPermission(this, a, executor, this.getParameterChangeAccessLevel(index));
if(args.length == 3 && args[2].equals("leeg")){
if(this.setParameter(index, "")){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar een lege status");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar een lege status");
}
}else{
StringBuilder sb = new StringBuilder();
for(int i = 2; i < args.length - 1; i++){
sb.append(args[i]);
sb.append(' ');
}
sb.append(args[args.length - 1]);
String v = sb.toString();
if(attribSys.hasAttrib("verkleur")){
if(isSectionSignFormatAccepted(index)){
v = AdvancedChat.verkleurUitgebreid(v);
a.sendMessage("§eSectionSign-format is uitgevoerd");
}else{
a.sendMessage("§4SectionSign-format is niet geaccepteerd voor de parameter op index " + index);
}
}
if(this.setParameter(index, v)){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar \"§r§f" + v + "§r§e\"");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar \"§r§f" + v + "§r§4\"");
}
}
}else{
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §cparameter <parameterNaam> [nieuwe waarde]");
}
}else{
return false;
}
return true;
}
@Override
public ArrayList<String> autoCompleteObjectCommand(String[] args, ArrayList<String> a) throws Exception{
a = super.autoCompleteObjectCommand(args, a);
String label = args[0].toLowerCase();
if(args.length == 1){
if("parameter".startsWith(label))a.add("parameter");
}
return a;
}
}
|
173309_3 | /*
* Copyright 2008-2013 LinkedIn, 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 voldemort.server.scheduler;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.annotations.jmx.JmxGetter;
import voldemort.server.storage.ScanPermitWrapper;
import voldemort.store.StorageEngine;
import voldemort.store.StoreDefinition;
import voldemort.store.metadata.MetadataStore;
import voldemort.store.metadata.MetadataStore.VoldemortState;
import voldemort.utils.ClosableIterator;
import voldemort.utils.EventThrottler;
import voldemort.utils.Pair;
import voldemort.utils.Time;
import voldemort.utils.Utils;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Versioned;
/**
* Expire old data
*
*
*/
public class DataCleanupJob<K, V, T> implements Runnable {
private static final Logger logger = Logger.getLogger(DataCleanupJob.class);
private final StorageEngine<K, V, T> store;
private final ScanPermitWrapper cleanupPermits;
private final String storeName;
private final Time time;
private long totalEntriesScanned = 0;
private AtomicLong scanProgressThisRun;
private long totalEntriesDeleted = 0;
private AtomicLong deleteProgressThisRun;
private MetadataStore metadataStore;
public DataCleanupJob(StorageEngine<K, V, T> store,
ScanPermitWrapper cleanupPermits,
String storeName,
Time time,
MetadataStore metadataStore) {
this.store = Utils.notNull(store);
this.cleanupPermits = Utils.notNull(cleanupPermits);
this.storeName = Utils.notNull(storeName);
this.time = Utils.notNull(time);
this.metadataStore = Utils.notNull(metadataStore);
this.scanProgressThisRun = new AtomicLong(0);
this.deleteProgressThisRun = new AtomicLong(0);
}
private boolean isServerInNormalState() {
if(metadataStore != null
&& metadataStore.getServerStateUnlocked() != VoldemortState.NORMAL_SERVER) {
logger.info("Datacleanup on store " + store.getName()
+ " skipped since server is not normal..");
return false;
}
return true;
}
private boolean isServerInOfflineState() {
if(metadataStore != null
&& metadataStore.getServerStateUnlocked() != VoldemortState.OFFLINE_SERVER) {
logger.info("Datacleanup on store " + store.getName()
+ " skipped since server is not offline..");
return false;
}
return true;
}
@Override
public void run() {
// if the server is neither normal nor offline , skip this run.
if(!isServerInNormalState() && !isServerInOfflineState()) {
return;
}
StoreDefinition storeDef = null;
try {
storeDef = MetadataStore.getStoreDef(storeName, metadataStore);
} catch (VoldemortException ex) {
logger.info("Error retrieving store " + storeName + " for data cleanup job ", ex);
return;
}
Integer retentionDays = storeDef.getRetentionDays();
if (retentionDays == null || retentionDays <= 0) {
logger.info("Store " + storeName
+ " does not have retention period set, skipping cleanup job . RetentionDays " + retentionDays);
return;
}
long maxAgeMs = retentionDays * Time.MS_PER_DAY;
logger.info("Store " + storeName + " cleanup job is starting with RetentionDays " + retentionDays);
acquireCleanupPermit(scanProgressThisRun, deleteProgressThisRun);
ClosableIterator<Pair<K, Versioned<V>>> iterator = null;
try {
int maxReadRate = storeDef.hasRetentionScanThrottleRate() ? storeDef.getRetentionScanThrottleRate()
: Integer.MAX_VALUE;
EventThrottler throttler = new EventThrottler(maxReadRate);
store.beginBatchModifications();
logger.info("Starting data cleanup on store \"" + store.getName() + "\"...");
long now = time.getMilliseconds();
iterator = store.entries();
while(iterator.hasNext()) {
// check if we have been interrupted
if(Thread.currentThread().isInterrupted()) {
logger.info("Datacleanup job halted.");
return;
}
final long INETERVAL = 10000;
long entriesScanned = scanProgressThisRun.get();
if(entriesScanned % INETERVAL == 0) {
if(!isServerInNormalState() && !isServerInOfflineState()) {
return;
}
}
scanProgressThisRun.incrementAndGet();
Pair<K, Versioned<V>> keyAndVal = iterator.next();
VectorClock clock = (VectorClock) keyAndVal.getSecond().getVersion();
if(now - clock.getTimestamp() > maxAgeMs) {
store.delete(keyAndVal.getFirst(), clock);
final long entriesDeleted = this.deleteProgressThisRun.incrementAndGet();
if(logger.isDebugEnabled() && entriesDeleted % INETERVAL == 0) {
logger.debug("Deleted item " + this.deleteProgressThisRun.get());
}
}
// throttle on number of entries.
throttler.maybeThrottle(1);
}
// log the total items scanned, so we will get an idea of data
// growth in a cheap, periodic way
logger.info("Data cleanup on store \"" + store.getName() + "\" is complete; "
+ this.deleteProgressThisRun.get() + " items deleted. "
+ scanProgressThisRun.get() + " items scanned");
} catch(Exception e) {
logger.error("Error in data cleanup job for store " + store.getName() + ": ", e);
} finally {
closeIterator(iterator);
logger.info("Releasing lock after data cleanup on \"" + store.getName() + "\".");
this.cleanupPermits.release(this.getClass().getCanonicalName());
synchronized(this) {
totalEntriesScanned += scanProgressThisRun.get();
scanProgressThisRun.set(0);
totalEntriesDeleted += deleteProgressThisRun.get();
deleteProgressThisRun.set(0);
}
store.endBatchModifications();
}
}
private void closeIterator(ClosableIterator<Pair<K, Versioned<V>>> iterator) {
try {
if(iterator != null)
iterator.close();
} catch(Exception e) {
logger.error("Error in closing iterator " + store.getName() + " ", e);
}
}
private void acquireCleanupPermit(AtomicLong scanProgress, AtomicLong deleteProgress) {
logger.info("Acquiring lock to perform data cleanup on \"" + store.getName() + "\".");
try {
this.cleanupPermits.acquire(scanProgress, deleteProgress, this.getClass()
.getCanonicalName());
} catch(InterruptedException e) {
throw new IllegalStateException("Datacleanup interrupted while waiting for cleanup permit.",
e);
}
}
@JmxGetter(name = "numEntriesScanned", description = "Returns number of entries scanned")
public synchronized long getEntriesScanned() {
return totalEntriesScanned + scanProgressThisRun.get();
}
@JmxGetter(name = "numEntriesDeleted", description = "Returns number of entries deleted")
public synchronized long getEntriesDeleted() {
return totalEntriesDeleted + deleteProgressThisRun.get();
}
}
| voldemort/voldemort | src/java/voldemort/server/scheduler/DataCleanupJob.java | 2,265 | // check if we have been interrupted | line_comment | nl | /*
* Copyright 2008-2013 LinkedIn, 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 voldemort.server.scheduler;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.annotations.jmx.JmxGetter;
import voldemort.server.storage.ScanPermitWrapper;
import voldemort.store.StorageEngine;
import voldemort.store.StoreDefinition;
import voldemort.store.metadata.MetadataStore;
import voldemort.store.metadata.MetadataStore.VoldemortState;
import voldemort.utils.ClosableIterator;
import voldemort.utils.EventThrottler;
import voldemort.utils.Pair;
import voldemort.utils.Time;
import voldemort.utils.Utils;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Versioned;
/**
* Expire old data
*
*
*/
public class DataCleanupJob<K, V, T> implements Runnable {
private static final Logger logger = Logger.getLogger(DataCleanupJob.class);
private final StorageEngine<K, V, T> store;
private final ScanPermitWrapper cleanupPermits;
private final String storeName;
private final Time time;
private long totalEntriesScanned = 0;
private AtomicLong scanProgressThisRun;
private long totalEntriesDeleted = 0;
private AtomicLong deleteProgressThisRun;
private MetadataStore metadataStore;
public DataCleanupJob(StorageEngine<K, V, T> store,
ScanPermitWrapper cleanupPermits,
String storeName,
Time time,
MetadataStore metadataStore) {
this.store = Utils.notNull(store);
this.cleanupPermits = Utils.notNull(cleanupPermits);
this.storeName = Utils.notNull(storeName);
this.time = Utils.notNull(time);
this.metadataStore = Utils.notNull(metadataStore);
this.scanProgressThisRun = new AtomicLong(0);
this.deleteProgressThisRun = new AtomicLong(0);
}
private boolean isServerInNormalState() {
if(metadataStore != null
&& metadataStore.getServerStateUnlocked() != VoldemortState.NORMAL_SERVER) {
logger.info("Datacleanup on store " + store.getName()
+ " skipped since server is not normal..");
return false;
}
return true;
}
private boolean isServerInOfflineState() {
if(metadataStore != null
&& metadataStore.getServerStateUnlocked() != VoldemortState.OFFLINE_SERVER) {
logger.info("Datacleanup on store " + store.getName()
+ " skipped since server is not offline..");
return false;
}
return true;
}
@Override
public void run() {
// if the server is neither normal nor offline , skip this run.
if(!isServerInNormalState() && !isServerInOfflineState()) {
return;
}
StoreDefinition storeDef = null;
try {
storeDef = MetadataStore.getStoreDef(storeName, metadataStore);
} catch (VoldemortException ex) {
logger.info("Error retrieving store " + storeName + " for data cleanup job ", ex);
return;
}
Integer retentionDays = storeDef.getRetentionDays();
if (retentionDays == null || retentionDays <= 0) {
logger.info("Store " + storeName
+ " does not have retention period set, skipping cleanup job . RetentionDays " + retentionDays);
return;
}
long maxAgeMs = retentionDays * Time.MS_PER_DAY;
logger.info("Store " + storeName + " cleanup job is starting with RetentionDays " + retentionDays);
acquireCleanupPermit(scanProgressThisRun, deleteProgressThisRun);
ClosableIterator<Pair<K, Versioned<V>>> iterator = null;
try {
int maxReadRate = storeDef.hasRetentionScanThrottleRate() ? storeDef.getRetentionScanThrottleRate()
: Integer.MAX_VALUE;
EventThrottler throttler = new EventThrottler(maxReadRate);
store.beginBatchModifications();
logger.info("Starting data cleanup on store \"" + store.getName() + "\"...");
long now = time.getMilliseconds();
iterator = store.entries();
while(iterator.hasNext()) {
// check if<SUF>
if(Thread.currentThread().isInterrupted()) {
logger.info("Datacleanup job halted.");
return;
}
final long INETERVAL = 10000;
long entriesScanned = scanProgressThisRun.get();
if(entriesScanned % INETERVAL == 0) {
if(!isServerInNormalState() && !isServerInOfflineState()) {
return;
}
}
scanProgressThisRun.incrementAndGet();
Pair<K, Versioned<V>> keyAndVal = iterator.next();
VectorClock clock = (VectorClock) keyAndVal.getSecond().getVersion();
if(now - clock.getTimestamp() > maxAgeMs) {
store.delete(keyAndVal.getFirst(), clock);
final long entriesDeleted = this.deleteProgressThisRun.incrementAndGet();
if(logger.isDebugEnabled() && entriesDeleted % INETERVAL == 0) {
logger.debug("Deleted item " + this.deleteProgressThisRun.get());
}
}
// throttle on number of entries.
throttler.maybeThrottle(1);
}
// log the total items scanned, so we will get an idea of data
// growth in a cheap, periodic way
logger.info("Data cleanup on store \"" + store.getName() + "\" is complete; "
+ this.deleteProgressThisRun.get() + " items deleted. "
+ scanProgressThisRun.get() + " items scanned");
} catch(Exception e) {
logger.error("Error in data cleanup job for store " + store.getName() + ": ", e);
} finally {
closeIterator(iterator);
logger.info("Releasing lock after data cleanup on \"" + store.getName() + "\".");
this.cleanupPermits.release(this.getClass().getCanonicalName());
synchronized(this) {
totalEntriesScanned += scanProgressThisRun.get();
scanProgressThisRun.set(0);
totalEntriesDeleted += deleteProgressThisRun.get();
deleteProgressThisRun.set(0);
}
store.endBatchModifications();
}
}
private void closeIterator(ClosableIterator<Pair<K, Versioned<V>>> iterator) {
try {
if(iterator != null)
iterator.close();
} catch(Exception e) {
logger.error("Error in closing iterator " + store.getName() + " ", e);
}
}
private void acquireCleanupPermit(AtomicLong scanProgress, AtomicLong deleteProgress) {
logger.info("Acquiring lock to perform data cleanup on \"" + store.getName() + "\".");
try {
this.cleanupPermits.acquire(scanProgress, deleteProgress, this.getClass()
.getCanonicalName());
} catch(InterruptedException e) {
throw new IllegalStateException("Datacleanup interrupted while waiting for cleanup permit.",
e);
}
}
@JmxGetter(name = "numEntriesScanned", description = "Returns number of entries scanned")
public synchronized long getEntriesScanned() {
return totalEntriesScanned + scanProgressThisRun.get();
}
@JmxGetter(name = "numEntriesDeleted", description = "Returns number of entries deleted")
public synchronized long getEntriesDeleted() {
return totalEntriesDeleted + deleteProgressThisRun.get();
}
}
|
69875_8 | /* MOD_V2.0
* Copyright (c) 2012 OpenDA Association
* All rights reserved.
*
* This file is part of OpenDA.
*
* OpenDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* OpenDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OpenDA. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openda.dotnet;
import cli.OpenDA.DotNet.Bridge.DoublesExchangeItem;
import cli.OpenDA.DotNet.Bridge.ObservationDescriptions;
import org.openda.interfaces.*;
import org.openda.utils.Vector;
import java.io.File;
import java.util.List;
/**
* Java wrapper around .net class for a Model Instance
*/
public class ModelInstanceN2J implements org.openda.interfaces.IModelInstance, IModelExtensions
{
protected cli.OpenDA.DotNet.Interfaces.IModelInstance _dotNetModelInstance;
public ModelInstanceN2J(cli.OpenDA.DotNet.Interfaces.IModelInstance dotNetModelInstance)
{
_dotNetModelInstance = dotNetModelInstance;
}
public ModelInstanceN2J() {
}
public void initialize(File workingDir, String[] arguments) {
// no action needed, taken care of by constructor
}
public org.openda.interfaces.IInstance getParent()
{
return null;
}
public org.openda.interfaces.ITime getTimeHorizon()
{
return new TimeN2J(_dotNetModelInstance.get_TimeHorizon());
}
public org.openda.interfaces.ITime getCurrentTime()
{
return new TimeN2J(_dotNetModelInstance.get_CurrentTime());
}
public void compute(org.openda.interfaces.ITime targetTime)
{
_dotNetModelInstance.Compute(new cli.OpenDA.DotNet.Bridge.Time(targetTime.getMJD()));
}
public IVector[] getObservedLocalization(String exchageItemID, IObservationDescriptions observationDescriptions, double distance) {
// Check whether we are dealing with a C# implemention. No concersion is needed in that case
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
if (observationDescriptions instanceof ObservationDescriptionsJ2N){
dotNetObservationDescriptions= ((ObservationDescriptionsJ2N) observationDescriptions)._dotNetObsDescr;
}
else {
dotNetObservationDescriptions = translateObservationDesciptions(observationDescriptions);
}
/*
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
String [] keys =observationDescriptions.getPropertyKeys();
int nKeys=observationDescriptions.getPropertyCount();
int nObs =observationDescriptions.getObservationCount();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions;
if (nKeys>0 && nObs>0){
String[][] values = new String[nKeys][];
for (int iKey=0; iKey<keys.length; iKey++){
values[iKey] = observationDescriptions.getStringProperties(keys[iKey]);
}
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems,keys,values);
}
else {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems);
}
*/
// Call method
cli.OpenDA.DotNet.Interfaces.IVector[] dotNetVectors =
_dotNetModelInstance.GetObservedLocalization(exchageItemID, dotNetObservationDescriptions, distance);
IVector[] javaVectors = new IVector[dotNetVectors.length];
for (int i = 0; i < dotNetVectors.length; i++) {
javaVectors[i] = new Vector(dotNetVectors[i].get_Values());
}
return javaVectors;
}
public void announceObservedValues(IObservationDescriptions observationDescriptions) {
// no action needed (yet), currently wrapped .net models store all their output in files
// and therefore can always provide requested computed values at observation locations.
}
public ILocalizationDomains getLocalizationDomains(){
throw new UnsupportedOperationException(getClass().getName() + ": getLocalizationDomains not implemented.");
}
public IVector[] getObservedLocalization(IObservationDescriptions observationDescriptions, double distance) {
// Check whether we are dealing with a C# implemention. No concersion is needed in that case
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
if (observationDescriptions instanceof ObservationDescriptionsJ2N){
dotNetObservationDescriptions= ((ObservationDescriptionsJ2N) observationDescriptions)._dotNetObsDescr;
}
else {
dotNetObservationDescriptions = translateObservationDesciptions(observationDescriptions);
}
/*
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions =
new ObservationDescriptions(dotnetExchangeItems);
*/
cli.OpenDA.DotNet.Interfaces.IVector[] dotNetVectors =
_dotNetModelInstance.GetObservedLocalization(dotNetObservationDescriptions, distance);
IVector[] javaVectors = new IVector[dotNetVectors.length];
for (int i = 0; i < dotNetVectors.length; i++) {
javaVectors[i] = new Vector(dotNetVectors[i].get_Values());
}
return javaVectors;
}
public IVector[] getObservedLocalization(IObservationDescriptions observationDescriptions, double distance, int iDomain){
throw new UnsupportedOperationException(getClass().getName() + ": getObservedLocalization for domain not implemented.");
}
public IVector getObservedValues(IObservationDescriptions observationDescriptions) {
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
System.out.println("Nieuw spullen v1.0");
// Check whether we are dealing with a C# implementation. No conversion is needed in that case
if (observationDescriptions instanceof ObservationDescriptionsJ2N){
dotNetObservationDescriptions= ((ObservationDescriptionsJ2N) observationDescriptions)._dotNetObsDescr;
}
else {
dotNetObservationDescriptions = translateObservationDesciptions(observationDescriptions);
}
/*
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
String [] keys =observationDescriptions.getPropertyKeys();
int nKeys=observationDescriptions.getPropertyCount();
int nObs =observationDescriptions.getObservationCount();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
if (nKeys>0 && nObs>0){
String[][] values = new String[nKeys][];
for (int iKey=0; iKey<keys.length; iKey++){
values[iKey] = observationDescriptions.getStringProperties(keys[iKey]);
}
if (values[0].length != 0 && nObs == javaExchangeItems.size()) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems,keys,values);
}
}
if (dotNetObservationDescriptions == null) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems);
}
}
*/
// Call method
cli.OpenDA.DotNet.Interfaces.IVector dotNetVector =
_dotNetModelInstance.GetObservedValues(dotNetObservationDescriptions);
if (dotNetVector == null) {
// dotNet model does not implement IModelExtensions.getObservedValues()
return null;
}
IVector javaVector = new Vector(dotNetVector.get_Values());
return javaVector;
}
public String[] getExchangeItemIDs()
{
return _dotNetModelInstance.get_ExchangeItemIDs();
}
public String[] getExchangeItemIDs(org.openda.interfaces.IPrevExchangeItem.Role role)
{
return _dotNetModelInstance.GetExchangeItemIDs(role.ordinal());
}
public IExchangeItem getDataObjectExchangeItem(String exchangeItemID) {
throw new UnsupportedOperationException("org.openda.dotnet.ModelInstanceN2J.getDataObjectExchangeItem(): Not implemented yet.");
}
public IPrevExchangeItem getExchangeItem(String str)
{
return new ExchangeItemN2J(_dotNetModelInstance.GetExchangeItem(str));
}
public IModelState saveInternalState()
{
return new ModelStateN2J(_dotNetModelInstance.SaveInternalState());
}
public void restoreInternalState(IModelState savedInternalState)
{
if (!(savedInternalState instanceof ModelStateN2J)) {
throw new RuntimeException("Unexpected saved internal state type: " +
savedInternalState.getClass().getName());
}
_dotNetModelInstance.RestoreInternalState(((ModelStateN2J) savedInternalState).getDotNetModelState());
}
public void releaseInternalState(IModelState savedInternalState)
{
if (!(savedInternalState instanceof ModelStateN2J)) {
throw new RuntimeException("Unexpected saved internal state type: " +
savedInternalState.getClass().getName());
}
_dotNetModelInstance.ReleaseInternalState(((ModelStateN2J) savedInternalState).getDotNetModelState());
}
public IModelState loadPersistentState(File persistentStateFile) {
return new ModelStateN2J(_dotNetModelInstance.LoadPersistentState(persistentStateFile.getAbsolutePath()));
}
public java.io.File getModelRunDir()
{
String modelRunDirPath = _dotNetModelInstance.get_ModelRunDirPath();
return modelRunDirPath != null ? new File(modelRunDirPath) : null;
}
public void finish()
{
_dotNetModelInstance.Finish();
}
public String toString()
{
return _dotNetModelInstance.toString();
}
public cli.OpenDA.DotNet.Interfaces.IModelInstance getDotNetModelInstance() {
return _dotNetModelInstance;
}
/**
* Translate an Observation description instance into a C# instance.
* This approach is far from optimal and generic but for now it works
*
* @param observationDescriptions I An observation description instance
*
*/
private cli.OpenDA.DotNet.Interfaces.IObservationDescriptions translateObservationDesciptions(IObservationDescriptions observationDescriptions){
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
String [] keys =observationDescriptions.getPropertyKeys();
int nKeys=observationDescriptions.getPropertyCount();
int nObs =observationDescriptions.getObservationCount();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
if (nKeys>0 && nObs>0){
String[][] values = new String[nKeys][];
for (int iKey=0; iKey<keys.length; iKey++){
values[iKey] = observationDescriptions.getStringProperties(keys[iKey]);
}
if (values[0].length != 0 && nObs == javaExchangeItems.size()) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems,keys,values);
}
}
if (dotNetObservationDescriptions == null) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems);
}
return dotNetObservationDescriptions;
}
}
| vortechbv/OpenDA | dotnet_bridge/java/src/org/openda/dotnet/ModelInstanceN2J.java | 4,306 | /*
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions =
new ObservationDescriptions(dotnetExchangeItems);
*/ | block_comment | nl | /* MOD_V2.0
* Copyright (c) 2012 OpenDA Association
* All rights reserved.
*
* This file is part of OpenDA.
*
* OpenDA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* OpenDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OpenDA. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openda.dotnet;
import cli.OpenDA.DotNet.Bridge.DoublesExchangeItem;
import cli.OpenDA.DotNet.Bridge.ObservationDescriptions;
import org.openda.interfaces.*;
import org.openda.utils.Vector;
import java.io.File;
import java.util.List;
/**
* Java wrapper around .net class for a Model Instance
*/
public class ModelInstanceN2J implements org.openda.interfaces.IModelInstance, IModelExtensions
{
protected cli.OpenDA.DotNet.Interfaces.IModelInstance _dotNetModelInstance;
public ModelInstanceN2J(cli.OpenDA.DotNet.Interfaces.IModelInstance dotNetModelInstance)
{
_dotNetModelInstance = dotNetModelInstance;
}
public ModelInstanceN2J() {
}
public void initialize(File workingDir, String[] arguments) {
// no action needed, taken care of by constructor
}
public org.openda.interfaces.IInstance getParent()
{
return null;
}
public org.openda.interfaces.ITime getTimeHorizon()
{
return new TimeN2J(_dotNetModelInstance.get_TimeHorizon());
}
public org.openda.interfaces.ITime getCurrentTime()
{
return new TimeN2J(_dotNetModelInstance.get_CurrentTime());
}
public void compute(org.openda.interfaces.ITime targetTime)
{
_dotNetModelInstance.Compute(new cli.OpenDA.DotNet.Bridge.Time(targetTime.getMJD()));
}
public IVector[] getObservedLocalization(String exchageItemID, IObservationDescriptions observationDescriptions, double distance) {
// Check whether we are dealing with a C# implemention. No concersion is needed in that case
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
if (observationDescriptions instanceof ObservationDescriptionsJ2N){
dotNetObservationDescriptions= ((ObservationDescriptionsJ2N) observationDescriptions)._dotNetObsDescr;
}
else {
dotNetObservationDescriptions = translateObservationDesciptions(observationDescriptions);
}
/*
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
String [] keys =observationDescriptions.getPropertyKeys();
int nKeys=observationDescriptions.getPropertyCount();
int nObs =observationDescriptions.getObservationCount();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions;
if (nKeys>0 && nObs>0){
String[][] values = new String[nKeys][];
for (int iKey=0; iKey<keys.length; iKey++){
values[iKey] = observationDescriptions.getStringProperties(keys[iKey]);
}
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems,keys,values);
}
else {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems);
}
*/
// Call method
cli.OpenDA.DotNet.Interfaces.IVector[] dotNetVectors =
_dotNetModelInstance.GetObservedLocalization(exchageItemID, dotNetObservationDescriptions, distance);
IVector[] javaVectors = new IVector[dotNetVectors.length];
for (int i = 0; i < dotNetVectors.length; i++) {
javaVectors[i] = new Vector(dotNetVectors[i].get_Values());
}
return javaVectors;
}
public void announceObservedValues(IObservationDescriptions observationDescriptions) {
// no action needed (yet), currently wrapped .net models store all their output in files
// and therefore can always provide requested computed values at observation locations.
}
public ILocalizationDomains getLocalizationDomains(){
throw new UnsupportedOperationException(getClass().getName() + ": getLocalizationDomains not implemented.");
}
public IVector[] getObservedLocalization(IObservationDescriptions observationDescriptions, double distance) {
// Check whether we are dealing with a C# implemention. No concersion is needed in that case
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
if (observationDescriptions instanceof ObservationDescriptionsJ2N){
dotNetObservationDescriptions= ((ObservationDescriptionsJ2N) observationDescriptions)._dotNetObsDescr;
}
else {
dotNetObservationDescriptions = translateObservationDesciptions(observationDescriptions);
}
/*
List<IPrevExchangeItem> javaExchangeItems =<SUF>*/
cli.OpenDA.DotNet.Interfaces.IVector[] dotNetVectors =
_dotNetModelInstance.GetObservedLocalization(dotNetObservationDescriptions, distance);
IVector[] javaVectors = new IVector[dotNetVectors.length];
for (int i = 0; i < dotNetVectors.length; i++) {
javaVectors[i] = new Vector(dotNetVectors[i].get_Values());
}
return javaVectors;
}
public IVector[] getObservedLocalization(IObservationDescriptions observationDescriptions, double distance, int iDomain){
throw new UnsupportedOperationException(getClass().getName() + ": getObservedLocalization for domain not implemented.");
}
public IVector getObservedValues(IObservationDescriptions observationDescriptions) {
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
System.out.println("Nieuw spullen v1.0");
// Check whether we are dealing with a C# implementation. No conversion is needed in that case
if (observationDescriptions instanceof ObservationDescriptionsJ2N){
dotNetObservationDescriptions= ((ObservationDescriptionsJ2N) observationDescriptions)._dotNetObsDescr;
}
else {
dotNetObservationDescriptions = translateObservationDesciptions(observationDescriptions);
}
/*
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
String [] keys =observationDescriptions.getPropertyKeys();
int nKeys=observationDescriptions.getPropertyCount();
int nObs =observationDescriptions.getObservationCount();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
if (nKeys>0 && nObs>0){
String[][] values = new String[nKeys][];
for (int iKey=0; iKey<keys.length; iKey++){
values[iKey] = observationDescriptions.getStringProperties(keys[iKey]);
}
if (values[0].length != 0 && nObs == javaExchangeItems.size()) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems,keys,values);
}
}
if (dotNetObservationDescriptions == null) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems);
}
}
*/
// Call method
cli.OpenDA.DotNet.Interfaces.IVector dotNetVector =
_dotNetModelInstance.GetObservedValues(dotNetObservationDescriptions);
if (dotNetVector == null) {
// dotNet model does not implement IModelExtensions.getObservedValues()
return null;
}
IVector javaVector = new Vector(dotNetVector.get_Values());
return javaVector;
}
public String[] getExchangeItemIDs()
{
return _dotNetModelInstance.get_ExchangeItemIDs();
}
public String[] getExchangeItemIDs(org.openda.interfaces.IPrevExchangeItem.Role role)
{
return _dotNetModelInstance.GetExchangeItemIDs(role.ordinal());
}
public IExchangeItem getDataObjectExchangeItem(String exchangeItemID) {
throw new UnsupportedOperationException("org.openda.dotnet.ModelInstanceN2J.getDataObjectExchangeItem(): Not implemented yet.");
}
public IPrevExchangeItem getExchangeItem(String str)
{
return new ExchangeItemN2J(_dotNetModelInstance.GetExchangeItem(str));
}
public IModelState saveInternalState()
{
return new ModelStateN2J(_dotNetModelInstance.SaveInternalState());
}
public void restoreInternalState(IModelState savedInternalState)
{
if (!(savedInternalState instanceof ModelStateN2J)) {
throw new RuntimeException("Unexpected saved internal state type: " +
savedInternalState.getClass().getName());
}
_dotNetModelInstance.RestoreInternalState(((ModelStateN2J) savedInternalState).getDotNetModelState());
}
public void releaseInternalState(IModelState savedInternalState)
{
if (!(savedInternalState instanceof ModelStateN2J)) {
throw new RuntimeException("Unexpected saved internal state type: " +
savedInternalState.getClass().getName());
}
_dotNetModelInstance.ReleaseInternalState(((ModelStateN2J) savedInternalState).getDotNetModelState());
}
public IModelState loadPersistentState(File persistentStateFile) {
return new ModelStateN2J(_dotNetModelInstance.LoadPersistentState(persistentStateFile.getAbsolutePath()));
}
public java.io.File getModelRunDir()
{
String modelRunDirPath = _dotNetModelInstance.get_ModelRunDirPath();
return modelRunDirPath != null ? new File(modelRunDirPath) : null;
}
public void finish()
{
_dotNetModelInstance.Finish();
}
public String toString()
{
return _dotNetModelInstance.toString();
}
public cli.OpenDA.DotNet.Interfaces.IModelInstance getDotNetModelInstance() {
return _dotNetModelInstance;
}
/**
* Translate an Observation description instance into a C# instance.
* This approach is far from optimal and generic but for now it works
*
* @param observationDescriptions I An observation description instance
*
*/
private cli.OpenDA.DotNet.Interfaces.IObservationDescriptions translateObservationDesciptions(IObservationDescriptions observationDescriptions){
cli.OpenDA.DotNet.Interfaces.IObservationDescriptions dotNetObservationDescriptions = null;
List<IPrevExchangeItem> javaExchangeItems = observationDescriptions.getExchangeItems();
String [] keys =observationDescriptions.getPropertyKeys();
int nKeys=observationDescriptions.getPropertyCount();
int nObs =observationDescriptions.getObservationCount();
cli.OpenDA.DotNet.Interfaces.IExchangeItem[] dotnetExchangeItems =
new cli.OpenDA.DotNet.Interfaces.IExchangeItem[javaExchangeItems.size()];
for (int i = 0; i < javaExchangeItems.size(); i++) {
IPrevExchangeItem javaExchangeItem = javaExchangeItems.get(i);
cli.OpenDA.DotNet.Interfaces.IExchangeItem dotnetExchangeItem =
new DoublesExchangeItem(javaExchangeItem.getId(),
javaExchangeItem.getDescription(),
javaExchangeItem.getRole().ordinal(), 0d);
dotnetExchangeItem.set_Times(javaExchangeItem.getTimes());
dotnetExchangeItem.set_Values(javaExchangeItem.getValuesAsDoubles());
dotnetExchangeItems[i] = dotnetExchangeItem;
}
if (nKeys>0 && nObs>0){
String[][] values = new String[nKeys][];
for (int iKey=0; iKey<keys.length; iKey++){
values[iKey] = observationDescriptions.getStringProperties(keys[iKey]);
}
if (values[0].length != 0 && nObs == javaExchangeItems.size()) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems,keys,values);
}
}
if (dotNetObservationDescriptions == null) {
dotNetObservationDescriptions = new ObservationDescriptions(dotnetExchangeItems);
}
return dotNetObservationDescriptions;
}
}
|
175701_7 | package widgetESlate;
import gr.cti.eslate.base.container.ESlateComposer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.solr.common.util.Base64;
import org.cbook.cbookif.AssessmentMode;
import org.cbook.cbookif.CBookContext;
import org.cbook.cbookif.CBookEvent;
import org.cbook.cbookif.CBookEventHandler;
import org.cbook.cbookif.CBookEventListener;
import org.cbook.cbookif.CBookWidgetInstanceIF;
import org.cbook.cbookif.Constants;
import org.cbook.cbookif.SuccessStatus;
class ESlateInstance extends JPanel implements CBookWidgetInstanceIF, ActionListener, CBookEventListener, Constants {
/**
*
*/
private static final long serialVersionUID = -2675235738492539378L;
public String microworldToLoadURLLaunch = "XX";
public String microworldToLoadContentLaunch = "XX";
public String microworldToLoadPathLaunch = "XX";
public String microworldToLoadFileNameLaunch = "XX";
public String microworldToLoadURLSuspend = "XX";
public String microworldToLoadContentSuspend = "XX";
public String microworldToLoadPathSuspend = "XX";
public String microworldToLoadFileNameSuspend = "XX";
private String correct;
private Number maxScore = new Integer(10);
private Boolean checked;
private int score, failures;
private String initial = "";
private CBookContext context;
private boolean DEBUG_MODE = true;
private ESlateComposer instanceESC;
private CBookEventHandler handler = new CBookEventHandler(this);
private boolean showResult = true;
private Object logging, logid;
private boolean aftrek;
private AssessmentMode mode;
public int getScore() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlquestionateInstance --> getScore()"/* -> " + hasloaded*/);
}
return Math.max(0, score - failures);
}
public void setScore(int score) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setScore() -> " + score);
}
this.score = score;
}
public JComponent asComponent() {
return this;
}
ESlateInstance(CBookContext context, ESlateWidget sampleWidget) {
super(new BorderLayout());
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> ESlateInstance()");
}
this.context = context;
initialize();
// stop();
}
private void initialize() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> initialize()");
}
setBackground(Color.white);
correct = "42";
this.instanceESC = new ESlateComposer();
add(this.instanceESC,BorderLayout.CENTER);
this.instanceESC.initialize();
this.instanceESC.setMenuBarVisible(true);
this.instanceESC.setContainerTitleEnabled(false);
this.instanceESC.setControlBarsVisible(true);
this.instanceESC.setControlBarTitleActive(false);
this.instanceESC.setVisible(true);
}
public void setLaunchData(Map<String, ?> data, Map<String,Number> randomVars) {
String questionStr = (String) data.get("question");
initial = (String) data.get("initial");
correct = (String) data.get("answer");
/*questionStr = convert(questionStr, randomVars);
initial = convert(initial, randomVars);
correct = convert(correct, randomVars);*/
microworldToLoadURLLaunch = (String) data.get("microworldurl");
microworldToLoadPathLaunch = getTmpDir();
microworldToLoadFileNameLaunch = (String) data.get("microworldfilename");
microworldToLoadContentLaunch = (String) data.get("microworldcontent");
Path p1 = Paths.get((microworldToLoadPathLaunch + microworldToLoadFileNameLaunch).replace("\\\\", "\\") );
if( Files.isReadable(p1) ) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData(): Restoring from path");
}
String [] args2 = {(getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
try {
microworldToLoadContentLaunch = "";
byte[] fileContents = read(getTmpDir() + microworldToLoadFileNameLaunch);
microworldToLoadContentLaunch = compressString(encodeMicroworld(fileContents));
} catch (Exception ex) {
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> setLaunchData() --> Error while synchronizing data " + ex.getMessage());
}
}
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\"), false, true);
} else {
if(microworldToLoadContentSuspend.length() < 5) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData(): Loaded from launch data " + microworldToLoadPathLaunch + " " + microworldToLoadFileNameLaunch + " " + microworldToLoadContentLaunch.length() + " " + microworldToLoadContentSuspend.length());
}
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream((microworldToLoadPathLaunch + microworldToLoadFileNameLaunch).replace("\\\\", "\\")));
out.write((new String()).getBytes());
String bytecontent = uncompressString(microworldToLoadContentLaunch);
byte[] bb = decodeMicroworld(bytecontent);
out.write(bb);
out.flush();
out.close();
String [] args2 = {(getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\"), false, true);
} catch (Exception ex1) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData() -> " + ex1.getMessage());
}
}
} else {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData(): Loaded from Suspend data " + microworldToLoadPathLaunch + " " + microworldToLoadFileNameLaunch + " " + microworldToLoadContentLaunch.length() + " " + microworldToLoadContentSuspend.length());
}
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream((microworldToLoadPathLaunch + microworldToLoadFileNameLaunch).replace("\\\\", "\\")));
out.write((new String()).getBytes());
String bytecontent = uncompressString(microworldToLoadContentSuspend);
byte[] bb = decodeMicroworld(bytecontent);
out.write(bb);
out.flush();
out.close();
String [] args2 = {(getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\"), false, true);
} catch (Exception ex1) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData() -> " + ex1.getMessage());
}
}
}
}
maxScore = (Number) data.get("maxScore");
if(maxScore == null)
maxScore = new Integer(10);
}
private String convert(String str, Map<String, Number> randomVars) {
StringBuffer sb = new StringBuffer();
String[] x = str.split("#");
boolean flip = false;
for (int i = 0; i < x.length; i++) {
if(flip) {
Object object = randomVars.get(x[i]);
if(object == null) object = "#" + x[i] + "#";
sb.append(object);
} else {
sb.append(x[i]);
}
flip = !flip;
}
return sb.toString();
}
public void setState(Map<String,?> state) {
microworldToLoadURLSuspend = (String) state.get("microworldurl");
microworldToLoadPathSuspend = (String) state.get("microworldpath");
microworldToLoadFileNameSuspend = (String) state.get("microworldfilename");
microworldToLoadContentSuspend = (String) state.get("microworldcontent");
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setState(): " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
String [] args2 = {(getTmpDir() + microworldToLoadFileNameSuspend).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream((getTmpDir() + microworldToLoadFileNameSuspend).replace("\\\\", "\\")));
out.write((new String()).getBytes());
String bytecontent = uncompressString(microworldToLoadContentSuspend);
byte[] bb = decodeMicroworld(bytecontent);
out.write(bb);
out.flush();
out.close();
} catch (Exception ex1) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"DBG: Error while writing encoded data to file: " + ex1.getMessage());
}
}
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameSuspend).replace("\\\\", "\\"), false, true);
}
public Map<String,?> getState() {
this.instanceESC.saveMicroworld(false);
this.instanceESC.closeMicroworld(false);
if(microworldToLoadURLSuspend.equals("XX") && microworldToLoadPathSuspend.equals("XX") && microworldToLoadFileNameSuspend.equals("XX")) {
microworldToLoadPathSuspend = getTmpDir();
microworldToLoadFileNameSuspend = microworldToLoadFileNameLaunch;
} else {
microworldToLoadPathLaunch = getTmpDir();
microworldToLoadFileNameLaunch = microworldToLoadFileNameSuspend;
}
try {
//microworldToLoadContentSuspend = "";
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> getState() --> Synchronizing data with " + this.microworldToLoadPathSuspend + this.microworldToLoadFileNameSuspend);
}
byte[] fileContents = read(getTmpDir() + this.microworldToLoadFileNameSuspend);
microworldToLoadContentSuspend = compressString(encodeMicroworld(fileContents));
} catch (Exception ex) {
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> getState() --> Error while synchronizing data " + ex.getMessage());
}
}
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Writing " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
Hashtable<String,Object> h = new Hashtable<String, Object>();
h.put("microworldurl", microworldToLoadURLSuspend);
h.put("microworldpath", microworldToLoadPathSuspend);
h.put("microworldfilename", microworldToLoadFileNameSuspend);
h.put("microworldcontent", microworldToLoadContentSuspend);
/*try{
File file = new File(getTmpDir() + this.microworldToLoadFileNameSuspend);
if(file.delete()){
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Successful clean up " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
}else{
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Failed clean up " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
}
}catch(Exception e){
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Error while cleaning up " + e.getMessage() );
}
}*/
if(checked != null)
h.put("checked", checked);
return h;
}
public void actionPerformed(ActionEvent _) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> actionPerformed()");
}
String input = "DUMMY";
if( aftrek && ! checked.booleanValue() )
failures += 1;
// Single command, single message
handler.fire(USER_INPUT, input);
// Do logging via an event listener
if(isLogging())
{
HashMap<String,Object> map = new HashMap<String, Object>();
map.put(USER_INPUT, input);
map.put("success_status", getSuccessStatus());
map.put("score", new Integer(getScore()));
map.put(LOG_ID, logid);
handler.fire(LOGGING, map);
}
}
// boilerplate
public void addCBookEventListener(CBookEventListener listener,
String command) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> addCBookEventListener()");
}
handler.addCBookEventListener(listener, command);
}
public void removeCBookEventListener(CBookEventListener listener,
String command) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> addCBookEventListener()");
}
handler.removeCBookEventListener(listener, command);
}
public void acceptCBookEvent(CBookEvent event) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> acceptCBookEvent()");
}
String command = event.getCommand();
if(USER_INPUT.equals(command))
{
}
if("check".equals(command))
{
// no parameters: kijkna()
// met parameter "checked" Boolean zet nagekeken, save in state!
Object checked = event.getParameter("checked");
if(Boolean.TRUE.equals(checked))
showResult = true;
if(Boolean.FALSE.equals(checked))
showResult = false;
String input = "DUMMY";
handler.fire(USER_INPUT, input);
repaint();
}
}
public SuccessStatus getSuccessStatus() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getSuccessStatus()");
}
if(checked == null)
return SuccessStatus.UNKNOWN;
if(checked.booleanValue())
return SuccessStatus.PASSED;
return SuccessStatus.FAILED;
}
public void setAssessmentMode(AssessmentMode mode) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setAssessmentMode()");
}
this.mode = mode;
showResult =
mode == AssessmentMode.OEFENEN ||
mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
aftrek = mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
}
public void init() {
// logging = context.getProperty(LOGGING);
// logid = context.getProperty(LOG_ID);
// if(isLogging())
// System.err.println("log to " + logid);
// Color foreground = (Color)context.getProperty(FOREGROUND);
// setForeground(foreground);
// Color background = (Color)context.getProperty(BACKGROUND);
// setBackground(background);
// Font font = (Font) context.getProperty(FONT);
// setFont(font);
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> init()");
}
}
private boolean isLogging() {
// if (DEBUG_MODE) {
// JOptionPane.showMessageDialog(new JFrame(),
// "ESlateInstance --> isLogging()");
// }
return Boolean.TRUE.equals(logging);
}
public void start() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> start()");
}
}
public void stop() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> stop()");
}
//this.instanceESC.saveMicroworld(false);
/*if(!this.microworldToLoadPath.equals("XX")) {
try {
microworldToLoadContent = "";
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Synchronizing data with " + this.microworldToLoadPath + this.microworldToLoadFileName);
}
byte[] fileContents = read(this.microworldToLoadPath + this.microworldToLoadFileName);
microworldToLoadContent = compressString(encodeMicroworld(fileContents));
mwdToLoadContent.setText(microworldToLoadContent);
} catch (Exception ex) {
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Error while synchronizing data " + ex.getMessage());
}
}
}
check.setEnabled(false);
answer.setEnabled(false);*/
}
public void destroy() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> destroy()");
}
//this.instanceESC.saveMicroworld(false);
// if(!this.microworldToLoadPath.equals("XX")) {
// try {
//
// microworldToLoadContent = "";
// if(DEBUG_MODE) {
// JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Synchronizing data with " + this.microworldToLoadPath + this.microworldToLoadFileName);
// }
// byte[] fileContents = read(this.microworldToLoadPath + this.microworldToLoadFileName);
// microworldToLoadContent = compressString(encodeMicroworld(fileContents));
// mwdToLoadContent.setText(microworldToLoadContent);
// } catch (Exception ex) {
// if(DEBUG_MODE) {
// JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Error while synchronizing data " + ex.getMessage());
// }
// }
// }
}
public void reset() {
setAssessmentMode(mode);
setState(Collections.<String, String> emptyMap());
failures = 0;
}
public CBookEventListener asEventListener() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> asEventListener()");
}
return this;
}
public String compressString(String srcTxt) throws IOException {
ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
GZIPOutputStream zos = new GZIPOutputStream(rstBao);
zos.write(srcTxt.getBytes());
IOUtils.closeQuietly(zos);
byte[] bytes = rstBao.toByteArray();
return Base64.byteArrayToBase64(bytes,0,bytes.length);
}
private static byte[] decodeMicroworld(String microworldDataString) {
return org.apache.commons.codec.binary.Base64
.decodeBase64(microworldDataString);
}
public String uncompressString(String zippedBase64Str) throws IOException {
String result = null;
byte[] bytes = Base64.base64ToByteArray(zippedBase64Str);
GZIPInputStream zi = null;
try {
zi = new GZIPInputStream(new ByteArrayInputStream(bytes));
result = IOUtils.toString(zi);
} finally {
IOUtils.closeQuietly(zi);
}
return result;
}
public static String encodeMicroworld(byte[] microworldByteArray) {
return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(microworldByteArray);
}
private String getTmpDir() {
return System.getProperty("java.io.tmpdir")
+ System.getProperty("file.separator");
}
byte[] read(String aInputFileName){
File file = new File(aInputFileName);
byte[] result = new byte[(int)file.length()];
try {
InputStream input = null;
try {
int totalBytesRead = 0;
input = new BufferedInputStream(new FileInputStream(file));
while(totalBytesRead < result.length){
int bytesRemaining = result.length - totalBytesRead;
int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
if (bytesRead > 0){
totalBytesRead = totalBytesRead + bytesRead;
}
}
}
finally {
input.close();
}
}
catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}
return result;
}
}
| vpapakir/myeslate | widgetESlate/src/widgetESlate/ESlateInstance.java | 6,865 | // met parameter "checked" Boolean zet nagekeken, save in state! | line_comment | nl | package widgetESlate;
import gr.cti.eslate.base.container.ESlateComposer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.solr.common.util.Base64;
import org.cbook.cbookif.AssessmentMode;
import org.cbook.cbookif.CBookContext;
import org.cbook.cbookif.CBookEvent;
import org.cbook.cbookif.CBookEventHandler;
import org.cbook.cbookif.CBookEventListener;
import org.cbook.cbookif.CBookWidgetInstanceIF;
import org.cbook.cbookif.Constants;
import org.cbook.cbookif.SuccessStatus;
class ESlateInstance extends JPanel implements CBookWidgetInstanceIF, ActionListener, CBookEventListener, Constants {
/**
*
*/
private static final long serialVersionUID = -2675235738492539378L;
public String microworldToLoadURLLaunch = "XX";
public String microworldToLoadContentLaunch = "XX";
public String microworldToLoadPathLaunch = "XX";
public String microworldToLoadFileNameLaunch = "XX";
public String microworldToLoadURLSuspend = "XX";
public String microworldToLoadContentSuspend = "XX";
public String microworldToLoadPathSuspend = "XX";
public String microworldToLoadFileNameSuspend = "XX";
private String correct;
private Number maxScore = new Integer(10);
private Boolean checked;
private int score, failures;
private String initial = "";
private CBookContext context;
private boolean DEBUG_MODE = true;
private ESlateComposer instanceESC;
private CBookEventHandler handler = new CBookEventHandler(this);
private boolean showResult = true;
private Object logging, logid;
private boolean aftrek;
private AssessmentMode mode;
public int getScore() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlquestionateInstance --> getScore()"/* -> " + hasloaded*/);
}
return Math.max(0, score - failures);
}
public void setScore(int score) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setScore() -> " + score);
}
this.score = score;
}
public JComponent asComponent() {
return this;
}
ESlateInstance(CBookContext context, ESlateWidget sampleWidget) {
super(new BorderLayout());
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> ESlateInstance()");
}
this.context = context;
initialize();
// stop();
}
private void initialize() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> initialize()");
}
setBackground(Color.white);
correct = "42";
this.instanceESC = new ESlateComposer();
add(this.instanceESC,BorderLayout.CENTER);
this.instanceESC.initialize();
this.instanceESC.setMenuBarVisible(true);
this.instanceESC.setContainerTitleEnabled(false);
this.instanceESC.setControlBarsVisible(true);
this.instanceESC.setControlBarTitleActive(false);
this.instanceESC.setVisible(true);
}
public void setLaunchData(Map<String, ?> data, Map<String,Number> randomVars) {
String questionStr = (String) data.get("question");
initial = (String) data.get("initial");
correct = (String) data.get("answer");
/*questionStr = convert(questionStr, randomVars);
initial = convert(initial, randomVars);
correct = convert(correct, randomVars);*/
microworldToLoadURLLaunch = (String) data.get("microworldurl");
microworldToLoadPathLaunch = getTmpDir();
microworldToLoadFileNameLaunch = (String) data.get("microworldfilename");
microworldToLoadContentLaunch = (String) data.get("microworldcontent");
Path p1 = Paths.get((microworldToLoadPathLaunch + microworldToLoadFileNameLaunch).replace("\\\\", "\\") );
if( Files.isReadable(p1) ) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData(): Restoring from path");
}
String [] args2 = {(getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
try {
microworldToLoadContentLaunch = "";
byte[] fileContents = read(getTmpDir() + microworldToLoadFileNameLaunch);
microworldToLoadContentLaunch = compressString(encodeMicroworld(fileContents));
} catch (Exception ex) {
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> setLaunchData() --> Error while synchronizing data " + ex.getMessage());
}
}
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\"), false, true);
} else {
if(microworldToLoadContentSuspend.length() < 5) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData(): Loaded from launch data " + microworldToLoadPathLaunch + " " + microworldToLoadFileNameLaunch + " " + microworldToLoadContentLaunch.length() + " " + microworldToLoadContentSuspend.length());
}
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream((microworldToLoadPathLaunch + microworldToLoadFileNameLaunch).replace("\\\\", "\\")));
out.write((new String()).getBytes());
String bytecontent = uncompressString(microworldToLoadContentLaunch);
byte[] bb = decodeMicroworld(bytecontent);
out.write(bb);
out.flush();
out.close();
String [] args2 = {(getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\"), false, true);
} catch (Exception ex1) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData() -> " + ex1.getMessage());
}
}
} else {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData(): Loaded from Suspend data " + microworldToLoadPathLaunch + " " + microworldToLoadFileNameLaunch + " " + microworldToLoadContentLaunch.length() + " " + microworldToLoadContentSuspend.length());
}
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream((microworldToLoadPathLaunch + microworldToLoadFileNameLaunch).replace("\\\\", "\\")));
out.write((new String()).getBytes());
String bytecontent = uncompressString(microworldToLoadContentSuspend);
byte[] bb = decodeMicroworld(bytecontent);
out.write(bb);
out.flush();
out.close();
String [] args2 = {(getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameLaunch).replace("\\\\", "\\"), false, true);
} catch (Exception ex1) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setLaunchData() -> " + ex1.getMessage());
}
}
}
}
maxScore = (Number) data.get("maxScore");
if(maxScore == null)
maxScore = new Integer(10);
}
private String convert(String str, Map<String, Number> randomVars) {
StringBuffer sb = new StringBuffer();
String[] x = str.split("#");
boolean flip = false;
for (int i = 0; i < x.length; i++) {
if(flip) {
Object object = randomVars.get(x[i]);
if(object == null) object = "#" + x[i] + "#";
sb.append(object);
} else {
sb.append(x[i]);
}
flip = !flip;
}
return sb.toString();
}
public void setState(Map<String,?> state) {
microworldToLoadURLSuspend = (String) state.get("microworldurl");
microworldToLoadPathSuspend = (String) state.get("microworldpath");
microworldToLoadFileNameSuspend = (String) state.get("microworldfilename");
microworldToLoadContentSuspend = (String) state.get("microworldcontent");
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setState(): " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
String [] args2 = {(getTmpDir() + microworldToLoadFileNameSuspend).replace("\\\\", "\\")};
this.instanceESC.closeMicroworld(false);
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream((getTmpDir() + microworldToLoadFileNameSuspend).replace("\\\\", "\\")));
out.write((new String()).getBytes());
String bytecontent = uncompressString(microworldToLoadContentSuspend);
byte[] bb = decodeMicroworld(bytecontent);
out.write(bb);
out.flush();
out.close();
} catch (Exception ex1) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"DBG: Error while writing encoded data to file: " + ex1.getMessage());
}
}
this.instanceESC.initialize2();
this.instanceESC.startESlate2(args2, true);
boolean hasloaded = this.instanceESC.loadLocalMicroworld((getTmpDir() + microworldToLoadFileNameSuspend).replace("\\\\", "\\"), false, true);
}
public Map<String,?> getState() {
this.instanceESC.saveMicroworld(false);
this.instanceESC.closeMicroworld(false);
if(microworldToLoadURLSuspend.equals("XX") && microworldToLoadPathSuspend.equals("XX") && microworldToLoadFileNameSuspend.equals("XX")) {
microworldToLoadPathSuspend = getTmpDir();
microworldToLoadFileNameSuspend = microworldToLoadFileNameLaunch;
} else {
microworldToLoadPathLaunch = getTmpDir();
microworldToLoadFileNameLaunch = microworldToLoadFileNameSuspend;
}
try {
//microworldToLoadContentSuspend = "";
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> getState() --> Synchronizing data with " + this.microworldToLoadPathSuspend + this.microworldToLoadFileNameSuspend);
}
byte[] fileContents = read(getTmpDir() + this.microworldToLoadFileNameSuspend);
microworldToLoadContentSuspend = compressString(encodeMicroworld(fileContents));
} catch (Exception ex) {
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> getState() --> Error while synchronizing data " + ex.getMessage());
}
}
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Writing " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
Hashtable<String,Object> h = new Hashtable<String, Object>();
h.put("microworldurl", microworldToLoadURLSuspend);
h.put("microworldpath", microworldToLoadPathSuspend);
h.put("microworldfilename", microworldToLoadFileNameSuspend);
h.put("microworldcontent", microworldToLoadContentSuspend);
/*try{
File file = new File(getTmpDir() + this.microworldToLoadFileNameSuspend);
if(file.delete()){
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Successful clean up " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
}else{
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Failed clean up " + microworldToLoadPathSuspend + " " + microworldToLoadFileNameSuspend + " " + microworldToLoadContentSuspend.length() );
}
}
}catch(Exception e){
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getState(): Error while cleaning up " + e.getMessage() );
}
}*/
if(checked != null)
h.put("checked", checked);
return h;
}
public void actionPerformed(ActionEvent _) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> actionPerformed()");
}
String input = "DUMMY";
if( aftrek && ! checked.booleanValue() )
failures += 1;
// Single command, single message
handler.fire(USER_INPUT, input);
// Do logging via an event listener
if(isLogging())
{
HashMap<String,Object> map = new HashMap<String, Object>();
map.put(USER_INPUT, input);
map.put("success_status", getSuccessStatus());
map.put("score", new Integer(getScore()));
map.put(LOG_ID, logid);
handler.fire(LOGGING, map);
}
}
// boilerplate
public void addCBookEventListener(CBookEventListener listener,
String command) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> addCBookEventListener()");
}
handler.addCBookEventListener(listener, command);
}
public void removeCBookEventListener(CBookEventListener listener,
String command) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> addCBookEventListener()");
}
handler.removeCBookEventListener(listener, command);
}
public void acceptCBookEvent(CBookEvent event) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> acceptCBookEvent()");
}
String command = event.getCommand();
if(USER_INPUT.equals(command))
{
}
if("check".equals(command))
{
// no parameters: kijkna()
// met parameter<SUF>
Object checked = event.getParameter("checked");
if(Boolean.TRUE.equals(checked))
showResult = true;
if(Boolean.FALSE.equals(checked))
showResult = false;
String input = "DUMMY";
handler.fire(USER_INPUT, input);
repaint();
}
}
public SuccessStatus getSuccessStatus() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> getSuccessStatus()");
}
if(checked == null)
return SuccessStatus.UNKNOWN;
if(checked.booleanValue())
return SuccessStatus.PASSED;
return SuccessStatus.FAILED;
}
public void setAssessmentMode(AssessmentMode mode) {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> setAssessmentMode()");
}
this.mode = mode;
showResult =
mode == AssessmentMode.OEFENEN ||
mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
aftrek = mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
}
public void init() {
// logging = context.getProperty(LOGGING);
// logid = context.getProperty(LOG_ID);
// if(isLogging())
// System.err.println("log to " + logid);
// Color foreground = (Color)context.getProperty(FOREGROUND);
// setForeground(foreground);
// Color background = (Color)context.getProperty(BACKGROUND);
// setBackground(background);
// Font font = (Font) context.getProperty(FONT);
// setFont(font);
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> init()");
}
}
private boolean isLogging() {
// if (DEBUG_MODE) {
// JOptionPane.showMessageDialog(new JFrame(),
// "ESlateInstance --> isLogging()");
// }
return Boolean.TRUE.equals(logging);
}
public void start() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> start()");
}
}
public void stop() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> stop()");
}
//this.instanceESC.saveMicroworld(false);
/*if(!this.microworldToLoadPath.equals("XX")) {
try {
microworldToLoadContent = "";
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Synchronizing data with " + this.microworldToLoadPath + this.microworldToLoadFileName);
}
byte[] fileContents = read(this.microworldToLoadPath + this.microworldToLoadFileName);
microworldToLoadContent = compressString(encodeMicroworld(fileContents));
mwdToLoadContent.setText(microworldToLoadContent);
} catch (Exception ex) {
if(DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Error while synchronizing data " + ex.getMessage());
}
}
}
check.setEnabled(false);
answer.setEnabled(false);*/
}
public void destroy() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> destroy()");
}
//this.instanceESC.saveMicroworld(false);
// if(!this.microworldToLoadPath.equals("XX")) {
// try {
//
// microworldToLoadContent = "";
// if(DEBUG_MODE) {
// JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Synchronizing data with " + this.microworldToLoadPath + this.microworldToLoadFileName);
// }
// byte[] fileContents = read(this.microworldToLoadPath + this.microworldToLoadFileName);
// microworldToLoadContent = compressString(encodeMicroworld(fileContents));
// mwdToLoadContent.setText(microworldToLoadContent);
// } catch (Exception ex) {
// if(DEBUG_MODE) {
// JOptionPane.showMessageDialog(new JFrame(),"ESlateInstance --> stop() --> Error while synchronizing data " + ex.getMessage());
// }
// }
// }
}
public void reset() {
setAssessmentMode(mode);
setState(Collections.<String, String> emptyMap());
failures = 0;
}
public CBookEventListener asEventListener() {
if (DEBUG_MODE) {
JOptionPane.showMessageDialog(new JFrame(),
"ESlateInstance --> asEventListener()");
}
return this;
}
public String compressString(String srcTxt) throws IOException {
ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
GZIPOutputStream zos = new GZIPOutputStream(rstBao);
zos.write(srcTxt.getBytes());
IOUtils.closeQuietly(zos);
byte[] bytes = rstBao.toByteArray();
return Base64.byteArrayToBase64(bytes,0,bytes.length);
}
private static byte[] decodeMicroworld(String microworldDataString) {
return org.apache.commons.codec.binary.Base64
.decodeBase64(microworldDataString);
}
public String uncompressString(String zippedBase64Str) throws IOException {
String result = null;
byte[] bytes = Base64.base64ToByteArray(zippedBase64Str);
GZIPInputStream zi = null;
try {
zi = new GZIPInputStream(new ByteArrayInputStream(bytes));
result = IOUtils.toString(zi);
} finally {
IOUtils.closeQuietly(zi);
}
return result;
}
public static String encodeMicroworld(byte[] microworldByteArray) {
return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(microworldByteArray);
}
private String getTmpDir() {
return System.getProperty("java.io.tmpdir")
+ System.getProperty("file.separator");
}
byte[] read(String aInputFileName){
File file = new File(aInputFileName);
byte[] result = new byte[(int)file.length()];
try {
InputStream input = null;
try {
int totalBytesRead = 0;
input = new BufferedInputStream(new FileInputStream(file));
while(totalBytesRead < result.length){
int bytesRemaining = result.length - totalBytesRead;
int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
if (bytesRead > 0){
totalBytesRead = totalBytesRead + bytesRead;
}
}
}
finally {
input.close();
}
}
catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}
return result;
}
}
|
175696_4 | package widgetsample;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.cbook.cbookif.AssessmentMode;
import org.cbook.cbookif.CBookContext;
import org.cbook.cbookif.CBookEvent;
import org.cbook.cbookif.CBookEventHandler;
import org.cbook.cbookif.CBookEventListener;
import org.cbook.cbookif.CBookWidgetInstanceIF;
import org.cbook.cbookif.Constants;
import org.cbook.cbookif.SuccessStatus;
class SampleInstance extends JPanel implements CBookWidgetInstanceIF, ActionListener, CBookEventListener, Constants {
private JLabel question;
private JTextField answer;
private JButton check;
private String correct;
private Number maxScore = new Integer(10);
private Boolean checked;
private int score, failures;
private String initial = "";
private CBookContext context;
private CBookEventHandler handler = new CBookEventHandler(this);
private boolean showResult = true;
private Object logging, logid;
private boolean aftrek;
private AssessmentMode mode;
public int getScore() {
return Math.max(0, score - failures);
}
public void setScore(int score) {
this.score = score;
}
public JComponent asComponent() {
return this;
}
SampleInstance(CBookContext context, SampleWidget sampleWidget) {
super(new BorderLayout());
this.context = context;
initialize();
stop();
}
private void initialize() {
setBackground(Color.white);
question = new JLabel();
answer = new JTextField();
check = new JButton("check");
correct = "42";
add(question, BorderLayout.NORTH);
add(answer, BorderLayout.CENTER);
add(check, BorderLayout.SOUTH);
check.addActionListener(this);
answer.addActionListener(this);
}
public void setLaunchData(Map<String, ?> data, Map<String,Number> randomVars) {
String questionStr = (String) data.get("question");
initial = (String) data.get("initial");
correct = (String) data.get("answer");
questionStr = convert(questionStr, randomVars);
initial = convert(initial, randomVars);
correct = convert(correct, randomVars);
maxScore = (Number) data.get("maxScore");
if(maxScore == null)
maxScore = new Integer(10);
answer.setText(initial);
// Ask the question to the user:
String name = context.getProperty(LEARNER_ID) + ": ";
question.setText(name + questionStr + "?");
check.setText("check");
}
private String convert(String str, Map<String, Number> randomVars) {
StringBuffer sb = new StringBuffer();
String[] x = str.split("#");
boolean flip = false;
for (int i = 0; i < x.length; i++) {
if(flip) {
Object object = randomVars.get(x[i]);
if(object == null) object = "#" + x[i] + "#";
sb.append(object);
} else {
sb.append(x[i]);
}
flip = !flip;
}
return sb.toString();
}
public void setState(Map<String,?> state) {
String answer = (String) state.get("answer");
checked = (Boolean) state.get("checked");
if(checked != null)
{
showResult = true;
setCheckMark(checked.booleanValue());
}
else
{
check.setText("check");
score = 0;
}
if(answer != null)
this.answer.setText(answer);
else
this.answer.setText(initial);
}
private void setCheckMark(boolean correct) {
String text = "KO";
score = 0;
if(correct) {
text = "OK";
score = maxScore.intValue();
}
if(showResult)
{
check.setText(text);
checked = Boolean.valueOf(correct);
}
else
{
check.setText("check");
checked = null;
}
}
public Map<String,?> getState() {
Hashtable<String,Object> h = new Hashtable<String, Object>();
h.put("answer", answer.getText());
if(checked != null)
h.put("checked", checked);
return h;
}
public void actionPerformed(ActionEvent _) {
String input = answer.getText().trim();
setCheckMark( correct .equals( input));
if( aftrek && ! checked.booleanValue() )
failures += 1;
// Single command, single message
handler.fire(USER_INPUT, input);
handler.fire(CHANGED);
// Do logging via an event listener
if(isLogging())
{
HashMap<String,Object> map = new HashMap<String, Object>();
map.put(USER_INPUT, input);
map.put("success_status", getSuccessStatus());
map.put("score", new Integer(getScore()));
map.put(LOG_ID, logid);
handler.fire(LOGGING, map);
}
}
// boilerplate
public void addCBookEventListener(CBookEventListener listener,
String command) {
handler.addCBookEventListener(listener, command);
}
public void removeCBookEventListener(CBookEventListener listener,
String command) {
handler.removeCBookEventListener(listener, command);
}
public void acceptCBookEvent(CBookEvent event) {
String command = event.getCommand();
if(USER_INPUT.equals(command))
{
answer.setText(String.valueOf(event.getMessage()));
}
if("check".equals(command))
{
// no parameters: kijkna()
// met parameter "checked" Boolean zet nagekeken, save in state!
Object checked = event.getParameter("checked");
if(Boolean.TRUE.equals(checked))
showResult = true;
if(Boolean.FALSE.equals(checked))
showResult = false;
String input = answer.getText().trim();
setCheckMark(input.equals(correct));
handler.fire(USER_INPUT, input);
repaint();
}
}
public SuccessStatus getSuccessStatus() {
if(checked == null)
return SuccessStatus.UNKNOWN;
if(checked.booleanValue())
return SuccessStatus.PASSED;
return SuccessStatus.FAILED;
}
public void setAssessmentMode(AssessmentMode mode) {
this.mode = mode;
showResult =
mode == AssessmentMode.OEFENEN ||
mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
aftrek = mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
}
public void init() {
logging = context.getProperty(LOGGING);
logid = context.getProperty(LOG_ID);
if(isLogging())
System.err.println("log to " + logid);
Color foreground = (Color)context.getProperty(FOREGROUND);
setForeground(foreground);
Color background = (Color)context.getProperty(BACKGROUND);
setBackground(background);
Font font = (Font) context.getProperty(FONT);
setFont(font);
}
private boolean isLogging() {
return Boolean.TRUE.equals(logging);
}
public void start() {
check.setEnabled(true);
answer.setEnabled(true);
}
public void stop() {
check.setEnabled(false);
answer.setEnabled(false);
}
public void destroy() {
}
public void reset() {
setAssessmentMode(mode);
setState(Collections.<String, String> emptyMap());
failures = 0;
}
public CBookEventListener asEventListener() {
return this;
}
}
| vpapakir/mymcsqared | widgetsample/src/widgetsample/SampleInstance.java | 2,260 | // met parameter "checked" Boolean zet nagekeken, save in state! | line_comment | nl | package widgetsample;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.cbook.cbookif.AssessmentMode;
import org.cbook.cbookif.CBookContext;
import org.cbook.cbookif.CBookEvent;
import org.cbook.cbookif.CBookEventHandler;
import org.cbook.cbookif.CBookEventListener;
import org.cbook.cbookif.CBookWidgetInstanceIF;
import org.cbook.cbookif.Constants;
import org.cbook.cbookif.SuccessStatus;
class SampleInstance extends JPanel implements CBookWidgetInstanceIF, ActionListener, CBookEventListener, Constants {
private JLabel question;
private JTextField answer;
private JButton check;
private String correct;
private Number maxScore = new Integer(10);
private Boolean checked;
private int score, failures;
private String initial = "";
private CBookContext context;
private CBookEventHandler handler = new CBookEventHandler(this);
private boolean showResult = true;
private Object logging, logid;
private boolean aftrek;
private AssessmentMode mode;
public int getScore() {
return Math.max(0, score - failures);
}
public void setScore(int score) {
this.score = score;
}
public JComponent asComponent() {
return this;
}
SampleInstance(CBookContext context, SampleWidget sampleWidget) {
super(new BorderLayout());
this.context = context;
initialize();
stop();
}
private void initialize() {
setBackground(Color.white);
question = new JLabel();
answer = new JTextField();
check = new JButton("check");
correct = "42";
add(question, BorderLayout.NORTH);
add(answer, BorderLayout.CENTER);
add(check, BorderLayout.SOUTH);
check.addActionListener(this);
answer.addActionListener(this);
}
public void setLaunchData(Map<String, ?> data, Map<String,Number> randomVars) {
String questionStr = (String) data.get("question");
initial = (String) data.get("initial");
correct = (String) data.get("answer");
questionStr = convert(questionStr, randomVars);
initial = convert(initial, randomVars);
correct = convert(correct, randomVars);
maxScore = (Number) data.get("maxScore");
if(maxScore == null)
maxScore = new Integer(10);
answer.setText(initial);
// Ask the question to the user:
String name = context.getProperty(LEARNER_ID) + ": ";
question.setText(name + questionStr + "?");
check.setText("check");
}
private String convert(String str, Map<String, Number> randomVars) {
StringBuffer sb = new StringBuffer();
String[] x = str.split("#");
boolean flip = false;
for (int i = 0; i < x.length; i++) {
if(flip) {
Object object = randomVars.get(x[i]);
if(object == null) object = "#" + x[i] + "#";
sb.append(object);
} else {
sb.append(x[i]);
}
flip = !flip;
}
return sb.toString();
}
public void setState(Map<String,?> state) {
String answer = (String) state.get("answer");
checked = (Boolean) state.get("checked");
if(checked != null)
{
showResult = true;
setCheckMark(checked.booleanValue());
}
else
{
check.setText("check");
score = 0;
}
if(answer != null)
this.answer.setText(answer);
else
this.answer.setText(initial);
}
private void setCheckMark(boolean correct) {
String text = "KO";
score = 0;
if(correct) {
text = "OK";
score = maxScore.intValue();
}
if(showResult)
{
check.setText(text);
checked = Boolean.valueOf(correct);
}
else
{
check.setText("check");
checked = null;
}
}
public Map<String,?> getState() {
Hashtable<String,Object> h = new Hashtable<String, Object>();
h.put("answer", answer.getText());
if(checked != null)
h.put("checked", checked);
return h;
}
public void actionPerformed(ActionEvent _) {
String input = answer.getText().trim();
setCheckMark( correct .equals( input));
if( aftrek && ! checked.booleanValue() )
failures += 1;
// Single command, single message
handler.fire(USER_INPUT, input);
handler.fire(CHANGED);
// Do logging via an event listener
if(isLogging())
{
HashMap<String,Object> map = new HashMap<String, Object>();
map.put(USER_INPUT, input);
map.put("success_status", getSuccessStatus());
map.put("score", new Integer(getScore()));
map.put(LOG_ID, logid);
handler.fire(LOGGING, map);
}
}
// boilerplate
public void addCBookEventListener(CBookEventListener listener,
String command) {
handler.addCBookEventListener(listener, command);
}
public void removeCBookEventListener(CBookEventListener listener,
String command) {
handler.removeCBookEventListener(listener, command);
}
public void acceptCBookEvent(CBookEvent event) {
String command = event.getCommand();
if(USER_INPUT.equals(command))
{
answer.setText(String.valueOf(event.getMessage()));
}
if("check".equals(command))
{
// no parameters: kijkna()
// met parameter<SUF>
Object checked = event.getParameter("checked");
if(Boolean.TRUE.equals(checked))
showResult = true;
if(Boolean.FALSE.equals(checked))
showResult = false;
String input = answer.getText().trim();
setCheckMark(input.equals(correct));
handler.fire(USER_INPUT, input);
repaint();
}
}
public SuccessStatus getSuccessStatus() {
if(checked == null)
return SuccessStatus.UNKNOWN;
if(checked.booleanValue())
return SuccessStatus.PASSED;
return SuccessStatus.FAILED;
}
public void setAssessmentMode(AssessmentMode mode) {
this.mode = mode;
showResult =
mode == AssessmentMode.OEFENEN ||
mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
aftrek = mode == AssessmentMode.OEFENEN_STRAFPUNTEN;
}
public void init() {
logging = context.getProperty(LOGGING);
logid = context.getProperty(LOG_ID);
if(isLogging())
System.err.println("log to " + logid);
Color foreground = (Color)context.getProperty(FOREGROUND);
setForeground(foreground);
Color background = (Color)context.getProperty(BACKGROUND);
setBackground(background);
Font font = (Font) context.getProperty(FONT);
setFont(font);
}
private boolean isLogging() {
return Boolean.TRUE.equals(logging);
}
public void start() {
check.setEnabled(true);
answer.setEnabled(true);
}
public void stop() {
check.setEnabled(false);
answer.setEnabled(false);
}
public void destroy() {
}
public void reset() {
setAssessmentMode(mode);
setState(Collections.<String, String> emptyMap());
failures = 0;
}
public CBookEventListener asEventListener() {
return this;
}
}
|
122429_2 | package nl.vpro.amara;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
import nl.vpro.amara.domain.*;
/**
* @author Michiel Meeuwissen
* @since 0.2
*/
//@Ignore("This is integration test requiring actual key in ~/conf/amara.properties")
@Slf4j
public class VideosClientITest extends AbstractClientsTest {
public static String example = "{\"video_url\":\"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\"title\":\"De invloed van de SER // Adviezen en regeringsbeleid\",\"description\":\"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet.\",\"primary_audio_language_code\":\"nl\",\"thumbnail\":\"http://images-test.poms.omroep.nl/image/32071124.jpg\",\"metadata\":{\"location\":\"WO_NTR_425175\",\"speaker-name\":\"De invloed van de SER\"},\"team\":\"netinnederland-staging\",\"project\":\"current\"}";
public static String video = "{\n" +
" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" +
" \"title\" : \"De invloed van de SER // Adviezen en regeringsbeleid\",\n" +
" \"description\" : \"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet. \",\n" +
" \"primary_audio_language_code\" : \"nl\",\n" +
//" \"thumbnail\" : \"http://images-test.poms.omroep.nl/image/32071124.jpg\",\n" +
" \"metadata\" : {\n" +
" \"location\" : \"WO_NTR_425175\",\n" +
" \"speaker-name\" : \"De invloed van de SER\"\n" +
" },\n" +
" \"team\" : \"netinnederland\",\n" +
" \"project\" : \"current\"\n" +
"}";
public static String anothervideo = "{\n" +
" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/nep/WO_NTR_15925207.mp4?a\",\n" +
//" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" +
" \"title\" : \"Fragment NOS: Op vakantie naar Syrie\",\n" +
" \"description\" : \"Op vakantie naar Syrie\",\n" +
" \"primary_audio_language_code\" : \"nl\",\n" +
//" \"thumbnail\" : \"http://images.poms.omroep.nl/image/s620/1329508.jpg\",\n" +
" \"metadata\" : {\n" +
" \"location\" : \"WO_NTR_15925207\",\n" +
" \"speaker-name\" : \"Fragment NOS: Op vakantie naar Syrie\"\n" +
" },\n" +
" \"team\" : \"netinnederland\",\n" +
" \"project\" : \"current\"\n" +
"}";
@Test
public void postSubtitles() throws IOException {
Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example);
in.setAction("save-draft");
System.out.println(client.videos().post(in, "6dNTmqJsQf1x", "nl"));
}
/*
@Test
public void postSubtitles2() throws IOException {
Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example);
in.setAction("save-draft");
System.out.println(client.videos().post(constructVideo(), "6dNTmqJsQf1x", "nl"));
}
*/
protected Video constructVideo() {
String pomsMidBroadcast = "POW_03372509";
String videoTitel = "test";
String speakerName = "";
String thumbnailUrl = "http://images-test.poms.omroep.nl/image/32071124.jpg";
VideoMetadata amaraVideoMetadata = new VideoMetadata(speakerName, pomsMidBroadcast);
Video amaraVideo = new Video("http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4",
"nl",
videoTitel,
"descriptoin",
client.getTeam(),
amaraVideoMetadata);
amaraVideo.setThumbnail(thumbnailUrl);
amaraVideo.setProject("current");
return amaraVideo;
}
@Test
// GIVES 504. I don't know why.
public void postVideo() throws IOException {
Video in = AmaraObjectMapper.INSTANCE.readerFor(Video.class).readValue(anothervideo);
//
System.out.println(anothervideo);
System.out.println(client.videos().post(in));
}
@Test
public void getSubtitles() {
Subtitles subtitles = client.videos().getSubtitles("BNkV7s6mKMNb", "ar", "vtt");
log.info("" + subtitles);
}
@Test
public void getVideo() {
Video video = client.videos().get("BNkV7s6mKMNb");
log.info("" + video);
}
@Test
public void list() {
Iterator<Video> video = client.videos().list();
video.forEachRemaining((v) -> {
log.info("" + v);
});
}
}
| vpro/amara-java | src/test/java/nl/vpro/amara/VideosClientITest.java | 1,680 | //download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\"title\":\"De invloed van de SER // Adviezen en regeringsbeleid\",\"description\":\"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet.\",\"primary_audio_language_code\":\"nl\",\"thumbnail\":\"http://images-test.poms.omroep.nl/image/32071124.jpg\",\"metadata\":{\"location\":\"WO_NTR_425175\",\"speaker-name\":\"De invloed van de SER\"},\"team\":\"netinnederland-staging\",\"project\":\"current\"}"; | line_comment | nl | package nl.vpro.amara;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
import nl.vpro.amara.domain.*;
/**
* @author Michiel Meeuwissen
* @since 0.2
*/
//@Ignore("This is integration test requiring actual key in ~/conf/amara.properties")
@Slf4j
public class VideosClientITest extends AbstractClientsTest {
public static String example = "{\"video_url\":\"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\"title\":\"De invloed<SUF>
public static String video = "{\n" +
" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" +
" \"title\" : \"De invloed van de SER // Adviezen en regeringsbeleid\",\n" +
" \"description\" : \"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet. \",\n" +
" \"primary_audio_language_code\" : \"nl\",\n" +
//" \"thumbnail\" : \"http://images-test.poms.omroep.nl/image/32071124.jpg\",\n" +
" \"metadata\" : {\n" +
" \"location\" : \"WO_NTR_425175\",\n" +
" \"speaker-name\" : \"De invloed van de SER\"\n" +
" },\n" +
" \"team\" : \"netinnederland\",\n" +
" \"project\" : \"current\"\n" +
"}";
public static String anothervideo = "{\n" +
" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/nep/WO_NTR_15925207.mp4?a\",\n" +
//" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" +
" \"title\" : \"Fragment NOS: Op vakantie naar Syrie\",\n" +
" \"description\" : \"Op vakantie naar Syrie\",\n" +
" \"primary_audio_language_code\" : \"nl\",\n" +
//" \"thumbnail\" : \"http://images.poms.omroep.nl/image/s620/1329508.jpg\",\n" +
" \"metadata\" : {\n" +
" \"location\" : \"WO_NTR_15925207\",\n" +
" \"speaker-name\" : \"Fragment NOS: Op vakantie naar Syrie\"\n" +
" },\n" +
" \"team\" : \"netinnederland\",\n" +
" \"project\" : \"current\"\n" +
"}";
@Test
public void postSubtitles() throws IOException {
Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example);
in.setAction("save-draft");
System.out.println(client.videos().post(in, "6dNTmqJsQf1x", "nl"));
}
/*
@Test
public void postSubtitles2() throws IOException {
Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example);
in.setAction("save-draft");
System.out.println(client.videos().post(constructVideo(), "6dNTmqJsQf1x", "nl"));
}
*/
protected Video constructVideo() {
String pomsMidBroadcast = "POW_03372509";
String videoTitel = "test";
String speakerName = "";
String thumbnailUrl = "http://images-test.poms.omroep.nl/image/32071124.jpg";
VideoMetadata amaraVideoMetadata = new VideoMetadata(speakerName, pomsMidBroadcast);
Video amaraVideo = new Video("http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4",
"nl",
videoTitel,
"descriptoin",
client.getTeam(),
amaraVideoMetadata);
amaraVideo.setThumbnail(thumbnailUrl);
amaraVideo.setProject("current");
return amaraVideo;
}
@Test
// GIVES 504. I don't know why.
public void postVideo() throws IOException {
Video in = AmaraObjectMapper.INSTANCE.readerFor(Video.class).readValue(anothervideo);
//
System.out.println(anothervideo);
System.out.println(client.videos().post(in));
}
@Test
public void getSubtitles() {
Subtitles subtitles = client.videos().getSubtitles("BNkV7s6mKMNb", "ar", "vtt");
log.info("" + subtitles);
}
@Test
public void getVideo() {
Video video = client.videos().get("BNkV7s6mKMNb");
log.info("" + video);
}
@Test
public void list() {
Iterator<Video> video = client.videos().list();
video.forEachRemaining((v) -> {
log.info("" + v);
});
}
}
|
84266_1 | package nl.vpro.amara;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.vpro.amara.domain.Action;
import nl.vpro.amara.domain.Subtitles;
import nl.vpro.amara_poms.Config;
import nl.vpro.amara_poms.poms.PomsBroadcast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author joost
*/
public class SubtitlesTest {
final static Logger LOG = LoggerFactory.getLogger(SubtitlesTest.class);
@BeforeEach
public void setUp() {
Config.init();
}
@Test
public void testDummy() {
assertTrue(true);
}
@Test
public void testPost() {
Subtitles amaraSubtitles = new Subtitles("test subtitles", "vtt",
"WEBVTT\n" +
"\n" +
"1\n" +
"00:00:02.018 --> 00:00:05.007\n" +
"888\n" +
"\n" +
"2\n" +
"00:00:05.012 --> 00:00:07.018\n" +
"TUNE VAN DWDD\n", "test description", "complete");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, "gDq7bAA5XFCR", "nl");
assertNotNull(newAmaraSubtitles);
}
@Test
public void getActions() {
String video_id = "Ep1jZa6c2NRt";
List<Action> actions = Config.getAmaraClient().videos().getActions(video_id, "nl");
System.out.println("" + actions);
}
@Test
public void amarapoms3() throws IOException {
String video_id = "Ep1jZa6c2NRt";
PomsBroadcast pomsBroadcast = new PomsBroadcast("VPWON_1256298", null);
pomsBroadcast.downloadSubtitles();
Subtitles amaraSubtitles = new Subtitles("Blauw Bloed // Een interview met prinses Irene", "vtt",
pomsBroadcast.getSubtitles(), "Een interview met prinses Irene, we volgen koning Willem-Alexander bij de start van de Giro d'Italia en couturier Paul Schulten vertelt alles over koninklijke bloemetjesjurken.", "save-draft");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, video_id, "nl");
assertNotNull(newAmaraSubtitles);
}
public void testGetVTT() {
String amaraSubtitles = Config.getAmaraClient().videos().getAsVTT("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(amaraSubtitles);
}
public void testGet() {
Subtitles amaraSubtitles = Config.getAmaraClient().videos().getSubtitles("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(StringUtils.abbreviate(amaraSubtitles.getSubtitles(), 20));
LOG.info((amaraSubtitles.getVersion_no()));
}
}
| vpro/amara-poms | src/test/java/nl/vpro/amara/SubtitlesTest.java | 1,053 | // Een interview met prinses Irene", "vtt", | line_comment | nl | package nl.vpro.amara;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.vpro.amara.domain.Action;
import nl.vpro.amara.domain.Subtitles;
import nl.vpro.amara_poms.Config;
import nl.vpro.amara_poms.poms.PomsBroadcast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author joost
*/
public class SubtitlesTest {
final static Logger LOG = LoggerFactory.getLogger(SubtitlesTest.class);
@BeforeEach
public void setUp() {
Config.init();
}
@Test
public void testDummy() {
assertTrue(true);
}
@Test
public void testPost() {
Subtitles amaraSubtitles = new Subtitles("test subtitles", "vtt",
"WEBVTT\n" +
"\n" +
"1\n" +
"00:00:02.018 --> 00:00:05.007\n" +
"888\n" +
"\n" +
"2\n" +
"00:00:05.012 --> 00:00:07.018\n" +
"TUNE VAN DWDD\n", "test description", "complete");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, "gDq7bAA5XFCR", "nl");
assertNotNull(newAmaraSubtitles);
}
@Test
public void getActions() {
String video_id = "Ep1jZa6c2NRt";
List<Action> actions = Config.getAmaraClient().videos().getActions(video_id, "nl");
System.out.println("" + actions);
}
@Test
public void amarapoms3() throws IOException {
String video_id = "Ep1jZa6c2NRt";
PomsBroadcast pomsBroadcast = new PomsBroadcast("VPWON_1256298", null);
pomsBroadcast.downloadSubtitles();
Subtitles amaraSubtitles = new Subtitles("Blauw Bloed // Een interview<SUF>
pomsBroadcast.getSubtitles(), "Een interview met prinses Irene, we volgen koning Willem-Alexander bij de start van de Giro d'Italia en couturier Paul Schulten vertelt alles over koninklijke bloemetjesjurken.", "save-draft");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, video_id, "nl");
assertNotNull(newAmaraSubtitles);
}
public void testGetVTT() {
String amaraSubtitles = Config.getAmaraClient().videos().getAsVTT("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(amaraSubtitles);
}
public void testGet() {
Subtitles amaraSubtitles = Config.getAmaraClient().videos().getSubtitles("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(StringUtils.abbreviate(amaraSubtitles.getSubtitles(), 20));
LOG.info((amaraSubtitles.getVersion_no()));
}
}
|
53961_1 | package nl.vpro.io.prepr.domain;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.*;
import com.google.common.base.MoreObjects;
/**
* @author Michiel Meeuwissen
* @since 0.1
*/
@Data
@JsonTypeInfo(
visible = true,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
use = JsonTypeInfo.Id.NAME, property="label",
defaultImpl = Void.class
)
@JsonSubTypes({
@JsonSubTypes.Type(value = PreprWebhook.class, name = PreprWebhook.LABEL),
@JsonSubTypes.Type(value = PreprTimeline.class, name = PreprTimeline.LABEL),
@JsonSubTypes.Type(value = PreprShow.class, name = PreprShow.LABEL),
@JsonSubTypes.Type(value = PreprShowDetail.class, name = PreprShowDetail.LABEL),
@JsonSubTypes.Type(value = PreprPhoto.class, name = PreprPhoto.LABEL),
@JsonSubTypes.Type(value = PreprProfilePhoto.class,name = PreprProfilePhoto.LABEL),
@JsonSubTypes.Type(value = PreprVideo.class, name = PreprVideo.LABEL),
@JsonSubTypes.Type(value = PreprAudio.class, name = PreprAudio.LABEL),
@JsonSubTypes.Type(value = PreprCover.class, name = PreprCover.LABEL),
@JsonSubTypes.Type(value = PreprPost.class, name = PreprPost.LABEL),
@JsonSubTypes.Type(value = PreprHeading.class, name = PreprHeading.LABEL),
@JsonSubTypes.Type(value = PreprText.class, name = PreprText.LABEL),
@JsonSubTypes.Type(value = PreprMedia.class, name = PreprMedia.LABEL),
@JsonSubTypes.Type(value = PreprTrackPlay.class, name = PreprTrackPlay.LABEL),
@JsonSubTypes.Type(value = PreprTrack.class, name = PreprTrack.LABEL),
@JsonSubTypes.Type(value = PreprChannel.class, name = PreprChannel.LABEL),
@JsonSubTypes.Type(value = PreprNewsCast.class, name = PreprNewsCast.LABEL),
@JsonSubTypes.Type(value = PreprTag.class, name = PreprTag.LABEL),
@JsonSubTypes.Type(value = PreprTagGroup.class, name = PreprTagGroup.LABEL),
@JsonSubTypes.Type(value = PreprGuide.class, name = PreprGuide.LABEL),
@JsonSubTypes.Type(value = PreprImaging.class, name = PreprImaging.LABEL),
@JsonSubTypes.Type(value = PreprTalk.class, name = PreprTalk.LABEL),
@JsonSubTypes.Type(value = PreprTrafficTalk.class, name = PreprTrafficTalk.LABEL),
@JsonSubTypes.Type(value = PreprWeatherTalk.class, name = PreprWeatherTalk.LABEL),
@JsonSubTypes.Type(value = PreprWeatherServiceProvider.class, name = PreprWeatherServiceProvider.LABEL),
@JsonSubTypes.Type(value = PreprCommercial.class, name = PreprCommercial.LABEL),
@JsonSubTypes.Type(value = PreprNewsBulletin.class,name = PreprNewsBulletin.LABEL),
@JsonSubTypes.Type(value = PreprPublication.class,name = PreprPublication.LABEL),
@JsonSubTypes.Type(value = PreprPublicationModel.class,name = PreprPublicationModel.LABEL),
@JsonSubTypes.Type(value = PreprPublished_NLNL.class,name = PreprPublished_NLNL.LABEL),
@JsonSubTypes.Type(value = PreprNLNL.class,name = PreprNLNL.LABEL)
})
@Slf4j
public class PreprAbstractObject {
public static final String CRID_PREFIX = "crid://prepr.io/";
/**
* Ik dacht dat ids altijd UUID's waren?
* <p>
* Tim Hanssen [10:28 AM]
* In principe wel, tenzij ze uit een import komen. Bij FunX is dat het geval.
*/
String id;
Instant created_on;
Instant changed_on;
Instant last_seen;
String label;
String body;
String description;
String prev_description;
String summary;
public String getCrid() {
String label = getLabel();
if (label == null) {
log.debug("No label");
}
return label == null ? null : CRID_PREFIX + getLabel().toLowerCase() + "/" + getId();
}
public UUID getUUID() {
return UUID.fromString(id);
}
@Override
public final String toString() {
return toStringHelper().toString();
}
/**
* In some posts you can have a content:null
* Ik zie inderdaad weer 'element' en niet 'elements'.
* Bij Heading and Text heb je nu 'content: null'.
* Tom Swinkels
* 2:31 PM
* Klopt, dat is even niet anders voor nu
* Michiel Meeuwissen
* 2:32 PM
* Kan het ook niet null zijn?
*
*
* Tom Swinkels
* 2:32 PM
* Nee behalve bij media
*
* So, this makes it ignored
*/
@JsonProperty
public void setContent(List<PreprAsset> ignored) {
if (ignored != null) {
log.warn("Incoming value that is ignored {}", ignored);
}
}
MoreObjects.ToStringHelper toStringHelper() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("crid", getCrid())
.add("body", body);
}
}
| vpro/prepr | src/main/java/nl/vpro/io/prepr/domain/PreprAbstractObject.java | 1,642 | /**
* Ik dacht dat ids altijd UUID's waren?
* <p>
* Tim Hanssen [10:28 AM]
* In principe wel, tenzij ze uit een import komen. Bij FunX is dat het geval.
*/ | block_comment | nl | package nl.vpro.io.prepr.domain;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.*;
import com.google.common.base.MoreObjects;
/**
* @author Michiel Meeuwissen
* @since 0.1
*/
@Data
@JsonTypeInfo(
visible = true,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
use = JsonTypeInfo.Id.NAME, property="label",
defaultImpl = Void.class
)
@JsonSubTypes({
@JsonSubTypes.Type(value = PreprWebhook.class, name = PreprWebhook.LABEL),
@JsonSubTypes.Type(value = PreprTimeline.class, name = PreprTimeline.LABEL),
@JsonSubTypes.Type(value = PreprShow.class, name = PreprShow.LABEL),
@JsonSubTypes.Type(value = PreprShowDetail.class, name = PreprShowDetail.LABEL),
@JsonSubTypes.Type(value = PreprPhoto.class, name = PreprPhoto.LABEL),
@JsonSubTypes.Type(value = PreprProfilePhoto.class,name = PreprProfilePhoto.LABEL),
@JsonSubTypes.Type(value = PreprVideo.class, name = PreprVideo.LABEL),
@JsonSubTypes.Type(value = PreprAudio.class, name = PreprAudio.LABEL),
@JsonSubTypes.Type(value = PreprCover.class, name = PreprCover.LABEL),
@JsonSubTypes.Type(value = PreprPost.class, name = PreprPost.LABEL),
@JsonSubTypes.Type(value = PreprHeading.class, name = PreprHeading.LABEL),
@JsonSubTypes.Type(value = PreprText.class, name = PreprText.LABEL),
@JsonSubTypes.Type(value = PreprMedia.class, name = PreprMedia.LABEL),
@JsonSubTypes.Type(value = PreprTrackPlay.class, name = PreprTrackPlay.LABEL),
@JsonSubTypes.Type(value = PreprTrack.class, name = PreprTrack.LABEL),
@JsonSubTypes.Type(value = PreprChannel.class, name = PreprChannel.LABEL),
@JsonSubTypes.Type(value = PreprNewsCast.class, name = PreprNewsCast.LABEL),
@JsonSubTypes.Type(value = PreprTag.class, name = PreprTag.LABEL),
@JsonSubTypes.Type(value = PreprTagGroup.class, name = PreprTagGroup.LABEL),
@JsonSubTypes.Type(value = PreprGuide.class, name = PreprGuide.LABEL),
@JsonSubTypes.Type(value = PreprImaging.class, name = PreprImaging.LABEL),
@JsonSubTypes.Type(value = PreprTalk.class, name = PreprTalk.LABEL),
@JsonSubTypes.Type(value = PreprTrafficTalk.class, name = PreprTrafficTalk.LABEL),
@JsonSubTypes.Type(value = PreprWeatherTalk.class, name = PreprWeatherTalk.LABEL),
@JsonSubTypes.Type(value = PreprWeatherServiceProvider.class, name = PreprWeatherServiceProvider.LABEL),
@JsonSubTypes.Type(value = PreprCommercial.class, name = PreprCommercial.LABEL),
@JsonSubTypes.Type(value = PreprNewsBulletin.class,name = PreprNewsBulletin.LABEL),
@JsonSubTypes.Type(value = PreprPublication.class,name = PreprPublication.LABEL),
@JsonSubTypes.Type(value = PreprPublicationModel.class,name = PreprPublicationModel.LABEL),
@JsonSubTypes.Type(value = PreprPublished_NLNL.class,name = PreprPublished_NLNL.LABEL),
@JsonSubTypes.Type(value = PreprNLNL.class,name = PreprNLNL.LABEL)
})
@Slf4j
public class PreprAbstractObject {
public static final String CRID_PREFIX = "crid://prepr.io/";
/**
* Ik dacht dat<SUF>*/
String id;
Instant created_on;
Instant changed_on;
Instant last_seen;
String label;
String body;
String description;
String prev_description;
String summary;
public String getCrid() {
String label = getLabel();
if (label == null) {
log.debug("No label");
}
return label == null ? null : CRID_PREFIX + getLabel().toLowerCase() + "/" + getId();
}
public UUID getUUID() {
return UUID.fromString(id);
}
@Override
public final String toString() {
return toStringHelper().toString();
}
/**
* In some posts you can have a content:null
* Ik zie inderdaad weer 'element' en niet 'elements'.
* Bij Heading and Text heb je nu 'content: null'.
* Tom Swinkels
* 2:31 PM
* Klopt, dat is even niet anders voor nu
* Michiel Meeuwissen
* 2:32 PM
* Kan het ook niet null zijn?
*
*
* Tom Swinkels
* 2:32 PM
* Nee behalve bij media
*
* So, this makes it ignored
*/
@JsonProperty
public void setContent(List<PreprAsset> ignored) {
if (ignored != null) {
log.warn("Incoming value that is ignored {}", ignored);
}
}
MoreObjects.ToStringHelper toStringHelper() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("crid", getCrid())
.add("body", body);
}
}
|
11535_1 | package nl.vpro.rs.converters;
import java.time.Instant;
import java.time.ZoneId;
import java.util.regex.Pattern;
import jakarta.ws.rs.ext.ParamConverter;
import jakarta.ws.rs.ext.Provider;
import nl.vpro.util.TimeUtils;
/**
* @author Michiel Meeuwissen
* @since 0.31
*/
@Provider
public class InstantParamConverter implements ParamConverter<Instant> {
private static final ZoneId ZONE_ID = ZoneId.of("Europe/Amsterdam");
static InstantParamConverter INSTANCE = new InstantParamConverter();
private static final Pattern NUMERIC = Pattern.compile("\\d+");
@Override
public Instant fromString(String value) {
if (value == null || value.length() == 0) {
return null;
}
// zo kunnen we het gewoon op de URL copy/pasten. + -> " " -> +....
value = value.replaceAll(" ", "+");
return TimeUtils.parse(value).orElse(null);
}
@Override
public String toString(Instant value) {
if (value == null) {
return null;
}
return value.toString();
}
}
| vpro/vpro-shared | vpro-shared-rs/src/main/java/nl/vpro/rs/converters/InstantParamConverter.java | 326 | // zo kunnen we het gewoon op de URL copy/pasten. + -> " " -> +.... | line_comment | nl | package nl.vpro.rs.converters;
import java.time.Instant;
import java.time.ZoneId;
import java.util.regex.Pattern;
import jakarta.ws.rs.ext.ParamConverter;
import jakarta.ws.rs.ext.Provider;
import nl.vpro.util.TimeUtils;
/**
* @author Michiel Meeuwissen
* @since 0.31
*/
@Provider
public class InstantParamConverter implements ParamConverter<Instant> {
private static final ZoneId ZONE_ID = ZoneId.of("Europe/Amsterdam");
static InstantParamConverter INSTANCE = new InstantParamConverter();
private static final Pattern NUMERIC = Pattern.compile("\\d+");
@Override
public Instant fromString(String value) {
if (value == null || value.length() == 0) {
return null;
}
// zo kunnen<SUF>
value = value.replaceAll(" ", "+");
return TimeUtils.parse(value).orElse(null);
}
@Override
public String toString(Instant value) {
if (value == null) {
return null;
}
return value.toString();
}
}
|
127401_1 | package com.mybaggage.controllers;
import com.jfoenix.controls.JFXButton;
import com.mybaggage.Utilities;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.FadeTransition;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author Ludo Bak
*/
public class AdminController implements Initializable {
@FXML
private AnchorPane holderPane;
@FXML
private JFXButton btnHome;
@FXML
private Button btnLogOut;
@FXML
private Button btnExit;
@FXML
private Button btnHelpdesk;
@FXML
private Button btnBagage;
@FXML
private Button btnUM;
@FXML
private Button btnRegistreerSchadevergoeding;
@FXML
private Button btnBagageZoeken;
@FXML
private Button btnBagageOverzicht;
@FXML
private Button btnBagageToevoegen;
AnchorPane bagageOverzicht, bagageZoeken, faq, helpdesk, fxml2, inlogscherm, UM, registreerSchadevergoeding;
//Zet waarden leeg en maakt nieuwe objecten via classes.
Stage dialogStage = new Stage();
Scene scene;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSet resultSet2 = null;
@Override
public void initialize(URL url, ResourceBundle rb) {
//Load all fxmls in a cache
try {
bagageOverzicht = FXMLLoader.load(getClass().getResource("BagageOverzicht.fxml"));
bagageZoeken = FXMLLoader.load(getClass().getResource("FXML2.fxml"));
inlogscherm = FXMLLoader.load(getClass().getResource("Inlogscherm.fxml"));
faq = FXMLLoader.load(getClass().getResource("FAQ.fxml"));
fxml2 = FXMLLoader.load(getClass().getResource("Rapportage.fxml"));
UM = FXMLLoader.load(getClass().getResource("UM.fxml"));
helpdesk = FXMLLoader.load(getClass().getResource("HelpdeskAdmin.fxml"));
registreerSchadevergoeding = FXMLLoader.load(getClass().getResource("RegistreerSchadevergoeding.fxml"));
setNode(fxml2);
} catch (IOException ex) {
Logger.getLogger(MedewerkerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void logOff(ActionEvent event) throws IOException {
Node source = (Node) event.getSource();
dialogStage = (Stage) source.getScene().getWindow();
dialogStage.close();
scene = new Scene((Parent) FXMLLoader.load(getClass().getResource("Inlogscherm.fxml")));
dialogStage.setScene(scene);
dialogStage.show();
}
@FXML
private void exit(ActionEvent event) throws IOException {
Stage stage = (Stage) btnExit.getScene().getWindow();
stage.close();
}
//Set selected node to a content holder
private void setNode(Node node) {
holderPane.getChildren().clear();
holderPane.getChildren().add((Node) node);
FadeTransition ft = new FadeTransition(Duration.millis(1500));
ft.setNode(node);
ft.setFromValue(0.1);
ft.setToValue(1);
ft.setCycleCount(1);
ft.setAutoReverse(false);
ft.play();
}
/**
* Keyboard-shortcuts methode om te navigeren met F-Keys.
*
* @author Ismail Bahar (500783727)
*/
@FXML
private void keyPressed(KeyEvent event) throws IOException {
switch (event.getCode()) {
case F2:
Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane);
break;
case F3:
Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane);
break;
case F4:
Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane);
break;
case F5:
Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane);
break;
case F6:
Utilities.switchSchermNaarFXML("FAQ.fxml", holderPane);
break;
case F7:
Utilities.switchSchermNaarFXML("HelpdeskAdmin.fxml", holderPane);
break;
case F8:
Utilities.switchSchermNaarFXML("UM.fxml", holderPane);
break;
default:
break;
}
}
@FXML
private void openHome(ActionEvent event) {
setNode(fxml2);
}
@FXML
private void openBagageToevoegen(ActionEvent event) throws IOException {
//setNode(bagageToevoegen);
Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane);
}
@FXML
private void openBagageOverzicht(ActionEvent event) throws IOException {
//setNode(bagageOverzicht);
Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane);
}
@FXML
private void openBagageZoeken(ActionEvent event) throws IOException {
//setNode(bagageZoeken);
Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane);
}
@FXML
private void openContact(ActionEvent event) {
setNode(faq);
}
@FXML
private void openHelpdesk(ActionEvent event) {
setNode(helpdesk);
}
@FXML
private void openUM(ActionEvent event) {
setNode(UM);
}
@FXML
private void openRegistreerSchadevergoeding(ActionEvent event) throws IOException {
//setNode(registreerSchadevergoeding);
Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane);
}
}
| vriesr032/MyBaggage | src/main/java/com/mybaggage/controllers/AdminController.java | 1,963 | //Zet waarden leeg en maakt nieuwe objecten via classes. | line_comment | nl | package com.mybaggage.controllers;
import com.jfoenix.controls.JFXButton;
import com.mybaggage.Utilities;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.FadeTransition;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author Ludo Bak
*/
public class AdminController implements Initializable {
@FXML
private AnchorPane holderPane;
@FXML
private JFXButton btnHome;
@FXML
private Button btnLogOut;
@FXML
private Button btnExit;
@FXML
private Button btnHelpdesk;
@FXML
private Button btnBagage;
@FXML
private Button btnUM;
@FXML
private Button btnRegistreerSchadevergoeding;
@FXML
private Button btnBagageZoeken;
@FXML
private Button btnBagageOverzicht;
@FXML
private Button btnBagageToevoegen;
AnchorPane bagageOverzicht, bagageZoeken, faq, helpdesk, fxml2, inlogscherm, UM, registreerSchadevergoeding;
//Zet waarden<SUF>
Stage dialogStage = new Stage();
Scene scene;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSet resultSet2 = null;
@Override
public void initialize(URL url, ResourceBundle rb) {
//Load all fxmls in a cache
try {
bagageOverzicht = FXMLLoader.load(getClass().getResource("BagageOverzicht.fxml"));
bagageZoeken = FXMLLoader.load(getClass().getResource("FXML2.fxml"));
inlogscherm = FXMLLoader.load(getClass().getResource("Inlogscherm.fxml"));
faq = FXMLLoader.load(getClass().getResource("FAQ.fxml"));
fxml2 = FXMLLoader.load(getClass().getResource("Rapportage.fxml"));
UM = FXMLLoader.load(getClass().getResource("UM.fxml"));
helpdesk = FXMLLoader.load(getClass().getResource("HelpdeskAdmin.fxml"));
registreerSchadevergoeding = FXMLLoader.load(getClass().getResource("RegistreerSchadevergoeding.fxml"));
setNode(fxml2);
} catch (IOException ex) {
Logger.getLogger(MedewerkerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void logOff(ActionEvent event) throws IOException {
Node source = (Node) event.getSource();
dialogStage = (Stage) source.getScene().getWindow();
dialogStage.close();
scene = new Scene((Parent) FXMLLoader.load(getClass().getResource("Inlogscherm.fxml")));
dialogStage.setScene(scene);
dialogStage.show();
}
@FXML
private void exit(ActionEvent event) throws IOException {
Stage stage = (Stage) btnExit.getScene().getWindow();
stage.close();
}
//Set selected node to a content holder
private void setNode(Node node) {
holderPane.getChildren().clear();
holderPane.getChildren().add((Node) node);
FadeTransition ft = new FadeTransition(Duration.millis(1500));
ft.setNode(node);
ft.setFromValue(0.1);
ft.setToValue(1);
ft.setCycleCount(1);
ft.setAutoReverse(false);
ft.play();
}
/**
* Keyboard-shortcuts methode om te navigeren met F-Keys.
*
* @author Ismail Bahar (500783727)
*/
@FXML
private void keyPressed(KeyEvent event) throws IOException {
switch (event.getCode()) {
case F2:
Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane);
break;
case F3:
Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane);
break;
case F4:
Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane);
break;
case F5:
Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane);
break;
case F6:
Utilities.switchSchermNaarFXML("FAQ.fxml", holderPane);
break;
case F7:
Utilities.switchSchermNaarFXML("HelpdeskAdmin.fxml", holderPane);
break;
case F8:
Utilities.switchSchermNaarFXML("UM.fxml", holderPane);
break;
default:
break;
}
}
@FXML
private void openHome(ActionEvent event) {
setNode(fxml2);
}
@FXML
private void openBagageToevoegen(ActionEvent event) throws IOException {
//setNode(bagageToevoegen);
Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane);
}
@FXML
private void openBagageOverzicht(ActionEvent event) throws IOException {
//setNode(bagageOverzicht);
Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane);
}
@FXML
private void openBagageZoeken(ActionEvent event) throws IOException {
//setNode(bagageZoeken);
Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane);
}
@FXML
private void openContact(ActionEvent event) {
setNode(faq);
}
@FXML
private void openHelpdesk(ActionEvent event) {
setNode(helpdesk);
}
@FXML
private void openUM(ActionEvent event) {
setNode(UM);
}
@FXML
private void openRegistreerSchadevergoeding(ActionEvent event) throws IOException {
//setNode(registreerSchadevergoeding);
Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane);
}
}
|
194139_0 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.gv;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.gba.web.services.zaken.algemeen.koppelenumeratie.KoppelEnumeratieType.*;
import static nl.procura.standard.Globalfunctions.fil;
import java.util.List;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.DateTime;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.GvDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Gv;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.components.fields.values.UsrFieldValue;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.zaken.algemeen.*;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.koppelenumeratie.KoppelEnumeratieType;
import nl.procura.gba.web.services.zaken.algemeen.status.ZaakStatusService;
public class GegevensVerstrekkingService extends AbstractZaakContactService<GvAanvraag>
implements ZaakService<GvAanvraag> {
public GegevensVerstrekkingService() {
super("Gv", ZaakType.GEGEVENSVERSTREKKING);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de gvaanvragen")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return GvDao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ZaakContact getContact(GvAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de gv aanvragen")
public List<GvAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList(copyList(GvDao.find(getArgumentenToMap(zaakArgumenten)), GvAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new GvAanvraag());
}
@Override
public GvAanvraag getStandardZaak(GvAanvraag zaak) {
GvAanvraag zaakImpl = getInstance(zaak, GvAanvraag.class);
zaak.getProcessen().getProcessen().addAll(copyList(zaakImpl.getGvProces(), GvAanvraagProces.class));
return super.getStandardZaak(zaak);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return GvDao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
/**
* Opslaan van de gvaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het opslaan van het record")
public void save(GvAanvraag zaak) {
ZaakStatusService zaakStatussen = getZaakStatussen();
boolean isNietToekennen = KoppelEnumeratieType.TK_NEE.is(zaak.getToekenningType());
boolean isNuToekennen = KoppelEnumeratieType.TK_JA.is(zaak.getToekenningType());
if (isNietToekennen) { // Bij de aanvraag
zaakStatussen.setInitieleStatus(zaak, ZaakStatusType.GEWEIGERD, "Niet toegekend");
} else if (isNuToekennen) { // Bij de aanvraag
zaakStatussen.setInitieleStatus(zaak, ZaakStatusType.VERWERKT, "Verstrekt");
} else {
zaakStatussen.setInitieleStatus(zaak, ZaakStatusType.INBEHANDELING, "");
}
opslaanStandaardZaak(zaak);
callListeners(ServiceEvent.CHANGE);
}
public void saveProces(GvAanvraag zaak, GvAanvraagProces zaakProces) {
if (zaakProces != null) {
GvAanvraagProces gvProcesImpl = zaakProces;
if (!zaakProces.isStored()) {
gvProcesImpl.setIngevoerdDoor(new UsrFieldValue(getServices().getGebruiker()));
gvProcesImpl.setDatumTijdInvoer(new DateTime());
gvProcesImpl.setGv(findEntity(Gv.class, zaak.getCGv()));
}
saveEntity(gvProcesImpl);
boolean isToekenningVoorwaardelijk = TK_JA_VOORWAARDELIJK.is(zaak.getToekenningType());
boolean isKenbaarMaken = PA_KENBAAR_MAKEN.is(zaakProces.getProcesActieType());
boolean isNietVerstrekken = PA_NIET_VERSTREKKEN.is(zaakProces.getProcesActieType());
boolean isNuVerstrekken = PA_NU_VERSTREKKEN.is(zaakProces.getProcesActieType());
boolean isNaTermijnVerstrekken = PA_NA_TERMIJN_VERSTREKKEN.is(zaakProces.getProcesActieType());
ZaakStatusService zaakStatussen = getZaakStatussen();
if (isToekenningVoorwaardelijk) { // Bij de behandeling na de kenbaarheidstermijn
if (isKenbaarMaken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.INBEHANDELING, "");
} else if (isNietVerstrekken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.GEWEIGERD, "Niet verstrekken");
} else if (isNaTermijnVerstrekken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.INBEHANDELING, "Verstrekken na termijn");
} else if (isNuVerstrekken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.VERWERKT, "Wel verstrekken");
} else {
zaakStatussen.updateStatus(zaak, ZaakStatusUtils.getInitieleStatus(this, zaak), "");
}
}
}
}
/**
* Verwijderen van de gvaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen van het record")
public void delete(GvAanvraag zaak) {
if (fil(zaak.getZaakId())) {
ConditionalMap map = new ConditionalMap();
map.put(GvDao.ZAAK_ID, zaak.getZaakId());
map.put(GvDao.MAX_CORRECT_RESULTS, 1);
removeEntities(GvDao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
return getAlgemeneArgumentenToMap(zaakArgumenten);
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/gv/GegevensVerstrekkingService.java | 2,826 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/ | block_comment | nl | /*
* Copyright 2021 -<SUF>*/
package nl.procura.gba.web.services.zaken.gv;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.gba.web.services.zaken.algemeen.koppelenumeratie.KoppelEnumeratieType.*;
import static nl.procura.standard.Globalfunctions.fil;
import java.util.List;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.DateTime;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.GvDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Gv;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.components.fields.values.UsrFieldValue;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.zaken.algemeen.*;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.koppelenumeratie.KoppelEnumeratieType;
import nl.procura.gba.web.services.zaken.algemeen.status.ZaakStatusService;
public class GegevensVerstrekkingService extends AbstractZaakContactService<GvAanvraag>
implements ZaakService<GvAanvraag> {
public GegevensVerstrekkingService() {
super("Gv", ZaakType.GEGEVENSVERSTREKKING);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de gvaanvragen")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return GvDao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ZaakContact getContact(GvAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de gv aanvragen")
public List<GvAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList(copyList(GvDao.find(getArgumentenToMap(zaakArgumenten)), GvAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new GvAanvraag());
}
@Override
public GvAanvraag getStandardZaak(GvAanvraag zaak) {
GvAanvraag zaakImpl = getInstance(zaak, GvAanvraag.class);
zaak.getProcessen().getProcessen().addAll(copyList(zaakImpl.getGvProces(), GvAanvraagProces.class));
return super.getStandardZaak(zaak);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return GvDao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
/**
* Opslaan van de gvaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het opslaan van het record")
public void save(GvAanvraag zaak) {
ZaakStatusService zaakStatussen = getZaakStatussen();
boolean isNietToekennen = KoppelEnumeratieType.TK_NEE.is(zaak.getToekenningType());
boolean isNuToekennen = KoppelEnumeratieType.TK_JA.is(zaak.getToekenningType());
if (isNietToekennen) { // Bij de aanvraag
zaakStatussen.setInitieleStatus(zaak, ZaakStatusType.GEWEIGERD, "Niet toegekend");
} else if (isNuToekennen) { // Bij de aanvraag
zaakStatussen.setInitieleStatus(zaak, ZaakStatusType.VERWERKT, "Verstrekt");
} else {
zaakStatussen.setInitieleStatus(zaak, ZaakStatusType.INBEHANDELING, "");
}
opslaanStandaardZaak(zaak);
callListeners(ServiceEvent.CHANGE);
}
public void saveProces(GvAanvraag zaak, GvAanvraagProces zaakProces) {
if (zaakProces != null) {
GvAanvraagProces gvProcesImpl = zaakProces;
if (!zaakProces.isStored()) {
gvProcesImpl.setIngevoerdDoor(new UsrFieldValue(getServices().getGebruiker()));
gvProcesImpl.setDatumTijdInvoer(new DateTime());
gvProcesImpl.setGv(findEntity(Gv.class, zaak.getCGv()));
}
saveEntity(gvProcesImpl);
boolean isToekenningVoorwaardelijk = TK_JA_VOORWAARDELIJK.is(zaak.getToekenningType());
boolean isKenbaarMaken = PA_KENBAAR_MAKEN.is(zaakProces.getProcesActieType());
boolean isNietVerstrekken = PA_NIET_VERSTREKKEN.is(zaakProces.getProcesActieType());
boolean isNuVerstrekken = PA_NU_VERSTREKKEN.is(zaakProces.getProcesActieType());
boolean isNaTermijnVerstrekken = PA_NA_TERMIJN_VERSTREKKEN.is(zaakProces.getProcesActieType());
ZaakStatusService zaakStatussen = getZaakStatussen();
if (isToekenningVoorwaardelijk) { // Bij de behandeling na de kenbaarheidstermijn
if (isKenbaarMaken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.INBEHANDELING, "");
} else if (isNietVerstrekken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.GEWEIGERD, "Niet verstrekken");
} else if (isNaTermijnVerstrekken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.INBEHANDELING, "Verstrekken na termijn");
} else if (isNuVerstrekken) {
zaakStatussen.updateStatus(zaak, ZaakStatusType.VERWERKT, "Wel verstrekken");
} else {
zaakStatussen.updateStatus(zaak, ZaakStatusUtils.getInitieleStatus(this, zaak), "");
}
}
}
}
/**
* Verwijderen van de gvaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen van het record")
public void delete(GvAanvraag zaak) {
if (fil(zaak.getZaakId())) {
ConditionalMap map = new ConditionalMap();
map.put(GvDao.ZAAK_ID, zaak.getZaakId());
map.put(GvDao.MAX_CORRECT_RESULTS, 1);
removeEntities(GvDao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
return getAlgemeneArgumentenToMap(zaakArgumenten);
}
}
|
142151_0 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.burgerzaken.dossiers.model.deaths;
import nl.procura.burgerzaken.dossiers.model.base.PersistableEnum;
import lombok.Getter;
@Getter
public enum WrittenDeclarantType implements PersistableEnum<String> {
PROSECUTOR("O", "De officier van justitie"),
ASSISTANT_PROSECUTOR("H", "De hulpofficier van justitie");
private final String code;
private final String description;
WrittenDeclarantType(String code, String description) {
this.code = code;
this.description = description;
}
}
| vrijBRP/vrijBRP-Dossiers | domain/src/main/java/nl/procura/burgerzaken/dossiers/model/deaths/WrittenDeclarantType.java | 423 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/ | block_comment | nl | /*
* Copyright 2021 -<SUF>*/
package nl.procura.burgerzaken.dossiers.model.deaths;
import nl.procura.burgerzaken.dossiers.model.base.PersistableEnum;
import lombok.Getter;
@Getter
public enum WrittenDeclarantType implements PersistableEnum<String> {
PROSECUTOR("O", "De officier van justitie"),
ASSISTANT_PROSECUTOR("H", "De hulpofficier van justitie");
private final String code;
private final String description;
WrittenDeclarantType(String code, String description) {
this.code = code;
this.description = description;
}
}
|
165632_2 | package nl.procura.haalcentraal.brp.bevragen.resources.bipV1_3;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import nl.procura.gbaws.testdata.Testdata;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.BadRequestFoutbericht;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.GeslachtEnum;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.IngeschrevenPersoonHal;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.KindHalBasis;
import lombok.SneakyThrows;
/**
* {@link features/fields.features}
*/
public class FieldsTest extends IngeschrevenPersonenResourceTest {
/*
Scenario: De fields-parameter is niet opgenomen
Als een ingeschreven persoon wordt geraadpleegd zonder fields-parameter
Dan worden alle attributen van de resource teruggegeven
En worden alle relaties van de resource teruggegeven
En wordt er geen gerelateerde sub-resource teruggegeven in _embedded
*/
@Test
public void mustReturnAll() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(2, persoon.getLinks().getOuders().size());
assertEquals(1, persoon.getLinks().getKinderen().size());
assertEquals(1, persoon.getLinks().getPartners().size());
assertNull(persoon.getEmbedded());
}
/*
Scenario: Slechts één enkel attribuut wordt gevraagd
Als een ingeschreven persoon wordt geraadpleegd met fields=geslachtsaanduiding
Dan worden alleen attributen geslachtsaanduiding en _links teruggegeven
En bevat _links alleen attribuut self
*/
@Test
public void mustReturnOnlyAttribute() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geslachtsaanduiding")
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(GeslachtEnum.VROUW, persoon.getGeslachtsaanduiding());
assertNull(persoon.getEmbedded());
assertNull(persoon.getNaam());
assertNull(persoon.getLinks().getPartners());
assertNull(persoon.getLinks().getOuders());
assertNull(persoon.getLinks().getKinderen());
}
/*
Scenario: Meerdere attributen worden gevraagd
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,burgerlijkeStaat,geslachtsaanduiding
Dan worden alleen attributen burgerservicenummer, burgerlijkeStaat, geslachtsaanduiding en _links teruggegeven
En bevat _links alleen attribuut self
*/
/*
Scenario: Hele groep wordt gevraagd
Gegeven de te raadplegen persoon heeft voornamen, geslachtsnaam en voorvoegsel
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,naam
Dan worden alleen attributen burgerservicenummer, naam en _links teruggegeven
En bevat _links alleen attribuut self
*/
@Test
public void mustReturnMultipleAttributes() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geslachtsaanduiding", "naam")
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(GeslachtEnum.VROUW, persoon.getGeslachtsaanduiding());
assertNull(persoon.getEmbedded());
assertEquals("Moulin", persoon.getNaam().getGeslachtsnaam());
}
/*
Scenario: Een of enkele attributen binnen een groep worden gevraagd
Als een ingeschreven persoon wordt geraadpleegd met fields=naam.aanschrijfwijze,naam.voornamen
Dan worden alleen attributen naam en _links teruggegeven
En bevat naam alleen attributen aanschrijfwijze en voornamen
En bevat _links alleen attribuut self
*/
@Test
public void mustReturnAttributesInsideGroup() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geslachtsaanduiding", "naam.voornamen")
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(GeslachtEnum.VROUW, persoon.getGeslachtsaanduiding());
assertNull(persoon.getEmbedded());
assertEquals("Brigitte", persoon.getNaam().getVoornamen());
assertNull(persoon.getNaam().getGeslachtsnaam());
}
/*
Scenario: Relaties (links) vragen (en beperken) in het antwoord
Gegeven de te raadplegen persoon heeft een actuele partner(partnerschap of huwelijk), ouders en kinderen
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,naam,_links.partners
Dan worden alleen attributen burgerservicenummer, naam en _links teruggegeven
En bevat _links alleen attributen self en partners
*/
public void mustReturnOnlyPartnerLinks() {
// Fix fields=_links.partners
}
/*
Scenario: Gebruik van de fields parameter heeft geen invloed op embedded sub-resources
Als een ingeschreven persoon wordt geraadpleegd met fields=geboorte.land&expand=kinderen
Dan worden alleen attributen geboorte, _links en _embedded teruggegeven
En bevat geboorte alleen attribuut land
En bevat _links alleen attribuut self
En bevat _embedded alleen attribuut kinderen
En bevat elk voorkomen van _embedded.kinderen attribuut burgerservicenummer met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut naam met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut geboorte.datum met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut geboorte.plaats met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut geboorte.land met een waarde
*/
@Test
public void mustReturnEmbeddedResourcesWithfields() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geboorte.land")
.expand("kinderen");
var persoon = getIngeschrevenPersoon(params);
assertNull(persoon.getGeslachtsaanduiding());
assertNull(persoon.getNaam());
assertNull(persoon.getEmbedded().getOuders());
assertNull(persoon.getEmbedded().getPartners());
assertEquals("Frankrijk", persoon.getGeboorte().getLand().getOmschrijving());
assertNull(persoon.getGeboorte().getDatum());
assertNull(persoon.getGeboorte().getPlaats());
KindHalBasis kindHalBasis = persoon.getEmbedded().getKinderen().get(0);
assertEquals("Hélène", kindHalBasis.getNaam().getVoornamen());
assertEquals(LocalDate.of(1950, 07, 23), kindHalBasis.getGeboorte().getDatum().getDatum());
assertEquals("Narbonne", kindHalBasis.getGeboorte().getPlaats().getOmschrijving());
assertEquals("5002", kindHalBasis.getGeboorte().getLand().getCode());
}
/*
Scenario: Gebruik van de expand parameter heeft geen invloed op de inhoud van de resource
Als een ingeschreven persoon wordt geraadpleegd met fields=_links.partners&expand=kinderen
Dan worden alleen attributen _links en _embedded teruggegeven
En bevat _links alleen attributen self en partners
En bevat _embedded alleen attribuut kinderen
*/
@Test
public void mustReturnResourceWithExpandParameters() {
// Fix fields=_links.partners
}
/*
Scenario: Vragen van specifieke velden met de expand parameter heeft geen invloed op de inhoud van de resource, alleen op de inhoud van de embedded subresource
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,naam,geboorte&expand=kinderen.naam.voornamen
Dan bevat elk voorkomen van_embedded.kinderen attribuut naam.voornamen met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut _links.self met een waarde
En bevat elk voorkomen van _embedded.kinderen alleen attributen naam en _links
En bevat in elk voorkomen van _embedded.kinderen naam alleen attribuut voornamen
En bevat in elk voorkomen van _embedded.kinderen _links alleen attribuut self
En wordt attribuut burgerservicenummer teruggegeven
En wordt attribuut naam.voornamen teruggegeven
En wordt attribuut naam.geslachtsnaam teruggegeven
En wordt attribuut naam.voorvoegsel teruggegeven
En wordt attribuut geboorte teruggegeven
En wordt attribuut _links.self teruggegeven
En wordt attribuut _links.kinderen teruggegeven
*/
@Test
public void mustReturnResourceWithParameterFields() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999995935L)
.fields("burgerservicenummer", "naam", "geboorte")
.expand("kinderen.naam.voornamen");
var persoon = getIngeschrevenPersoon(params);
assertNull(persoon.getGeslachtsaanduiding());
assertEquals("Janssen", persoon.getNaam().getGeslachtsnaam());
assertNull(persoon.getEmbedded().getKinderen().get(0).getNaam().getGeslachtsnaam());
assertEquals("Jeroen", persoon.getEmbedded().getKinderen().get(0).getNaam().getVoornamen());
assertNull(persoon.getEmbedded().getKinderen().get(1).getNaam().getGeslachtsnaam());
assertEquals("Patrick", persoon.getEmbedded().getKinderen().get(1).getNaam().getVoornamen());
}
/*
Scenario: Lege fields parameter geeft alle attributen
Als een ingeschreven persoon wordt geraadpleegd met fields=
Dan levert dit alle attributen die een waarde hebben en waarvoor autorisatie is
*/
@Test
@SneakyThrows
public void mustReturnNoAttributesWithEmptyFields() {
enqueueResponse(new String(Testdata.getPersonDataAsBytes(999995935L, Testdata.DataSet.GBAV)));
String response = mockMvc.perform(get(CONTEXT_PATH
+ "/api/v1.3/ingeschrevenpersonen/999995935?fields=")
.contextPath(CONTEXT_PATH))
.andReturn()
.getResponse()
.getContentAsString(UTF_8);
IngeschrevenPersoonHal persoon = objectMapper.readValue(response, IngeschrevenPersoonHal.class);
assertEquals("Janssen", persoon.getNaam().getGeslachtsnaam());
}
/*
Scenario: Fields parameter met attribuutnaam die niet bestaat
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,geslachtsaanduiding,bestaatniet
Dan levert dit een foutmelding
*/
@Test
@SneakyThrows
public void mustReturnErrorWithNonExistingFieldParameter() {
enqueueResponse(new String(Testdata.getPersonDataAsBytes(999995935L, Testdata.DataSet.GBAV)));
String response = mockMvc.perform(get(CONTEXT_PATH
+ "/api/v1.3/ingeschrevenpersonen/999995935?fields=burgerservicenummer,geslachtsaanduiding,bestaatniet")
.contextPath(CONTEXT_PATH))
.andReturn()
.getResponse()
.getContentAsString(UTF_8);
BadRequestFoutbericht foutbericht = objectMapper.readValue(response, BadRequestFoutbericht.class);
assertEquals(400, foutbericht.getStatus());
}
/*
Scenario: Fields parameter met attribuutnaam met onjuist case
Als een ingeschreven persoon wordt geraadpleegd met fields=BurgerServiceNummer
Dan levert dit een foutmelding
*/
@Test
@SneakyThrows
public void mustReturnErrorWithIncorrectLetterCasing() {
enqueueResponse(new String(Testdata.getPersonDataAsBytes(999995935L, Testdata.DataSet.GBAV)));
String response = mockMvc.perform(get(CONTEXT_PATH
+ "/api/v1.3/ingeschrevenpersonen/999995935?fields=BurgerServiceNummer")
.contextPath(CONTEXT_PATH))
.andReturn()
.getResponse()
.getContentAsString(UTF_8);
BadRequestFoutbericht foutbericht = objectMapper.readValue(response, BadRequestFoutbericht.class);
assertEquals(400, foutbericht.getStatus());
}
/*
Scenario: Met fields vragen om attributen uit een subresource
Als een ingeschreven persoon wordt geraadpleegd met expand=kinderen&fields=kinderen.naam
Dan levert dit een foutmelding
*/
public void mustReturnErrorWhenRequestingFieldsFromSubresource() {
// Not testable as this moment
}
/*
Scenario: Fields vraagt om een groep attributen en de gebruiker is niet geautoriseerd voor al deze attributen
Gegeven de gebruiker is geautoriseerd voor geboortedatum
En de gebruiker is niet geautoriseerd voor geboorteplaats en ook niet voor geboorteland
Als een ingeschreven persoon wordt geraadpleegd met fields=geboorte
Dan wordt attribuut geboorte.datum teruggegeven
En is in het antwoord attribuut geboorte.plaats niet aanwezig
En is in het antwoord attribuut geboorte.land niet aanwezig
En wordt attribuut _links.self teruggegeven
En bevat _links alleen attribuut self
*/
public void mustReturnOnlyAuthorizedAttributes() {
// Not testable as this moment
}
/*
Scenario: Fields vraagt specifiek om een gegeven waarvoor deze niet geautoriseerd is
Gegeven de gebruiker is geautoriseerd voor geboortedatum
En de gebruiker is niet geautoriseerd voor geboorteplaats
Als een ingeschreven persoon wordt geraadpleegd met fields=geboorte.datum,geboorte.plaats
Dan wordt attribuut geboorte.datum teruggegeven
En is in het antwoord attribuut geboorte.plaats niet aanwezig
En is in het antwoord attribuut geboorte.land niet aanwezig
En wordt attribuut _links.self teruggegeven
*/
public void mustReturnOnlyAuthorizedAttributesFromFields() {
// Not testable as this moment
}
/*
Scenario: Fields bevat attributen die bij de geraadpleegde persoon geen waarde hebben
Gegeven de te raadplegen persoon verblijft in het buitenland
Als een ingeschreven persoon wordt geraadpleegd met fields=verblijfplaats.postcode,verblijfplaats.huisnummer
Dan wordt alleen attribuut _links teruggegeven
En bevat _links alleen attribuut self
En is in het antwoord attribuut verblijfplaats.adresregel1 niet aanwezig
En is in het antwoord attribuut verblijfplaats.land niet aanwezig
En is in het antwoord attribuut verblijfplaats.postcode niet aanwezig
En is in het antwoord attribuut verblijfplaats.huisnummer niet aanwezig
*/
public void mustNotReturnNLAddressFields() {
// Not testable as this moment
}
}
| vrijBRP/vrijBRP-Haal-Centraal-BRP-bevragen | application/src/test/java/nl/procura/haalcentraal/brp/bevragen/resources/bipV1_3/FieldsTest.java | 4,466 | /*
Scenario: Slechts één enkel attribuut wordt gevraagd
Als een ingeschreven persoon wordt geraadpleegd met fields=geslachtsaanduiding
Dan worden alleen attributen geslachtsaanduiding en _links teruggegeven
En bevat _links alleen attribuut self
*/ | block_comment | nl | package nl.procura.haalcentraal.brp.bevragen.resources.bipV1_3;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import nl.procura.gbaws.testdata.Testdata;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.BadRequestFoutbericht;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.GeslachtEnum;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.IngeschrevenPersoonHal;
import nl.vng.realisatie.haalcentraal.rest.generated.model.bipv1_3.KindHalBasis;
import lombok.SneakyThrows;
/**
* {@link features/fields.features}
*/
public class FieldsTest extends IngeschrevenPersonenResourceTest {
/*
Scenario: De fields-parameter is niet opgenomen
Als een ingeschreven persoon wordt geraadpleegd zonder fields-parameter
Dan worden alle attributen van de resource teruggegeven
En worden alle relaties van de resource teruggegeven
En wordt er geen gerelateerde sub-resource teruggegeven in _embedded
*/
@Test
public void mustReturnAll() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(2, persoon.getLinks().getOuders().size());
assertEquals(1, persoon.getLinks().getKinderen().size());
assertEquals(1, persoon.getLinks().getPartners().size());
assertNull(persoon.getEmbedded());
}
/*
Scenario: Slechts één<SUF>*/
@Test
public void mustReturnOnlyAttribute() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geslachtsaanduiding")
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(GeslachtEnum.VROUW, persoon.getGeslachtsaanduiding());
assertNull(persoon.getEmbedded());
assertNull(persoon.getNaam());
assertNull(persoon.getLinks().getPartners());
assertNull(persoon.getLinks().getOuders());
assertNull(persoon.getLinks().getKinderen());
}
/*
Scenario: Meerdere attributen worden gevraagd
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,burgerlijkeStaat,geslachtsaanduiding
Dan worden alleen attributen burgerservicenummer, burgerlijkeStaat, geslachtsaanduiding en _links teruggegeven
En bevat _links alleen attribuut self
*/
/*
Scenario: Hele groep wordt gevraagd
Gegeven de te raadplegen persoon heeft voornamen, geslachtsnaam en voorvoegsel
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,naam
Dan worden alleen attributen burgerservicenummer, naam en _links teruggegeven
En bevat _links alleen attribuut self
*/
@Test
public void mustReturnMultipleAttributes() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geslachtsaanduiding", "naam")
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(GeslachtEnum.VROUW, persoon.getGeslachtsaanduiding());
assertNull(persoon.getEmbedded());
assertEquals("Moulin", persoon.getNaam().getGeslachtsnaam());
}
/*
Scenario: Een of enkele attributen binnen een groep worden gevraagd
Als een ingeschreven persoon wordt geraadpleegd met fields=naam.aanschrijfwijze,naam.voornamen
Dan worden alleen attributen naam en _links teruggegeven
En bevat naam alleen attributen aanschrijfwijze en voornamen
En bevat _links alleen attribuut self
*/
@Test
public void mustReturnAttributesInsideGroup() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geslachtsaanduiding", "naam.voornamen")
.expand("");
var persoon = getIngeschrevenPersoon(params);
assertEquals(GeslachtEnum.VROUW, persoon.getGeslachtsaanduiding());
assertNull(persoon.getEmbedded());
assertEquals("Brigitte", persoon.getNaam().getVoornamen());
assertNull(persoon.getNaam().getGeslachtsnaam());
}
/*
Scenario: Relaties (links) vragen (en beperken) in het antwoord
Gegeven de te raadplegen persoon heeft een actuele partner(partnerschap of huwelijk), ouders en kinderen
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,naam,_links.partners
Dan worden alleen attributen burgerservicenummer, naam en _links teruggegeven
En bevat _links alleen attributen self en partners
*/
public void mustReturnOnlyPartnerLinks() {
// Fix fields=_links.partners
}
/*
Scenario: Gebruik van de fields parameter heeft geen invloed op embedded sub-resources
Als een ingeschreven persoon wordt geraadpleegd met fields=geboorte.land&expand=kinderen
Dan worden alleen attributen geboorte, _links en _embedded teruggegeven
En bevat geboorte alleen attribuut land
En bevat _links alleen attribuut self
En bevat _embedded alleen attribuut kinderen
En bevat elk voorkomen van _embedded.kinderen attribuut burgerservicenummer met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut naam met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut geboorte.datum met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut geboorte.plaats met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut geboorte.land met een waarde
*/
@Test
public void mustReturnEmbeddedResourcesWithfields() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999992545L)
.fields("geboorte.land")
.expand("kinderen");
var persoon = getIngeschrevenPersoon(params);
assertNull(persoon.getGeslachtsaanduiding());
assertNull(persoon.getNaam());
assertNull(persoon.getEmbedded().getOuders());
assertNull(persoon.getEmbedded().getPartners());
assertEquals("Frankrijk", persoon.getGeboorte().getLand().getOmschrijving());
assertNull(persoon.getGeboorte().getDatum());
assertNull(persoon.getGeboorte().getPlaats());
KindHalBasis kindHalBasis = persoon.getEmbedded().getKinderen().get(0);
assertEquals("Hélène", kindHalBasis.getNaam().getVoornamen());
assertEquals(LocalDate.of(1950, 07, 23), kindHalBasis.getGeboorte().getDatum().getDatum());
assertEquals("Narbonne", kindHalBasis.getGeboorte().getPlaats().getOmschrijving());
assertEquals("5002", kindHalBasis.getGeboorte().getLand().getCode());
}
/*
Scenario: Gebruik van de expand parameter heeft geen invloed op de inhoud van de resource
Als een ingeschreven persoon wordt geraadpleegd met fields=_links.partners&expand=kinderen
Dan worden alleen attributen _links en _embedded teruggegeven
En bevat _links alleen attributen self en partners
En bevat _embedded alleen attribuut kinderen
*/
@Test
public void mustReturnResourceWithExpandParameters() {
// Fix fields=_links.partners
}
/*
Scenario: Vragen van specifieke velden met de expand parameter heeft geen invloed op de inhoud van de resource, alleen op de inhoud van de embedded subresource
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,naam,geboorte&expand=kinderen.naam.voornamen
Dan bevat elk voorkomen van_embedded.kinderen attribuut naam.voornamen met een waarde
En bevat elk voorkomen van_embedded.kinderen attribuut _links.self met een waarde
En bevat elk voorkomen van _embedded.kinderen alleen attributen naam en _links
En bevat in elk voorkomen van _embedded.kinderen naam alleen attribuut voornamen
En bevat in elk voorkomen van _embedded.kinderen _links alleen attribuut self
En wordt attribuut burgerservicenummer teruggegeven
En wordt attribuut naam.voornamen teruggegeven
En wordt attribuut naam.geslachtsnaam teruggegeven
En wordt attribuut naam.voorvoegsel teruggegeven
En wordt attribuut geboorte teruggegeven
En wordt attribuut _links.self teruggegeven
En wordt attribuut _links.kinderen teruggegeven
*/
@Test
public void mustReturnResourceWithParameterFields() {
var params = new IngeschrevenPersonenTestParams()
.bsns(999995935L)
.fields("burgerservicenummer", "naam", "geboorte")
.expand("kinderen.naam.voornamen");
var persoon = getIngeschrevenPersoon(params);
assertNull(persoon.getGeslachtsaanduiding());
assertEquals("Janssen", persoon.getNaam().getGeslachtsnaam());
assertNull(persoon.getEmbedded().getKinderen().get(0).getNaam().getGeslachtsnaam());
assertEquals("Jeroen", persoon.getEmbedded().getKinderen().get(0).getNaam().getVoornamen());
assertNull(persoon.getEmbedded().getKinderen().get(1).getNaam().getGeslachtsnaam());
assertEquals("Patrick", persoon.getEmbedded().getKinderen().get(1).getNaam().getVoornamen());
}
/*
Scenario: Lege fields parameter geeft alle attributen
Als een ingeschreven persoon wordt geraadpleegd met fields=
Dan levert dit alle attributen die een waarde hebben en waarvoor autorisatie is
*/
@Test
@SneakyThrows
public void mustReturnNoAttributesWithEmptyFields() {
enqueueResponse(new String(Testdata.getPersonDataAsBytes(999995935L, Testdata.DataSet.GBAV)));
String response = mockMvc.perform(get(CONTEXT_PATH
+ "/api/v1.3/ingeschrevenpersonen/999995935?fields=")
.contextPath(CONTEXT_PATH))
.andReturn()
.getResponse()
.getContentAsString(UTF_8);
IngeschrevenPersoonHal persoon = objectMapper.readValue(response, IngeschrevenPersoonHal.class);
assertEquals("Janssen", persoon.getNaam().getGeslachtsnaam());
}
/*
Scenario: Fields parameter met attribuutnaam die niet bestaat
Als een ingeschreven persoon wordt geraadpleegd met fields=burgerservicenummer,geslachtsaanduiding,bestaatniet
Dan levert dit een foutmelding
*/
@Test
@SneakyThrows
public void mustReturnErrorWithNonExistingFieldParameter() {
enqueueResponse(new String(Testdata.getPersonDataAsBytes(999995935L, Testdata.DataSet.GBAV)));
String response = mockMvc.perform(get(CONTEXT_PATH
+ "/api/v1.3/ingeschrevenpersonen/999995935?fields=burgerservicenummer,geslachtsaanduiding,bestaatniet")
.contextPath(CONTEXT_PATH))
.andReturn()
.getResponse()
.getContentAsString(UTF_8);
BadRequestFoutbericht foutbericht = objectMapper.readValue(response, BadRequestFoutbericht.class);
assertEquals(400, foutbericht.getStatus());
}
/*
Scenario: Fields parameter met attribuutnaam met onjuist case
Als een ingeschreven persoon wordt geraadpleegd met fields=BurgerServiceNummer
Dan levert dit een foutmelding
*/
@Test
@SneakyThrows
public void mustReturnErrorWithIncorrectLetterCasing() {
enqueueResponse(new String(Testdata.getPersonDataAsBytes(999995935L, Testdata.DataSet.GBAV)));
String response = mockMvc.perform(get(CONTEXT_PATH
+ "/api/v1.3/ingeschrevenpersonen/999995935?fields=BurgerServiceNummer")
.contextPath(CONTEXT_PATH))
.andReturn()
.getResponse()
.getContentAsString(UTF_8);
BadRequestFoutbericht foutbericht = objectMapper.readValue(response, BadRequestFoutbericht.class);
assertEquals(400, foutbericht.getStatus());
}
/*
Scenario: Met fields vragen om attributen uit een subresource
Als een ingeschreven persoon wordt geraadpleegd met expand=kinderen&fields=kinderen.naam
Dan levert dit een foutmelding
*/
public void mustReturnErrorWhenRequestingFieldsFromSubresource() {
// Not testable as this moment
}
/*
Scenario: Fields vraagt om een groep attributen en de gebruiker is niet geautoriseerd voor al deze attributen
Gegeven de gebruiker is geautoriseerd voor geboortedatum
En de gebruiker is niet geautoriseerd voor geboorteplaats en ook niet voor geboorteland
Als een ingeschreven persoon wordt geraadpleegd met fields=geboorte
Dan wordt attribuut geboorte.datum teruggegeven
En is in het antwoord attribuut geboorte.plaats niet aanwezig
En is in het antwoord attribuut geboorte.land niet aanwezig
En wordt attribuut _links.self teruggegeven
En bevat _links alleen attribuut self
*/
public void mustReturnOnlyAuthorizedAttributes() {
// Not testable as this moment
}
/*
Scenario: Fields vraagt specifiek om een gegeven waarvoor deze niet geautoriseerd is
Gegeven de gebruiker is geautoriseerd voor geboortedatum
En de gebruiker is niet geautoriseerd voor geboorteplaats
Als een ingeschreven persoon wordt geraadpleegd met fields=geboorte.datum,geboorte.plaats
Dan wordt attribuut geboorte.datum teruggegeven
En is in het antwoord attribuut geboorte.plaats niet aanwezig
En is in het antwoord attribuut geboorte.land niet aanwezig
En wordt attribuut _links.self teruggegeven
*/
public void mustReturnOnlyAuthorizedAttributesFromFields() {
// Not testable as this moment
}
/*
Scenario: Fields bevat attributen die bij de geraadpleegde persoon geen waarde hebben
Gegeven de te raadplegen persoon verblijft in het buitenland
Als een ingeschreven persoon wordt geraadpleegd met fields=verblijfplaats.postcode,verblijfplaats.huisnummer
Dan wordt alleen attribuut _links teruggegeven
En bevat _links alleen attribuut self
En is in het antwoord attribuut verblijfplaats.adresregel1 niet aanwezig
En is in het antwoord attribuut verblijfplaats.land niet aanwezig
En is in het antwoord attribuut verblijfplaats.postcode niet aanwezig
En is in het antwoord attribuut verblijfplaats.huisnummer niet aanwezig
*/
public void mustNotReturnNLAddressFields() {
// Not testable as this moment
}
}
|
97545_4 | package com.vladsch.flexmark.ext.tables.internal;
import com.vladsch.flexmark.ast.Paragraph;
import com.vladsch.flexmark.ast.Text;
import com.vladsch.flexmark.ast.WhiteSpace;
import com.vladsch.flexmark.ext.tables.*;
import com.vladsch.flexmark.parser.InlineParser;
import com.vladsch.flexmark.parser.block.CharacterNodeFactory;
import com.vladsch.flexmark.parser.block.ParagraphPreProcessor;
import com.vladsch.flexmark.parser.block.ParagraphPreProcessorFactory;
import com.vladsch.flexmark.parser.block.ParserState;
import com.vladsch.flexmark.parser.core.ReferencePreProcessorFactory;
import com.vladsch.flexmark.util.ast.Block;
import com.vladsch.flexmark.util.ast.DoNotDecorate;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.ast.NodeIterator;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.format.TableFormatOptions;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Pattern;
public class TableParagraphPreProcessor implements ParagraphPreProcessor {
private static BitSet pipeCharacters = new BitSet();
private static BitSet separatorCharacters = new BitSet();
static {
pipeCharacters.set('|');
separatorCharacters.set('|');
separatorCharacters.set(':');
separatorCharacters.set('-');
}
private static HashMap<Character, CharacterNodeFactory> pipeNodeMap = new HashMap<>();
static {
pipeNodeMap.put('|', new CharacterNodeFactory() {
@Override
public boolean skipNext(char c) {
return c == ' ' || c == '\t';
//return false;
}
@Override
public boolean skipPrev(char c) {
return c == ' ' || c == '\t';
//return false;
}
@Override
public boolean wantSkippedWhitespace() {
return true;
}
@Override
public Node get() {
return new TableColumnSeparator();
}
});
}
private static HashMap<Character, CharacterNodeFactory> pipeIntelliJNodeMap = new HashMap<>();
static {
pipeIntelliJNodeMap.put('|', new CharacterNodeFactory() {
@Override
public boolean skipNext(char c) {
return c == ' ' || c == '\t';
//return false;
}
@Override
public boolean skipPrev(char c) {
return c == ' ' || c == '\t' /*|| c == TableFormatOptions.INTELLIJ_DUMMY_IDENTIFIER_CHAR*/;
//return false;
}
@Override
public boolean wantSkippedWhitespace() {
return true;
}
@Override
public Node get() {
return new TableColumnSeparator();
}
});
}
public static ParagraphPreProcessorFactory Factory() {
return new ParagraphPreProcessorFactory() {
@Override
public boolean affectsGlobalScope() {
return false;
}
@Nullable
@Override
public Set<Class<?>> getAfterDependents() {
HashSet<Class<?>> set = new HashSet<>();
set.add(ReferencePreProcessorFactory.class);
return set;
}
@Nullable
@Override
public Set<Class<?>> getBeforeDependents() {
return null;
}
@Override
public ParagraphPreProcessor apply(ParserState state) {
return new TableParagraphPreProcessor(state.getProperties());
}
};
}
final private TableParserOptions options;
Pattern TABLE_HEADER_SEPARATOR;
public static Pattern getTableHeaderSeparator(int minColumnDashes, String intellijDummyIdentifier) {
int minCol = minColumnDashes >= 1 ? minColumnDashes : 1;
int minColDash = minColumnDashes >= 2 ? minColumnDashes - 1 : 1;
int minColDashes = minColumnDashes >= 3 ? minColumnDashes - 2 : 1;
// to prevent conversion to arabic numbers, using string
String COL = String.format(Locale.US, "(?:" + "\\s*-{%d,}\\s*|\\s*:-{%d,}\\s*|\\s*-{%d,}:\\s*|\\s*:-{%d,}:\\s*" + ")", minCol, minColDash, minColDash, minColDashes);
boolean noIntelliJ = intellijDummyIdentifier.isEmpty();
String add = noIntelliJ ? "" : TableFormatOptions.INTELLIJ_DUMMY_IDENTIFIER;
String sp = noIntelliJ ? "\\s" : "(?:\\s" + add + "?)";
String ds = noIntelliJ ? "-" : "(?:-" + add + "?)";
String pipe = noIntelliJ ? "\\|" : "(?:" + add + "?\\|" + add + "?)";
//COL = COL.replace("\\s", sp).replace("-", ds);
String regex = "\\|" + COL + "\\|?\\s*" + "|" +
COL + "\\|\\s*" + "|" +
"\\|?" + "(?:" + COL + "\\|)+" + COL + "\\|?\\s*";
String withIntelliJ = regex.replace("\\s", sp).replace("\\|", pipe).replace("-", ds);
return Pattern.compile(withIntelliJ);
}
private TableParagraphPreProcessor(DataHolder options) {
this.options = new TableParserOptions(options);
//isIntellijDummyIdentifier = Parser.INTELLIJ_DUMMY_IDENTIFIER.getFrom(options);
//intellijDummyIdentifier = isIntellijDummyIdentifier ? INTELLIJ_DUMMY_IDENTIFIER : "";
this.TABLE_HEADER_SEPARATOR = getTableHeaderSeparator(this.options.minSeparatorDashes, "");
}
private static class TableSeparatorRow extends TableRow implements DoNotDecorate {
public TableSeparatorRow() {
}
public TableSeparatorRow(BasedSequence chars) {
super(chars);
}
}
@Override
public int preProcessBlock(Paragraph block, ParserState state) {
InlineParser inlineParser = state.getInlineParser();
ArrayList<BasedSequence> tableLines = new ArrayList<>();
int separatorLineNumber = -1;
BasedSequence separatorLine = null;
int blockIndent = block.getLineIndent(0);
BasedSequence captionLine = null;
BitSet separators = separatorCharacters;
HashMap<Character, CharacterNodeFactory> nodeMap = pipeNodeMap;
int i = 0;
for (BasedSequence rowLine : block.getContentLines()) {
int rowNumber = tableLines.size();
if (separatorLineNumber == -1 && rowNumber > options.maxHeaderRows) return 0; // too many header rows
if (rowLine.indexOf('|') < 0) {
if (separatorLineNumber == -1) return 0;
if (options.withCaption) {
BasedSequence trimmed = rowLine.trim();
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
captionLine = trimmed;
}
}
break;
}
// NOTE: block lines now contain leading indent spaces which should be ignored
BasedSequence trimmedRowLine = rowLine.subSequence(block.getLineIndent(rowNumber));
if (separatorLineNumber == -1) {
if (rowNumber >= options.minHeaderRows
&& TABLE_HEADER_SEPARATOR.matcher(trimmedRowLine).matches()) {
// must start with | or cell, whitespace means its not a separator line
if (rowLine.charAt(0) != ' ' && rowLine.charAt(0) != '\t' || rowLine.charAt(0) != '|') {
separatorLineNumber = rowNumber;
separatorLine = trimmedRowLine;
} else if (rowLine.charAt(0) == ' ' || rowLine.charAt(0) == '\t') {
block.setHasTableSeparator(true);
}
}
}
tableLines.add(trimmedRowLine);
i++;
}
if (separatorLineNumber == -1) return 0;
ArrayList<TableRow> tableRows = new ArrayList<>();
for (BasedSequence rowLine : tableLines) {
int rowNumber = tableRows.size();
BasedSequence fullRowLine = block.getLineIndent(rowNumber) <= blockIndent ? rowLine.trimEOL() : rowLine.baseSubSequence(rowLine.getStartOffset() - (block.getLineIndent(rowNumber) - blockIndent), rowLine.getEndOffset() - rowLine.eolEndLength());
boolean isSeparator = rowNumber == separatorLineNumber;
TableRow tableRow = new TableRow(fullRowLine);
int tableRowNumber;
List<Node> sepList;
if (isSeparator) {
TableSeparatorRow fakeRow = new TableSeparatorRow(fullRowLine);
sepList = inlineParser.parseCustom(fullRowLine, fakeRow, separators, nodeMap);
tableRow.takeChildren(fakeRow);
//sepList = inlineParser.parseCustom(fullRowLine, tableRow, separators, nodeMap);
tableRowNumber = 0;
} else {
sepList = inlineParser.parseCustom(fullRowLine, tableRow, pipeCharacters, pipeNodeMap);
if (rowNumber < separatorLineNumber) tableRowNumber = rowNumber + 1;
else tableRowNumber = rowNumber - separatorLineNumber;
// can have table separators embedded inside inline elements, need to convert them to text
// and remove them from sepList
if (sepList != null) {
sepList = cleanUpInlinedSeparators(inlineParser, tableRow, sepList);
}
}
if (sepList == null) {
if (rowNumber <= separatorLineNumber) return 0;
break;
}
tableRow.setRowNumber(tableRowNumber);
tableRows.add(tableRow);
}
// table is done, could be earlier than the lines tested earlier, may need to truncate lines
Block tableBlock = new TableBlock(tableLines.subList(0, tableRows.size()));
Node section = new TableHead(tableLines.get(0).subSequence(0, 0));
tableBlock.appendChild(section);
List<TableCell.Alignment> alignments = parseAlignment(separatorLine);
int rowNumber = 0;
int separatorColumns = alignments.size();
for (TableRow tableRow : tableRows) {
if (rowNumber == separatorLineNumber) {
section.setCharsFromContent();
section = new TableSeparator();
tableBlock.appendChild(section);
} else if (rowNumber == separatorLineNumber + 1) {
section.setCharsFromContent();
section = new TableBody();
tableBlock.appendChild(section);
}
boolean firstCell = true;
int cellCount = 0;
NodeIterator nodes = new NodeIterator(tableRow.getFirstChild());
TableRow newTableRow = new TableRow(tableRow.getChars());
newTableRow.setRowNumber(tableRow.getRowNumber());
int accumulatedSpanOffset = 0;
while (nodes.hasNext()) {
if (cellCount >= separatorColumns && options.discardExtraColumns) {
if (options.headerSeparatorColumnMatch && rowNumber < separatorLineNumber) {
// header/separator mismatch
return 0;
}
break;
}
//TableCell tableCell = rowNumber == separatorLineNumber ? new TableSeparatorCell() : new TableCell();
TableCell tableCell = new TableCell();
if (firstCell && nodes.peek() instanceof TableColumnSeparator) {
Node columnSep = nodes.next();
tableCell.setOpeningMarker(columnSep.getChars());
columnSep.unlink();
firstCell = false;
}
TableCell.Alignment alignment = cellCount + accumulatedSpanOffset < separatorColumns ? alignments.get(cellCount + accumulatedSpanOffset) : null;
tableCell.setHeader(rowNumber < separatorLineNumber);
tableCell.setAlignment(alignment);
// take all until separator or end of iterator
while (nodes.hasNext()) {
if (nodes.peek() instanceof TableColumnSeparator) break;
tableCell.appendChild(nodes.next());
}
// accumulate closers, and optional spans
BasedSequence closingMarker = null;
int span = 1;
while (nodes.hasNext()) {
if (!(nodes.peek() instanceof TableColumnSeparator)) break;
if (closingMarker == null) {
closingMarker = nodes.next().getChars();
if (!options.columnSpans) break;
} else {
BasedSequence nextSep = nodes.peek().getChars();
if (!closingMarker.isContinuedBy(nextSep)) break;
closingMarker = closingMarker.spliceAtEnd(nextSep);
nodes.next().unlink();
span++;
}
}
accumulatedSpanOffset += span - 1;
if (closingMarker != null) tableCell.setClosingMarker(closingMarker);
tableCell.setChars(tableCell.getChildChars());
// option to keep cell whitespace, if yes, then convert it to text and merge adjacent text nodes
if (options.trimCellWhitespace) tableCell.trimWhiteSpace();
else tableCell.mergeWhiteSpace();
// NOTE: here we get only chars which do not reflect out-of-base characters, prefixes and removed text
tableCell.setText(tableCell.getChildChars());
tableCell.setCharsFromContent();
tableCell.setSpan(span);
newTableRow.appendChild(tableCell);
cellCount++;
}
if (options.headerSeparatorColumnMatch && rowNumber < separatorLineNumber && cellCount < separatorColumns) {
// no match
return 0;
}
while (options.appendMissingColumns && cellCount < separatorColumns) {
TableCell tableCell = new TableCell();
tableCell.setHeader(rowNumber < separatorLineNumber);
tableCell.setAlignment(alignments.get(cellCount));
newTableRow.appendChild(tableCell);
cellCount++;
}
newTableRow.setCharsFromContent();
section.appendChild(newTableRow);
rowNumber++;
}
section.setCharsFromContent();
if (section instanceof TableSeparator) {
TableBody tableBody = new TableBody(section.getChars().subSequence(section.getChars().length()));
tableBlock.appendChild(tableBody);
}
// Add caption if the option is enabled
if (captionLine != null) {
TableCaption caption = new TableCaption(captionLine.subSequence(0, 1), captionLine.subSequence(1, captionLine.length() - 1), captionLine.subSequence(captionLine.length() - 1));
inlineParser.parse(caption.getText(), caption);
caption.setCharsFromContent();
tableBlock.appendChild(caption);
}
tableBlock.setCharsFromContent();
block.insertBefore(tableBlock);
state.blockAdded(tableBlock);
return tableBlock.getChars().length();
}
List<Node> cleanUpInlinedSeparators(InlineParser inlineParser, TableRow tableRow, List<Node> sepList) {
// any separators which do not have tableRow as parent are embedded into inline elements and should be
// converted back to text
ArrayList<Node> removedSeparators = null;
ArrayList<Node> mergeTextParents = null;
for (Node node : sepList) {
if (node.getParent() != null && node.getParent() != tableRow) {
// embedded, convert it and surrounding whitespace to text
Node firstNode = node.getPrevious() instanceof WhiteSpace ? node.getPrevious() : node;
Node lastNode = node.getNext() instanceof WhiteSpace ? node.getNext() : node;
Text text = new Text(node.baseSubSequence(firstNode.getStartOffset(), lastNode.getEndOffset()));
node.insertBefore(text);
node.unlink();
firstNode.unlink();
lastNode.unlink();
if (removedSeparators == null) {
removedSeparators = new ArrayList<>();
mergeTextParents = new ArrayList<>();
}
removedSeparators.add(node);
mergeTextParents.add(text.getParent());
}
}
if (mergeTextParents != null) {
for (Node parent : mergeTextParents) {
inlineParser.mergeTextNodes(parent.getFirstChild(), parent.getLastChild());
}
if (removedSeparators.size() == sepList.size()) {
return null;
} else {
ArrayList<Node> newSeparators = new ArrayList<>(sepList);
newSeparators.removeAll(removedSeparators);
return newSeparators;
}
}
return sepList;
}
private List<TableCell.Alignment> parseAlignment(BasedSequence separatorLine) {
List<BasedSequence> parts = split(separatorLine, false, false);
List<TableCell.Alignment> alignments = new ArrayList<>();
for (BasedSequence part : parts) {
BasedSequence trimmed = part.trim();
boolean left = trimmed.startsWith(":");
boolean right = trimmed.endsWith(":");
TableCell.Alignment alignment = getAlignment(left, right);
alignments.add(alignment);
}
return alignments;
}
@SuppressWarnings("SameParameterValue")
private static List<BasedSequence> split(BasedSequence input, boolean columnSpans, boolean wantPipes) {
BasedSequence line = input.trim();
int lineLength = line.length();
List<BasedSequence> segments = new ArrayList<>();
if (line.startsWith("|")) {
if (wantPipes) segments.add(line.subSequence(0, 1));
line = line.subSequence(1, lineLength);
lineLength--;
}
boolean escape = false;
int lastPos = 0;
int cellChars = 0;
for (int i = 0; i < lineLength; i++) {
char c = line.charAt(i);
if (escape) {
escape = false;
cellChars++;
} else {
switch (c) {
case '\\':
escape = true;
// Removing the escaping '\' is handled by the inline parser later, so add it to cell
cellChars++;
break;
case '|':
if (!columnSpans || lastPos < i) segments.add(line.subSequence(lastPos, i));
if (wantPipes) segments.add(line.subSequence(i, i + 1));
lastPos = i + 1;
cellChars = 0;
break;
default:
cellChars++;
}
}
}
if (cellChars > 0) {
segments.add(line.subSequence(lastPos, lineLength));
}
return segments;
}
private static TableCell.Alignment getAlignment(boolean left, boolean right) {
if (left && right) {
return TableCell.Alignment.CENTER;
} else if (left) {
return TableCell.Alignment.LEFT;
} else if (right) {
return TableCell.Alignment.RIGHT;
} else {
return null;
}
}
}
| vsch/flexmark-java | flexmark-ext-tables/src/main/java/com/vladsch/flexmark/ext/tables/internal/TableParagraphPreProcessor.java | 5,299 | //intellijDummyIdentifier = isIntellijDummyIdentifier ? INTELLIJ_DUMMY_IDENTIFIER : ""; | line_comment | nl | package com.vladsch.flexmark.ext.tables.internal;
import com.vladsch.flexmark.ast.Paragraph;
import com.vladsch.flexmark.ast.Text;
import com.vladsch.flexmark.ast.WhiteSpace;
import com.vladsch.flexmark.ext.tables.*;
import com.vladsch.flexmark.parser.InlineParser;
import com.vladsch.flexmark.parser.block.CharacterNodeFactory;
import com.vladsch.flexmark.parser.block.ParagraphPreProcessor;
import com.vladsch.flexmark.parser.block.ParagraphPreProcessorFactory;
import com.vladsch.flexmark.parser.block.ParserState;
import com.vladsch.flexmark.parser.core.ReferencePreProcessorFactory;
import com.vladsch.flexmark.util.ast.Block;
import com.vladsch.flexmark.util.ast.DoNotDecorate;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.ast.NodeIterator;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.format.TableFormatOptions;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Pattern;
public class TableParagraphPreProcessor implements ParagraphPreProcessor {
private static BitSet pipeCharacters = new BitSet();
private static BitSet separatorCharacters = new BitSet();
static {
pipeCharacters.set('|');
separatorCharacters.set('|');
separatorCharacters.set(':');
separatorCharacters.set('-');
}
private static HashMap<Character, CharacterNodeFactory> pipeNodeMap = new HashMap<>();
static {
pipeNodeMap.put('|', new CharacterNodeFactory() {
@Override
public boolean skipNext(char c) {
return c == ' ' || c == '\t';
//return false;
}
@Override
public boolean skipPrev(char c) {
return c == ' ' || c == '\t';
//return false;
}
@Override
public boolean wantSkippedWhitespace() {
return true;
}
@Override
public Node get() {
return new TableColumnSeparator();
}
});
}
private static HashMap<Character, CharacterNodeFactory> pipeIntelliJNodeMap = new HashMap<>();
static {
pipeIntelliJNodeMap.put('|', new CharacterNodeFactory() {
@Override
public boolean skipNext(char c) {
return c == ' ' || c == '\t';
//return false;
}
@Override
public boolean skipPrev(char c) {
return c == ' ' || c == '\t' /*|| c == TableFormatOptions.INTELLIJ_DUMMY_IDENTIFIER_CHAR*/;
//return false;
}
@Override
public boolean wantSkippedWhitespace() {
return true;
}
@Override
public Node get() {
return new TableColumnSeparator();
}
});
}
public static ParagraphPreProcessorFactory Factory() {
return new ParagraphPreProcessorFactory() {
@Override
public boolean affectsGlobalScope() {
return false;
}
@Nullable
@Override
public Set<Class<?>> getAfterDependents() {
HashSet<Class<?>> set = new HashSet<>();
set.add(ReferencePreProcessorFactory.class);
return set;
}
@Nullable
@Override
public Set<Class<?>> getBeforeDependents() {
return null;
}
@Override
public ParagraphPreProcessor apply(ParserState state) {
return new TableParagraphPreProcessor(state.getProperties());
}
};
}
final private TableParserOptions options;
Pattern TABLE_HEADER_SEPARATOR;
public static Pattern getTableHeaderSeparator(int minColumnDashes, String intellijDummyIdentifier) {
int minCol = minColumnDashes >= 1 ? minColumnDashes : 1;
int minColDash = minColumnDashes >= 2 ? minColumnDashes - 1 : 1;
int minColDashes = minColumnDashes >= 3 ? minColumnDashes - 2 : 1;
// to prevent conversion to arabic numbers, using string
String COL = String.format(Locale.US, "(?:" + "\\s*-{%d,}\\s*|\\s*:-{%d,}\\s*|\\s*-{%d,}:\\s*|\\s*:-{%d,}:\\s*" + ")", minCol, minColDash, minColDash, minColDashes);
boolean noIntelliJ = intellijDummyIdentifier.isEmpty();
String add = noIntelliJ ? "" : TableFormatOptions.INTELLIJ_DUMMY_IDENTIFIER;
String sp = noIntelliJ ? "\\s" : "(?:\\s" + add + "?)";
String ds = noIntelliJ ? "-" : "(?:-" + add + "?)";
String pipe = noIntelliJ ? "\\|" : "(?:" + add + "?\\|" + add + "?)";
//COL = COL.replace("\\s", sp).replace("-", ds);
String regex = "\\|" + COL + "\\|?\\s*" + "|" +
COL + "\\|\\s*" + "|" +
"\\|?" + "(?:" + COL + "\\|)+" + COL + "\\|?\\s*";
String withIntelliJ = regex.replace("\\s", sp).replace("\\|", pipe).replace("-", ds);
return Pattern.compile(withIntelliJ);
}
private TableParagraphPreProcessor(DataHolder options) {
this.options = new TableParserOptions(options);
//isIntellijDummyIdentifier = Parser.INTELLIJ_DUMMY_IDENTIFIER.getFrom(options);
//intellijDummyIdentifier =<SUF>
this.TABLE_HEADER_SEPARATOR = getTableHeaderSeparator(this.options.minSeparatorDashes, "");
}
private static class TableSeparatorRow extends TableRow implements DoNotDecorate {
public TableSeparatorRow() {
}
public TableSeparatorRow(BasedSequence chars) {
super(chars);
}
}
@Override
public int preProcessBlock(Paragraph block, ParserState state) {
InlineParser inlineParser = state.getInlineParser();
ArrayList<BasedSequence> tableLines = new ArrayList<>();
int separatorLineNumber = -1;
BasedSequence separatorLine = null;
int blockIndent = block.getLineIndent(0);
BasedSequence captionLine = null;
BitSet separators = separatorCharacters;
HashMap<Character, CharacterNodeFactory> nodeMap = pipeNodeMap;
int i = 0;
for (BasedSequence rowLine : block.getContentLines()) {
int rowNumber = tableLines.size();
if (separatorLineNumber == -1 && rowNumber > options.maxHeaderRows) return 0; // too many header rows
if (rowLine.indexOf('|') < 0) {
if (separatorLineNumber == -1) return 0;
if (options.withCaption) {
BasedSequence trimmed = rowLine.trim();
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
captionLine = trimmed;
}
}
break;
}
// NOTE: block lines now contain leading indent spaces which should be ignored
BasedSequence trimmedRowLine = rowLine.subSequence(block.getLineIndent(rowNumber));
if (separatorLineNumber == -1) {
if (rowNumber >= options.minHeaderRows
&& TABLE_HEADER_SEPARATOR.matcher(trimmedRowLine).matches()) {
// must start with | or cell, whitespace means its not a separator line
if (rowLine.charAt(0) != ' ' && rowLine.charAt(0) != '\t' || rowLine.charAt(0) != '|') {
separatorLineNumber = rowNumber;
separatorLine = trimmedRowLine;
} else if (rowLine.charAt(0) == ' ' || rowLine.charAt(0) == '\t') {
block.setHasTableSeparator(true);
}
}
}
tableLines.add(trimmedRowLine);
i++;
}
if (separatorLineNumber == -1) return 0;
ArrayList<TableRow> tableRows = new ArrayList<>();
for (BasedSequence rowLine : tableLines) {
int rowNumber = tableRows.size();
BasedSequence fullRowLine = block.getLineIndent(rowNumber) <= blockIndent ? rowLine.trimEOL() : rowLine.baseSubSequence(rowLine.getStartOffset() - (block.getLineIndent(rowNumber) - blockIndent), rowLine.getEndOffset() - rowLine.eolEndLength());
boolean isSeparator = rowNumber == separatorLineNumber;
TableRow tableRow = new TableRow(fullRowLine);
int tableRowNumber;
List<Node> sepList;
if (isSeparator) {
TableSeparatorRow fakeRow = new TableSeparatorRow(fullRowLine);
sepList = inlineParser.parseCustom(fullRowLine, fakeRow, separators, nodeMap);
tableRow.takeChildren(fakeRow);
//sepList = inlineParser.parseCustom(fullRowLine, tableRow, separators, nodeMap);
tableRowNumber = 0;
} else {
sepList = inlineParser.parseCustom(fullRowLine, tableRow, pipeCharacters, pipeNodeMap);
if (rowNumber < separatorLineNumber) tableRowNumber = rowNumber + 1;
else tableRowNumber = rowNumber - separatorLineNumber;
// can have table separators embedded inside inline elements, need to convert them to text
// and remove them from sepList
if (sepList != null) {
sepList = cleanUpInlinedSeparators(inlineParser, tableRow, sepList);
}
}
if (sepList == null) {
if (rowNumber <= separatorLineNumber) return 0;
break;
}
tableRow.setRowNumber(tableRowNumber);
tableRows.add(tableRow);
}
// table is done, could be earlier than the lines tested earlier, may need to truncate lines
Block tableBlock = new TableBlock(tableLines.subList(0, tableRows.size()));
Node section = new TableHead(tableLines.get(0).subSequence(0, 0));
tableBlock.appendChild(section);
List<TableCell.Alignment> alignments = parseAlignment(separatorLine);
int rowNumber = 0;
int separatorColumns = alignments.size();
for (TableRow tableRow : tableRows) {
if (rowNumber == separatorLineNumber) {
section.setCharsFromContent();
section = new TableSeparator();
tableBlock.appendChild(section);
} else if (rowNumber == separatorLineNumber + 1) {
section.setCharsFromContent();
section = new TableBody();
tableBlock.appendChild(section);
}
boolean firstCell = true;
int cellCount = 0;
NodeIterator nodes = new NodeIterator(tableRow.getFirstChild());
TableRow newTableRow = new TableRow(tableRow.getChars());
newTableRow.setRowNumber(tableRow.getRowNumber());
int accumulatedSpanOffset = 0;
while (nodes.hasNext()) {
if (cellCount >= separatorColumns && options.discardExtraColumns) {
if (options.headerSeparatorColumnMatch && rowNumber < separatorLineNumber) {
// header/separator mismatch
return 0;
}
break;
}
//TableCell tableCell = rowNumber == separatorLineNumber ? new TableSeparatorCell() : new TableCell();
TableCell tableCell = new TableCell();
if (firstCell && nodes.peek() instanceof TableColumnSeparator) {
Node columnSep = nodes.next();
tableCell.setOpeningMarker(columnSep.getChars());
columnSep.unlink();
firstCell = false;
}
TableCell.Alignment alignment = cellCount + accumulatedSpanOffset < separatorColumns ? alignments.get(cellCount + accumulatedSpanOffset) : null;
tableCell.setHeader(rowNumber < separatorLineNumber);
tableCell.setAlignment(alignment);
// take all until separator or end of iterator
while (nodes.hasNext()) {
if (nodes.peek() instanceof TableColumnSeparator) break;
tableCell.appendChild(nodes.next());
}
// accumulate closers, and optional spans
BasedSequence closingMarker = null;
int span = 1;
while (nodes.hasNext()) {
if (!(nodes.peek() instanceof TableColumnSeparator)) break;
if (closingMarker == null) {
closingMarker = nodes.next().getChars();
if (!options.columnSpans) break;
} else {
BasedSequence nextSep = nodes.peek().getChars();
if (!closingMarker.isContinuedBy(nextSep)) break;
closingMarker = closingMarker.spliceAtEnd(nextSep);
nodes.next().unlink();
span++;
}
}
accumulatedSpanOffset += span - 1;
if (closingMarker != null) tableCell.setClosingMarker(closingMarker);
tableCell.setChars(tableCell.getChildChars());
// option to keep cell whitespace, if yes, then convert it to text and merge adjacent text nodes
if (options.trimCellWhitespace) tableCell.trimWhiteSpace();
else tableCell.mergeWhiteSpace();
// NOTE: here we get only chars which do not reflect out-of-base characters, prefixes and removed text
tableCell.setText(tableCell.getChildChars());
tableCell.setCharsFromContent();
tableCell.setSpan(span);
newTableRow.appendChild(tableCell);
cellCount++;
}
if (options.headerSeparatorColumnMatch && rowNumber < separatorLineNumber && cellCount < separatorColumns) {
// no match
return 0;
}
while (options.appendMissingColumns && cellCount < separatorColumns) {
TableCell tableCell = new TableCell();
tableCell.setHeader(rowNumber < separatorLineNumber);
tableCell.setAlignment(alignments.get(cellCount));
newTableRow.appendChild(tableCell);
cellCount++;
}
newTableRow.setCharsFromContent();
section.appendChild(newTableRow);
rowNumber++;
}
section.setCharsFromContent();
if (section instanceof TableSeparator) {
TableBody tableBody = new TableBody(section.getChars().subSequence(section.getChars().length()));
tableBlock.appendChild(tableBody);
}
// Add caption if the option is enabled
if (captionLine != null) {
TableCaption caption = new TableCaption(captionLine.subSequence(0, 1), captionLine.subSequence(1, captionLine.length() - 1), captionLine.subSequence(captionLine.length() - 1));
inlineParser.parse(caption.getText(), caption);
caption.setCharsFromContent();
tableBlock.appendChild(caption);
}
tableBlock.setCharsFromContent();
block.insertBefore(tableBlock);
state.blockAdded(tableBlock);
return tableBlock.getChars().length();
}
List<Node> cleanUpInlinedSeparators(InlineParser inlineParser, TableRow tableRow, List<Node> sepList) {
// any separators which do not have tableRow as parent are embedded into inline elements and should be
// converted back to text
ArrayList<Node> removedSeparators = null;
ArrayList<Node> mergeTextParents = null;
for (Node node : sepList) {
if (node.getParent() != null && node.getParent() != tableRow) {
// embedded, convert it and surrounding whitespace to text
Node firstNode = node.getPrevious() instanceof WhiteSpace ? node.getPrevious() : node;
Node lastNode = node.getNext() instanceof WhiteSpace ? node.getNext() : node;
Text text = new Text(node.baseSubSequence(firstNode.getStartOffset(), lastNode.getEndOffset()));
node.insertBefore(text);
node.unlink();
firstNode.unlink();
lastNode.unlink();
if (removedSeparators == null) {
removedSeparators = new ArrayList<>();
mergeTextParents = new ArrayList<>();
}
removedSeparators.add(node);
mergeTextParents.add(text.getParent());
}
}
if (mergeTextParents != null) {
for (Node parent : mergeTextParents) {
inlineParser.mergeTextNodes(parent.getFirstChild(), parent.getLastChild());
}
if (removedSeparators.size() == sepList.size()) {
return null;
} else {
ArrayList<Node> newSeparators = new ArrayList<>(sepList);
newSeparators.removeAll(removedSeparators);
return newSeparators;
}
}
return sepList;
}
private List<TableCell.Alignment> parseAlignment(BasedSequence separatorLine) {
List<BasedSequence> parts = split(separatorLine, false, false);
List<TableCell.Alignment> alignments = new ArrayList<>();
for (BasedSequence part : parts) {
BasedSequence trimmed = part.trim();
boolean left = trimmed.startsWith(":");
boolean right = trimmed.endsWith(":");
TableCell.Alignment alignment = getAlignment(left, right);
alignments.add(alignment);
}
return alignments;
}
@SuppressWarnings("SameParameterValue")
private static List<BasedSequence> split(BasedSequence input, boolean columnSpans, boolean wantPipes) {
BasedSequence line = input.trim();
int lineLength = line.length();
List<BasedSequence> segments = new ArrayList<>();
if (line.startsWith("|")) {
if (wantPipes) segments.add(line.subSequence(0, 1));
line = line.subSequence(1, lineLength);
lineLength--;
}
boolean escape = false;
int lastPos = 0;
int cellChars = 0;
for (int i = 0; i < lineLength; i++) {
char c = line.charAt(i);
if (escape) {
escape = false;
cellChars++;
} else {
switch (c) {
case '\\':
escape = true;
// Removing the escaping '\' is handled by the inline parser later, so add it to cell
cellChars++;
break;
case '|':
if (!columnSpans || lastPos < i) segments.add(line.subSequence(lastPos, i));
if (wantPipes) segments.add(line.subSequence(i, i + 1));
lastPos = i + 1;
cellChars = 0;
break;
default:
cellChars++;
}
}
}
if (cellChars > 0) {
segments.add(line.subSequence(lastPos, lineLength));
}
return segments;
}
private static TableCell.Alignment getAlignment(boolean left, boolean right) {
if (left && right) {
return TableCell.Alignment.CENTER;
} else if (left) {
return TableCell.Alignment.LEFT;
} else if (right) {
return TableCell.Alignment.RIGHT;
} else {
return null;
}
}
}
|
169141_5 | /*
* 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 com.ventas.dao;
import com.ventas.model.Vendedor;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author vjimenez
*/
public class VendedorDao extends Dao {
public void registrar(Vendedor ven) throws Exception{
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareStatement("INSERT into vendedor (vRuc,vRzS,vDir,vLug,vMap,vFnc,vTlf,vCl1,vCl2,vCe1,vCe2,vCom,vFot,vFio,vFfo,vMcs,vUsr,vPas,vAcc) values(?,?,?,?,?,STR_TO_DATE(?,'%d/%m/%Y'),?,?,?,?,?,?,?,STR_TO_DATE(?,'%d/%m/%Y'),STR_TO_DATE(?,'%d/%m/%Y'),?,?,?,?)");
st.setString(1,ven.getVruc());
st.setString(2, ven.getVrzs());
st.setString(3, ven.getVdir());
st.setString(4, ven.getVlug());
st.setString(5, ven.getVmap());
st.setString(6, ven.getVfnc());
st.setString(7, ven.getVtlf());
st.setString(8, ven.getVcl1());
st.setString(9, ven.getVcl2());
st.setString(10, ven.getVce1());
st.setString(11, ven.getVce2());
st.setFloat(12, ven.getVcom());
st.setBinaryStream(13,ven.getVfot());
st.setString(14, ven.getVfio());
st.setString(15, ven.getVffo());
st.setString(16, ven.getVmcs());
st.setString(17, ven.getVusr());
st.setString(18, ven.getVpas());
st.setString(19, ven.getVacc());
st.executeUpdate();
} catch (Exception e) {
throw e;
}finally{
this.Cerrar();
}
}
public List<Vendedor> listar() throws Exception{
List<Vendedor> lista;
ResultSet rs;
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareCall("SELECT vCod,vRuc,vRzS,vDir,vLug,vMap,vFnc,vTlf,vCl1,vCl2,vCe1,vCe2,vCom,vFio,vFfo,vMcs,vFot,vUsr,vPas,vAcc FROM vendedor");
rs = st.executeQuery();
lista = new ArrayList<>();
while(rs.next()){
Vendedor ven = new Vendedor();
ven.setVcod(rs.getString("vCod"));
ven.setVruc(rs.getString("vRuc"));
ven.setVrzs(rs.getString("vRzS"));
ven.setVdir(rs.getString("vDir"));
ven.setVlug(rs.getString("vLug"));
ven.setVmap(rs.getString("vMap"));
ven.setVfnc(rs.getString("vFnc"));
ven.setVtlf(rs.getString("vTlf"));
ven.setVcl1(rs.getString("vCl1"));
ven.setVcl2(rs.getString("vCl2"));
ven.setVce1(rs.getString("vCe1"));
ven.setVce2(rs.getString("vCe2"));
ven.setVcom(rs.getFloat("vCom"));
ven.setVfot(rs.getBinaryStream("vFot"));
ven.setVfio(rs.getString("vFio"));
ven.setVffo(rs.getString("vFfo"));
ven.setVmcs(rs.getString("vMcs"));
ven.setVusr(rs.getString("vUsr"));
ven.setVpas(rs.getString("vPas"));
ven.setVacc(rs.getString("vAcc"));
lista.add(ven);
}
} catch (Exception e) {
throw e;
}
finally{
this.Cerrar();
}
return lista;
}
public Vendedor leerID(Vendedor ven) throws Exception{
Vendedor vens = null;
ResultSet rs;
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareCall("SELECT vCod,vRuc,vRzS,vDir,vLug,vMap,DATE_FORMAT(vFnc,'%d/%m/%Y') vFnc,vTlf,vCl1,vCl2,vCe1,vCe2,vCom, DATE_FORMAT(vFio,'%d/%m/%Y') vFio, DATE_FORMAT(vFfo,'%d/%m/%Y') vFfo,vMcs,vRft,vFot,vUsr,vPas,vAcc FROM vendedor WHERE vCod=?");
st.setString(1,ven.getVcod());
rs =st.executeQuery();
while (rs.next()) {
vens = new Vendedor();
vens.setVcod(rs.getString("vCod"));
vens.setVruc(rs.getString("vRuc"));
vens.setVrzs(rs.getString("vRzS"));
vens.setVdir(rs.getString("vDir"));
vens.setVlug(rs.getString("vLug"));
vens.setVmap(rs.getString("vMap"));
vens.setVfnc(rs.getString("vFnc"));
vens.setVtlf(rs.getString("vTlf"));
vens.setVcl1(rs.getString("vCl1"));
vens.setVcl2(rs.getString("vCl2"));
vens.setVce1(rs.getString("vCe1"));
vens.setVce2(rs.getString("vCe2"));
vens.setVcom(rs.getFloat("vCom"));
vens.setVfio(rs.getString("vFio"));
vens.setVffo(rs.getString("vFfo"));
vens.setVmcs(rs.getString("vMcs"));
vens.setVrft(rs.getString("vRft"));
vens.setVfot(rs.getAsciiStream("vFot"));
vens.setVusr(rs.getString("vUsr"));
vens.setVpas(rs.getString("vPas"));
vens.setVacc(rs.getString("vAcc"));
}
} catch (Exception e) {
throw e;
}
finally{
this.Cerrar();
}
return vens;
}
public void modificar(Vendedor ven) throws Exception{
try {
// DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
// java.util.Date fecha = null; // crea objetos tipo util.Date y sql.Date
// java.sql.Date fecha2 = null;
// fecha = ft.parse(ven.getVfnc()); // convierte el string en util.Date
// fecha2 = new java.sql.Date(fecha.getTime());
this.Conectar();
PreparedStatement st;
if(ven.getVruc()!=null){
st = this.getCn().prepareStatement("UPDATE vendedor SET vRuc=?,vRzS=?,vDir=?,vLug=?,vMap=?,vFnc=STR_TO_DATE(?,'%d/%m/%Y'),vTlf=?,vCl1=?,vCl2=?,vCe1=?,vCe2=?,vCom=?,vRft=?,vFot=?,vFio=STR_TO_DATE(?,'%d/%m/%Y'),vFfo=STR_TO_DATE(?,'%d/%m/%Y'),vMcs=?,vUsr=?,vPas=?,vAcc=? WHERE vCod = ?");
}else{
st = this.getCn().prepareStatement("UPDATE vendedor SET vRuc=?,vRzS=?,vDir=?,vLug=?,vMap=?,vFnc=STR_TO_DATE(?,'%d/%m/%Y'),vTlf=?,vCl1=?,vCl2=?,vCe1=?,vCe2=?,vCom=?,vRft=?,vFio=STR_TO_DATE(?,'%d/%m/%Y'),vFfo=STR_TO_DATE(?,'%d/%m/%Y'),vMcs=?,vUsr=?,vPas=?,vAcc=? WHERE vCod = ?");
}
st.setString(1,ven.getVruc());
st.setString(2, ven.getVrzs());
st.setString(3, ven.getVdir());
st.setString(4, ven.getVlug());
st.setString(5, ven.getVmap());
st.setString(6, ven.getVfnc());
st.setString(7, ven.getVtlf());
st.setString(8, ven.getVcl1());
st.setString(9, ven.getVcl2());
st.setString(10, ven.getVce1());
st.setString(11, ven.getVce2());
st.setFloat(12, ven.getVcom());
st.setString(13,ven.getVrft());
st.setBinaryStream(14,ven.getVfot());
st.setString(15, ven.getVfio());
st.setString(16, ven.getVffo());
st.setString(17, ven.getVmcs());
st.setString(18, ven.getVusr());
st.setString(19, ven.getVpas());
st.setString(20, ven.getVacc());
st.setString(21,ven.getVcod());
st.executeUpdate();
} catch (Exception e) {
throw e;
}finally{
this.Cerrar();
}
}
public void eliminar(Vendedor ven) throws Exception{
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareStatement("DELETE FROM vendedor WHERE vCod = ?");
st.setString(1,ven.getVcod());
st.executeUpdate();
} catch (Exception e) {
throw e;
}finally{
this.Cerrar();
}
}
}
| vtorero/sistemaVentas | WebApplication2/src/java/com/ventas/dao/VendedorDao.java | 3,095 | // fecha = ft.parse(ven.getVfnc()); // convierte el string en util.Date | line_comment | nl | /*
* 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 com.ventas.dao;
import com.ventas.model.Vendedor;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author vjimenez
*/
public class VendedorDao extends Dao {
public void registrar(Vendedor ven) throws Exception{
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareStatement("INSERT into vendedor (vRuc,vRzS,vDir,vLug,vMap,vFnc,vTlf,vCl1,vCl2,vCe1,vCe2,vCom,vFot,vFio,vFfo,vMcs,vUsr,vPas,vAcc) values(?,?,?,?,?,STR_TO_DATE(?,'%d/%m/%Y'),?,?,?,?,?,?,?,STR_TO_DATE(?,'%d/%m/%Y'),STR_TO_DATE(?,'%d/%m/%Y'),?,?,?,?)");
st.setString(1,ven.getVruc());
st.setString(2, ven.getVrzs());
st.setString(3, ven.getVdir());
st.setString(4, ven.getVlug());
st.setString(5, ven.getVmap());
st.setString(6, ven.getVfnc());
st.setString(7, ven.getVtlf());
st.setString(8, ven.getVcl1());
st.setString(9, ven.getVcl2());
st.setString(10, ven.getVce1());
st.setString(11, ven.getVce2());
st.setFloat(12, ven.getVcom());
st.setBinaryStream(13,ven.getVfot());
st.setString(14, ven.getVfio());
st.setString(15, ven.getVffo());
st.setString(16, ven.getVmcs());
st.setString(17, ven.getVusr());
st.setString(18, ven.getVpas());
st.setString(19, ven.getVacc());
st.executeUpdate();
} catch (Exception e) {
throw e;
}finally{
this.Cerrar();
}
}
public List<Vendedor> listar() throws Exception{
List<Vendedor> lista;
ResultSet rs;
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareCall("SELECT vCod,vRuc,vRzS,vDir,vLug,vMap,vFnc,vTlf,vCl1,vCl2,vCe1,vCe2,vCom,vFio,vFfo,vMcs,vFot,vUsr,vPas,vAcc FROM vendedor");
rs = st.executeQuery();
lista = new ArrayList<>();
while(rs.next()){
Vendedor ven = new Vendedor();
ven.setVcod(rs.getString("vCod"));
ven.setVruc(rs.getString("vRuc"));
ven.setVrzs(rs.getString("vRzS"));
ven.setVdir(rs.getString("vDir"));
ven.setVlug(rs.getString("vLug"));
ven.setVmap(rs.getString("vMap"));
ven.setVfnc(rs.getString("vFnc"));
ven.setVtlf(rs.getString("vTlf"));
ven.setVcl1(rs.getString("vCl1"));
ven.setVcl2(rs.getString("vCl2"));
ven.setVce1(rs.getString("vCe1"));
ven.setVce2(rs.getString("vCe2"));
ven.setVcom(rs.getFloat("vCom"));
ven.setVfot(rs.getBinaryStream("vFot"));
ven.setVfio(rs.getString("vFio"));
ven.setVffo(rs.getString("vFfo"));
ven.setVmcs(rs.getString("vMcs"));
ven.setVusr(rs.getString("vUsr"));
ven.setVpas(rs.getString("vPas"));
ven.setVacc(rs.getString("vAcc"));
lista.add(ven);
}
} catch (Exception e) {
throw e;
}
finally{
this.Cerrar();
}
return lista;
}
public Vendedor leerID(Vendedor ven) throws Exception{
Vendedor vens = null;
ResultSet rs;
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareCall("SELECT vCod,vRuc,vRzS,vDir,vLug,vMap,DATE_FORMAT(vFnc,'%d/%m/%Y') vFnc,vTlf,vCl1,vCl2,vCe1,vCe2,vCom, DATE_FORMAT(vFio,'%d/%m/%Y') vFio, DATE_FORMAT(vFfo,'%d/%m/%Y') vFfo,vMcs,vRft,vFot,vUsr,vPas,vAcc FROM vendedor WHERE vCod=?");
st.setString(1,ven.getVcod());
rs =st.executeQuery();
while (rs.next()) {
vens = new Vendedor();
vens.setVcod(rs.getString("vCod"));
vens.setVruc(rs.getString("vRuc"));
vens.setVrzs(rs.getString("vRzS"));
vens.setVdir(rs.getString("vDir"));
vens.setVlug(rs.getString("vLug"));
vens.setVmap(rs.getString("vMap"));
vens.setVfnc(rs.getString("vFnc"));
vens.setVtlf(rs.getString("vTlf"));
vens.setVcl1(rs.getString("vCl1"));
vens.setVcl2(rs.getString("vCl2"));
vens.setVce1(rs.getString("vCe1"));
vens.setVce2(rs.getString("vCe2"));
vens.setVcom(rs.getFloat("vCom"));
vens.setVfio(rs.getString("vFio"));
vens.setVffo(rs.getString("vFfo"));
vens.setVmcs(rs.getString("vMcs"));
vens.setVrft(rs.getString("vRft"));
vens.setVfot(rs.getAsciiStream("vFot"));
vens.setVusr(rs.getString("vUsr"));
vens.setVpas(rs.getString("vPas"));
vens.setVacc(rs.getString("vAcc"));
}
} catch (Exception e) {
throw e;
}
finally{
this.Cerrar();
}
return vens;
}
public void modificar(Vendedor ven) throws Exception{
try {
// DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
// java.util.Date fecha = null; // crea objetos tipo util.Date y sql.Date
// java.sql.Date fecha2 = null;
// fecha =<SUF>
// fecha2 = new java.sql.Date(fecha.getTime());
this.Conectar();
PreparedStatement st;
if(ven.getVruc()!=null){
st = this.getCn().prepareStatement("UPDATE vendedor SET vRuc=?,vRzS=?,vDir=?,vLug=?,vMap=?,vFnc=STR_TO_DATE(?,'%d/%m/%Y'),vTlf=?,vCl1=?,vCl2=?,vCe1=?,vCe2=?,vCom=?,vRft=?,vFot=?,vFio=STR_TO_DATE(?,'%d/%m/%Y'),vFfo=STR_TO_DATE(?,'%d/%m/%Y'),vMcs=?,vUsr=?,vPas=?,vAcc=? WHERE vCod = ?");
}else{
st = this.getCn().prepareStatement("UPDATE vendedor SET vRuc=?,vRzS=?,vDir=?,vLug=?,vMap=?,vFnc=STR_TO_DATE(?,'%d/%m/%Y'),vTlf=?,vCl1=?,vCl2=?,vCe1=?,vCe2=?,vCom=?,vRft=?,vFio=STR_TO_DATE(?,'%d/%m/%Y'),vFfo=STR_TO_DATE(?,'%d/%m/%Y'),vMcs=?,vUsr=?,vPas=?,vAcc=? WHERE vCod = ?");
}
st.setString(1,ven.getVruc());
st.setString(2, ven.getVrzs());
st.setString(3, ven.getVdir());
st.setString(4, ven.getVlug());
st.setString(5, ven.getVmap());
st.setString(6, ven.getVfnc());
st.setString(7, ven.getVtlf());
st.setString(8, ven.getVcl1());
st.setString(9, ven.getVcl2());
st.setString(10, ven.getVce1());
st.setString(11, ven.getVce2());
st.setFloat(12, ven.getVcom());
st.setString(13,ven.getVrft());
st.setBinaryStream(14,ven.getVfot());
st.setString(15, ven.getVfio());
st.setString(16, ven.getVffo());
st.setString(17, ven.getVmcs());
st.setString(18, ven.getVusr());
st.setString(19, ven.getVpas());
st.setString(20, ven.getVacc());
st.setString(21,ven.getVcod());
st.executeUpdate();
} catch (Exception e) {
throw e;
}finally{
this.Cerrar();
}
}
public void eliminar(Vendedor ven) throws Exception{
try {
this.Conectar();
PreparedStatement st = this.getCn().prepareStatement("DELETE FROM vendedor WHERE vCod = ?");
st.setString(1,ven.getVcod());
st.executeUpdate();
} catch (Exception e) {
throw e;
}finally{
this.Cerrar();
}
}
}
|
209078_1 | package stsfinegrain.utilities;
import java.util.ArrayList;
/**
* @author Davor Jovanović
*/
public class MatrixOperations {
public static double [][] scalarMultiplication(double[][] matrix, double factor, int m, int n){
double [][] rezMatrix = new double[m][n];
for(int i=0; i<m; i++ )
for(int j=0; j<n; j++)
rezMatrix[i][j] = matrix[i][j]*factor;
return rezMatrix;
}
public static double [][] addition(double[][] matrix1, double[][]matrix2, int m, int n){
double[][] rezMatrix = new double[m][n];
for(int i=0; i<m; i++)
for(int j=0; j<n; j++) rezMatrix[i][j] = matrix1[i][j]+matrix2[i][j];
return rezMatrix;
}
public static double[][] findMaxElemAndRemove (double[][] matrix, int m, int n, ArrayList<Double> ro) {
if (m==0 || n==0) return null;
double[][] rezMatrix=new double[m-1][n-1];
int skipI=0;
int skipJ=0;
double max=0.0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
if(matrix[i][j] > max) {
skipI = i;
skipJ = j;
max = matrix[i][j];
}
// construct rezMatrix
if(max == 0.0) return null;
int ii = 0;
int jj = 0;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if (skipI != i && skipJ != j) rezMatrix[ii][jj++] = matrix[i][j];
}
if (skipI != i) ii++;
// and reset jj to zero
jj = 0;
}
// add to ro list
ro.add(max);
return rezMatrix;
}
}
| vukbatanovic/STSFineGrain | src/stsfinegrain/utilities/MatrixOperations.java | 589 | // and reset jj to zero | line_comment | nl | package stsfinegrain.utilities;
import java.util.ArrayList;
/**
* @author Davor Jovanović
*/
public class MatrixOperations {
public static double [][] scalarMultiplication(double[][] matrix, double factor, int m, int n){
double [][] rezMatrix = new double[m][n];
for(int i=0; i<m; i++ )
for(int j=0; j<n; j++)
rezMatrix[i][j] = matrix[i][j]*factor;
return rezMatrix;
}
public static double [][] addition(double[][] matrix1, double[][]matrix2, int m, int n){
double[][] rezMatrix = new double[m][n];
for(int i=0; i<m; i++)
for(int j=0; j<n; j++) rezMatrix[i][j] = matrix1[i][j]+matrix2[i][j];
return rezMatrix;
}
public static double[][] findMaxElemAndRemove (double[][] matrix, int m, int n, ArrayList<Double> ro) {
if (m==0 || n==0) return null;
double[][] rezMatrix=new double[m-1][n-1];
int skipI=0;
int skipJ=0;
double max=0.0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
if(matrix[i][j] > max) {
skipI = i;
skipJ = j;
max = matrix[i][j];
}
// construct rezMatrix
if(max == 0.0) return null;
int ii = 0;
int jj = 0;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if (skipI != i && skipJ != j) rezMatrix[ii][jj++] = matrix[i][j];
}
if (skipI != i) ii++;
// and reset<SUF>
jj = 0;
}
// add to ro list
ro.add(max);
return rezMatrix;
}
}
|
193013_12 | package edu.uta.sis.nagnomore.web.testing;
import edu.uta.sis.nagnomore.domain.data.*;
import edu.uta.sis.nagnomore.domain.service.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* Created by mare on 11.7.2016.
*/
@Controller
public class TestDataController {
@Autowired
CategoryService cs;
@Autowired
FamilyService familyService;
@Autowired
UserService us;
@Autowired
TaskService ts;
@Autowired
TaskSkeletonService tss;
@RequestMapping(value="/test/riinatest")
public String testMe(){
return "/jsp/testi/testidata";
}
@RequestMapping(value="/react/nagnomore")
public String pleaseDeliver(){
return "/jsp/index";
}
@RequestMapping(value="/test/getcategories")
public @ResponseBody List<Category> getCategoryDataViaAjax(){
List<Category> list = cs.getCategories();
return list;
}
@RequestMapping(value="/test/getfamilies")
public @ResponseBody List<WwwFamily> getFamilyDataViaAjax(){
List<WwwFamily> list = familyService.listAllFamilies();
return list;
}
@RequestMapping(value="/test/getfamilymembers")
public @ResponseBody List<WwwUser> getFamilyMemberDataViaAjax(){
List<WwwUser> list = us.getUsers();
return list;
}
@RequestMapping(value="/test/gettasks")
public @ResponseBody List<Task> getTaskDataViaAjax(){
List<Task> list = ts.findAll();
return list;
}
@RequestMapping(value="/test/puttask", method = RequestMethod.POST)
public @ResponseBody List<Task> putTaskAndDeliver(@RequestBody TaskSkeleton taskSkeleton){
System.out.println(taskSkeleton.toString());
Task task = tss.convertToTask(taskSkeleton);
ts.addTask(task);
List<Task> list = ts.findAll();
return list;
}
@RequestMapping(value="/test/putdatatestajax")
public String postDataViaAjax(@RequestBody List<Category> list){
Iterator<Category> listIterator = list.iterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next().toString());
}
return "/jsp/testi/testidata";
}
@RequestMapping(value="/test/createdata")
public String createTestData(){
deleteAllData();
//Tarvitaan muutama kategoria. Kopioidaan suoraan yltä Eeron koodis.
Category ce1 = new Category();
ce1.setTitle("Harrastukset");
ce1.setDescription("Kategoria harrastusluonteiselle toiminnalle.");
cs.create(ce1);
Category ce2 = new Category();
ce2.setTitle("Lääkkeet");
ce2.setDescription("Kategoria muistutuksille lääkkeenottoajoista.");
cs.create(ce2);
Category ce3 = new Category();
ce3.setTitle("Kotityöt");
ce3.setDescription("Kategoria kotitöille.");
cs.create(ce3);
//Tarvitaan yksi perhe. Kopioidaan suoraan Hannan koodia (TestiaHannan-kontrollerista)
WwwFamily wwwFamily = new WwwFamily();
wwwFamily.setFamilyName("Rujot");
familyService.addFamily(wwwFamily);
WwwFamily familyFromDb = familyService.findFamilyByName("Rujot");
// Tarvitaan kaksi aikuista ja kolme lasta perheeseen. Kopioidaan suoraan Viljamin koodia.
// public WwwUser(Long id, String username, String password, String email, String fullName, String phoneNumber, String role, Boolean enabled)
WwwUser u1 = new WwwUser(null, "Pekka", "salasana", "[email protected]", "Pekka Rujo", "123456789", "ROLE_CHILD", true);
u1.setFamily(familyFromDb);
us.create(u1);
WwwUser u2 = new WwwUser(null, "Ville", "salasana", "[email protected]", "Ville Rujo", "123456789", "ROLE_PARENT", true);
u2.setFamily(familyFromDb);
us.create(u2);
WwwUser u3 = new WwwUser(null, "Maija", "salasana", "[email protected]", "Maija Rujo", "123456789", "ROLE_PARENT", true);
u3.setFamily(familyFromDb);
us.create(u3);
WwwUser u4 = new WwwUser(null, "Joona", "salasana", "[email protected]", "Joona Rujo", "123456789", "ROLE_CHILD", true);
u4.setFamily(familyFromDb);
us.create(u4);
WwwUser u5 = new WwwUser(null, "Mette", "salasana", "[email protected]", "Mette Rujo", "123456789", "ROLE_CHILD", true);
u5.setFamily(familyFromDb);
us.create(u5);
//Nyt on olemassa kategoriat, perhe ja sen jäsenet. Luodaan useita taskeja erilaisilla kombinaatioilla.
//Haetaan kaikki tärkeä valmiiksi kannasta. Perheenjäseniä on 5 ja kategorioita 3.
List<WwwUser> familyMembers = us.getUsersByFamily(familyFromDb);
List<Category> categories = cs.getCategories();
Category harrastukset = categories.get(0);
Category laakkeet = categories.get(1);
Category kotityot = categories.get(2);
//Ensin 5 harrastustaskia
String[] harrastusTitlet = new String[] { "Osta uusi koripallo", "Osta hiekkahousut", "Maksa lisenssi", "Varaa liput", "Selvitä turnaus"};
String[] harrastusDescit = new String[] { "Koon 4 koripallo. Stadiumissa ei ollut.", "Ennen seuraavaa turnausta", "Heinäkuun aikana", "Tanssiesitykset myydään loppuun", "Majoitus ja kuljetus epäselvää"};
for(int i = 0; i < 5; i++){
DateTime now = DateTime.now();
this.createTestTask(harrastusTitlet[i], harrastusDescit[i], now, createDue(now), createPriority(), createBoolean(), createBoolean(), harrastukset, selectFamilyMember(familyMembers), selectFamilyMember(familyMembers), familyFromDb, selectStatus() );
}
// Sitten 5 lääkkeisiin liittyvää
String[] laakeTitlet = new String[] { "Antibiootit", "Antihistamiini", "Vakuutus", "Sivuvaikutukset", "Peruskorvattavuus"};
String[] laakeDescit = new String[] { "Kahdeksan tunnin välein", "Aamulla, tarv. illalla", "Hae korvausta kesän lääkkeistä", "Raportoi sivuvaikutukset", "Tilaa B-lausunto peruskorvattavuutta varten"};
for(int i = 0; i < 5; i++){
DateTime now = DateTime.now();
this.createTestTask(laakeTitlet[i], laakeDescit[i], now, createDue(now), createPriority(), createBoolean(), createBoolean(), harrastukset, selectFamilyMember(familyMembers), selectFamilyMember(familyMembers), familyFromDb, selectStatus() );
}
// Lopuksi 10 kotitöihin liittyvää
String[] kotiTitlet = new String[] { "Imurointi", "Ikkunat", "Tiivistys", "Matot", "Vaatehuone", "Lakanat", "Kirjahylly", "Eteinen", "Jääkaappi", "Liesituulettimen lamppu"};
String[] kotiDescit = new String[] { "Imuroi eteinen ja keittiö", "Pese ikkunat", "Tiivistä ikkunat", "Pese matot", "Järjestä vaatehuoneesta pienet kirpparille", "Vaihda lakanat", "Aakkosta kirjat", "Asenna uusi avainnaulakko", "Jääkaapista vanhat maustekastikkeet plus pesu", "Liesituulettimen lamppu, saa Clas Ohlsonilta, malli 4438910"};
for(int i = 0; i < 10 ; i++){
DateTime now = DateTime.now();
this.createTestTask(kotiTitlet[i], kotiDescit[i], now, createDue(now), createPriority(), createBoolean(), createBoolean(), harrastukset, selectFamilyMember(familyMembers), selectFamilyMember(familyMembers), familyFromDb, selectStatus() );
}
return "/jsp/testi/valmis";
}
@RequestMapping(value="/test/emptydb")
public String deleteTestData(){
deleteAllData();
return "/jsp/testi/tyhja";
}
private void deleteAllData(){
//Kannassa on dataa tauluissa userentity, task, family, categories
//Poistojärjestys task -> categories -> userentity -> family
List<Task> taskList = ts.findAll();
Iterator<Task> taskListIterator = taskList.iterator();
while(taskListIterator.hasNext()){
ts.remove(taskListIterator.next());
}
List<Category> categoryList = cs.getCategories();
Iterator<Category> catListIterator = categoryList.iterator();
while(catListIterator.hasNext()){
cs.remove(catListIterator.next());
}
List<WwwUser> userList = us.getUsers();
Iterator<WwwUser> userListIterator = userList.iterator();
while(userListIterator.hasNext()){
us.remove(userListIterator.next().getId());
}
List<WwwFamily> familyList = familyService.listAllFamilies();
Iterator<WwwFamily> familyListIterator = familyList.iterator();
while(familyListIterator.hasNext()){
familyService.removeFamily(familyListIterator.next().getId());
}
}
private void createTestTask(String title, String description,
DateTime created, DateTime due,
int priority, Boolean privacy,
Boolean alarm, Category category,
WwwUser creator, WwwUser assignee,
WwwFamily family, Task.Status status
) {
Task t = new Task();
t.setTitle(title);
t.setDescription(description);
t.setCreated(created);
t.setDue(due);
t.setPriority(priority);
t.setPrivacy(privacy);
t.setAlarm(alarm);
t.setCategory(category);
t.setCreator(creator);
t.setAssignee(assignee);
t.setStatus(status);
t.setFamily(family);
ts.addTask(t);
}
private DateTime createDue(DateTime created){
Random r = new Random();
//Random int between [1-14]
int i = r.nextInt(14) + 1;
return created.plusDays(i);
}
private int createPriority(){
Random r = new Random();
//Random int between [0-3]
int i = r.nextInt(4);
return i;
}
private boolean createBoolean(){
Random r = new Random();
boolean answer = true;
int i = r.nextInt(2);
if(i == 0){
answer = false;
}
else if(i == 1){
answer = true;
}
return answer;
}
private WwwUser selectFamilyMember(List<WwwUser> familyMembers){
Random r = new Random();
int max = familyMembers.size();
//index between [0, familyMembers.size()[
int i = r.nextInt(max);
return familyMembers.get(i);
}
private Task.Status selectStatus(){
Task.Status[] statuses = new Task.Status[]{Task.Status.NEEDS_ACTION, Task.Status.IN_PROGRESS, Task.Status.COMPLETED};
Random r = new Random();
int max = statuses.length ;
int i = r.nextInt(max);
return statuses[i];
}
}
| vyli/NagNoMore | NagNoMore/src/main/java/edu/uta/sis/nagnomore/web/testing/TestDataController.java | 3,569 | //Random int between [1-14] | line_comment | nl | package edu.uta.sis.nagnomore.web.testing;
import edu.uta.sis.nagnomore.domain.data.*;
import edu.uta.sis.nagnomore.domain.service.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* Created by mare on 11.7.2016.
*/
@Controller
public class TestDataController {
@Autowired
CategoryService cs;
@Autowired
FamilyService familyService;
@Autowired
UserService us;
@Autowired
TaskService ts;
@Autowired
TaskSkeletonService tss;
@RequestMapping(value="/test/riinatest")
public String testMe(){
return "/jsp/testi/testidata";
}
@RequestMapping(value="/react/nagnomore")
public String pleaseDeliver(){
return "/jsp/index";
}
@RequestMapping(value="/test/getcategories")
public @ResponseBody List<Category> getCategoryDataViaAjax(){
List<Category> list = cs.getCategories();
return list;
}
@RequestMapping(value="/test/getfamilies")
public @ResponseBody List<WwwFamily> getFamilyDataViaAjax(){
List<WwwFamily> list = familyService.listAllFamilies();
return list;
}
@RequestMapping(value="/test/getfamilymembers")
public @ResponseBody List<WwwUser> getFamilyMemberDataViaAjax(){
List<WwwUser> list = us.getUsers();
return list;
}
@RequestMapping(value="/test/gettasks")
public @ResponseBody List<Task> getTaskDataViaAjax(){
List<Task> list = ts.findAll();
return list;
}
@RequestMapping(value="/test/puttask", method = RequestMethod.POST)
public @ResponseBody List<Task> putTaskAndDeliver(@RequestBody TaskSkeleton taskSkeleton){
System.out.println(taskSkeleton.toString());
Task task = tss.convertToTask(taskSkeleton);
ts.addTask(task);
List<Task> list = ts.findAll();
return list;
}
@RequestMapping(value="/test/putdatatestajax")
public String postDataViaAjax(@RequestBody List<Category> list){
Iterator<Category> listIterator = list.iterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next().toString());
}
return "/jsp/testi/testidata";
}
@RequestMapping(value="/test/createdata")
public String createTestData(){
deleteAllData();
//Tarvitaan muutama kategoria. Kopioidaan suoraan yltä Eeron koodis.
Category ce1 = new Category();
ce1.setTitle("Harrastukset");
ce1.setDescription("Kategoria harrastusluonteiselle toiminnalle.");
cs.create(ce1);
Category ce2 = new Category();
ce2.setTitle("Lääkkeet");
ce2.setDescription("Kategoria muistutuksille lääkkeenottoajoista.");
cs.create(ce2);
Category ce3 = new Category();
ce3.setTitle("Kotityöt");
ce3.setDescription("Kategoria kotitöille.");
cs.create(ce3);
//Tarvitaan yksi perhe. Kopioidaan suoraan Hannan koodia (TestiaHannan-kontrollerista)
WwwFamily wwwFamily = new WwwFamily();
wwwFamily.setFamilyName("Rujot");
familyService.addFamily(wwwFamily);
WwwFamily familyFromDb = familyService.findFamilyByName("Rujot");
// Tarvitaan kaksi aikuista ja kolme lasta perheeseen. Kopioidaan suoraan Viljamin koodia.
// public WwwUser(Long id, String username, String password, String email, String fullName, String phoneNumber, String role, Boolean enabled)
WwwUser u1 = new WwwUser(null, "Pekka", "salasana", "[email protected]", "Pekka Rujo", "123456789", "ROLE_CHILD", true);
u1.setFamily(familyFromDb);
us.create(u1);
WwwUser u2 = new WwwUser(null, "Ville", "salasana", "[email protected]", "Ville Rujo", "123456789", "ROLE_PARENT", true);
u2.setFamily(familyFromDb);
us.create(u2);
WwwUser u3 = new WwwUser(null, "Maija", "salasana", "[email protected]", "Maija Rujo", "123456789", "ROLE_PARENT", true);
u3.setFamily(familyFromDb);
us.create(u3);
WwwUser u4 = new WwwUser(null, "Joona", "salasana", "[email protected]", "Joona Rujo", "123456789", "ROLE_CHILD", true);
u4.setFamily(familyFromDb);
us.create(u4);
WwwUser u5 = new WwwUser(null, "Mette", "salasana", "[email protected]", "Mette Rujo", "123456789", "ROLE_CHILD", true);
u5.setFamily(familyFromDb);
us.create(u5);
//Nyt on olemassa kategoriat, perhe ja sen jäsenet. Luodaan useita taskeja erilaisilla kombinaatioilla.
//Haetaan kaikki tärkeä valmiiksi kannasta. Perheenjäseniä on 5 ja kategorioita 3.
List<WwwUser> familyMembers = us.getUsersByFamily(familyFromDb);
List<Category> categories = cs.getCategories();
Category harrastukset = categories.get(0);
Category laakkeet = categories.get(1);
Category kotityot = categories.get(2);
//Ensin 5 harrastustaskia
String[] harrastusTitlet = new String[] { "Osta uusi koripallo", "Osta hiekkahousut", "Maksa lisenssi", "Varaa liput", "Selvitä turnaus"};
String[] harrastusDescit = new String[] { "Koon 4 koripallo. Stadiumissa ei ollut.", "Ennen seuraavaa turnausta", "Heinäkuun aikana", "Tanssiesitykset myydään loppuun", "Majoitus ja kuljetus epäselvää"};
for(int i = 0; i < 5; i++){
DateTime now = DateTime.now();
this.createTestTask(harrastusTitlet[i], harrastusDescit[i], now, createDue(now), createPriority(), createBoolean(), createBoolean(), harrastukset, selectFamilyMember(familyMembers), selectFamilyMember(familyMembers), familyFromDb, selectStatus() );
}
// Sitten 5 lääkkeisiin liittyvää
String[] laakeTitlet = new String[] { "Antibiootit", "Antihistamiini", "Vakuutus", "Sivuvaikutukset", "Peruskorvattavuus"};
String[] laakeDescit = new String[] { "Kahdeksan tunnin välein", "Aamulla, tarv. illalla", "Hae korvausta kesän lääkkeistä", "Raportoi sivuvaikutukset", "Tilaa B-lausunto peruskorvattavuutta varten"};
for(int i = 0; i < 5; i++){
DateTime now = DateTime.now();
this.createTestTask(laakeTitlet[i], laakeDescit[i], now, createDue(now), createPriority(), createBoolean(), createBoolean(), harrastukset, selectFamilyMember(familyMembers), selectFamilyMember(familyMembers), familyFromDb, selectStatus() );
}
// Lopuksi 10 kotitöihin liittyvää
String[] kotiTitlet = new String[] { "Imurointi", "Ikkunat", "Tiivistys", "Matot", "Vaatehuone", "Lakanat", "Kirjahylly", "Eteinen", "Jääkaappi", "Liesituulettimen lamppu"};
String[] kotiDescit = new String[] { "Imuroi eteinen ja keittiö", "Pese ikkunat", "Tiivistä ikkunat", "Pese matot", "Järjestä vaatehuoneesta pienet kirpparille", "Vaihda lakanat", "Aakkosta kirjat", "Asenna uusi avainnaulakko", "Jääkaapista vanhat maustekastikkeet plus pesu", "Liesituulettimen lamppu, saa Clas Ohlsonilta, malli 4438910"};
for(int i = 0; i < 10 ; i++){
DateTime now = DateTime.now();
this.createTestTask(kotiTitlet[i], kotiDescit[i], now, createDue(now), createPriority(), createBoolean(), createBoolean(), harrastukset, selectFamilyMember(familyMembers), selectFamilyMember(familyMembers), familyFromDb, selectStatus() );
}
return "/jsp/testi/valmis";
}
@RequestMapping(value="/test/emptydb")
public String deleteTestData(){
deleteAllData();
return "/jsp/testi/tyhja";
}
private void deleteAllData(){
//Kannassa on dataa tauluissa userentity, task, family, categories
//Poistojärjestys task -> categories -> userentity -> family
List<Task> taskList = ts.findAll();
Iterator<Task> taskListIterator = taskList.iterator();
while(taskListIterator.hasNext()){
ts.remove(taskListIterator.next());
}
List<Category> categoryList = cs.getCategories();
Iterator<Category> catListIterator = categoryList.iterator();
while(catListIterator.hasNext()){
cs.remove(catListIterator.next());
}
List<WwwUser> userList = us.getUsers();
Iterator<WwwUser> userListIterator = userList.iterator();
while(userListIterator.hasNext()){
us.remove(userListIterator.next().getId());
}
List<WwwFamily> familyList = familyService.listAllFamilies();
Iterator<WwwFamily> familyListIterator = familyList.iterator();
while(familyListIterator.hasNext()){
familyService.removeFamily(familyListIterator.next().getId());
}
}
private void createTestTask(String title, String description,
DateTime created, DateTime due,
int priority, Boolean privacy,
Boolean alarm, Category category,
WwwUser creator, WwwUser assignee,
WwwFamily family, Task.Status status
) {
Task t = new Task();
t.setTitle(title);
t.setDescription(description);
t.setCreated(created);
t.setDue(due);
t.setPriority(priority);
t.setPrivacy(privacy);
t.setAlarm(alarm);
t.setCategory(category);
t.setCreator(creator);
t.setAssignee(assignee);
t.setStatus(status);
t.setFamily(family);
ts.addTask(t);
}
private DateTime createDue(DateTime created){
Random r = new Random();
//Random int<SUF>
int i = r.nextInt(14) + 1;
return created.plusDays(i);
}
private int createPriority(){
Random r = new Random();
//Random int between [0-3]
int i = r.nextInt(4);
return i;
}
private boolean createBoolean(){
Random r = new Random();
boolean answer = true;
int i = r.nextInt(2);
if(i == 0){
answer = false;
}
else if(i == 1){
answer = true;
}
return answer;
}
private WwwUser selectFamilyMember(List<WwwUser> familyMembers){
Random r = new Random();
int max = familyMembers.size();
//index between [0, familyMembers.size()[
int i = r.nextInt(max);
return familyMembers.get(i);
}
private Task.Status selectStatus(){
Task.Status[] statuses = new Task.Status[]{Task.Status.NEEDS_ACTION, Task.Status.IN_PROGRESS, Task.Status.COMPLETED};
Random r = new Random();
int max = statuses.length ;
int i = r.nextInt(max);
return statuses[i];
}
}
|
183029_28 | /*
* (c) COPYRIGHT 1999 World Wide Web Consortium
* (Massachusetts Institute of Technology, Institut National de Recherche
* en Informatique et en Automatique, Keio University).
* All Rights Reserved. http://www.w3.org/Consortium/Legal/
*
* $Id$
*/
package org.w3c.css.util;
import org.w3c.css.css.StyleSheet;
import org.w3c.css.parser.Frame;
import org.w3c.www.http.HttpAcceptCharset;
import org.w3c.www.http.HttpAcceptCharsetList;
import org.w3c.www.http.HttpFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Philippe Le Hegaret
* @version $Revision$
*/
public class ApplContext {
// the charset of the first source (url/uploaded/text)
public static Charset defaultCharset;
public static Charset utf8Charset;
static {
try {
defaultCharset = Charset.forName("iso-8859-1");
utf8Charset = Charset.forName("utf-8");
} catch (Exception ex) {
// we are in deep trouble here
defaultCharset = null;
utf8Charset = null;
}
}
private class BomEncoding {
Charset uriCharset = null;
boolean fromBom = false;
private BomEncoding(Charset c, boolean fb) {
uriCharset = c;
fromBom = fb;
}
private BomEncoding(Charset c) {
this(c, false);
}
private BomEncoding() {
}
}
// charset definition of traversed URLs
private HashMap<URL, BomEncoding> uricharsets = null;
// namespace definitions
private HashMap<URL, HashMap<String, String>> namespaces = null;
// default prefix
public static String defaultPrefix = "*defaultprefix*";
public static String noPrefix = "*noprefix*";
private ArrayList<URL> linkedmedia = new ArrayList<URL>();
String credential = null;
String lang;
Messages msgs;
Frame frame;
StyleSheet styleSheet = null;
CssVersion version = CssVersion.getDefault();
CssProfile profile = CssProfile.NONE;
String input;
Class cssselectorstyle;
int origin = -1;
String medium;
private String link;
int warningLevel = 0;
boolean treatVendorExtensionsAsWarnings = false;
boolean treatCssHacksAsWarnings = false;
boolean suggestPropertyName = true;
private String propertyKey = null;
public boolean followlinks() {
return followlinks;
}
public void setFollowlinks(boolean followlinks) {
this.followlinks = followlinks;
}
boolean followlinks = true;
FakeFile fakefile = null;
String faketext = null;
Charset faketextcharset = null;
URL fakeurl = null;
URL referrer = null;
/**
* Creates a new ApplContext
*/
public ApplContext(String lang) {
this.lang = lang;
msgs = new Messages(lang);
}
public int getWarningLevel() {
return warningLevel;
}
public void setWarningLevel(int warningLevel) {
this.warningLevel = warningLevel;
}
public ArrayList<URL> getLinkedURIs() {
return linkedmedia;
}
public void addLinkedURI(URL url) {
if (url != null) {
linkedmedia.add(url);
}
}
// as ugly as everything else
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public void setFrame(Frame frame) {
this.frame = frame;
frame.ac = this;
}
public Frame getFrame() {
return frame;
}
public void setStyleSheet(StyleSheet styleSheet) {
this.styleSheet = styleSheet;
}
public StyleSheet getStyleSheet() {
return styleSheet;
}
public Class getCssSelectorsStyle() {
return cssselectorstyle;
}
public void setCssSelectorsStyle(Class s) {
cssselectorstyle = s;
}
public Messages getMsg() {
return msgs;
}
public String getContentType() {
return (msgs != null) ? msgs.getString("content-type") : null;
}
public String getContentLanguage() {
return (msgs != null) ? msgs.getString("content-language") : null;
}
/**
* Searches the properties list for a content-encoding one. If it does not
* exist, searches for output-encoding-name. If it still does not exists,
* the method returns the default utf-8 value
*
* @return the output encoding of this ApplContext
*/
public String getContentEncoding() {
// return (msgs != null) ? msgs.getString("content-encoding") : null;
String res = null;
if (msgs != null) {
res = msgs.getString("content-encoding");
if (res == null) {
res = msgs.getString("output-encoding-name");
}
if (res != null) {
// if an encoding has been found, return it
return res;
}
}
// default encoding
return Utf8Properties.ENCODING;
}
public String getLang() {
return lang;
}
public void setCssVersion(String cssversion) {
version = CssVersion.resolve(this, cssversion);
propertyKey = null;
}
public void setCssVersion(CssVersion version) {
this.version = version;
propertyKey = null;
}
public String getCssVersionString() {
return version.toString();
}
public CssVersion getCssVersion() {
return version;
}
public void setProfile(String profile) {
this.profile = CssProfile.resolve(this, profile);
propertyKey = null;
}
/**
* get the String used to fetch the relevant property file
*/
public String getPropertyKey() {
if (propertyKey != null) {
return propertyKey;
}
if (profile == CssProfile.SVG && version == CssVersion.CSS3) {
propertyKey = version.toString() + profile.toString();
return propertyKey;
}
if (profile != CssProfile.EMPTY && profile != CssProfile.NONE) {
propertyKey = profile.toString();
} else {
propertyKey = version.toString();
}
return propertyKey;
}
public CssProfile getCssProfile() {
return profile;
}
public String getProfileString() {
return profile.toString();
}
public void setCssVersionAndProfile(String spec) {
// for things like SVG, version will be set to the default one
// CSS21 in that case, as defined in CssVersion
// and profile will be resolved to svg.
//
// if the version resolve then profile will default to NONE
// TODO should we check profile first and if SVG or MOBILE
// set specific version of CSS (like CSS2 and not CSS21 for MOBILE) ?
if ((spec == null) || spec.isEmpty()) {
version = CssVersion.getDefault();
profile = CssProfile.SVG;
} else {
String low = spec.toLowerCase();
version = CssVersion.resolve(this, low);
profile = CssProfile.resolve(this, low);
// some special cases...
// http://www.atsc.org/cms/index.php/standards/published-standards/71-atsc-a100-standard
if (profile.equals(CssProfile.ATSCTV)) {
version = CssVersion.CSS2;
}
}
}
public void setOrigin(int origin) {
this.origin = origin;
}
public int getOrigin() {
return origin;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getMedium() {
return medium;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getLink() {
return link;
}
public void setLink(String queryString) {
this.link = queryString;
}
public boolean getTreatVendorExtensionsAsWarnings() {
return treatVendorExtensionsAsWarnings;
}
/**
* Change the behaviour of error reporting for vendor extensions.
*
* @param treatVendorExtensionsAsWarnings
*
*/
public void setTreatVendorExtensionsAsWarnings(
boolean treatVendorExtensionsAsWarnings) {
this.treatVendorExtensionsAsWarnings = treatVendorExtensionsAsWarnings;
}
public boolean getTreatCssHacksAsWarnings() {
return treatCssHacksAsWarnings;
}
/**
* Change the behaviour of error reporting for CSS Hacks.
*
* @param treatCssHacksAsWarnings
*/
public void setTreatCssHacksAsWarnings(boolean treatCssHacksAsWarnings) {
this.treatCssHacksAsWarnings = treatCssHacksAsWarnings;
}
public boolean getSuggestPropertyName() {
return suggestPropertyName;
}
public void setSuggestPropertyName(boolean b) {
suggestPropertyName = b;
}
/**
* Sets the content encoding to the first charset that appears in
* <i>acceptCharset</i>. If the charset is not supported, the content
* encoding will be utf-8
*
* @param acceptCharset a String representing the Accept-Charset request parameter
*/
public void setContentEncoding(String acceptCharset) {
if (acceptCharset != null) {
// uses some Jigsaw classes to parse the Accept-Charset
// these classes need to load a lot of stuff, so it may be quite
// long the first time
HttpAcceptCharsetList charsetList;
HttpAcceptCharset[] charsets;
charsetList = HttpFactory.parseAcceptCharsetList(acceptCharset);
charsets = (HttpAcceptCharset[]) charsetList.getValue();
String encoding = null;
double quality = 0.0;
String biasedcharset = getMsg().getString("output-encoding-name");
for (int i = 0; i < charsets.length && quality < 1.0; i++) {
HttpAcceptCharset charset = charsets[i];
String currentCharset = charset.getCharset();
// checks that the charset is supported by Java
if (isCharsetSupported(currentCharset)) {
double currentQuality = charset.getQuality();
// we prefer utf-8
// FIXME (the bias value and the biased charset
// should be dependant on the language)
if ((biasedcharset != null) &&
!biasedcharset.equalsIgnoreCase(currentCharset)) {
currentQuality *= 0.5;
}
if (currentQuality > quality) {
quality = currentQuality;
encoding = charset.getCharset();
}
}
}
if (encoding != null) {
getMsg().properties.setProperty("content-encoding", encoding);
} else {
// no valid charset
getMsg().properties.remove("content-encoding");
}
} else {
// no Accept-Charset given
getMsg().properties.remove("content-encoding");
}
}
private boolean isCharsetSupported(String charset) {
if ("*".equals(charset)) {
return true;
}
try {
return Charset.isSupported(charset);
} catch (Exception e) {
return false;
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, String charset, boolean from_bom) {
if (uricharsets == null) {
uricharsets = new HashMap<>();
}
Charset c = null;
try {
c = Charset.forName(charset);
} catch (IllegalCharsetNameException icex) {
// FIXME add a warning in the CSS
} catch (UnsupportedCharsetException ucex) {
// FIXME inform about lack of support
}
if (c != null) {
uricharsets.put(url, new BomEncoding(c, from_bom));
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, Charset charset) {
if (uricharsets == null) {
uricharsets = new HashMap<URL, BomEncoding>();
}
uricharsets.put(url, new BomEncoding(charset));
}
public boolean isCharsetFromBOM(URL url) {
BomEncoding b;
if (uricharsets == null) {
return false;
}
b = uricharsets.get(url);
if (b != null) {
return b.fromBom;
}
return false;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public String getCharsetForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b != null) {
return b.uriCharset.toString();
}
return null;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public Charset getCharsetObjForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b == null) {
return null;
}
return b.uriCharset;
}
/**
* store content of uploaded file
*/
public void setFakeFile(FakeFile fakefile) {
this.fakefile = fakefile;
}
/**
* store content of entered text
*/
public void setFakeText(String faketext, Charset faketextcharset) {
this.faketext = faketext;
this.faketextcharset = faketextcharset;
}
public InputStream getFakeInputStream(URL source)
throws IOException {
InputStream is = null;
Charset c = null;
if (fakefile != null) {
is = fakefile.getInputStream();
}
if (faketext != null) {
is = new ByteArrayInputStream(faketext.getBytes(faketextcharset));
c = faketextcharset;
}
if (is == null) {
return null;
}
if (c == null) {
c = getCharsetObjForURL(source);
}
if (c == null) {
UnicodeInputStream uis = new UnicodeInputStream(is);
String guessedCharset = uis.getEncodingFromStream();
if (guessedCharset != null) {
setCharsetForURL(source, guessedCharset, true);
}
return uis;
} else {
if (utf8Charset.compareTo(c) == 0) {
return new UnicodeInputStream(is);
}
}
return is;
}
public boolean isInputFake() {
return ((faketext != null) || (fakefile != null));
}
public void setFakeURL(String fakeurl) {
try {
this.fakeurl = new URL(fakeurl);
} catch (Exception ex) {
}
}
public URL getFakeURL() {
return fakeurl;
}
/**
* support for namespaces
*/
public void setNamespace(URL url, String prefix, String nsname) {
if (namespaces == null) {
namespaces = new HashMap<URL, HashMap<String, String>>();
}
// reformat the prefix if null.
String realPrefix = ((prefix != null) && !prefix.isEmpty()) ? prefix : defaultPrefix;
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
nsdefs = new HashMap<String, String>();
nsdefs.put(realPrefix, nsname);
namespaces.put(url, nsdefs);
} else {
// do we need to check if we have a redefinition ?
nsdefs.put(realPrefix, nsname);
}
}
// true if a namespace is defined in the document (CSS fragment)
// defined by the URL, with prefix "prefix"
public boolean isNamespaceDefined(URL url, String prefix) {
if (prefix == null) { // no prefix, always match
return true;
}
if (prefix.equals("*")) { // any ns, always true
return true;
}
String realPrefix = (!prefix.isEmpty()) ? prefix : defaultPrefix;
if (namespaces == null) { // no ns defined -> fail
return false;
}
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
return false;
}
return nsdefs.containsKey(realPrefix);
}
/**
* Set the current referrer for possible linked style sheets
*
* @param referrer the referring URL
*/
public void setReferrer(URL referrer) {
this.referrer = referrer;
}
/**
* get the referrer URL (or null if not relevant)
*
* @return an URL
*/
public URL getReferrer() {
return referrer;
}
}
| w3c/css-validator | org/w3c/css/util/ApplContext.java | 4,908 | // no valid charset | line_comment | nl | /*
* (c) COPYRIGHT 1999 World Wide Web Consortium
* (Massachusetts Institute of Technology, Institut National de Recherche
* en Informatique et en Automatique, Keio University).
* All Rights Reserved. http://www.w3.org/Consortium/Legal/
*
* $Id$
*/
package org.w3c.css.util;
import org.w3c.css.css.StyleSheet;
import org.w3c.css.parser.Frame;
import org.w3c.www.http.HttpAcceptCharset;
import org.w3c.www.http.HttpAcceptCharsetList;
import org.w3c.www.http.HttpFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Philippe Le Hegaret
* @version $Revision$
*/
public class ApplContext {
// the charset of the first source (url/uploaded/text)
public static Charset defaultCharset;
public static Charset utf8Charset;
static {
try {
defaultCharset = Charset.forName("iso-8859-1");
utf8Charset = Charset.forName("utf-8");
} catch (Exception ex) {
// we are in deep trouble here
defaultCharset = null;
utf8Charset = null;
}
}
private class BomEncoding {
Charset uriCharset = null;
boolean fromBom = false;
private BomEncoding(Charset c, boolean fb) {
uriCharset = c;
fromBom = fb;
}
private BomEncoding(Charset c) {
this(c, false);
}
private BomEncoding() {
}
}
// charset definition of traversed URLs
private HashMap<URL, BomEncoding> uricharsets = null;
// namespace definitions
private HashMap<URL, HashMap<String, String>> namespaces = null;
// default prefix
public static String defaultPrefix = "*defaultprefix*";
public static String noPrefix = "*noprefix*";
private ArrayList<URL> linkedmedia = new ArrayList<URL>();
String credential = null;
String lang;
Messages msgs;
Frame frame;
StyleSheet styleSheet = null;
CssVersion version = CssVersion.getDefault();
CssProfile profile = CssProfile.NONE;
String input;
Class cssselectorstyle;
int origin = -1;
String medium;
private String link;
int warningLevel = 0;
boolean treatVendorExtensionsAsWarnings = false;
boolean treatCssHacksAsWarnings = false;
boolean suggestPropertyName = true;
private String propertyKey = null;
public boolean followlinks() {
return followlinks;
}
public void setFollowlinks(boolean followlinks) {
this.followlinks = followlinks;
}
boolean followlinks = true;
FakeFile fakefile = null;
String faketext = null;
Charset faketextcharset = null;
URL fakeurl = null;
URL referrer = null;
/**
* Creates a new ApplContext
*/
public ApplContext(String lang) {
this.lang = lang;
msgs = new Messages(lang);
}
public int getWarningLevel() {
return warningLevel;
}
public void setWarningLevel(int warningLevel) {
this.warningLevel = warningLevel;
}
public ArrayList<URL> getLinkedURIs() {
return linkedmedia;
}
public void addLinkedURI(URL url) {
if (url != null) {
linkedmedia.add(url);
}
}
// as ugly as everything else
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public void setFrame(Frame frame) {
this.frame = frame;
frame.ac = this;
}
public Frame getFrame() {
return frame;
}
public void setStyleSheet(StyleSheet styleSheet) {
this.styleSheet = styleSheet;
}
public StyleSheet getStyleSheet() {
return styleSheet;
}
public Class getCssSelectorsStyle() {
return cssselectorstyle;
}
public void setCssSelectorsStyle(Class s) {
cssselectorstyle = s;
}
public Messages getMsg() {
return msgs;
}
public String getContentType() {
return (msgs != null) ? msgs.getString("content-type") : null;
}
public String getContentLanguage() {
return (msgs != null) ? msgs.getString("content-language") : null;
}
/**
* Searches the properties list for a content-encoding one. If it does not
* exist, searches for output-encoding-name. If it still does not exists,
* the method returns the default utf-8 value
*
* @return the output encoding of this ApplContext
*/
public String getContentEncoding() {
// return (msgs != null) ? msgs.getString("content-encoding") : null;
String res = null;
if (msgs != null) {
res = msgs.getString("content-encoding");
if (res == null) {
res = msgs.getString("output-encoding-name");
}
if (res != null) {
// if an encoding has been found, return it
return res;
}
}
// default encoding
return Utf8Properties.ENCODING;
}
public String getLang() {
return lang;
}
public void setCssVersion(String cssversion) {
version = CssVersion.resolve(this, cssversion);
propertyKey = null;
}
public void setCssVersion(CssVersion version) {
this.version = version;
propertyKey = null;
}
public String getCssVersionString() {
return version.toString();
}
public CssVersion getCssVersion() {
return version;
}
public void setProfile(String profile) {
this.profile = CssProfile.resolve(this, profile);
propertyKey = null;
}
/**
* get the String used to fetch the relevant property file
*/
public String getPropertyKey() {
if (propertyKey != null) {
return propertyKey;
}
if (profile == CssProfile.SVG && version == CssVersion.CSS3) {
propertyKey = version.toString() + profile.toString();
return propertyKey;
}
if (profile != CssProfile.EMPTY && profile != CssProfile.NONE) {
propertyKey = profile.toString();
} else {
propertyKey = version.toString();
}
return propertyKey;
}
public CssProfile getCssProfile() {
return profile;
}
public String getProfileString() {
return profile.toString();
}
public void setCssVersionAndProfile(String spec) {
// for things like SVG, version will be set to the default one
// CSS21 in that case, as defined in CssVersion
// and profile will be resolved to svg.
//
// if the version resolve then profile will default to NONE
// TODO should we check profile first and if SVG or MOBILE
// set specific version of CSS (like CSS2 and not CSS21 for MOBILE) ?
if ((spec == null) || spec.isEmpty()) {
version = CssVersion.getDefault();
profile = CssProfile.SVG;
} else {
String low = spec.toLowerCase();
version = CssVersion.resolve(this, low);
profile = CssProfile.resolve(this, low);
// some special cases...
// http://www.atsc.org/cms/index.php/standards/published-standards/71-atsc-a100-standard
if (profile.equals(CssProfile.ATSCTV)) {
version = CssVersion.CSS2;
}
}
}
public void setOrigin(int origin) {
this.origin = origin;
}
public int getOrigin() {
return origin;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getMedium() {
return medium;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getLink() {
return link;
}
public void setLink(String queryString) {
this.link = queryString;
}
public boolean getTreatVendorExtensionsAsWarnings() {
return treatVendorExtensionsAsWarnings;
}
/**
* Change the behaviour of error reporting for vendor extensions.
*
* @param treatVendorExtensionsAsWarnings
*
*/
public void setTreatVendorExtensionsAsWarnings(
boolean treatVendorExtensionsAsWarnings) {
this.treatVendorExtensionsAsWarnings = treatVendorExtensionsAsWarnings;
}
public boolean getTreatCssHacksAsWarnings() {
return treatCssHacksAsWarnings;
}
/**
* Change the behaviour of error reporting for CSS Hacks.
*
* @param treatCssHacksAsWarnings
*/
public void setTreatCssHacksAsWarnings(boolean treatCssHacksAsWarnings) {
this.treatCssHacksAsWarnings = treatCssHacksAsWarnings;
}
public boolean getSuggestPropertyName() {
return suggestPropertyName;
}
public void setSuggestPropertyName(boolean b) {
suggestPropertyName = b;
}
/**
* Sets the content encoding to the first charset that appears in
* <i>acceptCharset</i>. If the charset is not supported, the content
* encoding will be utf-8
*
* @param acceptCharset a String representing the Accept-Charset request parameter
*/
public void setContentEncoding(String acceptCharset) {
if (acceptCharset != null) {
// uses some Jigsaw classes to parse the Accept-Charset
// these classes need to load a lot of stuff, so it may be quite
// long the first time
HttpAcceptCharsetList charsetList;
HttpAcceptCharset[] charsets;
charsetList = HttpFactory.parseAcceptCharsetList(acceptCharset);
charsets = (HttpAcceptCharset[]) charsetList.getValue();
String encoding = null;
double quality = 0.0;
String biasedcharset = getMsg().getString("output-encoding-name");
for (int i = 0; i < charsets.length && quality < 1.0; i++) {
HttpAcceptCharset charset = charsets[i];
String currentCharset = charset.getCharset();
// checks that the charset is supported by Java
if (isCharsetSupported(currentCharset)) {
double currentQuality = charset.getQuality();
// we prefer utf-8
// FIXME (the bias value and the biased charset
// should be dependant on the language)
if ((biasedcharset != null) &&
!biasedcharset.equalsIgnoreCase(currentCharset)) {
currentQuality *= 0.5;
}
if (currentQuality > quality) {
quality = currentQuality;
encoding = charset.getCharset();
}
}
}
if (encoding != null) {
getMsg().properties.setProperty("content-encoding", encoding);
} else {
// no valid<SUF>
getMsg().properties.remove("content-encoding");
}
} else {
// no Accept-Charset given
getMsg().properties.remove("content-encoding");
}
}
private boolean isCharsetSupported(String charset) {
if ("*".equals(charset)) {
return true;
}
try {
return Charset.isSupported(charset);
} catch (Exception e) {
return false;
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, String charset, boolean from_bom) {
if (uricharsets == null) {
uricharsets = new HashMap<>();
}
Charset c = null;
try {
c = Charset.forName(charset);
} catch (IllegalCharsetNameException icex) {
// FIXME add a warning in the CSS
} catch (UnsupportedCharsetException ucex) {
// FIXME inform about lack of support
}
if (c != null) {
uricharsets.put(url, new BomEncoding(c, from_bom));
}
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public void setCharsetForURL(URL url, Charset charset) {
if (uricharsets == null) {
uricharsets = new HashMap<URL, BomEncoding>();
}
uricharsets.put(url, new BomEncoding(charset));
}
public boolean isCharsetFromBOM(URL url) {
BomEncoding b;
if (uricharsets == null) {
return false;
}
b = uricharsets.get(url);
if (b != null) {
return b.fromBom;
}
return false;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public String getCharsetForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b != null) {
return b.uriCharset.toString();
}
return null;
}
/**
* used for storing the charset of the document in use
* and its update by a @charset statement, or through
* automatic discovery
*/
public Charset getCharsetObjForURL(URL url) {
BomEncoding b;
if (uricharsets == null) {
return null;
}
b = uricharsets.get(url);
if (b == null) {
return null;
}
return b.uriCharset;
}
/**
* store content of uploaded file
*/
public void setFakeFile(FakeFile fakefile) {
this.fakefile = fakefile;
}
/**
* store content of entered text
*/
public void setFakeText(String faketext, Charset faketextcharset) {
this.faketext = faketext;
this.faketextcharset = faketextcharset;
}
public InputStream getFakeInputStream(URL source)
throws IOException {
InputStream is = null;
Charset c = null;
if (fakefile != null) {
is = fakefile.getInputStream();
}
if (faketext != null) {
is = new ByteArrayInputStream(faketext.getBytes(faketextcharset));
c = faketextcharset;
}
if (is == null) {
return null;
}
if (c == null) {
c = getCharsetObjForURL(source);
}
if (c == null) {
UnicodeInputStream uis = new UnicodeInputStream(is);
String guessedCharset = uis.getEncodingFromStream();
if (guessedCharset != null) {
setCharsetForURL(source, guessedCharset, true);
}
return uis;
} else {
if (utf8Charset.compareTo(c) == 0) {
return new UnicodeInputStream(is);
}
}
return is;
}
public boolean isInputFake() {
return ((faketext != null) || (fakefile != null));
}
public void setFakeURL(String fakeurl) {
try {
this.fakeurl = new URL(fakeurl);
} catch (Exception ex) {
}
}
public URL getFakeURL() {
return fakeurl;
}
/**
* support for namespaces
*/
public void setNamespace(URL url, String prefix, String nsname) {
if (namespaces == null) {
namespaces = new HashMap<URL, HashMap<String, String>>();
}
// reformat the prefix if null.
String realPrefix = ((prefix != null) && !prefix.isEmpty()) ? prefix : defaultPrefix;
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
nsdefs = new HashMap<String, String>();
nsdefs.put(realPrefix, nsname);
namespaces.put(url, nsdefs);
} else {
// do we need to check if we have a redefinition ?
nsdefs.put(realPrefix, nsname);
}
}
// true if a namespace is defined in the document (CSS fragment)
// defined by the URL, with prefix "prefix"
public boolean isNamespaceDefined(URL url, String prefix) {
if (prefix == null) { // no prefix, always match
return true;
}
if (prefix.equals("*")) { // any ns, always true
return true;
}
String realPrefix = (!prefix.isEmpty()) ? prefix : defaultPrefix;
if (namespaces == null) { // no ns defined -> fail
return false;
}
HashMap<String, String> nsdefs = namespaces.get(url);
if (nsdefs == null) {
return false;
}
return nsdefs.containsKey(realPrefix);
}
/**
* Set the current referrer for possible linked style sheets
*
* @param referrer the referring URL
*/
public void setReferrer(URL referrer) {
this.referrer = referrer;
}
/**
* get the referrer URL (or null if not relevant)
*
* @return an URL
*/
public URL getReferrer() {
return referrer;
}
}
|
184855_1 | package com.adobe.epubcheck.util;
import java.io.File;
import java.io.PrintWriter;
import java.text.CharacterIterator;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.adobe.epubcheck.api.MasterReport;
import com.adobe.epubcheck.api.EPUBLocation;
import com.adobe.epubcheck.messages.Message;
import com.adobe.epubcheck.messages.Severity;
import com.adobe.epubcheck.reporting.CheckMessage;
/**
* Abstract class to generate a report in XML.
*
* It collects the information needed for the report and provides helper methods to generate proper XML.
* In order to generate a specific XML, the generateReport method should be provided in a derived class.
*
*/
public abstract class XmlReportAbstract extends MasterReport {
protected PrintWriter out;
protected String epubCheckName = "epubcheck";
protected String epubCheckVersion;
protected String epubCheckDate = "2012-10-31"; // default date to be
// overridden by the property
protected String generationDate;
protected String creationDate;
protected String lastModifiedDate;
protected String identifier;
protected Set<String> titles = new LinkedHashSet<String>();
protected final Set<String> creators = new LinkedHashSet<String>();
protected final Set<String> contributors = new LinkedHashSet<String>();
protected final Set<String> subjects = new LinkedHashSet<String>();
protected String publisher;
protected final Set<String> rights = new LinkedHashSet<String>();
protected String date;
protected final Set<String> mediaTypes = new LinkedHashSet<String>();
protected String formatName;
protected String formatVersion;
protected long pagesCount;
protected long charsCount;
protected String language;
protected final Set<String> embeddedFonts = new LinkedHashSet<String>();
protected final Set<String> refFonts = new LinkedHashSet<String>();
protected final Set<String> references = new LinkedHashSet<String>();
protected boolean hasEncryption;
protected boolean hasSignatures;
protected boolean hasAudio;
protected boolean hasVideo;
protected boolean hasFixedLayout;
protected boolean hasScripts;
protected final List<CheckMessage> warns = new ArrayList<CheckMessage>();
protected final List<CheckMessage> errors = new ArrayList<CheckMessage>();
protected final List<CheckMessage> fatalErrors = new ArrayList<CheckMessage>();
protected final List<CheckMessage> hints = new ArrayList<CheckMessage>();
public XmlReportAbstract(PrintWriter out, String ePubName, String versionEpubCheck) {
this.out = out;
this.setEpubFileName(PathUtil.removeWorkingDirectory(ePubName));
this.epubCheckVersion = versionEpubCheck;
}
public void initialize() {
}
@Override
public void close() {
}
@Override
public void message(Message message, EPUBLocation location, Object... args) {
Severity s = message.getSeverity();
switch (s) {
case FATAL:
CheckMessage.addCheckMessage(fatalErrors, message, location, args);
break;
case ERROR:
CheckMessage.addCheckMessage(errors, message, location, args);
break;
case WARNING:
CheckMessage.addCheckMessage(warns, message, location, args);
break;
case USAGE:
CheckMessage.addCheckMessage(hints, message, location, args);
break;
case INFO:
break;
case SUPPRESSED:
break;
default:
break;
}
}
@Override
public void info(String resource, FeatureEnum feature, String value) {
// Dont store 'null' values
if (value == null) return;
switch (feature) {
case TOOL_DATE:
if (value != null && !value.startsWith("$")) {
this.epubCheckDate = value;
}
break;
case TOOL_NAME:
this.epubCheckName = value;
break;
case TOOL_VERSION:
this.epubCheckVersion = value;
break;
case FORMAT_NAME:
this.formatName = value;
break;
case FORMAT_VERSION:
this.formatVersion = value;
break;
case CREATION_DATE:
this.creationDate = value;
break;
case MODIFIED_DATE:
this.lastModifiedDate = value;
break;
case PAGES_COUNT:
this.pagesCount = Long.parseLong(value);
break;
case CHARS_COUNT:
this.charsCount += Long.parseLong(value);
break;
case DECLARED_MIMETYPE:
mediaTypes.add(value);
if (value != null && value.startsWith("audio/")) {
this.hasAudio = true;
} else if (value != null && value.startsWith("video/")) {
this.hasVideo = true;
}
break;
case FONT_EMBEDDED:
this.embeddedFonts.add(value);
break;
case FONT_REFERENCE:
this.refFonts.add(value);
break;
case REFERENCE:
this.references.add(value);
break;
case DC_LANGUAGE:
this.language = value;
break;
case DC_TITLE:
this.titles.add(value);
break;
case DC_CREATOR:
this.creators.add(value);
break;
case DC_CONTRIBUTOR:
this.contributors.add(value);
break;
case DC_PUBLISHER:
this.publisher = value;
break;
case DC_SUBJECT:
this.subjects.add(value);
break;
case DC_RIGHTS:
this.rights.add(value);
break;
case DC_DATE:
this.date = value;
break;
case UNIQUE_IDENT:
if (resource == null) {
this.identifier = value;
}
break;
case HAS_SIGNATURES:
this.hasSignatures = true;
break;
case HAS_ENCRYPTION:
this.hasEncryption = true;
break;
case HAS_FIXED_LAYOUT:
this.hasFixedLayout = true;
break;
case HAS_SCRIPTS:
this.hasScripts = true;
break;
case SPINE_INDEX:
break;
default:
break;
}
}
protected String getNameFromPath(String path) {
if (path == null || path.length() == 0) {
return null;
}
// Try / because of uris
int lastSlash = path.lastIndexOf('/');
if (lastSlash == -1) {
if (File.separatorChar != '/') {
int lastSlash2 = path.lastIndexOf(File.separatorChar);
if (lastSlash2 == -1) {
return path;
} else {
return path.substring(lastSlash2 + 1);
}
} else {
return path;
}
} else {
return path.substring(lastSlash + 1);
}
}
/**
* Method to implement effective report generation.
* @return errorCode
*/
public abstract int generateReport();
// Variables for report generation
private Document doc;
private Element currentEl;
private String namespaceURI;
private Map<String, String> namespaces;
public void setNamespace(String uri) {
namespaceURI = uri;
}
public void addPrefixNamespace(String prefix, String uri) {
namespaces.put(prefix, uri);
}
public int generate() {
namespaces = new HashMap<String, String>();
int returnCode = 1;
try {
// Initialize the DOM
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
// Calculate the report
returnCode = generateReport();
if (returnCode == 0) {
// Output the report
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
returnCode = 1;
} catch (TransformerException e) {
//System.err.println(Messages.get("error_generating_report"));
System.err.println("Error while generating the XML report " + e.getMessage());
e.printStackTrace();
returnCode = 1;
} finally {
if (out != null) {
out.flush();
out.close();
}
}
return returnCode;
}
protected String capitalize(String in) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
if (i == 0)
sb.append(Character.toUpperCase(c));
else
sb.append(c);
}
return sb.toString();
}
private Element makeElement(String name) {
Element el;
int index = name.indexOf(':');
if (index == -1) {
if (namespaceURI == null) {
el = doc.createElement(name);
} else {
el = doc.createElementNS(namespaceURI, name);
}
} else {
String prefix = name.substring(0, index);
String uri = namespaces.get(prefix);
if (uri == null) {
el = doc.createElement(name);
} else {
el = doc.createElementNS(uri, name);
}
}
return el;
}
private Attr makeAttribute(KeyValue<String, String> kv) {
Attr attr;
String attName = kv.getKey();
int iAttr = attName.indexOf(':');
if (iAttr == -1) {
attr = doc.createAttribute(attName);
} else {
String prefix = attName.substring(0, iAttr);
String uri = namespaces.get(prefix);
if (uri == null) {
attr = doc.createAttribute(attName);
} else {
attr = doc.createAttributeNS(uri, attName);
}
}
attr.setValue(kv.getValue());
return attr;
}
protected void startElement(String name, List<KeyValue<String, String>> attrs) {
if (name == null || name.trim().length() == 0) {
return;
}
Element el = makeElement(name.trim());
if (attrs != null && attrs.size() != 0) {
for (KeyValue<String, String> attr : attrs) {
el.setAttributeNode(makeAttribute(attr));
}
}
if (currentEl == null) {
doc.appendChild(el);
} else {
currentEl.appendChild(el);
}
currentEl = el;
}
@SuppressWarnings("unchecked")
protected void startElement(String name, KeyValue<String, String>... attrs) {
startElement(name, Arrays.asList(attrs));
}
protected void startElement(String name) {
startElement(name, (List<KeyValue<String, String>>) null);
}
protected void endElement(String name) {
if (currentEl == null) return;
Node parent = currentEl.getParentNode();
if (parent == null || parent == doc) {
currentEl = null;
} else if (parent instanceof Element) {
currentEl = (Element)currentEl.getParentNode();
} else {
System.out.println("Pb at Element [" + currentEl.getLocalName() + "] with parent " + parent);
}
}
protected void generateElement(String name, String value) {
if (name == null || name.trim().length() == 0 || value == null || value.trim().length() == 0) {
return;
}
Element el = makeElement(name.trim());
el.appendChild(doc.createTextNode(correctToUtf8(value.trim())));
currentEl.appendChild(el);
}
@SuppressWarnings("unchecked")
protected void generateElement(String name, String value, KeyValue<String, String>... attrs) {
generateElement(name, value, Arrays.asList(attrs));
}
protected void generateElement(String name, String value, List<KeyValue<String, String>> attrs) {
if (name == null || name.trim().length() == 0) {
return;
}
Element el = makeElement(name);
if (attrs != null && attrs.size() != 0) {
for (KeyValue<String, String> attr : attrs) {
el.setAttributeNode(makeAttribute(attr));
}
}
if (value != null && value.trim().length() != 0) {
el.appendChild(doc.createTextNode(correctToUtf8(value.trim())));
}
currentEl.appendChild(el);
}
/**
* Make sure the string contains valid UTF-8 characters
* @param inputString
* @return escaped String
*/
protected static String correctToUtf8(String inputString) {
final StringBuilder result = new StringBuilder(inputString.length());
final StringCharacterIterator it = new StringCharacterIterator(inputString);
char ch = it.current();
boolean modified = false;
while (ch != CharacterIterator.DONE) {
if (Character.isISOControl(ch)) {
if (ch == '\r' || ch == '\n') {
result.append(ch);
} else {
modified = true;
result.append(String.format("0x%x", (int) ch));
}
} else {
result.append(ch);
}
ch = it.next();
}
if (!modified) return inputString;
return result.toString();
}
/**
* Transform time into ISO 8601 string.
*/
protected static String fromTime(final long time) {
Date date = new Date(time);
// Waiting for Java 7: SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date);
return formatted.substring(0, 22) + ":" + formatted.substring(22);
}
}
| w3c/epubcheck | src/main/java/com/adobe/epubcheck/util/XmlReportAbstract.java | 4,167 | // default date to be | line_comment | nl | package com.adobe.epubcheck.util;
import java.io.File;
import java.io.PrintWriter;
import java.text.CharacterIterator;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.adobe.epubcheck.api.MasterReport;
import com.adobe.epubcheck.api.EPUBLocation;
import com.adobe.epubcheck.messages.Message;
import com.adobe.epubcheck.messages.Severity;
import com.adobe.epubcheck.reporting.CheckMessage;
/**
* Abstract class to generate a report in XML.
*
* It collects the information needed for the report and provides helper methods to generate proper XML.
* In order to generate a specific XML, the generateReport method should be provided in a derived class.
*
*/
public abstract class XmlReportAbstract extends MasterReport {
protected PrintWriter out;
protected String epubCheckName = "epubcheck";
protected String epubCheckVersion;
protected String epubCheckDate = "2012-10-31"; // default date<SUF>
// overridden by the property
protected String generationDate;
protected String creationDate;
protected String lastModifiedDate;
protected String identifier;
protected Set<String> titles = new LinkedHashSet<String>();
protected final Set<String> creators = new LinkedHashSet<String>();
protected final Set<String> contributors = new LinkedHashSet<String>();
protected final Set<String> subjects = new LinkedHashSet<String>();
protected String publisher;
protected final Set<String> rights = new LinkedHashSet<String>();
protected String date;
protected final Set<String> mediaTypes = new LinkedHashSet<String>();
protected String formatName;
protected String formatVersion;
protected long pagesCount;
protected long charsCount;
protected String language;
protected final Set<String> embeddedFonts = new LinkedHashSet<String>();
protected final Set<String> refFonts = new LinkedHashSet<String>();
protected final Set<String> references = new LinkedHashSet<String>();
protected boolean hasEncryption;
protected boolean hasSignatures;
protected boolean hasAudio;
protected boolean hasVideo;
protected boolean hasFixedLayout;
protected boolean hasScripts;
protected final List<CheckMessage> warns = new ArrayList<CheckMessage>();
protected final List<CheckMessage> errors = new ArrayList<CheckMessage>();
protected final List<CheckMessage> fatalErrors = new ArrayList<CheckMessage>();
protected final List<CheckMessage> hints = new ArrayList<CheckMessage>();
public XmlReportAbstract(PrintWriter out, String ePubName, String versionEpubCheck) {
this.out = out;
this.setEpubFileName(PathUtil.removeWorkingDirectory(ePubName));
this.epubCheckVersion = versionEpubCheck;
}
public void initialize() {
}
@Override
public void close() {
}
@Override
public void message(Message message, EPUBLocation location, Object... args) {
Severity s = message.getSeverity();
switch (s) {
case FATAL:
CheckMessage.addCheckMessage(fatalErrors, message, location, args);
break;
case ERROR:
CheckMessage.addCheckMessage(errors, message, location, args);
break;
case WARNING:
CheckMessage.addCheckMessage(warns, message, location, args);
break;
case USAGE:
CheckMessage.addCheckMessage(hints, message, location, args);
break;
case INFO:
break;
case SUPPRESSED:
break;
default:
break;
}
}
@Override
public void info(String resource, FeatureEnum feature, String value) {
// Dont store 'null' values
if (value == null) return;
switch (feature) {
case TOOL_DATE:
if (value != null && !value.startsWith("$")) {
this.epubCheckDate = value;
}
break;
case TOOL_NAME:
this.epubCheckName = value;
break;
case TOOL_VERSION:
this.epubCheckVersion = value;
break;
case FORMAT_NAME:
this.formatName = value;
break;
case FORMAT_VERSION:
this.formatVersion = value;
break;
case CREATION_DATE:
this.creationDate = value;
break;
case MODIFIED_DATE:
this.lastModifiedDate = value;
break;
case PAGES_COUNT:
this.pagesCount = Long.parseLong(value);
break;
case CHARS_COUNT:
this.charsCount += Long.parseLong(value);
break;
case DECLARED_MIMETYPE:
mediaTypes.add(value);
if (value != null && value.startsWith("audio/")) {
this.hasAudio = true;
} else if (value != null && value.startsWith("video/")) {
this.hasVideo = true;
}
break;
case FONT_EMBEDDED:
this.embeddedFonts.add(value);
break;
case FONT_REFERENCE:
this.refFonts.add(value);
break;
case REFERENCE:
this.references.add(value);
break;
case DC_LANGUAGE:
this.language = value;
break;
case DC_TITLE:
this.titles.add(value);
break;
case DC_CREATOR:
this.creators.add(value);
break;
case DC_CONTRIBUTOR:
this.contributors.add(value);
break;
case DC_PUBLISHER:
this.publisher = value;
break;
case DC_SUBJECT:
this.subjects.add(value);
break;
case DC_RIGHTS:
this.rights.add(value);
break;
case DC_DATE:
this.date = value;
break;
case UNIQUE_IDENT:
if (resource == null) {
this.identifier = value;
}
break;
case HAS_SIGNATURES:
this.hasSignatures = true;
break;
case HAS_ENCRYPTION:
this.hasEncryption = true;
break;
case HAS_FIXED_LAYOUT:
this.hasFixedLayout = true;
break;
case HAS_SCRIPTS:
this.hasScripts = true;
break;
case SPINE_INDEX:
break;
default:
break;
}
}
protected String getNameFromPath(String path) {
if (path == null || path.length() == 0) {
return null;
}
// Try / because of uris
int lastSlash = path.lastIndexOf('/');
if (lastSlash == -1) {
if (File.separatorChar != '/') {
int lastSlash2 = path.lastIndexOf(File.separatorChar);
if (lastSlash2 == -1) {
return path;
} else {
return path.substring(lastSlash2 + 1);
}
} else {
return path;
}
} else {
return path.substring(lastSlash + 1);
}
}
/**
* Method to implement effective report generation.
* @return errorCode
*/
public abstract int generateReport();
// Variables for report generation
private Document doc;
private Element currentEl;
private String namespaceURI;
private Map<String, String> namespaces;
public void setNamespace(String uri) {
namespaceURI = uri;
}
public void addPrefixNamespace(String prefix, String uri) {
namespaces.put(prefix, uri);
}
public int generate() {
namespaces = new HashMap<String, String>();
int returnCode = 1;
try {
// Initialize the DOM
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
// Calculate the report
returnCode = generateReport();
if (returnCode == 0) {
// Output the report
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
returnCode = 1;
} catch (TransformerException e) {
//System.err.println(Messages.get("error_generating_report"));
System.err.println("Error while generating the XML report " + e.getMessage());
e.printStackTrace();
returnCode = 1;
} finally {
if (out != null) {
out.flush();
out.close();
}
}
return returnCode;
}
protected String capitalize(String in) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
if (i == 0)
sb.append(Character.toUpperCase(c));
else
sb.append(c);
}
return sb.toString();
}
private Element makeElement(String name) {
Element el;
int index = name.indexOf(':');
if (index == -1) {
if (namespaceURI == null) {
el = doc.createElement(name);
} else {
el = doc.createElementNS(namespaceURI, name);
}
} else {
String prefix = name.substring(0, index);
String uri = namespaces.get(prefix);
if (uri == null) {
el = doc.createElement(name);
} else {
el = doc.createElementNS(uri, name);
}
}
return el;
}
private Attr makeAttribute(KeyValue<String, String> kv) {
Attr attr;
String attName = kv.getKey();
int iAttr = attName.indexOf(':');
if (iAttr == -1) {
attr = doc.createAttribute(attName);
} else {
String prefix = attName.substring(0, iAttr);
String uri = namespaces.get(prefix);
if (uri == null) {
attr = doc.createAttribute(attName);
} else {
attr = doc.createAttributeNS(uri, attName);
}
}
attr.setValue(kv.getValue());
return attr;
}
protected void startElement(String name, List<KeyValue<String, String>> attrs) {
if (name == null || name.trim().length() == 0) {
return;
}
Element el = makeElement(name.trim());
if (attrs != null && attrs.size() != 0) {
for (KeyValue<String, String> attr : attrs) {
el.setAttributeNode(makeAttribute(attr));
}
}
if (currentEl == null) {
doc.appendChild(el);
} else {
currentEl.appendChild(el);
}
currentEl = el;
}
@SuppressWarnings("unchecked")
protected void startElement(String name, KeyValue<String, String>... attrs) {
startElement(name, Arrays.asList(attrs));
}
protected void startElement(String name) {
startElement(name, (List<KeyValue<String, String>>) null);
}
protected void endElement(String name) {
if (currentEl == null) return;
Node parent = currentEl.getParentNode();
if (parent == null || parent == doc) {
currentEl = null;
} else if (parent instanceof Element) {
currentEl = (Element)currentEl.getParentNode();
} else {
System.out.println("Pb at Element [" + currentEl.getLocalName() + "] with parent " + parent);
}
}
protected void generateElement(String name, String value) {
if (name == null || name.trim().length() == 0 || value == null || value.trim().length() == 0) {
return;
}
Element el = makeElement(name.trim());
el.appendChild(doc.createTextNode(correctToUtf8(value.trim())));
currentEl.appendChild(el);
}
@SuppressWarnings("unchecked")
protected void generateElement(String name, String value, KeyValue<String, String>... attrs) {
generateElement(name, value, Arrays.asList(attrs));
}
protected void generateElement(String name, String value, List<KeyValue<String, String>> attrs) {
if (name == null || name.trim().length() == 0) {
return;
}
Element el = makeElement(name);
if (attrs != null && attrs.size() != 0) {
for (KeyValue<String, String> attr : attrs) {
el.setAttributeNode(makeAttribute(attr));
}
}
if (value != null && value.trim().length() != 0) {
el.appendChild(doc.createTextNode(correctToUtf8(value.trim())));
}
currentEl.appendChild(el);
}
/**
* Make sure the string contains valid UTF-8 characters
* @param inputString
* @return escaped String
*/
protected static String correctToUtf8(String inputString) {
final StringBuilder result = new StringBuilder(inputString.length());
final StringCharacterIterator it = new StringCharacterIterator(inputString);
char ch = it.current();
boolean modified = false;
while (ch != CharacterIterator.DONE) {
if (Character.isISOControl(ch)) {
if (ch == '\r' || ch == '\n') {
result.append(ch);
} else {
modified = true;
result.append(String.format("0x%x", (int) ch));
}
} else {
result.append(ch);
}
ch = it.next();
}
if (!modified) return inputString;
return result.toString();
}
/**
* Transform time into ISO 8601 string.
*/
protected static String fromTime(final long time) {
Date date = new Date(time);
// Waiting for Java 7: SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date);
return formatted.substring(0, 22) + ":" + formatted.substring(22);
}
}
|
167657_0 | package ap.edu.schademeldingap.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import ap.edu.schademeldingap.controllers.MeldingController;
import ap.edu.schademeldingap.models.Melding;
import ap.edu.schademeldingap.R;
public class NieuweMeldingActivity extends AbstractActivity {
private MeldingController mc;
static final int REQUEST_IMAGE_CAPTURE = 1;
private EditText vrijeInvoer;
private EditText beschrijvingSchade;
private ImageView imageThumbnail;
private Spinner spinnerCat;
private Spinner spinnerLokaal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nieuwe_melding);
setTitle("SCHADE MELDEN");
//variabelen linken aan de UI
Button buttonMeldenSchade = findViewById(R.id.buttonMeldenSchade);
Button buttonFoto = findViewById(R.id.buttonFoto);
vrijeInvoer = findViewById(R.id.editVrijeInvoer);
beschrijvingSchade = findViewById(R.id.editBeschrijving);
imageThumbnail = findViewById(R.id.imageThumbnail);
spinnerCat = findViewById(R.id.spinnerCategorie);
final Spinner spinnerVerdieping = findViewById(R.id.spinnerVerdieping);
spinnerLokaal = findViewById(R.id.spinnerLokaal);
//De juiste lokalen tonen bij desbetreffende verdiepingen
spinnerVerdieping.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiepMin1);
break;
case 1:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiepGelijkVloer);
break;
case 2:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep1);
break;
case 3:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep2);
break;
case 4:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep3);
break;
case 5:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep4);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//unused
}
});
//Button listerens
buttonFoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
} else {
dispatchTakePictureIntent();
}
}
});
buttonMeldenSchade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!validateForm()) {
return;
}
String name = getIntent().getStringExtra(getString(R.string.key_naam));
String lokaal = spinnerLokaal.getSelectedItem().toString();
Melding melding = new Melding(name,
spinnerVerdieping.getSelectedItem().toString(),
lokaal.substring(0,3),
vrijeInvoer.getText().toString(),
spinnerCat.getSelectedItem().toString(),
beschrijvingSchade.getText().toString(),
lokaal.substring(3));
mc = new MeldingController();
mc.nieuweMelding(melding, imageThumbnail, v.getContext());
showDialogInfoToActivity(NieuweMeldingActivity.this, HomeActivity.class,
getString(R.string.geslaagd),
getString(R.string.melding_succes));
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
//Show permission explanation dialog...
showDialogAlert(NieuweMeldingActivity.this, getString(R.string.camera_permissie), getString(R.string.cam_toestemming));
Log.d("perm", "show permission explanation dialog");
} else {
//Never ask again selected, or device policy prohibits the app from having that permission.
//So, disable that feature, or fall back to another situation...
showDialogAlert(NieuweMeldingActivity.this, getString(R.string.camera_permissie), getString(R.string.cam_toestemming_extra));
Log.d("perm", "Never ask again selected or...");
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageThumbnail.setImageBitmap(imageBitmap);
}
}
private void fillSpinnerLokaalWithAdapter(int verdiepingArrayAdapter) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, verdiepingArrayAdapter, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerLokaal.setAdapter(adapter);
}
private boolean validateForm() {
boolean valid = true;
if (imageThumbnail.getDrawable() == null) {
showDialogAlert(NieuweMeldingActivity.this, getString(R.string.fout), getString(R.string.foto_is_verplicht));
valid = false;
}
return valid;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
} | wa1id/Schade-Rapportering-AP | app/src/main/java/ap/edu/schademeldingap/activities/NieuweMeldingActivity.java | 2,081 | //variabelen linken aan de UI | line_comment | nl | package ap.edu.schademeldingap.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import ap.edu.schademeldingap.controllers.MeldingController;
import ap.edu.schademeldingap.models.Melding;
import ap.edu.schademeldingap.R;
public class NieuweMeldingActivity extends AbstractActivity {
private MeldingController mc;
static final int REQUEST_IMAGE_CAPTURE = 1;
private EditText vrijeInvoer;
private EditText beschrijvingSchade;
private ImageView imageThumbnail;
private Spinner spinnerCat;
private Spinner spinnerLokaal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nieuwe_melding);
setTitle("SCHADE MELDEN");
//variabelen linken<SUF>
Button buttonMeldenSchade = findViewById(R.id.buttonMeldenSchade);
Button buttonFoto = findViewById(R.id.buttonFoto);
vrijeInvoer = findViewById(R.id.editVrijeInvoer);
beschrijvingSchade = findViewById(R.id.editBeschrijving);
imageThumbnail = findViewById(R.id.imageThumbnail);
spinnerCat = findViewById(R.id.spinnerCategorie);
final Spinner spinnerVerdieping = findViewById(R.id.spinnerVerdieping);
spinnerLokaal = findViewById(R.id.spinnerLokaal);
//De juiste lokalen tonen bij desbetreffende verdiepingen
spinnerVerdieping.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiepMin1);
break;
case 1:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiepGelijkVloer);
break;
case 2:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep1);
break;
case 3:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep2);
break;
case 4:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep3);
break;
case 5:
fillSpinnerLokaalWithAdapter(R.array.lokaalVerdiep4);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//unused
}
});
//Button listerens
buttonFoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
} else {
dispatchTakePictureIntent();
}
}
});
buttonMeldenSchade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!validateForm()) {
return;
}
String name = getIntent().getStringExtra(getString(R.string.key_naam));
String lokaal = spinnerLokaal.getSelectedItem().toString();
Melding melding = new Melding(name,
spinnerVerdieping.getSelectedItem().toString(),
lokaal.substring(0,3),
vrijeInvoer.getText().toString(),
spinnerCat.getSelectedItem().toString(),
beschrijvingSchade.getText().toString(),
lokaal.substring(3));
mc = new MeldingController();
mc.nieuweMelding(melding, imageThumbnail, v.getContext());
showDialogInfoToActivity(NieuweMeldingActivity.this, HomeActivity.class,
getString(R.string.geslaagd),
getString(R.string.melding_succes));
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
//Show permission explanation dialog...
showDialogAlert(NieuweMeldingActivity.this, getString(R.string.camera_permissie), getString(R.string.cam_toestemming));
Log.d("perm", "show permission explanation dialog");
} else {
//Never ask again selected, or device policy prohibits the app from having that permission.
//So, disable that feature, or fall back to another situation...
showDialogAlert(NieuweMeldingActivity.this, getString(R.string.camera_permissie), getString(R.string.cam_toestemming_extra));
Log.d("perm", "Never ask again selected or...");
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageThumbnail.setImageBitmap(imageBitmap);
}
}
private void fillSpinnerLokaalWithAdapter(int verdiepingArrayAdapter) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, verdiepingArrayAdapter, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerLokaal.setAdapter(adapter);
}
private boolean validateForm() {
boolean valid = true;
if (imageThumbnail.getDrawable() == null) {
showDialogAlert(NieuweMeldingActivity.this, getString(R.string.fout), getString(R.string.foto_is_verplicht));
valid = false;
}
return valid;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
} |
5587_4 | /*
* This file is part of Waarp Project (named also Waarp or GG).
*
* Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
* tags. See the COPYRIGHT.txt in the distribution for a full listing of
* individual contributors.
*
* All Waarp Project 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.
*
* Waarp 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
* Waarp . If not, see <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.context.task;
import org.waarp.common.command.exception.CommandAbstractException;
import org.waarp.common.logging.WaarpLogger;
import org.waarp.common.logging.WaarpLoggerFactory;
import org.waarp.common.utility.WaarpStringUtils;
import org.waarp.openr66.context.ErrorCode;
import org.waarp.openr66.context.R66Session;
import org.waarp.openr66.context.filesystem.R66Dir;
import org.waarp.openr66.context.filesystem.R66File;
import org.waarp.openr66.database.data.DbTaskRunner;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException;
import org.waarp.openr66.protocol.utils.R66Future;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* Abstract implementation of task
*/
public abstract class AbstractTask implements Runnable {
/**
* Internal Logger
*/
private static final WaarpLogger logger =
WaarpLoggerFactory.getLogger(AbstractTask.class);
protected static final Pattern BLANK = Pattern.compile(" ");
/**
* Current full path of current FILENAME
*/
public static final String TRUEFULLPATH = "#TRUEFULLPATH#";
/**
* Current FILENAME (basename) (change in retrieval part)
*/
public static final String TRUEFILENAME = "#TRUEFILENAME#";
/**
* Current full path of Original FILENAME (as transmitted) (before changing
* in
* retrieval part)
*/
public static final String ORIGINALFULLPATH = "#ORIGINALFULLPATH#";
/**
* Original FILENAME (basename) (before changing in retrieval part)
*/
public static final String ORIGINALFILENAME = "#ORIGINALFILENAME#";
/**
* Size of the current FILE
*/
public static final String FILESIZE = "#FILESIZE#";
/**
* Current full path of current RULE
*/
public static final String RULE = "#RULE#";
/**
* Date in yyyyMMdd format
*/
public static final String DATE = "#DATE#";
/**
* Hour in HHmmss format
*/
public static final String HOUR = "#HOUR#";
/**
* Remote host id (if not the initiator of the call)
*/
public static final String REMOTEHOST = "#REMOTEHOST#";
/**
* Remote host address
*/
public static final String REMOTEHOSTADDR = "#REMOTEHOSTADDR#";
/**
* Local host id
*/
public static final String LOCALHOST = "#LOCALHOST#";
/**
* Local host address
*/
public static final String LOCALHOSTADDR = "#LOCALHOSTADDR#";
/**
* Transfer id
*/
public static final String TRANSFERID = "#TRANSFERID#";
/**
* Requester Host
*/
public static final String REQUESTERHOST = "#REQUESTERHOST#";
/**
* Requested Host
*/
public static final String REQUESTEDHOST = "#REQUESTEDHOST#";
/**
* Full Transfer id (TRANSFERID_REQUESTERHOST_REQUESTEDHOST)
*/
public static final String FULLTRANSFERID = "#FULLTRANSFERID#";
/**
* Current or final RANK of block
*/
public static final String RANKTRANSFER = "#RANKTRANSFER#";
/**
* Block size used
*/
public static final String BLOCKSIZE = "#BLOCKSIZE#";
/**
* IN Path used
*/
public static final String INPATH = "#INPATH#";
/**
* OUT Path used
*/
public static final String OUTPATH = "#OUTPATH#";
/**
* WORK Path used
*/
public static final String WORKPATH = "#WORKPATH#";
/**
* ARCH Path used
*/
public static final String ARCHPATH = "#ARCHPATH#";
/**
* HOME Path used
*/
public static final String HOMEPATH = "#HOMEPATH#";
/**
* Last Current Error Message
*/
public static final String ERRORMSG = "#ERRORMSG#";
/**
* Last Current Error Code
*/
public static final String ERRORCODE = "#ERRORCODE#";
/**
* Last Current Error Code in Full String
*/
public static final String ERRORSTRCODE = "#ERRORSTRCODE#";
/**
* If specified, no Wait for Task Validation (default is wait)
*/
public static final String NOWAIT = "#NOWAIT#";
/**
* If specified, use the LocalExec Daemon specified in the global
* configuration (default no usage of
* LocalExec)
*/
public static final String LOCALEXEC = "#LOCALEXEC#";
/**
* Type of operation
*/
final TaskType type;
/**
* Argument from Rule
*/
final String argRule;
/**
* Delay from Rule (if applicable)
*/
final int delay;
/**
* Argument from Transfer
*/
final String argTransfer;
/**
* Current session
*/
final R66Session session;
/**
* R66Future of completion
*/
final R66Future futureCompletion;
/**
* Do we wait for a validation of the task ? Default = True
*/
boolean waitForValidation = true;
/**
* Do we need to use LocalExec for an Exec Task ? Default = False
*/
boolean useLocalExec;
/**
* Constructor
*
* @param type
* @param delay
* @param argRule
* @param argTransfer
* @param session
*/
AbstractTask(TaskType type, int delay, String argRule, String argTransfer,
R66Session session) {
this.type = type;
this.delay = delay;
this.argRule = argRule;
this.argTransfer = argTransfer;
this.session = session;
futureCompletion = new R66Future(true);
}
/**
* @return the TaskType of this AbstractTask
*/
public TaskType getType() {
return type;
}
/**
* This is the only interface to execute an operator.
*/
@Override
public abstract void run();
/**
* @return True if the operation is in success status
*/
public boolean isSuccess() {
futureCompletion.awaitOrInterruptible();
return futureCompletion.isSuccess();
}
/**
* @return the R66Future of completion
*/
public R66Future getFutureCompletion() {
return futureCompletion;
}
/**
* @param arg as the Format string where FIXED items will be
* replaced by
* context values and next using
* argFormat as format second argument; this arg comes from the
* rule
* itself
* @param argFormat as format second argument; this argFormat comes
* from
* the transfer Information itself
*
* @return The string with replaced values from context and second argument
*/
protected String getReplacedValue(String arg, Object[] argFormat) {
final StringBuilder builder = new StringBuilder(arg);
// check NOWAIT and LOCALEXEC
if (arg.contains(NOWAIT)) {
waitForValidation = false;
WaarpStringUtils.replaceAll(builder, NOWAIT, "");
}
if (arg.contains(LOCALEXEC)) {
useLocalExec = true;
WaarpStringUtils.replaceAll(builder, LOCALEXEC, "");
}
File trueFile = null;
if (session.getFile() != null) {
trueFile = session.getFile().getTrueFile();
}
if (trueFile != null) {
WaarpStringUtils
.replaceAll(builder, TRUEFULLPATH, trueFile.getAbsolutePath());
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, R66Dir
.getFinalUniqueFilename(session.getFile()));
WaarpStringUtils
.replaceAll(builder, FILESIZE, Long.toString(trueFile.length()));
} else {
WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, "nofile");
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, "nofile");
WaarpStringUtils.replaceAll(builder, FILESIZE, "0");
}
final DbTaskRunner runner = session.getRunner();
if (runner != null) {
WaarpStringUtils
.replaceAll(builder, ORIGINALFULLPATH, runner.getOriginalFilename());
WaarpStringUtils.replaceAll(builder, ORIGINALFILENAME, R66File
.getBasename(runner.getOriginalFilename()));
WaarpStringUtils.replaceAll(builder, RULE, runner.getRuleId());
}
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final Date date = new Date();
WaarpStringUtils.replaceAll(builder, DATE, dateFormat.format(date));
dateFormat = new SimpleDateFormat("HHmmss");
WaarpStringUtils.replaceAll(builder, HOUR, dateFormat.format(date));
if (session.getAuth() != null) {
WaarpStringUtils
.replaceAll(builder, REMOTEHOST, session.getAuth().getUser());
try {
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration
.getHostId(session.getAuth().isSsl()));
} catch (final OpenR66ProtocolNoSslException e) {
// replace by standard name
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration.getHostId());
}
}
if (session.getRemoteAddress() != null) {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR,
session.getRemoteAddress().toString());
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR,
session.getLocalAddress().toString());
} else {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, "unknown");
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, "unknown");
}
if (runner != null) {
WaarpStringUtils.replaceAll(builder, TRANSFERID,
Long.toString(runner.getSpecialId()));
final String requester = runner.getRequester();
WaarpStringUtils.replaceAll(builder, REQUESTERHOST, requester);
final String requested = runner.getRequested();
WaarpStringUtils.replaceAll(builder, REQUESTEDHOST, requested);
WaarpStringUtils.replaceAll(builder, FULLTRANSFERID,
runner.getSpecialId() + "_" + requester +
'_' + requested);
WaarpStringUtils.replaceAll(builder, RANKTRANSFER,
Integer.toString(runner.getRank()));
}
WaarpStringUtils.replaceAll(builder, BLOCKSIZE,
Integer.toString(session.getBlockSize()));
R66Dir dir = new R66Dir(session);
if (runner != null) {
if (runner.isRecvThrough() || runner.isSendThrough()) {
try {
dir.changeDirectoryNotChecked(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
} else {
try {
dir.changeDirectory(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
} else {
try {
dir.changeDirectory(Configuration.configuration.getInPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getOutPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getWorkingPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
WaarpStringUtils.replaceAll(builder, HOMEPATH,
Configuration.configuration.getBaseDirectory());
if (session.getLocalChannelReference() == null) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
} else {
try {
WaarpStringUtils.replaceAll(builder, ERRORMSG,
session.getLocalChannelReference()
.getErrorMessage());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORCODE,
session.getLocalChannelReference()
.getCurrentCode().getCode());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORSTRCODE,
session.getLocalChannelReference()
.getCurrentCode().name());
} catch (final NullPointerException e) {
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
}
}
// finalname
if (argFormat != null && argFormat.length > 0) {
try {
return String.format(builder.toString(), argFormat);
} catch (final Exception e) {
// ignored error since bad argument in static rule info
logger.error("Bad format in Rule: {" + builder + "} " + e.getMessage());
}
}
return builder.toString();
}
}
| waarp/Waarp-All | WaarpR66/src/main/java/org/waarp/openr66/context/task/AbstractTask.java | 4,743 | /**
* Current FILENAME (basename) (change in retrieval part)
*/ | block_comment | nl | /*
* This file is part of Waarp Project (named also Waarp or GG).
*
* Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
* tags. See the COPYRIGHT.txt in the distribution for a full listing of
* individual contributors.
*
* All Waarp Project 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.
*
* Waarp 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
* Waarp . If not, see <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.context.task;
import org.waarp.common.command.exception.CommandAbstractException;
import org.waarp.common.logging.WaarpLogger;
import org.waarp.common.logging.WaarpLoggerFactory;
import org.waarp.common.utility.WaarpStringUtils;
import org.waarp.openr66.context.ErrorCode;
import org.waarp.openr66.context.R66Session;
import org.waarp.openr66.context.filesystem.R66Dir;
import org.waarp.openr66.context.filesystem.R66File;
import org.waarp.openr66.database.data.DbTaskRunner;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException;
import org.waarp.openr66.protocol.utils.R66Future;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* Abstract implementation of task
*/
public abstract class AbstractTask implements Runnable {
/**
* Internal Logger
*/
private static final WaarpLogger logger =
WaarpLoggerFactory.getLogger(AbstractTask.class);
protected static final Pattern BLANK = Pattern.compile(" ");
/**
* Current full path of current FILENAME
*/
public static final String TRUEFULLPATH = "#TRUEFULLPATH#";
/**
* Current FILENAME (basename)<SUF>*/
public static final String TRUEFILENAME = "#TRUEFILENAME#";
/**
* Current full path of Original FILENAME (as transmitted) (before changing
* in
* retrieval part)
*/
public static final String ORIGINALFULLPATH = "#ORIGINALFULLPATH#";
/**
* Original FILENAME (basename) (before changing in retrieval part)
*/
public static final String ORIGINALFILENAME = "#ORIGINALFILENAME#";
/**
* Size of the current FILE
*/
public static final String FILESIZE = "#FILESIZE#";
/**
* Current full path of current RULE
*/
public static final String RULE = "#RULE#";
/**
* Date in yyyyMMdd format
*/
public static final String DATE = "#DATE#";
/**
* Hour in HHmmss format
*/
public static final String HOUR = "#HOUR#";
/**
* Remote host id (if not the initiator of the call)
*/
public static final String REMOTEHOST = "#REMOTEHOST#";
/**
* Remote host address
*/
public static final String REMOTEHOSTADDR = "#REMOTEHOSTADDR#";
/**
* Local host id
*/
public static final String LOCALHOST = "#LOCALHOST#";
/**
* Local host address
*/
public static final String LOCALHOSTADDR = "#LOCALHOSTADDR#";
/**
* Transfer id
*/
public static final String TRANSFERID = "#TRANSFERID#";
/**
* Requester Host
*/
public static final String REQUESTERHOST = "#REQUESTERHOST#";
/**
* Requested Host
*/
public static final String REQUESTEDHOST = "#REQUESTEDHOST#";
/**
* Full Transfer id (TRANSFERID_REQUESTERHOST_REQUESTEDHOST)
*/
public static final String FULLTRANSFERID = "#FULLTRANSFERID#";
/**
* Current or final RANK of block
*/
public static final String RANKTRANSFER = "#RANKTRANSFER#";
/**
* Block size used
*/
public static final String BLOCKSIZE = "#BLOCKSIZE#";
/**
* IN Path used
*/
public static final String INPATH = "#INPATH#";
/**
* OUT Path used
*/
public static final String OUTPATH = "#OUTPATH#";
/**
* WORK Path used
*/
public static final String WORKPATH = "#WORKPATH#";
/**
* ARCH Path used
*/
public static final String ARCHPATH = "#ARCHPATH#";
/**
* HOME Path used
*/
public static final String HOMEPATH = "#HOMEPATH#";
/**
* Last Current Error Message
*/
public static final String ERRORMSG = "#ERRORMSG#";
/**
* Last Current Error Code
*/
public static final String ERRORCODE = "#ERRORCODE#";
/**
* Last Current Error Code in Full String
*/
public static final String ERRORSTRCODE = "#ERRORSTRCODE#";
/**
* If specified, no Wait for Task Validation (default is wait)
*/
public static final String NOWAIT = "#NOWAIT#";
/**
* If specified, use the LocalExec Daemon specified in the global
* configuration (default no usage of
* LocalExec)
*/
public static final String LOCALEXEC = "#LOCALEXEC#";
/**
* Type of operation
*/
final TaskType type;
/**
* Argument from Rule
*/
final String argRule;
/**
* Delay from Rule (if applicable)
*/
final int delay;
/**
* Argument from Transfer
*/
final String argTransfer;
/**
* Current session
*/
final R66Session session;
/**
* R66Future of completion
*/
final R66Future futureCompletion;
/**
* Do we wait for a validation of the task ? Default = True
*/
boolean waitForValidation = true;
/**
* Do we need to use LocalExec for an Exec Task ? Default = False
*/
boolean useLocalExec;
/**
* Constructor
*
* @param type
* @param delay
* @param argRule
* @param argTransfer
* @param session
*/
AbstractTask(TaskType type, int delay, String argRule, String argTransfer,
R66Session session) {
this.type = type;
this.delay = delay;
this.argRule = argRule;
this.argTransfer = argTransfer;
this.session = session;
futureCompletion = new R66Future(true);
}
/**
* @return the TaskType of this AbstractTask
*/
public TaskType getType() {
return type;
}
/**
* This is the only interface to execute an operator.
*/
@Override
public abstract void run();
/**
* @return True if the operation is in success status
*/
public boolean isSuccess() {
futureCompletion.awaitOrInterruptible();
return futureCompletion.isSuccess();
}
/**
* @return the R66Future of completion
*/
public R66Future getFutureCompletion() {
return futureCompletion;
}
/**
* @param arg as the Format string where FIXED items will be
* replaced by
* context values and next using
* argFormat as format second argument; this arg comes from the
* rule
* itself
* @param argFormat as format second argument; this argFormat comes
* from
* the transfer Information itself
*
* @return The string with replaced values from context and second argument
*/
protected String getReplacedValue(String arg, Object[] argFormat) {
final StringBuilder builder = new StringBuilder(arg);
// check NOWAIT and LOCALEXEC
if (arg.contains(NOWAIT)) {
waitForValidation = false;
WaarpStringUtils.replaceAll(builder, NOWAIT, "");
}
if (arg.contains(LOCALEXEC)) {
useLocalExec = true;
WaarpStringUtils.replaceAll(builder, LOCALEXEC, "");
}
File trueFile = null;
if (session.getFile() != null) {
trueFile = session.getFile().getTrueFile();
}
if (trueFile != null) {
WaarpStringUtils
.replaceAll(builder, TRUEFULLPATH, trueFile.getAbsolutePath());
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, R66Dir
.getFinalUniqueFilename(session.getFile()));
WaarpStringUtils
.replaceAll(builder, FILESIZE, Long.toString(trueFile.length()));
} else {
WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, "nofile");
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, "nofile");
WaarpStringUtils.replaceAll(builder, FILESIZE, "0");
}
final DbTaskRunner runner = session.getRunner();
if (runner != null) {
WaarpStringUtils
.replaceAll(builder, ORIGINALFULLPATH, runner.getOriginalFilename());
WaarpStringUtils.replaceAll(builder, ORIGINALFILENAME, R66File
.getBasename(runner.getOriginalFilename()));
WaarpStringUtils.replaceAll(builder, RULE, runner.getRuleId());
}
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final Date date = new Date();
WaarpStringUtils.replaceAll(builder, DATE, dateFormat.format(date));
dateFormat = new SimpleDateFormat("HHmmss");
WaarpStringUtils.replaceAll(builder, HOUR, dateFormat.format(date));
if (session.getAuth() != null) {
WaarpStringUtils
.replaceAll(builder, REMOTEHOST, session.getAuth().getUser());
try {
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration
.getHostId(session.getAuth().isSsl()));
} catch (final OpenR66ProtocolNoSslException e) {
// replace by standard name
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration.getHostId());
}
}
if (session.getRemoteAddress() != null) {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR,
session.getRemoteAddress().toString());
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR,
session.getLocalAddress().toString());
} else {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, "unknown");
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, "unknown");
}
if (runner != null) {
WaarpStringUtils.replaceAll(builder, TRANSFERID,
Long.toString(runner.getSpecialId()));
final String requester = runner.getRequester();
WaarpStringUtils.replaceAll(builder, REQUESTERHOST, requester);
final String requested = runner.getRequested();
WaarpStringUtils.replaceAll(builder, REQUESTEDHOST, requested);
WaarpStringUtils.replaceAll(builder, FULLTRANSFERID,
runner.getSpecialId() + "_" + requester +
'_' + requested);
WaarpStringUtils.replaceAll(builder, RANKTRANSFER,
Integer.toString(runner.getRank()));
}
WaarpStringUtils.replaceAll(builder, BLOCKSIZE,
Integer.toString(session.getBlockSize()));
R66Dir dir = new R66Dir(session);
if (runner != null) {
if (runner.isRecvThrough() || runner.isSendThrough()) {
try {
dir.changeDirectoryNotChecked(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
} else {
try {
dir.changeDirectory(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
} else {
try {
dir.changeDirectory(Configuration.configuration.getInPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getOutPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getWorkingPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
WaarpStringUtils.replaceAll(builder, HOMEPATH,
Configuration.configuration.getBaseDirectory());
if (session.getLocalChannelReference() == null) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
} else {
try {
WaarpStringUtils.replaceAll(builder, ERRORMSG,
session.getLocalChannelReference()
.getErrorMessage());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORCODE,
session.getLocalChannelReference()
.getCurrentCode().getCode());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORSTRCODE,
session.getLocalChannelReference()
.getCurrentCode().name());
} catch (final NullPointerException e) {
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
}
}
// finalname
if (argFormat != null && argFormat.length > 0) {
try {
return String.format(builder.toString(), argFormat);
} catch (final Exception e) {
// ignored error since bad argument in static rule info
logger.error("Bad format in Rule: {" + builder + "} " + e.getMessage());
}
}
return builder.toString();
}
}
|
75872_55 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wad.db;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wad.xml.*;
/**
*
* @author Ralph Berendsen
*/
public class WriteGewensteProcessen {
private static Log log = LogFactory.getLog(WriteGewensteProcessen.class);
public static void writeDataSeries(Connection dbConnection,String selectorPk, String seriesPk){
Statement stmt_Write;
//Read data from selector
// ResultSet rs_selector;
// Statement stmt_selector;
// String analyseModuleFk = "";
// String patientFk = "";
// String seriesFk = "";
String seriesFk = seriesPk;
// String instanceFk = "";
// try {
// stmt_selector = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// rs_selector = stmt_selector.executeQuery("SELECT * FROM selector WHERE pk='"+selectorPk+"'");
// while (rs_selector.next()) {
// analyseModuleFk = rs_selector.getString("analysemodule_fk");
// }
// stmt_selector.close();
// rs_selector.close();
// } catch (SQLException ex) {
// Logger.getLogger(ReadFromPacsDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
//Controleren of de data al bestaat
ResultSet rs_gewenste;
Statement stmt_gewenste;
String sqlSelect = "SELECT * FROM gewenste_processen WHERE ";
sqlSelect = sqlSelect + "selector_fk='"+selectorPk+"' AND ";
sqlSelect = sqlSelect + "series_fk='"+seriesFk+"' AND ";
sqlSelect = sqlSelect + "status='0'";
Boolean rowExists = false;
try {
stmt_gewenste = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs_gewenste = stmt_gewenste.executeQuery(sqlSelect);
if (rs_gewenste.next()){
rowExists = true;
}
stmt_gewenste.close();
rs_gewenste.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
if (!rowExists){
//Write analyse_file
ArrayList<String> analyseFilePk = writeAnalyseFile(dbConnection, seriesFk, selectorPk);
//Write data to gewenste_processen
String sqlTable = "INSERT INTO gewenste_processen(";
String sqlColomn = "selector_fk,series_fk,analysemodule_input_fk,analysemodule_output_fk,status";
String sqlMiddle = ") values (";
String sqlValues = "'"+selectorPk+"','"+seriesFk+"','"+analyseFilePk.get(0)+"','"+analyseFilePk.get(1)+"','0'";
String sqlEnd = ")";
String sqlStatement = "";
try {
sqlStatement = sqlTable+sqlColomn+sqlMiddle+sqlValues+sqlEnd;
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int count = stmt_Write.executeUpdate(sqlStatement);
stmt_Write.close();
//WriteToIqcDatabase.UpdateSeriesStatus(dbConnection, seriesFk, "3");
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
}
}
public static void writeDataStudy(Connection dbConnection,String selectorPk, String studyPk){
Statement stmt_Write;
//Read data from selector
// ResultSet rs_selector;
// Statement stmt_selector;
// String analyseModuleFk = "";
// String patientFk = "";
String studyFk = studyPk;
// String serieFk = "";
// String instanceFk = "";
// try {
// stmt_selector = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// rs_selector = stmt_selector.executeQuery("SELECT * FROM selector WHERE pk='"+selectorPk+"'");
// while (rs_selector.next()) {
// analyseModuleFk = rs_selector.getString("analysemodule_fk");
// }
// stmt_selector.close();
// rs_selector.close();
// } catch (SQLException ex) {
// Logger.getLogger(ReadFromPacsDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
//Controleren of de data al bestaat
ResultSet rs_gewenste;
Statement stmt_gewenste;
String sqlSelect = "SELECT * FROM gewenste_processen WHERE ";
sqlSelect = sqlSelect + "selector_fk='"+selectorPk+"' AND ";
sqlSelect = sqlSelect + "study_fk='"+studyFk+"' AND ";
sqlSelect = sqlSelect + "status='0'";
Boolean rowExists = false;
try {
stmt_gewenste = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs_gewenste = stmt_gewenste.executeQuery(sqlSelect);
if (rs_gewenste.next()){
rowExists = true;
}
stmt_gewenste.close();
rs_gewenste.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
if (!rowExists){
//Write analyse_file
ArrayList<String> analyseFilePk = writeAnalyseFile(dbConnection, studyFk, selectorPk);
//Write data to gewenste_processen
String sqlTable = "INSERT INTO gewenste_processen(";
String sqlColomn = "selector_fk,study_fk,analysemodule_input_fk,analysemodule_output_fk,status";
String sqlMiddle = ") values (";
String sqlValues = "'"+selectorPk+"','"+studyFk+"','"+analyseFilePk.get(0)+"','"+analyseFilePk.get(1)+"','0'";
String sqlEnd = ")";
String sqlStatement = "";
try {
sqlStatement = sqlTable+sqlColomn+sqlMiddle+sqlValues+sqlEnd;
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int count = stmt_Write.executeUpdate(sqlStatement);
stmt_Write.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
}
}
public static void writeDataInstance(Connection dbConnection,String selectorPk, String instancePk){
Statement stmt_Write;
//Read data from selector
// ResultSet rs_selector;
// Statement stmt_selector;
// String analyseModuleFk = "";
// String patientFk = "";
// String seriesFk = "";
// String serieFk = "";
String instanceFk = instancePk;
// try {
// stmt_selector = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// rs_selector = stmt_selector.executeQuery("SELECT * FROM selector WHERE pk='"+selectorPk+"'");
// while (rs_selector.next()) {
// analyseModuleFk = rs_selector.getString("analysemodule_fk");
// }
// stmt_selector.close();
// rs_selector.close();
// } catch (SQLException ex) {
// Logger.getLogger(ReadFromPacsDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
//Controleren of de data al bestaat
ResultSet rs_gewenste;
Statement stmt_gewenste;
String sqlSelect = "SELECT * FROM gewenste_processen WHERE ";
sqlSelect = sqlSelect + "selector_fk='"+selectorPk+"' AND ";
sqlSelect = sqlSelect + "instance_fk='"+instanceFk+"' AND ";
sqlSelect = sqlSelect + "status='0'";
Boolean rowExists = false;
try {
stmt_gewenste = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs_gewenste = stmt_gewenste.executeQuery(sqlSelect);
if (rs_gewenste.next()){
rowExists = true;
}
stmt_gewenste.close();
rs_gewenste.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
if (!rowExists){
//Write analyse_file
ArrayList<String> analyseFilePk = writeAnalyseFile(dbConnection, instanceFk, selectorPk);
//Write data to gewenste_processen
String sqlTable = "INSERT INTO gewenste_processen(";
String sqlColomn = "selector_fk,instance_fk,analysemodule_input_fk,analysemodule_output_fk,status";
String sqlMiddle = ") values (";
String sqlValues = "'"+selectorPk+"','"+instanceFk+"','"+analyseFilePk.get(0)+"','"+analyseFilePk.get(1)+"','0'";
String sqlEnd = ")";
String sqlStatement = "";
try {
sqlStatement = sqlTable+sqlColomn+sqlMiddle+sqlValues+sqlEnd;
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int count = stmt_Write.executeUpdate(sqlStatement);
stmt_Write.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
}
}
//Write analysefile.xml information to analysefile table and return the pk
private static ArrayList<String> writeAnalyseFile(Connection dbConnection, String levelPk, String selectorFk){
Statement stmt_Write;
ArrayList<String> fks = new ArrayList<String>();
//Karakters zoals "-",":" en " " zijn niet wenselijk in een bestandsnaam, vandaar een eenvoudig formaat
//DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = new Date();
String anaModInputFilepath = "XML/analysemodule_input/";
String absAnaModInputFilepath = ReadConfigXML.readFileElement("analysemodule_input")+anaModInputFilepath;
AnalyseModuleInputValues anaModInputVal = writeFiles(dbConnection, levelPk, selectorFk, dateFormat.format(date));
String selectorName = anaModInputVal.getSelectorName();
String sqlTableInput = "INSERT INTO analysemodule_input(";
String sqlTableOutput = "INSERT INTO analysemodule_output(";
String sqlColomn = "filename, filepath";
String sqlMiddle = ") values (";
String sqlValuesInput = "'"+dateFormat.format(date)+".xml','"+anaModInputFilepath+selectorName+"/'";
String sqlValuesOutput = "'"+anaModInputVal.getAnalyseModuleOutputFilename()+"','"+anaModInputVal.getAnalyseModuleOutputFilepath()+"'";
String sqlEnd = ")";
String sqlStatementInput = sqlTableInput+sqlColomn+sqlMiddle+sqlValuesInput+sqlEnd;
String sqlStatementOutput = sqlTableOutput+sqlColomn+sqlMiddle+sqlValuesOutput+sqlEnd;
try {
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
int count = stmt_Write.executeUpdate(sqlStatementInput, Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1;
ResultSet rs = stmt_Write.getGeneratedKeys();
if (rs.next()){
autoIncKeyFromApi = rs.getInt(1);
}
rs.close();
stmt_Write.close();
fks.add(Integer.toString(autoIncKeyFromApi));
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
count = stmt_Write.executeUpdate(sqlStatementOutput, Statement.RETURN_GENERATED_KEYS);
autoIncKeyFromApi = -1;
rs = stmt_Write.getGeneratedKeys();
if (rs.next()){
autoIncKeyFromApi = rs.getInt(1);
}
rs.close();
stmt_Write.close();
fks.add(Integer.toString(autoIncKeyFromApi));
// \XML\analysemodule_output\selectorname\datetime\result.xml
return fks;
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
fks.add("-1");
fks.add("-1");
return fks;
}
private static AnalyseModuleInputValues writeFiles(Connection dbConnection, String levelPk, String selectorFk, String createDateTime){
AnalyseModuleInputValues analyseModuleInputValues = new AnalyseModuleInputValues(dbConnection, selectorFk, createDateTime);
AnalyseModuleOutputFile anaModOutFile = new AnalyseModuleOutputFile(dbConnection, selectorFk, createDateTime);
analyseModuleInputValues.setModuleOutput(anaModOutFile.getAbsoluteFilename());
analyseModuleInputValues.setAnalyseModuleOutputFilename(anaModOutFile.getFilename());
analyseModuleInputValues.setAnalyseModuleOutputFilepath(anaModOutFile.getFilepath());
// aanpassen bij absoluut filepath voor XML in config.xml
// String currentDir = System.getProperty("user.dir");
// File dir = new File(currentDir);
// String mainDir = dir.getParent();
// String anaModInputFilepath = ReadConfigXML.readFileElement("analysemodule_input");
String absAnaModInputFilepath = ReadConfigXML.readFileElement("XML")+"XML/analysemodule_input/";
//String anaModAbsFilename = anaModInputFilepath.replace("..", mainDir);
//String anaModAbsFilename = absAnaModInputFilepath.replace("/","\\");
GetPatientFromIqcDatabase patient = new GetPatientFromIqcDatabase( dbConnection, levelPk, analyseModuleInputValues.getAnalyseLevel());
AnalyseModuleInputFile anaModInputFile = new AnalyseModuleInputFile(patient.getPatient(), analyseModuleInputValues);
String selectorName = anaModOutFile.getSelectorName();
anaModInputFile.write(absAnaModInputFilepath+selectorName+File.separator+createDateTime+".xml");
return analyseModuleInputValues;
}
}
| wadqc/WAD_Services | WAD_Selector/src/wad/db/WriteGewensteProcessen.java | 4,545 | //Karakters zoals "-",":" en " " zijn niet wenselijk in een bestandsnaam, vandaar een eenvoudig formaat | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wad.db;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wad.xml.*;
/**
*
* @author Ralph Berendsen
*/
public class WriteGewensteProcessen {
private static Log log = LogFactory.getLog(WriteGewensteProcessen.class);
public static void writeDataSeries(Connection dbConnection,String selectorPk, String seriesPk){
Statement stmt_Write;
//Read data from selector
// ResultSet rs_selector;
// Statement stmt_selector;
// String analyseModuleFk = "";
// String patientFk = "";
// String seriesFk = "";
String seriesFk = seriesPk;
// String instanceFk = "";
// try {
// stmt_selector = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// rs_selector = stmt_selector.executeQuery("SELECT * FROM selector WHERE pk='"+selectorPk+"'");
// while (rs_selector.next()) {
// analyseModuleFk = rs_selector.getString("analysemodule_fk");
// }
// stmt_selector.close();
// rs_selector.close();
// } catch (SQLException ex) {
// Logger.getLogger(ReadFromPacsDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
//Controleren of de data al bestaat
ResultSet rs_gewenste;
Statement stmt_gewenste;
String sqlSelect = "SELECT * FROM gewenste_processen WHERE ";
sqlSelect = sqlSelect + "selector_fk='"+selectorPk+"' AND ";
sqlSelect = sqlSelect + "series_fk='"+seriesFk+"' AND ";
sqlSelect = sqlSelect + "status='0'";
Boolean rowExists = false;
try {
stmt_gewenste = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs_gewenste = stmt_gewenste.executeQuery(sqlSelect);
if (rs_gewenste.next()){
rowExists = true;
}
stmt_gewenste.close();
rs_gewenste.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
if (!rowExists){
//Write analyse_file
ArrayList<String> analyseFilePk = writeAnalyseFile(dbConnection, seriesFk, selectorPk);
//Write data to gewenste_processen
String sqlTable = "INSERT INTO gewenste_processen(";
String sqlColomn = "selector_fk,series_fk,analysemodule_input_fk,analysemodule_output_fk,status";
String sqlMiddle = ") values (";
String sqlValues = "'"+selectorPk+"','"+seriesFk+"','"+analyseFilePk.get(0)+"','"+analyseFilePk.get(1)+"','0'";
String sqlEnd = ")";
String sqlStatement = "";
try {
sqlStatement = sqlTable+sqlColomn+sqlMiddle+sqlValues+sqlEnd;
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int count = stmt_Write.executeUpdate(sqlStatement);
stmt_Write.close();
//WriteToIqcDatabase.UpdateSeriesStatus(dbConnection, seriesFk, "3");
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
}
}
public static void writeDataStudy(Connection dbConnection,String selectorPk, String studyPk){
Statement stmt_Write;
//Read data from selector
// ResultSet rs_selector;
// Statement stmt_selector;
// String analyseModuleFk = "";
// String patientFk = "";
String studyFk = studyPk;
// String serieFk = "";
// String instanceFk = "";
// try {
// stmt_selector = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// rs_selector = stmt_selector.executeQuery("SELECT * FROM selector WHERE pk='"+selectorPk+"'");
// while (rs_selector.next()) {
// analyseModuleFk = rs_selector.getString("analysemodule_fk");
// }
// stmt_selector.close();
// rs_selector.close();
// } catch (SQLException ex) {
// Logger.getLogger(ReadFromPacsDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
//Controleren of de data al bestaat
ResultSet rs_gewenste;
Statement stmt_gewenste;
String sqlSelect = "SELECT * FROM gewenste_processen WHERE ";
sqlSelect = sqlSelect + "selector_fk='"+selectorPk+"' AND ";
sqlSelect = sqlSelect + "study_fk='"+studyFk+"' AND ";
sqlSelect = sqlSelect + "status='0'";
Boolean rowExists = false;
try {
stmt_gewenste = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs_gewenste = stmt_gewenste.executeQuery(sqlSelect);
if (rs_gewenste.next()){
rowExists = true;
}
stmt_gewenste.close();
rs_gewenste.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
if (!rowExists){
//Write analyse_file
ArrayList<String> analyseFilePk = writeAnalyseFile(dbConnection, studyFk, selectorPk);
//Write data to gewenste_processen
String sqlTable = "INSERT INTO gewenste_processen(";
String sqlColomn = "selector_fk,study_fk,analysemodule_input_fk,analysemodule_output_fk,status";
String sqlMiddle = ") values (";
String sqlValues = "'"+selectorPk+"','"+studyFk+"','"+analyseFilePk.get(0)+"','"+analyseFilePk.get(1)+"','0'";
String sqlEnd = ")";
String sqlStatement = "";
try {
sqlStatement = sqlTable+sqlColomn+sqlMiddle+sqlValues+sqlEnd;
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int count = stmt_Write.executeUpdate(sqlStatement);
stmt_Write.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
}
}
public static void writeDataInstance(Connection dbConnection,String selectorPk, String instancePk){
Statement stmt_Write;
//Read data from selector
// ResultSet rs_selector;
// Statement stmt_selector;
// String analyseModuleFk = "";
// String patientFk = "";
// String seriesFk = "";
// String serieFk = "";
String instanceFk = instancePk;
// try {
// stmt_selector = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// rs_selector = stmt_selector.executeQuery("SELECT * FROM selector WHERE pk='"+selectorPk+"'");
// while (rs_selector.next()) {
// analyseModuleFk = rs_selector.getString("analysemodule_fk");
// }
// stmt_selector.close();
// rs_selector.close();
// } catch (SQLException ex) {
// Logger.getLogger(ReadFromPacsDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
//Controleren of de data al bestaat
ResultSet rs_gewenste;
Statement stmt_gewenste;
String sqlSelect = "SELECT * FROM gewenste_processen WHERE ";
sqlSelect = sqlSelect + "selector_fk='"+selectorPk+"' AND ";
sqlSelect = sqlSelect + "instance_fk='"+instanceFk+"' AND ";
sqlSelect = sqlSelect + "status='0'";
Boolean rowExists = false;
try {
stmt_gewenste = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs_gewenste = stmt_gewenste.executeQuery(sqlSelect);
if (rs_gewenste.next()){
rowExists = true;
}
stmt_gewenste.close();
rs_gewenste.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
if (!rowExists){
//Write analyse_file
ArrayList<String> analyseFilePk = writeAnalyseFile(dbConnection, instanceFk, selectorPk);
//Write data to gewenste_processen
String sqlTable = "INSERT INTO gewenste_processen(";
String sqlColomn = "selector_fk,instance_fk,analysemodule_input_fk,analysemodule_output_fk,status";
String sqlMiddle = ") values (";
String sqlValues = "'"+selectorPk+"','"+instanceFk+"','"+analyseFilePk.get(0)+"','"+analyseFilePk.get(1)+"','0'";
String sqlEnd = ")";
String sqlStatement = "";
try {
sqlStatement = sqlTable+sqlColomn+sqlMiddle+sqlValues+sqlEnd;
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int count = stmt_Write.executeUpdate(sqlStatement);
stmt_Write.close();
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
}
}
//Write analysefile.xml information to analysefile table and return the pk
private static ArrayList<String> writeAnalyseFile(Connection dbConnection, String levelPk, String selectorFk){
Statement stmt_Write;
ArrayList<String> fks = new ArrayList<String>();
//Karakters zoals<SUF>
//DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = new Date();
String anaModInputFilepath = "XML/analysemodule_input/";
String absAnaModInputFilepath = ReadConfigXML.readFileElement("analysemodule_input")+anaModInputFilepath;
AnalyseModuleInputValues anaModInputVal = writeFiles(dbConnection, levelPk, selectorFk, dateFormat.format(date));
String selectorName = anaModInputVal.getSelectorName();
String sqlTableInput = "INSERT INTO analysemodule_input(";
String sqlTableOutput = "INSERT INTO analysemodule_output(";
String sqlColomn = "filename, filepath";
String sqlMiddle = ") values (";
String sqlValuesInput = "'"+dateFormat.format(date)+".xml','"+anaModInputFilepath+selectorName+"/'";
String sqlValuesOutput = "'"+anaModInputVal.getAnalyseModuleOutputFilename()+"','"+anaModInputVal.getAnalyseModuleOutputFilepath()+"'";
String sqlEnd = ")";
String sqlStatementInput = sqlTableInput+sqlColomn+sqlMiddle+sqlValuesInput+sqlEnd;
String sqlStatementOutput = sqlTableOutput+sqlColomn+sqlMiddle+sqlValuesOutput+sqlEnd;
try {
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
int count = stmt_Write.executeUpdate(sqlStatementInput, Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1;
ResultSet rs = stmt_Write.getGeneratedKeys();
if (rs.next()){
autoIncKeyFromApi = rs.getInt(1);
}
rs.close();
stmt_Write.close();
fks.add(Integer.toString(autoIncKeyFromApi));
stmt_Write = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
count = stmt_Write.executeUpdate(sqlStatementOutput, Statement.RETURN_GENERATED_KEYS);
autoIncKeyFromApi = -1;
rs = stmt_Write.getGeneratedKeys();
if (rs.next()){
autoIncKeyFromApi = rs.getInt(1);
}
rs.close();
stmt_Write.close();
fks.add(Integer.toString(autoIncKeyFromApi));
// \XML\analysemodule_output\selectorname\datetime\result.xml
return fks;
} catch (SQLException ex) {
//LoggerWrapper.myLogger.log(Level.SEVERE, "{0} {1}", new Object[]{WriteGewensteProcessen.class.getName(), ex});
log.error(ex);
}
fks.add("-1");
fks.add("-1");
return fks;
}
private static AnalyseModuleInputValues writeFiles(Connection dbConnection, String levelPk, String selectorFk, String createDateTime){
AnalyseModuleInputValues analyseModuleInputValues = new AnalyseModuleInputValues(dbConnection, selectorFk, createDateTime);
AnalyseModuleOutputFile anaModOutFile = new AnalyseModuleOutputFile(dbConnection, selectorFk, createDateTime);
analyseModuleInputValues.setModuleOutput(anaModOutFile.getAbsoluteFilename());
analyseModuleInputValues.setAnalyseModuleOutputFilename(anaModOutFile.getFilename());
analyseModuleInputValues.setAnalyseModuleOutputFilepath(anaModOutFile.getFilepath());
// aanpassen bij absoluut filepath voor XML in config.xml
// String currentDir = System.getProperty("user.dir");
// File dir = new File(currentDir);
// String mainDir = dir.getParent();
// String anaModInputFilepath = ReadConfigXML.readFileElement("analysemodule_input");
String absAnaModInputFilepath = ReadConfigXML.readFileElement("XML")+"XML/analysemodule_input/";
//String anaModAbsFilename = anaModInputFilepath.replace("..", mainDir);
//String anaModAbsFilename = absAnaModInputFilepath.replace("/","\\");
GetPatientFromIqcDatabase patient = new GetPatientFromIqcDatabase( dbConnection, levelPk, analyseModuleInputValues.getAnalyseLevel());
AnalyseModuleInputFile anaModInputFile = new AnalyseModuleInputFile(patient.getPatient(), analyseModuleInputValues);
String selectorName = anaModOutFile.getSelectorName();
anaModInputFile.write(absAnaModInputFilepath+selectorName+File.separator+createDateTime+".xml");
return analyseModuleInputValues;
}
}
|
47993_2 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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 the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
* *
* Copyright (C) 2005 Robert KLEIN. [email protected] *
* Contributor(s): ______________________________________. *
*****************************************************************************/
package org.compiere.process;
import java.math.BigDecimal;
import org.compiere.model.I_AD_Role_Included;
import org.compiere.util.DB;
import org.compiere.util.Env;
/**
* Copy role access records
*
* @author Robert Klein
* @ author Paul Bowden
* @version $Id: CopyRole.java,v 1.0$
* @author Yamel Senih, [email protected], ERPCyA http://www.erpcya.com
* <li> BR [ 264 ] Bad index for Process SeqNo
* @see https://github.com/adempiere/adempiere/issues/264
*/
public class CopyRole extends SvrProcess
{
private int m_AD_Role_ID_From = 0;
private int m_AD_Role_ID_To = 0;
private int m_AD_Client_ID = 0;
private int m_AD_Org_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
// BR [ 264 ] Parameter Name Changed
else if (name.equals("AD_Role_ID"))
m_AD_Role_ID_From = para[i].getParameterAsInt();
else if (name.equals("AD_Role_To_ID"))
m_AD_Role_ID_To = para[i].getParameterAsInt();
else if (name.equals("AD_Client_ID"))
m_AD_Client_ID = para[i].getParameterAsInt();
else if (name.equals("AD_Org_ID"))
m_AD_Org_ID = para[i].getParameterAsInt();
}
} // prepare
/**
* Copy the role access records
* @return info
* @throws Exception
*/
protected String doIt() throws Exception
{
String[] tables = new String[] {"AD_Window_Access", "AD_Process_Access", "AD_Form_Access",
"AD_Workflow_Access", "AD_Task_Access", "AD_Document_Action_Access", "AD_Browse_Access",
I_AD_Role_Included.Table_Name,
};
String[] keycolumns = new String[] {"AD_Window_ID", "AD_Process_ID", "AD_Form_ID",
"AD_Workflow_ID", "AD_Task_ID", "C_DocType_ID, AD_Ref_List_ID", "AD_Browse_ID",
I_AD_Role_Included.COLUMNNAME_Included_Role_ID,
};
int action = 0;
for ( int i = 0; i < tables.length; i++ )
{
String table = tables[i];
String keycolumn = keycolumns[i];
String sql = "DELETE FROM " + table + " WHERE AD_Role_ID = " + m_AD_Role_ID_To;
int no = DB.executeUpdateEx(sql, get_TrxName());
addLog(action++, null, BigDecimal.valueOf(no), "Old records deleted from " + table );
final boolean column_IsReadWrite =
!table.equals("AD_Document_Action_Access")
&& !table.equals(I_AD_Role_Included.Table_Name);
final boolean column_SeqNo = table.equals(I_AD_Role_Included.Table_Name);
sql = "INSERT INTO " + table
+ " (AD_Client_ID, AD_Org_ID, Created, CreatedBy, Updated, UpdatedBy, "
+ "AD_Role_ID, " + keycolumn +", isActive";
if (column_SeqNo)
sql += ", SeqNo ";
if (column_IsReadWrite)
sql += ", isReadWrite) ";
else
sql += ") ";
sql += "SELECT " + m_AD_Client_ID
+ ", "+ m_AD_Org_ID
+ ", getdate(), "+ Env.getAD_User_ID(Env.getCtx())
+ ", getdate(), "+ Env.getAD_User_ID(Env.getCtx())
+ ", " + m_AD_Role_ID_To
+ ", " + keycolumn
+ ", IsActive ";
if (column_SeqNo)
sql += ", SeqNo ";
if (column_IsReadWrite)
sql += ", isReadWrite ";
sql += "FROM " + table + " WHERE AD_Role_ID = " + m_AD_Role_ID_From;
no = DB.executeUpdateEx (sql, get_TrxName());
addLog(action++, null, new BigDecimal(no), "New records inserted into " + table );
}
return "Role copied";
} // doIt
} // CopyRole
| wahello/adempiere | base/src/org/compiere/process/CopyRole.java | 1,814 | /**
* Prepare - e.g., get Parameters.
*/ | block_comment | nl | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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 the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
* *
* Copyright (C) 2005 Robert KLEIN. [email protected] *
* Contributor(s): ______________________________________. *
*****************************************************************************/
package org.compiere.process;
import java.math.BigDecimal;
import org.compiere.model.I_AD_Role_Included;
import org.compiere.util.DB;
import org.compiere.util.Env;
/**
* Copy role access records
*
* @author Robert Klein
* @ author Paul Bowden
* @version $Id: CopyRole.java,v 1.0$
* @author Yamel Senih, [email protected], ERPCyA http://www.erpcya.com
* <li> BR [ 264 ] Bad index for Process SeqNo
* @see https://github.com/adempiere/adempiere/issues/264
*/
public class CopyRole extends SvrProcess
{
private int m_AD_Role_ID_From = 0;
private int m_AD_Role_ID_To = 0;
private int m_AD_Client_ID = 0;
private int m_AD_Org_ID = 0;
/**
* Prepare - e.g.,<SUF>*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
// BR [ 264 ] Parameter Name Changed
else if (name.equals("AD_Role_ID"))
m_AD_Role_ID_From = para[i].getParameterAsInt();
else if (name.equals("AD_Role_To_ID"))
m_AD_Role_ID_To = para[i].getParameterAsInt();
else if (name.equals("AD_Client_ID"))
m_AD_Client_ID = para[i].getParameterAsInt();
else if (name.equals("AD_Org_ID"))
m_AD_Org_ID = para[i].getParameterAsInt();
}
} // prepare
/**
* Copy the role access records
* @return info
* @throws Exception
*/
protected String doIt() throws Exception
{
String[] tables = new String[] {"AD_Window_Access", "AD_Process_Access", "AD_Form_Access",
"AD_Workflow_Access", "AD_Task_Access", "AD_Document_Action_Access", "AD_Browse_Access",
I_AD_Role_Included.Table_Name,
};
String[] keycolumns = new String[] {"AD_Window_ID", "AD_Process_ID", "AD_Form_ID",
"AD_Workflow_ID", "AD_Task_ID", "C_DocType_ID, AD_Ref_List_ID", "AD_Browse_ID",
I_AD_Role_Included.COLUMNNAME_Included_Role_ID,
};
int action = 0;
for ( int i = 0; i < tables.length; i++ )
{
String table = tables[i];
String keycolumn = keycolumns[i];
String sql = "DELETE FROM " + table + " WHERE AD_Role_ID = " + m_AD_Role_ID_To;
int no = DB.executeUpdateEx(sql, get_TrxName());
addLog(action++, null, BigDecimal.valueOf(no), "Old records deleted from " + table );
final boolean column_IsReadWrite =
!table.equals("AD_Document_Action_Access")
&& !table.equals(I_AD_Role_Included.Table_Name);
final boolean column_SeqNo = table.equals(I_AD_Role_Included.Table_Name);
sql = "INSERT INTO " + table
+ " (AD_Client_ID, AD_Org_ID, Created, CreatedBy, Updated, UpdatedBy, "
+ "AD_Role_ID, " + keycolumn +", isActive";
if (column_SeqNo)
sql += ", SeqNo ";
if (column_IsReadWrite)
sql += ", isReadWrite) ";
else
sql += ") ";
sql += "SELECT " + m_AD_Client_ID
+ ", "+ m_AD_Org_ID
+ ", getdate(), "+ Env.getAD_User_ID(Env.getCtx())
+ ", getdate(), "+ Env.getAD_User_ID(Env.getCtx())
+ ", " + m_AD_Role_ID_To
+ ", " + keycolumn
+ ", IsActive ";
if (column_SeqNo)
sql += ", SeqNo ";
if (column_IsReadWrite)
sql += ", isReadWrite ";
sql += "FROM " + table + " WHERE AD_Role_ID = " + m_AD_Role_ID_From;
no = DB.executeUpdateEx (sql, get_TrxName());
addLog(action++, null, new BigDecimal(no), "New records inserted into " + table );
}
return "Role copied";
} // doIt
} // CopyRole
|
6675_3 | /*
* Copyright (c) 2002 - 2006 IBM Corporation.
* 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:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import java.util.Iterator;
/** A bit set is a set of elements, each of which corresponds to a unique integer from [0,MAX]. */
public final class BitSet<T> {
/** The backing bit vector that determines set membership. */
private final BitVector vector;
/** The bijection between integer to object. */
private OrdinalSetMapping<T> map;
/**
* Constructor: create an empty set corresponding to a given mapping
*
* @throws IllegalArgumentException if map is null
*/
public BitSet(OrdinalSetMapping<T> map) {
if (map == null) {
throw new IllegalArgumentException("map is null");
}
int length = map.getMaximumIndex();
vector = new BitVector(length);
this.map = map;
}
public static <T> BitSet<T> createBitSet(BitSet<T> B) {
if (B == null) {
throw new IllegalArgumentException("null B");
}
return new BitSet<>(B);
}
private BitSet(BitSet<T> B) {
this(B.map);
addAll(B);
}
/**
* Add all elements in bitset B to this bit set
*
* @throws IllegalArgumentException if B is null
*/
public void addAll(BitSet<?> B) {
if (B == null) {
throw new IllegalArgumentException("B is null");
}
vector.or(B.vector);
}
/** Add all bits in BitVector B to this bit set */
public void addAll(BitVector B) {
vector.or(B);
}
/** Add an object to this bit set. */
public void add(T o) {
int n = map.getMappedIndex(o);
vector.set(n);
}
/**
* Remove an object from this bit set.
*
* @param o the object to remove
*/
public void clear(T o) {
int n = map.getMappedIndex(o);
if (n == -1) {
return;
}
vector.clear(n);
}
/** Does this set contain a certain object? */
public boolean contains(T o) {
int n = map.getMappedIndex(o);
if (n == -1) {
return false;
}
return vector.get(n);
}
/**
* @return a String representation
*/
@Override
public String toString() {
return vector.toString();
}
/**
* Method copy. Copies the bits in the bit vector, but only assigns the object map. No need to
* create a new object/bit bijection object.
*
* @throws IllegalArgumentException if other is null
*/
public void copyBits(BitSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
vector.copyBits(other.vector);
map = other.map;
}
/**
* Does this object hold the same bits as other?
*
* @throws IllegalArgumentException if other is null
*/
public boolean sameBits(BitSet<?> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
return vector.equals(other.vector);
}
/** Not very efficient. */
public Iterator<T> iterator() {
return new Iterator<>() {
private int nextCounter = -1;
{
for (int i = 0; i < vector.length(); i++) {
if (vector.get(i)) {
nextCounter = i;
break;
}
}
}
@Override
public boolean hasNext() {
return (nextCounter != -1);
}
@Override
public T next() {
T result = map.getMappedObject(nextCounter);
int start = nextCounter + 1;
nextCounter = -1;
for (int i = start; i < vector.length(); i++) {
if (vector.get(i)) {
nextCounter = i;
break;
}
}
return result;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
public int size() {
return vector.populationCount();
}
public int length() {
return vector.length();
}
/** Set all the bits to 0. */
public void clearAll() {
vector.clearAll();
}
/** Set all the bits to 1. */
public void setAll() {
vector.setAll();
}
/**
* Perform intersection of two bitsets
*
* @param other the other bitset in the operation
* @throws IllegalArgumentException if other is null
*/
public void intersect(BitSet<?> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
vector.and(other.vector);
}
/**
* Perform the difference of two bit sets
*
* @param other the other bitset in the operation
* @throws IllegalArgumentException if other is null
*/
public void difference(BitSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
vector.and(BitVector.not(other.vector));
}
/** */
public boolean isEmpty() {
return size() == 0;
}
}
| wala/WALA | util/src/main/java/com/ibm/wala/util/intset/BitSet.java | 1,577 | /** The bijection between integer to object. */ | block_comment | nl | /*
* Copyright (c) 2002 - 2006 IBM Corporation.
* 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:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import java.util.Iterator;
/** A bit set is a set of elements, each of which corresponds to a unique integer from [0,MAX]. */
public final class BitSet<T> {
/** The backing bit vector that determines set membership. */
private final BitVector vector;
/** The bijection between<SUF>*/
private OrdinalSetMapping<T> map;
/**
* Constructor: create an empty set corresponding to a given mapping
*
* @throws IllegalArgumentException if map is null
*/
public BitSet(OrdinalSetMapping<T> map) {
if (map == null) {
throw new IllegalArgumentException("map is null");
}
int length = map.getMaximumIndex();
vector = new BitVector(length);
this.map = map;
}
public static <T> BitSet<T> createBitSet(BitSet<T> B) {
if (B == null) {
throw new IllegalArgumentException("null B");
}
return new BitSet<>(B);
}
private BitSet(BitSet<T> B) {
this(B.map);
addAll(B);
}
/**
* Add all elements in bitset B to this bit set
*
* @throws IllegalArgumentException if B is null
*/
public void addAll(BitSet<?> B) {
if (B == null) {
throw new IllegalArgumentException("B is null");
}
vector.or(B.vector);
}
/** Add all bits in BitVector B to this bit set */
public void addAll(BitVector B) {
vector.or(B);
}
/** Add an object to this bit set. */
public void add(T o) {
int n = map.getMappedIndex(o);
vector.set(n);
}
/**
* Remove an object from this bit set.
*
* @param o the object to remove
*/
public void clear(T o) {
int n = map.getMappedIndex(o);
if (n == -1) {
return;
}
vector.clear(n);
}
/** Does this set contain a certain object? */
public boolean contains(T o) {
int n = map.getMappedIndex(o);
if (n == -1) {
return false;
}
return vector.get(n);
}
/**
* @return a String representation
*/
@Override
public String toString() {
return vector.toString();
}
/**
* Method copy. Copies the bits in the bit vector, but only assigns the object map. No need to
* create a new object/bit bijection object.
*
* @throws IllegalArgumentException if other is null
*/
public void copyBits(BitSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
vector.copyBits(other.vector);
map = other.map;
}
/**
* Does this object hold the same bits as other?
*
* @throws IllegalArgumentException if other is null
*/
public boolean sameBits(BitSet<?> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
return vector.equals(other.vector);
}
/** Not very efficient. */
public Iterator<T> iterator() {
return new Iterator<>() {
private int nextCounter = -1;
{
for (int i = 0; i < vector.length(); i++) {
if (vector.get(i)) {
nextCounter = i;
break;
}
}
}
@Override
public boolean hasNext() {
return (nextCounter != -1);
}
@Override
public T next() {
T result = map.getMappedObject(nextCounter);
int start = nextCounter + 1;
nextCounter = -1;
for (int i = start; i < vector.length(); i++) {
if (vector.get(i)) {
nextCounter = i;
break;
}
}
return result;
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
public int size() {
return vector.populationCount();
}
public int length() {
return vector.length();
}
/** Set all the bits to 0. */
public void clearAll() {
vector.clearAll();
}
/** Set all the bits to 1. */
public void setAll() {
vector.setAll();
}
/**
* Perform intersection of two bitsets
*
* @param other the other bitset in the operation
* @throws IllegalArgumentException if other is null
*/
public void intersect(BitSet<?> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
vector.and(other.vector);
}
/**
* Perform the difference of two bit sets
*
* @param other the other bitset in the operation
* @throws IllegalArgumentException if other is null
*/
public void difference(BitSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
vector.and(BitVector.not(other.vector));
}
/** */
public boolean isEmpty() {
return size() == 0;
}
}
|
127171_12 | // Copyright (c) 2014 by B.W. van Schooten, [email protected]
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = ev;
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getAction();
int ptridx = (action & MotionEvent.ACTION_POINTER_ID_MASK)
>> MotionEvent.ACTION_POINTER_ID_SHIFT;
action &= MotionEvent.ACTION_MASK;
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX();
double y = me.getY();
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event: 2
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) handleTouchEvent(motionqueue[i]);
motionqueue[i] = null;
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
| wallabyway/glesjs | src/net/tmtg/glesjs/MainActivity.java | 2,290 | // down event: 0 | line_comment | nl | // Copyright (c) 2014 by B.W. van Schooten, [email protected]
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = ev;
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getAction();
int ptridx = (action & MotionEvent.ACTION_POINTER_ID_MASK)
>> MotionEvent.ACTION_POINTER_ID_SHIFT;
action &= MotionEvent.ACTION_MASK;
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX();
double y = me.getY();
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event:<SUF>
// move event: 2
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) handleTouchEvent(motionqueue[i]);
motionqueue[i] = null;
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
|
200676_29 | package org.aisen.weibo.sina.ui.widget.swipeback;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.aisen.weibo.sina.R;
import java.util.ArrayList;
import java.util.List;
public class SwipeBackLayout extends FrameLayout {
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
private static final int FULL_ALPHA = 255;
/**
* Edge flag indicating that the left edge should be affected.
*/
public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT;
/**
* Edge flag indicating that the right edge should be affected.
*/
public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT;
/**
* Edge flag indicating that the bottom edge should be affected.
*/
public static final int EDGE_BOTTOM = ViewDragHelper.EDGE_BOTTOM;
/**
* Edge flag set indicating all edges should be affected.
*/
public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT | EDGE_BOTTOM;
/**
* A view is not currently being dragged or animating as a result of a
* fling/snap.
*/
public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;
/**
* A view is currently being dragged. The position is currently changing as
* a result of user input or simulated user input.
*/
public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;
/**
* A view is currently settling into place as a result of a fling or
* predefined non-interactive motion.
*/
public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;
/**
* Default threshold of scroll
*/
private static final float DEFAULT_SCROLL_THRESHOLD = 0.3f;
private static final int OVERSCROLL_DISTANCE = 10;
private static final int[] EDGE_FLAGS = {
EDGE_LEFT, EDGE_RIGHT, EDGE_BOTTOM, EDGE_ALL
};
private int mEdgeFlag;
/**
* Threshold of scroll, we will close the activity, when scrollPercent over
* this value;
*/
private float mScrollThreshold = DEFAULT_SCROLL_THRESHOLD;
private Activity mActivity;
private boolean mEnable = true;
private View mContentView;
private ViewDragHelper mDragHelper;
private float mScrollPercent;
private int mContentLeft;
private int mContentTop;
/**
* The set of listeners to be sent events through.
*/
private List<SwipeListener> mListeners;
private Drawable mShadowLeft;
private Drawable mShadowRight;
private Drawable mShadowBottom;
private float mScrimOpacity;
private int mScrimColor = DEFAULT_SCRIM_COLOR;
private boolean mInLayout;
private Rect mTmpRect = new Rect();
/**
* Edge being dragged
*/
private int mTrackingEdge;
public SwipeBackLayout(Context context) {
this(context, null);
}
public SwipeBackLayout(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.SwipeBackLayoutStyle);
}
public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
mDragHelper = ViewDragHelper.create(this, new ViewDragCallback());
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBackLayout, defStyle,
R.style.SwipeBackLayout);
int edgeSize = a.getDimensionPixelSize(R.styleable.SwipeBackLayout_edge_size, -1);
if (edgeSize > 0)
setEdgeSize(edgeSize);
int mode = EDGE_FLAGS[a.getInt(R.styleable.SwipeBackLayout_edge_flag, 0)];
setEdgeTrackingEnabled(mode);
int shadowLeft = a.getResourceId(R.styleable.SwipeBackLayout_shadow_left,
R.drawable.shadow_left);
int shadowRight = a.getResourceId(R.styleable.SwipeBackLayout_shadow_right,
R.drawable.shadow_right);
int shadowBottom = a.getResourceId(R.styleable.SwipeBackLayout_shadow_bottom,
R.drawable.shadow_bottom);
setShadow(shadowLeft, EDGE_LEFT);
setShadow(shadowRight, EDGE_RIGHT);
setShadow(shadowBottom, EDGE_BOTTOM);
a.recycle();
final float density = getResources().getDisplayMetrics().density;
final float minVel = MIN_FLING_VELOCITY * density;
mDragHelper.setMinVelocity(minVel);
mDragHelper.setMaxVelocity(minVel * 2f);
}
/**
* Sets the sensitivity of the NavigationLayout.
*
* @param context The application context.
* @param sensitivity value between 0 and 1, the final value for touchSlop =
* ViewConfiguration.getScaledTouchSlop * (1 / s);
*/
public void setSensitivity(Context context, float sensitivity) {
mDragHelper.setSensitivity(context, sensitivity);
}
/**
* Set up contentView which will be moved by user gesture
*
* @param view
*/
private void setContentView(View view) {
mContentView = view;
}
public void setEnableGesture(boolean enable) {
mEnable = enable;
}
/**
* Enable edge tracking for the selected edges of the parent view. The
* callback's
* {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeTouched(int, int)}
* and
* {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeDragStarted(int, int)}
* methods will only be invoked for edges for which edge tracking has been
* enabled.
*
* @param edgeFlags Combination of edge flags describing the edges to watch
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setEdgeTrackingEnabled(int edgeFlags) {
mEdgeFlag = edgeFlags;
mDragHelper.setEdgeTrackingEnabled(mEdgeFlag);
}
/**
* Set a color to use for the scrim that obscures primary content while a
* drawer is open.
*
* @param color Color to use in 0xAARRGGBB format.
*/
public void setScrimColor(int color) {
mScrimColor = color;
invalidate();
}
/**
* Set the size of an edge. This is the range in pixels along the edges of
* this view that will actively detect edge touches or drags if edge
* tracking is enabled.
*
* @param size The size of an edge in pixels
*/
public void setEdgeSize(int size) {
mDragHelper.setEdgeSize(size);
}
/**
* Register a callback to be invoked when a swipe event is sent to this
* view.
*
* @param listener the swipe listener to attach to this view
* @deprecated use {@link #addSwipeListener} instead
*/
@Deprecated
public void setSwipeListener(SwipeListener listener) {
addSwipeListener(listener);
}
/**
* Add a callback to be invoked when a swipe event is sent to this view.
*
* @param listener the swipe listener to attach to this view
*/
public void addSwipeListener(SwipeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<SwipeListener>();
}
mListeners.add(listener);
}
/**
* Removes a listener from the set of listeners
*
* @param listener
*/
public void removeSwipeListener(SwipeListener listener) {
if (mListeners == null) {
return;
}
mListeners.remove(listener);
}
public static interface SwipeListener {
/**
* Invoke when state change
*
* @param state flag to describe scroll state
* @param scrollPercent scroll percent of this view
* @see #STATE_IDLE
* @see #STATE_DRAGGING
* @see #STATE_SETTLING
*/
public void onScrollStateChange(int state, float scrollPercent);
/**
* Invoke when edge touched
*
* @param edgeFlag edge flag describing the edge being touched
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void onEdgeTouch(int edgeFlag);
/**
* Invoke when scroll percent over the threshold for the first time
*/
public void onScrollOverThreshold();
}
/**
* Set scroll threshold, we will close the activity, when scrollPercent over
* this value
*
* @param threshold
*/
public void setScrollThresHold(float threshold) {
if (threshold >= 1.0f || threshold <= 0) {
throw new IllegalArgumentException("Threshold value should be between 0 and 1.0");
}
mScrollThreshold = threshold;
}
/**
* Set a drawable used for edge shadow.
*
* @param shadow Drawable to use
* @param edgeFlags Combination of edge flags describing the edge to set
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setShadow(Drawable shadow, int edgeFlag) {
if ((edgeFlag & EDGE_LEFT) != 0) {
mShadowLeft = shadow;
} else if ((edgeFlag & EDGE_RIGHT) != 0) {
mShadowRight = shadow;
} else if ((edgeFlag & EDGE_BOTTOM) != 0) {
mShadowBottom = shadow;
}
invalidate();
}
/**
* Set a drawable used for edge shadow.
*
* @param resId Resource of drawable to use
* @param edgeFlags Combination of edge flags describing the edge to set
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setShadow(int resId, int edgeFlag) {
setShadow(getResources().getDrawable(resId), edgeFlag);
}
/**
* Scroll out contentView and finish the activity
*/
public void scrollToFinishActivity() {
final int childWidth = mContentView.getWidth();
final int childHeight = mContentView.getHeight();
int left = 0, top = 0;
if ((mEdgeFlag & EDGE_LEFT) != 0) {
left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_LEFT;
} else if ((mEdgeFlag & EDGE_RIGHT) != 0) {
left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_RIGHT;
} else if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_BOTTOM;
}
mDragHelper.smoothSlideViewTo(mContentView, left, top);
invalidate();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
try {
return mDragHelper.shouldInterceptTouchEvent(event);
} catch (ArrayIndexOutOfBoundsException e) {
// FIXME: handle exception
// issues #9
return false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
mDragHelper.processTouchEvent(event);
return true;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mInLayout = true;
// mContentTop = SystemBarUtils.getStatusBarHeight(getContext());
if (mContentView != null)
mContentView.layout(mContentLeft, mContentTop,
mContentLeft + mContentView.getMeasuredWidth(),
mContentTop + mContentView.getMeasuredHeight());
mInLayout = false;
}
@Override
public void requestLayout() {
if (!mInLayout) {
super.requestLayout();
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final boolean drawContent = child == mContentView;
boolean ret = super.drawChild(canvas, child, drawingTime);
if (mScrimOpacity > 0 && drawContent
&& mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) {
drawShadow(canvas, child);
drawScrim(canvas, child);
}
return ret;
}
private void drawScrim(Canvas canvas, View child) {
final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
final int alpha = (int) (baseAlpha * mScrimOpacity);
final int color = alpha << 24 | (mScrimColor & 0xffffff);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
canvas.clipRect(0, 0, child.getLeft(), getHeight());
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight());
}
canvas.drawColor(color);
}
private void drawShadow(Canvas canvas, View child) {
final Rect childRect = mTmpRect;
child.getHitRect(childRect);
if ((mEdgeFlag & EDGE_LEFT) != 0) {
mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top,
childRect.left, childRect.bottom);
mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowLeft.draw(canvas);
}
if ((mEdgeFlag & EDGE_RIGHT) != 0) {
mShadowRight.setBounds(childRect.right, childRect.top,
childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom);
mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowRight.draw(canvas);
}
if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
mShadowBottom.setBounds(childRect.left, childRect.bottom, childRect.right,
childRect.bottom + mShadowBottom.getIntrinsicHeight());
mShadowBottom.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowBottom.draw(canvas);
}
}
public void attachToActivity(Activity activity) {
mActivity = activity;
TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
android.R.attr.windowBackground
});
int background = a.getResourceId(0, 0);
a.recycle();
// 这里可以设置背景颜色
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decorChild.setBackgroundResource(background);
// decorChild.setBackgroundColor(Color.parseColor("#fffafafa"));
decor.removeView(decorChild);
addView(decorChild);
setContentView(decorChild);
decor.addView(this);
}
@Override
public void computeScroll() {
mScrimOpacity = 1 - mScrollPercent;
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private class ViewDragCallback extends ViewDragHelper.Callback {
private boolean mIsScrollOverValid;
@Override
public boolean tryCaptureView(View view, int i) {
boolean ret = mDragHelper.isEdgeTouched(mEdgeFlag, i);
if (ret) {
if (mDragHelper.isEdgeTouched(EDGE_LEFT, i)) {
mTrackingEdge = EDGE_LEFT;
} else if (mDragHelper.isEdgeTouched(EDGE_RIGHT, i)) {
mTrackingEdge = EDGE_RIGHT;
} else if (mDragHelper.isEdgeTouched(EDGE_BOTTOM, i)) {
mTrackingEdge = EDGE_BOTTOM;
}
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onEdgeTouch(mTrackingEdge);
}
}
mIsScrollOverValid = true;
}
return ret;
}
@Override
public int getViewHorizontalDragRange(View child) {
return mEdgeFlag & (EDGE_LEFT | EDGE_RIGHT);
}
@Override
public int getViewVerticalDragRange(View child) {
return mEdgeFlag & EDGE_BOTTOM;
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
super.onViewPositionChanged(changedView, left, top, dx, dy);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth()));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth() + mShadowRight.getIntrinsicWidth()));
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
mScrollPercent = Math.abs((float) top
/ (mContentView.getHeight() + mShadowBottom.getIntrinsicHeight()));
}
mContentLeft = left;
mContentTop = top;
invalidate();
if (mScrollPercent < mScrollThreshold && !mIsScrollOverValid) {
mIsScrollOverValid = true;
}
if (mListeners != null && !mListeners.isEmpty()
&& mDragHelper.getViewDragState() == STATE_DRAGGING
&& mScrollPercent >= mScrollThreshold && mIsScrollOverValid) {
mIsScrollOverValid = false;
for (SwipeListener listener : mListeners) {
listener.onScrollOverThreshold();
}
}
if (mScrollPercent >= 1) {
if (!mActivity.isFinishing())
mActivity.finish();
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final int childWidth = releasedChild.getWidth();
final int childHeight = releasedChild.getHeight();
int left = 0, top = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? childWidth
+ mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE : 0;
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? -(childWidth
+ mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight
+ mShadowBottom.getIntrinsicHeight() + OVERSCROLL_DISTANCE) : 0;
}
mDragHelper.settleCapturedViewAt(left, top);
invalidate();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int ret = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
ret = Math.min(child.getWidth(), Math.max(left, 0));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
ret = Math.min(0, Math.max(left, -child.getWidth()));
}
return ret;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
int ret = 0;
if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
ret = Math.min(0, Math.max(top, -child.getHeight()));
}
return ret;
}
@Override
public void onViewDragStateChanged(int state) {
super.onViewDragStateChanged(state);
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onScrollStateChange(state, mScrollPercent);
}
}
}
}
}
| wangdan/AisenWeiBo | app/src/main/java/org/aisen/weibo/sina/ui/widget/swipeback/SwipeBackLayout.java | 5,994 | // mContentTop = SystemBarUtils.getStatusBarHeight(getContext()); | line_comment | nl | package org.aisen.weibo.sina.ui.widget.swipeback;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.aisen.weibo.sina.R;
import java.util.ArrayList;
import java.util.List;
public class SwipeBackLayout extends FrameLayout {
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
private static final int FULL_ALPHA = 255;
/**
* Edge flag indicating that the left edge should be affected.
*/
public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT;
/**
* Edge flag indicating that the right edge should be affected.
*/
public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT;
/**
* Edge flag indicating that the bottom edge should be affected.
*/
public static final int EDGE_BOTTOM = ViewDragHelper.EDGE_BOTTOM;
/**
* Edge flag set indicating all edges should be affected.
*/
public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT | EDGE_BOTTOM;
/**
* A view is not currently being dragged or animating as a result of a
* fling/snap.
*/
public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;
/**
* A view is currently being dragged. The position is currently changing as
* a result of user input or simulated user input.
*/
public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;
/**
* A view is currently settling into place as a result of a fling or
* predefined non-interactive motion.
*/
public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;
/**
* Default threshold of scroll
*/
private static final float DEFAULT_SCROLL_THRESHOLD = 0.3f;
private static final int OVERSCROLL_DISTANCE = 10;
private static final int[] EDGE_FLAGS = {
EDGE_LEFT, EDGE_RIGHT, EDGE_BOTTOM, EDGE_ALL
};
private int mEdgeFlag;
/**
* Threshold of scroll, we will close the activity, when scrollPercent over
* this value;
*/
private float mScrollThreshold = DEFAULT_SCROLL_THRESHOLD;
private Activity mActivity;
private boolean mEnable = true;
private View mContentView;
private ViewDragHelper mDragHelper;
private float mScrollPercent;
private int mContentLeft;
private int mContentTop;
/**
* The set of listeners to be sent events through.
*/
private List<SwipeListener> mListeners;
private Drawable mShadowLeft;
private Drawable mShadowRight;
private Drawable mShadowBottom;
private float mScrimOpacity;
private int mScrimColor = DEFAULT_SCRIM_COLOR;
private boolean mInLayout;
private Rect mTmpRect = new Rect();
/**
* Edge being dragged
*/
private int mTrackingEdge;
public SwipeBackLayout(Context context) {
this(context, null);
}
public SwipeBackLayout(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.SwipeBackLayoutStyle);
}
public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
mDragHelper = ViewDragHelper.create(this, new ViewDragCallback());
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBackLayout, defStyle,
R.style.SwipeBackLayout);
int edgeSize = a.getDimensionPixelSize(R.styleable.SwipeBackLayout_edge_size, -1);
if (edgeSize > 0)
setEdgeSize(edgeSize);
int mode = EDGE_FLAGS[a.getInt(R.styleable.SwipeBackLayout_edge_flag, 0)];
setEdgeTrackingEnabled(mode);
int shadowLeft = a.getResourceId(R.styleable.SwipeBackLayout_shadow_left,
R.drawable.shadow_left);
int shadowRight = a.getResourceId(R.styleable.SwipeBackLayout_shadow_right,
R.drawable.shadow_right);
int shadowBottom = a.getResourceId(R.styleable.SwipeBackLayout_shadow_bottom,
R.drawable.shadow_bottom);
setShadow(shadowLeft, EDGE_LEFT);
setShadow(shadowRight, EDGE_RIGHT);
setShadow(shadowBottom, EDGE_BOTTOM);
a.recycle();
final float density = getResources().getDisplayMetrics().density;
final float minVel = MIN_FLING_VELOCITY * density;
mDragHelper.setMinVelocity(minVel);
mDragHelper.setMaxVelocity(minVel * 2f);
}
/**
* Sets the sensitivity of the NavigationLayout.
*
* @param context The application context.
* @param sensitivity value between 0 and 1, the final value for touchSlop =
* ViewConfiguration.getScaledTouchSlop * (1 / s);
*/
public void setSensitivity(Context context, float sensitivity) {
mDragHelper.setSensitivity(context, sensitivity);
}
/**
* Set up contentView which will be moved by user gesture
*
* @param view
*/
private void setContentView(View view) {
mContentView = view;
}
public void setEnableGesture(boolean enable) {
mEnable = enable;
}
/**
* Enable edge tracking for the selected edges of the parent view. The
* callback's
* {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeTouched(int, int)}
* and
* {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeDragStarted(int, int)}
* methods will only be invoked for edges for which edge tracking has been
* enabled.
*
* @param edgeFlags Combination of edge flags describing the edges to watch
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setEdgeTrackingEnabled(int edgeFlags) {
mEdgeFlag = edgeFlags;
mDragHelper.setEdgeTrackingEnabled(mEdgeFlag);
}
/**
* Set a color to use for the scrim that obscures primary content while a
* drawer is open.
*
* @param color Color to use in 0xAARRGGBB format.
*/
public void setScrimColor(int color) {
mScrimColor = color;
invalidate();
}
/**
* Set the size of an edge. This is the range in pixels along the edges of
* this view that will actively detect edge touches or drags if edge
* tracking is enabled.
*
* @param size The size of an edge in pixels
*/
public void setEdgeSize(int size) {
mDragHelper.setEdgeSize(size);
}
/**
* Register a callback to be invoked when a swipe event is sent to this
* view.
*
* @param listener the swipe listener to attach to this view
* @deprecated use {@link #addSwipeListener} instead
*/
@Deprecated
public void setSwipeListener(SwipeListener listener) {
addSwipeListener(listener);
}
/**
* Add a callback to be invoked when a swipe event is sent to this view.
*
* @param listener the swipe listener to attach to this view
*/
public void addSwipeListener(SwipeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<SwipeListener>();
}
mListeners.add(listener);
}
/**
* Removes a listener from the set of listeners
*
* @param listener
*/
public void removeSwipeListener(SwipeListener listener) {
if (mListeners == null) {
return;
}
mListeners.remove(listener);
}
public static interface SwipeListener {
/**
* Invoke when state change
*
* @param state flag to describe scroll state
* @param scrollPercent scroll percent of this view
* @see #STATE_IDLE
* @see #STATE_DRAGGING
* @see #STATE_SETTLING
*/
public void onScrollStateChange(int state, float scrollPercent);
/**
* Invoke when edge touched
*
* @param edgeFlag edge flag describing the edge being touched
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void onEdgeTouch(int edgeFlag);
/**
* Invoke when scroll percent over the threshold for the first time
*/
public void onScrollOverThreshold();
}
/**
* Set scroll threshold, we will close the activity, when scrollPercent over
* this value
*
* @param threshold
*/
public void setScrollThresHold(float threshold) {
if (threshold >= 1.0f || threshold <= 0) {
throw new IllegalArgumentException("Threshold value should be between 0 and 1.0");
}
mScrollThreshold = threshold;
}
/**
* Set a drawable used for edge shadow.
*
* @param shadow Drawable to use
* @param edgeFlags Combination of edge flags describing the edge to set
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setShadow(Drawable shadow, int edgeFlag) {
if ((edgeFlag & EDGE_LEFT) != 0) {
mShadowLeft = shadow;
} else if ((edgeFlag & EDGE_RIGHT) != 0) {
mShadowRight = shadow;
} else if ((edgeFlag & EDGE_BOTTOM) != 0) {
mShadowBottom = shadow;
}
invalidate();
}
/**
* Set a drawable used for edge shadow.
*
* @param resId Resource of drawable to use
* @param edgeFlags Combination of edge flags describing the edge to set
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setShadow(int resId, int edgeFlag) {
setShadow(getResources().getDrawable(resId), edgeFlag);
}
/**
* Scroll out contentView and finish the activity
*/
public void scrollToFinishActivity() {
final int childWidth = mContentView.getWidth();
final int childHeight = mContentView.getHeight();
int left = 0, top = 0;
if ((mEdgeFlag & EDGE_LEFT) != 0) {
left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_LEFT;
} else if ((mEdgeFlag & EDGE_RIGHT) != 0) {
left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_RIGHT;
} else if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_BOTTOM;
}
mDragHelper.smoothSlideViewTo(mContentView, left, top);
invalidate();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
try {
return mDragHelper.shouldInterceptTouchEvent(event);
} catch (ArrayIndexOutOfBoundsException e) {
// FIXME: handle exception
// issues #9
return false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
mDragHelper.processTouchEvent(event);
return true;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mInLayout = true;
// mContentTop =<SUF>
if (mContentView != null)
mContentView.layout(mContentLeft, mContentTop,
mContentLeft + mContentView.getMeasuredWidth(),
mContentTop + mContentView.getMeasuredHeight());
mInLayout = false;
}
@Override
public void requestLayout() {
if (!mInLayout) {
super.requestLayout();
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final boolean drawContent = child == mContentView;
boolean ret = super.drawChild(canvas, child, drawingTime);
if (mScrimOpacity > 0 && drawContent
&& mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) {
drawShadow(canvas, child);
drawScrim(canvas, child);
}
return ret;
}
private void drawScrim(Canvas canvas, View child) {
final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
final int alpha = (int) (baseAlpha * mScrimOpacity);
final int color = alpha << 24 | (mScrimColor & 0xffffff);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
canvas.clipRect(0, 0, child.getLeft(), getHeight());
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight());
}
canvas.drawColor(color);
}
private void drawShadow(Canvas canvas, View child) {
final Rect childRect = mTmpRect;
child.getHitRect(childRect);
if ((mEdgeFlag & EDGE_LEFT) != 0) {
mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top,
childRect.left, childRect.bottom);
mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowLeft.draw(canvas);
}
if ((mEdgeFlag & EDGE_RIGHT) != 0) {
mShadowRight.setBounds(childRect.right, childRect.top,
childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom);
mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowRight.draw(canvas);
}
if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
mShadowBottom.setBounds(childRect.left, childRect.bottom, childRect.right,
childRect.bottom + mShadowBottom.getIntrinsicHeight());
mShadowBottom.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowBottom.draw(canvas);
}
}
public void attachToActivity(Activity activity) {
mActivity = activity;
TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
android.R.attr.windowBackground
});
int background = a.getResourceId(0, 0);
a.recycle();
// 这里可以设置背景颜色
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decorChild.setBackgroundResource(background);
// decorChild.setBackgroundColor(Color.parseColor("#fffafafa"));
decor.removeView(decorChild);
addView(decorChild);
setContentView(decorChild);
decor.addView(this);
}
@Override
public void computeScroll() {
mScrimOpacity = 1 - mScrollPercent;
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private class ViewDragCallback extends ViewDragHelper.Callback {
private boolean mIsScrollOverValid;
@Override
public boolean tryCaptureView(View view, int i) {
boolean ret = mDragHelper.isEdgeTouched(mEdgeFlag, i);
if (ret) {
if (mDragHelper.isEdgeTouched(EDGE_LEFT, i)) {
mTrackingEdge = EDGE_LEFT;
} else if (mDragHelper.isEdgeTouched(EDGE_RIGHT, i)) {
mTrackingEdge = EDGE_RIGHT;
} else if (mDragHelper.isEdgeTouched(EDGE_BOTTOM, i)) {
mTrackingEdge = EDGE_BOTTOM;
}
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onEdgeTouch(mTrackingEdge);
}
}
mIsScrollOverValid = true;
}
return ret;
}
@Override
public int getViewHorizontalDragRange(View child) {
return mEdgeFlag & (EDGE_LEFT | EDGE_RIGHT);
}
@Override
public int getViewVerticalDragRange(View child) {
return mEdgeFlag & EDGE_BOTTOM;
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
super.onViewPositionChanged(changedView, left, top, dx, dy);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth()));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth() + mShadowRight.getIntrinsicWidth()));
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
mScrollPercent = Math.abs((float) top
/ (mContentView.getHeight() + mShadowBottom.getIntrinsicHeight()));
}
mContentLeft = left;
mContentTop = top;
invalidate();
if (mScrollPercent < mScrollThreshold && !mIsScrollOverValid) {
mIsScrollOverValid = true;
}
if (mListeners != null && !mListeners.isEmpty()
&& mDragHelper.getViewDragState() == STATE_DRAGGING
&& mScrollPercent >= mScrollThreshold && mIsScrollOverValid) {
mIsScrollOverValid = false;
for (SwipeListener listener : mListeners) {
listener.onScrollOverThreshold();
}
}
if (mScrollPercent >= 1) {
if (!mActivity.isFinishing())
mActivity.finish();
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final int childWidth = releasedChild.getWidth();
final int childHeight = releasedChild.getHeight();
int left = 0, top = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? childWidth
+ mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE : 0;
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? -(childWidth
+ mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight
+ mShadowBottom.getIntrinsicHeight() + OVERSCROLL_DISTANCE) : 0;
}
mDragHelper.settleCapturedViewAt(left, top);
invalidate();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int ret = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
ret = Math.min(child.getWidth(), Math.max(left, 0));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
ret = Math.min(0, Math.max(left, -child.getWidth()));
}
return ret;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
int ret = 0;
if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
ret = Math.min(0, Math.max(top, -child.getHeight()));
}
return ret;
}
@Override
public void onViewDragStateChanged(int state) {
super.onViewDragStateChanged(state);
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onScrollStateChange(state, mScrollPercent);
}
}
}
}
}
|
18737_11 | package linkedlist;
/**
* 1)单链表的插入、删除、查找操作;
* 2)链表中存储的是int类型的数据;
*
* Author:Zheng
*/
public class SinglyLinkedList {
private Node head = null;
public Node findByValue(int value) {
Node p = head;
while (p != null && p.data != value) {
p = p.next;
}
return p;
}
public Node findByIndex(int index) {
Node p = head;
int pos = 0;
while (p != null && pos != index) {
p = p.next;
++pos;
}
return p;
}
//无头结点
//表头部插入
//这种操作将于输入的顺序相反,逆序
public void insertToHead(int value) {
Node newNode = new Node(value, null);
insertToHead(newNode);
}
public void insertToHead(Node newNode) {
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
//顺序插入
//链表尾部插入
public void insertTail(int value){
Node newNode = new Node(value, null);
//空链表,可以插入新节点作为head,也可以不操作
if (head == null){
head = newNode;
}else{
Node q = head;
while(q.next != null){
q = q.next;
}
newNode.next = q.next;
q.next = newNode;
}
}
public void insertAfter(Node p, int value) {
Node newNode = new Node(value, null);
insertAfter(p, newNode);
}
public void insertAfter(Node p, Node newNode) {
if (p == null) return;
newNode.next = p.next;
p.next = newNode;
}
public void insertBefore(Node p, int value) {
Node newNode = new Node(value, null);
insertBefore(p, newNode);
}
public void insertBefore(Node p, Node newNode) {
if (p == null) return;
if (head == p) {
insertToHead(newNode);
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
newNode.next = p;
q.next = newNode;
}
public void deleteByNode(Node p) {
if (p == null || head == null) return;
if (p == head) {
head = head.next;
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
q.next = q.next.next;
}
public void deleteByValue(int value) {
if (head == null) return;
Node p = head;
Node q = null;
while (p != null && p.data != value) {
q = p;
p = p.next;
}
if (p == null) return;
if (q == null) {
head = head.next;
} else {
q.next = q.next.next;
}
// 可重复删除指定value的代码
/*
if (head != null && head.data == value) {
head = head.next;
}
Node pNode = head;
while (pNode != null) {
if (pNode.next.data == data) {
pNode.next = pNode.next.next;
continue;
}
pNode = pNode.next;
}
*/
}
public void printAll() {
Node p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
//判断true or false
public boolean TFResult(Node left, Node right){
Node l = left;
Node r = right;
boolean flag=true;
System.out.println("left_:"+l.data);
System.out.println("right_:"+r.data);
while(l != null && r != null){
if (l.data == r.data){
l = l.next;
r = r.next;
continue;
}else{
flag=false;
break;
}
}
System.out.println("什么结果");
return flag;
/* if (l==null && r==null){
System.out.println("什么结果");
return true;
}else{
return false;
}*/
}
// 判断是否为回文
public boolean palindrome(){
if (head == null){
return false;
}else{
System.out.println("开始执行找到中间节点");
Node p = head;
Node q = head;
if (p.next == null){
System.out.println("只有一个元素");
return true;
}
while( q.next != null && q.next.next != null){
p = p.next;
q = q.next.next;
}
System.out.println("中间节点" + p.data);
System.out.println("开始执行奇数节点的回文判断");
Node leftLink = null;
Node rightLink = null;
if(q.next == null){
// p 一定为整个链表的中点,且节点数目为奇数
rightLink = p.next;
leftLink = inverseLinkList(p).next;
System.out.println("左边第一个节点"+leftLink.data);
System.out.println("右边第一个节点"+rightLink.data);
}else{
//p q 均为中点
rightLink = p.next;
leftLink = inverseLinkList(p);
}
return TFResult(leftLink, rightLink);
}
}
//带结点的链表翻转
public Node inverseLinkList_head(Node p){
// Head 为新建的一个头结点
Node Head = new Node(9999,null);
// p 为原来整个链表的头结点,现在Head指向 整个链表
Head.next = p;
/*
带头结点的链表翻转等价于
从第二个元素开始重新头插法建立链表
*/
Node Cur = p.next;
p.next = null;
Node next = null;
while(Cur != null){
next = Cur.next;
Cur.next = Head.next;
Head.next = Cur;
System.out.println("first " + Head.data);
Cur = next;
}
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return Head;
}
//无头结点的链表翻转
public Node inverseLinkList(Node p){
Node pre = null;
Node r = head;
System.out.println("z---" + r.data);
Node next= null;
while(r !=p){
next = r.next;
r.next = pre;
pre = r;
r = next;
}
r.next = pre;
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return r;
}
public static Node createNode(int value) {
return new Node(value, null);
}
public static class Node {
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
public static void main(String[]args){
SinglyLinkedList link = new SinglyLinkedList();
System.out.println("hello");
//int data[] = {1};
//int data[] = {1,2};
//int data[] = {1,2,3,1};
//int data[] = {1,2,5};
//int data[] = {1,2,2,1};
// int data[] = {1,2,5,2,1};
int data[] = {1,2,5,3,1};
for(int i =0; i < data.length; i++){
//link.insertToHead(data[i]);
link.insertTail(data[i]);
}
// link.printAll();
// Node p = link.inverseLinkList_head(link.head);
// while(p != null){
// System.out.println("aa"+p.data);
// p = p.next;
// }
System.out.println("打印原始:");
link.printAll();
if (link.palindrome()){
System.out.println("回文");
}else{
System.out.println("不是回文");
}
}
}
| wangzheng0822/algo | java/06_linkedlist/SinglyLinkedList.java | 2,437 | // Node p = link.inverseLinkList_head(link.head); | line_comment | nl | package linkedlist;
/**
* 1)单链表的插入、删除、查找操作;
* 2)链表中存储的是int类型的数据;
*
* Author:Zheng
*/
public class SinglyLinkedList {
private Node head = null;
public Node findByValue(int value) {
Node p = head;
while (p != null && p.data != value) {
p = p.next;
}
return p;
}
public Node findByIndex(int index) {
Node p = head;
int pos = 0;
while (p != null && pos != index) {
p = p.next;
++pos;
}
return p;
}
//无头结点
//表头部插入
//这种操作将于输入的顺序相反,逆序
public void insertToHead(int value) {
Node newNode = new Node(value, null);
insertToHead(newNode);
}
public void insertToHead(Node newNode) {
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
//顺序插入
//链表尾部插入
public void insertTail(int value){
Node newNode = new Node(value, null);
//空链表,可以插入新节点作为head,也可以不操作
if (head == null){
head = newNode;
}else{
Node q = head;
while(q.next != null){
q = q.next;
}
newNode.next = q.next;
q.next = newNode;
}
}
public void insertAfter(Node p, int value) {
Node newNode = new Node(value, null);
insertAfter(p, newNode);
}
public void insertAfter(Node p, Node newNode) {
if (p == null) return;
newNode.next = p.next;
p.next = newNode;
}
public void insertBefore(Node p, int value) {
Node newNode = new Node(value, null);
insertBefore(p, newNode);
}
public void insertBefore(Node p, Node newNode) {
if (p == null) return;
if (head == p) {
insertToHead(newNode);
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
newNode.next = p;
q.next = newNode;
}
public void deleteByNode(Node p) {
if (p == null || head == null) return;
if (p == head) {
head = head.next;
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
q.next = q.next.next;
}
public void deleteByValue(int value) {
if (head == null) return;
Node p = head;
Node q = null;
while (p != null && p.data != value) {
q = p;
p = p.next;
}
if (p == null) return;
if (q == null) {
head = head.next;
} else {
q.next = q.next.next;
}
// 可重复删除指定value的代码
/*
if (head != null && head.data == value) {
head = head.next;
}
Node pNode = head;
while (pNode != null) {
if (pNode.next.data == data) {
pNode.next = pNode.next.next;
continue;
}
pNode = pNode.next;
}
*/
}
public void printAll() {
Node p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
//判断true or false
public boolean TFResult(Node left, Node right){
Node l = left;
Node r = right;
boolean flag=true;
System.out.println("left_:"+l.data);
System.out.println("right_:"+r.data);
while(l != null && r != null){
if (l.data == r.data){
l = l.next;
r = r.next;
continue;
}else{
flag=false;
break;
}
}
System.out.println("什么结果");
return flag;
/* if (l==null && r==null){
System.out.println("什么结果");
return true;
}else{
return false;
}*/
}
// 判断是否为回文
public boolean palindrome(){
if (head == null){
return false;
}else{
System.out.println("开始执行找到中间节点");
Node p = head;
Node q = head;
if (p.next == null){
System.out.println("只有一个元素");
return true;
}
while( q.next != null && q.next.next != null){
p = p.next;
q = q.next.next;
}
System.out.println("中间节点" + p.data);
System.out.println("开始执行奇数节点的回文判断");
Node leftLink = null;
Node rightLink = null;
if(q.next == null){
// p 一定为整个链表的中点,且节点数目为奇数
rightLink = p.next;
leftLink = inverseLinkList(p).next;
System.out.println("左边第一个节点"+leftLink.data);
System.out.println("右边第一个节点"+rightLink.data);
}else{
//p q 均为中点
rightLink = p.next;
leftLink = inverseLinkList(p);
}
return TFResult(leftLink, rightLink);
}
}
//带结点的链表翻转
public Node inverseLinkList_head(Node p){
// Head 为新建的一个头结点
Node Head = new Node(9999,null);
// p 为原来整个链表的头结点,现在Head指向 整个链表
Head.next = p;
/*
带头结点的链表翻转等价于
从第二个元素开始重新头插法建立链表
*/
Node Cur = p.next;
p.next = null;
Node next = null;
while(Cur != null){
next = Cur.next;
Cur.next = Head.next;
Head.next = Cur;
System.out.println("first " + Head.data);
Cur = next;
}
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return Head;
}
//无头结点的链表翻转
public Node inverseLinkList(Node p){
Node pre = null;
Node r = head;
System.out.println("z---" + r.data);
Node next= null;
while(r !=p){
next = r.next;
r.next = pre;
pre = r;
r = next;
}
r.next = pre;
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return r;
}
public static Node createNode(int value) {
return new Node(value, null);
}
public static class Node {
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
public static void main(String[]args){
SinglyLinkedList link = new SinglyLinkedList();
System.out.println("hello");
//int data[] = {1};
//int data[] = {1,2};
//int data[] = {1,2,3,1};
//int data[] = {1,2,5};
//int data[] = {1,2,2,1};
// int data[] = {1,2,5,2,1};
int data[] = {1,2,5,3,1};
for(int i =0; i < data.length; i++){
//link.insertToHead(data[i]);
link.insertTail(data[i]);
}
// link.printAll();
// Node p<SUF>
// while(p != null){
// System.out.println("aa"+p.data);
// p = p.next;
// }
System.out.println("打印原始:");
link.printAll();
if (link.palindrome()){
System.out.println("回文");
}else{
System.out.println("不是回文");
}
}
}
|
78672_0 | package be.cegeka.stickyprint.core;
import be.cegeka.stickyprint.core.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
@Service
public class PrintingApplicationServiceImpl implements PrintingApplicationService {
@Autowired
private Printer printer;
@Autowired
private ImageRenderService imageRenderService;
static {
System.setProperty("com.sun.media.jai.disableMediaLib", "true");
}
//de volgende waarden zijn "good enough" voor 58mm papier, vooral gevonden door trail&error
public static final int FONT_SIZE = 200;
public static final int LIJN1_OFFSET = 40;
public static final int LIJN2_OFFSET = 42;
public static final Font FONT = new Font("SansSerif", Font.PLAIN, FONT_SIZE);
@Override
public PrintingResult print(PrintTask printTask) {
BufferedImage imageToPrint = createBitmap(printTask.getFirstLine(), printTask.getSecondLine());
printer.print(imageToPrint);
return new PrintingResult();
}
@Override
public ImageRenderResult print(HtmlSnippet htmlSnippet, PaperHeight paperHeight, PaperWidth paperWidth) {
ImageRenderResult imageRenderResult = imageRenderService.renderImage(htmlSnippet, paperHeight, paperWidth);
printer.print(rotate90DX(imageRenderResult.getResult()));
return imageRenderResult;
}
public BufferedImage createBitmap(PrintLine lijn1, PrintLine lijn2) {
int imgHeight = Printer.HEIGHT_58MM;
int imgWidth = getMinimumWidth(Printer.WIDTH_120MM, lijn1);
imgWidth = getMinimumWidth(imgWidth, lijn2);
BufferedImage img = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, imgWidth, imgHeight);
g2.setColor(Color.black);
g2.setFont(FONT);
g2.drawString(lijn1.getLineToPrint(),0 ,(imgHeight/2)- LIJN1_OFFSET);
g2.drawString(lijn2.getLineToPrint(),0,imgHeight- LIJN2_OFFSET);
return rotate90DX(img);
}
private static BufferedImage rotate90DX(BufferedImage src) {
int newWidth = src.getHeight();
int newHeight = src.getWidth();
AffineTransform transform = new AffineTransform();
transform.translate(newWidth, 0);
transform.rotate(Math.toRadians(90));
BufferedImage result = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = result.createGraphics();
g2d.drawImage(src, transform, null);
g2d.dispose();
return result;
}
static int getMinimumWidth(int currentWidth, PrintLine lijn) {
BufferedImage dummyImg = new BufferedImage(10000,400,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2 = dummyImg.createGraphics();
FontRenderContext fontRenderContext = g2.getFontRenderContext();
Rectangle2D stringBounds = FONT.getStringBounds(lijn.getLineToPrint(), fontRenderContext);
int width = Math.max(currentWidth,(int)stringBounds.getWidth()+20);
return width;
}
}
| wannessels/stickyprint | stickyprint-core/src/main/java/be/cegeka/stickyprint/core/PrintingApplicationServiceImpl.java | 1,021 | //de volgende waarden zijn "good enough" voor 58mm papier, vooral gevonden door trail&error | line_comment | nl | package be.cegeka.stickyprint.core;
import be.cegeka.stickyprint.core.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
@Service
public class PrintingApplicationServiceImpl implements PrintingApplicationService {
@Autowired
private Printer printer;
@Autowired
private ImageRenderService imageRenderService;
static {
System.setProperty("com.sun.media.jai.disableMediaLib", "true");
}
//de volgende<SUF>
public static final int FONT_SIZE = 200;
public static final int LIJN1_OFFSET = 40;
public static final int LIJN2_OFFSET = 42;
public static final Font FONT = new Font("SansSerif", Font.PLAIN, FONT_SIZE);
@Override
public PrintingResult print(PrintTask printTask) {
BufferedImage imageToPrint = createBitmap(printTask.getFirstLine(), printTask.getSecondLine());
printer.print(imageToPrint);
return new PrintingResult();
}
@Override
public ImageRenderResult print(HtmlSnippet htmlSnippet, PaperHeight paperHeight, PaperWidth paperWidth) {
ImageRenderResult imageRenderResult = imageRenderService.renderImage(htmlSnippet, paperHeight, paperWidth);
printer.print(rotate90DX(imageRenderResult.getResult()));
return imageRenderResult;
}
public BufferedImage createBitmap(PrintLine lijn1, PrintLine lijn2) {
int imgHeight = Printer.HEIGHT_58MM;
int imgWidth = getMinimumWidth(Printer.WIDTH_120MM, lijn1);
imgWidth = getMinimumWidth(imgWidth, lijn2);
BufferedImage img = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, imgWidth, imgHeight);
g2.setColor(Color.black);
g2.setFont(FONT);
g2.drawString(lijn1.getLineToPrint(),0 ,(imgHeight/2)- LIJN1_OFFSET);
g2.drawString(lijn2.getLineToPrint(),0,imgHeight- LIJN2_OFFSET);
return rotate90DX(img);
}
private static BufferedImage rotate90DX(BufferedImage src) {
int newWidth = src.getHeight();
int newHeight = src.getWidth();
AffineTransform transform = new AffineTransform();
transform.translate(newWidth, 0);
transform.rotate(Math.toRadians(90));
BufferedImage result = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = result.createGraphics();
g2d.drawImage(src, transform, null);
g2d.dispose();
return result;
}
static int getMinimumWidth(int currentWidth, PrintLine lijn) {
BufferedImage dummyImg = new BufferedImage(10000,400,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2 = dummyImg.createGraphics();
FontRenderContext fontRenderContext = g2.getFontRenderContext();
Rectangle2D stringBounds = FONT.getStringBounds(lijn.getLineToPrint(), fontRenderContext);
int width = Math.max(currentWidth,(int)stringBounds.getWidth()+20);
return width;
}
}
|
87108_4 | /**
* Author : wardb
* naam : Ward Beyens
* studentNr : r0703044
*/
package fact.it.www;
import fact.it.www.beans.Attractie;
import fact.it.www.beans.Bezoeker;
import fact.it.www.beans.Personeelslid;
import fact.it.www.beans.Persoon;
import fact.it.www.beans.Pretpark;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Author : wardb
* naam : Ward Beyens
* studentNr : r0703044
*/
@WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"})
public class ManageServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Personeelslid personeelslidEerste = new Personeelslid("Gertje", "Optnippertje");
Personeelslid personeelslidTweede = new Personeelslid("Thibaut", "Defrisco");
Personeelslid personeelslidDerde = new Personeelslid("Knapen", "Dokter");
Bezoeker bezoeker_1 = new Bezoeker("Noor", "Baeyens");
bezoeker_1.voegToeAanWishlist("Symbolica");
bezoeker_1.voegToeAanWishlist("Droomvlucht");
bezoeker_1.voegToeAanWishlist("Carnaval Festival");
bezoeker_1.voegToeAanWishlist("Fata Morgana");
bezoeker_1.voegToeAanWishlist("Sprookjesbos");
bezoeker_1.setPretparkcode(50);
Bezoeker bezoeker_2 = new Bezoeker("Ward", "Beyens");
bezoeker_2.voegToeAanWishlist("Baron 1898");
bezoeker_2.voegToeAanWishlist("Python");
bezoeker_2.voegToeAanWishlist("De Vliegende Hollander");
bezoeker_2.voegToeAanWishlist("Joris en de Draak");
bezoeker_2.voegToeAanWishlist("Fata Morgana");
bezoeker_2.setPretparkcode(100);
Persoon persoon = new Persoon("Ryan", "Reynolds");
Pretpark pretpark = new Pretpark("Magneto");
Attractie attractieEerste = new Attractie("Python", 3);
attractieEerste.setVerantwoordelijke(personeelslidEerste);
Attractie attractieTweede = new Attractie("Symbolica", 6);
attractieTweede.setVerantwoordelijke(personeelslidTweede);
Attractie attractieDerde = new Attractie("Fata Morgana", 10);
attractieDerde.setVerantwoordelijke(personeelslidDerde);
pretpark.voegAttractieToe(attractieEerste);
pretpark.voegAttractieToe(attractieTweede);
pretpark.voegAttractieToe(attractieDerde);
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Ward beyens</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Pretpark: " + pretpark.getNaam() + " </h1>");
out.println("<h3> Attracties: </h3>");
/*
out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + attractieEerste.getFoto()+ " </p>");
out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + attractieTweede.getFoto()+ " </p>");
out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + attractieDerde.getFoto()+ " </p>");
*/
out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + " </p>");
out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + " </p>");
out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + " </p>");
out.println("<h3> Bezoekers: </h3>");
out.println("<p> " + bezoeker_1.toString() + " heeft als wishlist: " + " <br> ");
for (int i = 0; i < 5; i++) {
out.print(bezoeker_1.getWishlist().get(i) + " ");
}
out.println("</p>");
out.println("<p> " + bezoeker_2.toString() + " heeft als wishlist: " + " <br> ");
for (int i = 0; i < 5; i++) {
out.print(bezoeker_2.getWishlist().get(i) + " ");
}
out.println("</p>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| wardbeyens/miniproject-java | Beyens_Ward_r0703044_Pretpark/src/java/fact/it/www/ManageServlet.java | 2,071 | /*
out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + attractieEerste.getFoto()+ " </p>");
out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + attractieTweede.getFoto()+ " </p>");
out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + attractieDerde.getFoto()+ " </p>");
*/ | block_comment | nl | /**
* Author : wardb
* naam : Ward Beyens
* studentNr : r0703044
*/
package fact.it.www;
import fact.it.www.beans.Attractie;
import fact.it.www.beans.Bezoeker;
import fact.it.www.beans.Personeelslid;
import fact.it.www.beans.Persoon;
import fact.it.www.beans.Pretpark;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Author : wardb
* naam : Ward Beyens
* studentNr : r0703044
*/
@WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"})
public class ManageServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Personeelslid personeelslidEerste = new Personeelslid("Gertje", "Optnippertje");
Personeelslid personeelslidTweede = new Personeelslid("Thibaut", "Defrisco");
Personeelslid personeelslidDerde = new Personeelslid("Knapen", "Dokter");
Bezoeker bezoeker_1 = new Bezoeker("Noor", "Baeyens");
bezoeker_1.voegToeAanWishlist("Symbolica");
bezoeker_1.voegToeAanWishlist("Droomvlucht");
bezoeker_1.voegToeAanWishlist("Carnaval Festival");
bezoeker_1.voegToeAanWishlist("Fata Morgana");
bezoeker_1.voegToeAanWishlist("Sprookjesbos");
bezoeker_1.setPretparkcode(50);
Bezoeker bezoeker_2 = new Bezoeker("Ward", "Beyens");
bezoeker_2.voegToeAanWishlist("Baron 1898");
bezoeker_2.voegToeAanWishlist("Python");
bezoeker_2.voegToeAanWishlist("De Vliegende Hollander");
bezoeker_2.voegToeAanWishlist("Joris en de Draak");
bezoeker_2.voegToeAanWishlist("Fata Morgana");
bezoeker_2.setPretparkcode(100);
Persoon persoon = new Persoon("Ryan", "Reynolds");
Pretpark pretpark = new Pretpark("Magneto");
Attractie attractieEerste = new Attractie("Python", 3);
attractieEerste.setVerantwoordelijke(personeelslidEerste);
Attractie attractieTweede = new Attractie("Symbolica", 6);
attractieTweede.setVerantwoordelijke(personeelslidTweede);
Attractie attractieDerde = new Attractie("Fata Morgana", 10);
attractieDerde.setVerantwoordelijke(personeelslidDerde);
pretpark.voegAttractieToe(attractieEerste);
pretpark.voegAttractieToe(attractieTweede);
pretpark.voegAttractieToe(attractieDerde);
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Ward beyens</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Pretpark: " + pretpark.getNaam() + " </h1>");
out.println("<h3> Attracties: </h3>");
/*
out.println("<p> " +<SUF>*/
out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + " </p>");
out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + " </p>");
out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + " </p>");
out.println("<h3> Bezoekers: </h3>");
out.println("<p> " + bezoeker_1.toString() + " heeft als wishlist: " + " <br> ");
for (int i = 0; i < 5; i++) {
out.print(bezoeker_1.getWishlist().get(i) + " ");
}
out.println("</p>");
out.println("<p> " + bezoeker_2.toString() + " heeft als wishlist: " + " <br> ");
for (int i = 0; i < 5; i++) {
out.print(bezoeker_2.getWishlist().get(i) + " ");
}
out.println("</p>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
20602_2 | import java.util.*;
import java.util.stream.*;
import java.lang.Math;
import java.lang.Exception;
public class PrefixTreeApp {
// returns up to n candidates start with given prefix
public static <T> List<Map.Entry<String, T>> lookup(PrefixTree.Node<T> t,
String key, int n) {
if (t == null)
return Collections.emptyList();
String prefix = "";
boolean match;
do {
match = false;
for (Map.Entry<String, PrefixTree.Node<T>> entry : t.subTrees.entrySet()) {
String k = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (k.startsWith(key)) { // key is prefix of k
return expand(prefix + k, tr, n);
}
if (key.startsWith(k)) {
match = true;
key = key.substring(k.length());
t = tr;
prefix = prefix + k;
break;
}
}
} while (match);
return Collections.emptyList();
}
static <T> List<Map.Entry<String, T>> expand(String prefix, PrefixTree.Node<T> t, int n) {
List<Map.Entry<String, T>> res = new ArrayList<>();
Queue<Map.Entry<String, PrefixTree.Node<T> >> q = new LinkedList<>();
q.offer(entryOf(prefix, t));
while(res.size() < n && !q.isEmpty()) {
Map.Entry<String, PrefixTree.Node<T>> entry = q.poll();
String s = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (tr.value.isPresent()) {
res.add(entryOf(s, tr.value.get()));
}
for (Map.Entry<String, PrefixTree.Node<T>> e :
new TreeMap<>(tr.subTrees).entrySet()) {
q.offer(entryOf(s + e.getKey(), e.getValue()));
}
}
return res;
}
static <K, V> Map.Entry<K, V> entryOf(K key, V val) {
return new AbstractMap.SimpleImmutableEntry<K, V>(key, val);
}
// T9 map
static final Map<Character, String> MAP_T9 = new HashMap<Character, String>(){{
put('1', ",."); put('2', "abc"); put('3', "def");
put('4', "ghi"); put('5', "jkl"); put('6', "mno");
put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");
}};
// T9 reverse map
static final Map<Character, Character> RMAP_T9 = new HashMap<Character, Character>(){{
for (Character d : MAP_T9.keySet()) {
String cs = MAP_T9.get(d);
for (int i = 0; i < cs.length(); ++i)
put(cs.charAt(i), d);
}
}};
/*
* The T9 reverse map can be built with stream, but it's hard to read
*
* static final Map<Character, Character> RMAP_T9 = MAP_T9.entrySet().stream()
* .flatMap(e -> e.getValue().chars().mapToObj(i -> (char)i)
* .map(c -> entryOf(c, e.getKey())))
* .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
*/
public static String digits(String w) {
StringBuilder d = new StringBuilder();
for(int i = 0; i < w.length(); ++i)
d.append(RMAP_T9.get(w.charAt(i)));
return d.toString();
}
static class Tuple<T> {
String prefix;
String key;
PrefixTree.Node<T> tree;
Tuple(String p, String k, PrefixTree.Node<T> t) {
prefix = p; key = k; tree = t;
}
public static <T> Tuple<T> of(String prefix, String key,
PrefixTree.Node<T> tree) {
return new Tuple<T>(prefix, key, tree);
}
}
static String limit(int n, String s) {
return s.substring(0, Math.min(n, s.length()));
}
public static <T> List<String> lookupT9(PrefixTree.Node<T> t, String key) {
List<String> res = new ArrayList<>();
if (t == null || key.isEmpty())
return res;
Queue<Tuple<T>> q = new LinkedList<>();
q.offer(Tuple.of("", key, t));
while (!q.isEmpty()) {
Tuple<T> elem = q.poll();
for (Map.Entry<String, PrefixTree.Node<T>> e :
elem.tree.subTrees.entrySet()) {
String k = e.getKey();
String ds = digits(k);
if (ds.startsWith(elem.key)) {
res.add(limit(key.length(), elem.prefix + k));
} else if (elem.key.startsWith(ds)) {
q.offer(Tuple.of(elem.prefix + k,
elem.key.substring(k.length()),
e.getValue()));
}
}
}
return res;
}
public static class Test {
final static String[] testKeys =
new String[]{"a", "an", "another", "abandon", "about", "adam", "boy", "body", "zoo"};
final static String[] testVals =
new String[]{"the first letter of English",
"used instead of 'a' when the following word begins witha vowel sound",
"one more person or thing or an extra amount",
"to leave a place, thing or person forever",
"on the subject of; connected with",
"a character in the Bible who was the first man made by God",
"a male child or, more generally, a male of any age",
"the whole physical structure that forms a person or animal",
"an area in which animals, especially wild animals, are kept so that people can go and look at them, or study them"};
static void testEdict() {
PrefixTree.Node<String> t = null;
Map<String, String> m = new HashMap<>();
int n = Math.min(testKeys.length, testVals.length);
for (int i = 0; i < n; ++i) {
t = PrefixTree.insert(t, testKeys[i], testVals[i]);
m.put(testKeys[i], testVals[i]);
}
verifyLookup(m, t, "a", 5);
verifyLookup(m, t, "a", 6);
verifyLookup(m, t, "a", 7);
verifyLookup(m, t, "ab", 2);
verifyLookup(m, t, "ab", 5);
verifyLookup(m, t, "b", 2);
verifyLookup(m, t, "bo", 5);
verifyLookup(m, t, "z", 3);
}
static void verifyLookup(Map<String, String> m, PrefixTree.Node<String> t, String key, int n) {
System.out.format("lookup %s with limit: %d\n", key, n);
SortedMap<String, String> m1 = new TreeMap<>();
for (Map.Entry<String, String> e : lookup(t, key, n)) {
m1.put(e.getKey(), e.getValue());
}
SortedMap<String, String> m2 =
take(n, toSortedMap(m.entrySet().stream()
.filter(e -> e.getKey().startsWith(key))));
if (!m2.equals(m1))
throw new RuntimeException("\n" + m1.toString() + "\n!=\n" + m2.toString());
System.out.println("result:\n" + m1.toString());
}
static <T> SortedMap<String, T> take(int n, SortedMap<String, T> m) {
return toSortedMap(m.entrySet().stream().limit(n));
}
static <K, V> SortedMap<K, V> toSortedMap(Stream<Map.Entry<K, V>> s) {
return new TreeMap<>(s.collect(Collectors.toMap(e -> e.getKey(), e ->e.getValue())));
}
public static void testT9() {
//System.out.println("T9 map: " + MAP_T9);
//System.out.println("reverse T9 map: " + RMAP_T9);
final String txt = "home good gone hood a another an";
final String[] words = txt.split("\\W+");
PrefixTree.Node<Integer> t = PrefixTree.fromString(txt);
for (String testDigits : new String[]{"4663", "22", "2668437"}) {
for (int i = 1; i <= testDigits.length(); ++i) {
String ds = limit(i, testDigits);
SortedSet<String> as = new TreeSet<>(lookupT9(t, ds));
SortedSet<String> bs = new TreeSet<>();
for (String w : words) {
String candidate = limit(i, w);
if (digits(candidate).equals(ds))
bs.add(candidate);
}
//System.out.println("T9 look up: " + as);
//System.out.println("Brute force:" + bs);
if (!as.equals(bs))
throw new RuntimeException("T9 look up " + as + "\n!=\n" +
"Brute force" + bs + "\n");
}
}
System.out.println("T9 verified");
}
public static void test() {
testEdict();
testT9();
}
}
}
| warmchang/AlgoXY-algorithms | datastruct/tree/trie/src/PrefixTreeApp.java | 2,711 | // T9 reverse map | line_comment | nl | import java.util.*;
import java.util.stream.*;
import java.lang.Math;
import java.lang.Exception;
public class PrefixTreeApp {
// returns up to n candidates start with given prefix
public static <T> List<Map.Entry<String, T>> lookup(PrefixTree.Node<T> t,
String key, int n) {
if (t == null)
return Collections.emptyList();
String prefix = "";
boolean match;
do {
match = false;
for (Map.Entry<String, PrefixTree.Node<T>> entry : t.subTrees.entrySet()) {
String k = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (k.startsWith(key)) { // key is prefix of k
return expand(prefix + k, tr, n);
}
if (key.startsWith(k)) {
match = true;
key = key.substring(k.length());
t = tr;
prefix = prefix + k;
break;
}
}
} while (match);
return Collections.emptyList();
}
static <T> List<Map.Entry<String, T>> expand(String prefix, PrefixTree.Node<T> t, int n) {
List<Map.Entry<String, T>> res = new ArrayList<>();
Queue<Map.Entry<String, PrefixTree.Node<T> >> q = new LinkedList<>();
q.offer(entryOf(prefix, t));
while(res.size() < n && !q.isEmpty()) {
Map.Entry<String, PrefixTree.Node<T>> entry = q.poll();
String s = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (tr.value.isPresent()) {
res.add(entryOf(s, tr.value.get()));
}
for (Map.Entry<String, PrefixTree.Node<T>> e :
new TreeMap<>(tr.subTrees).entrySet()) {
q.offer(entryOf(s + e.getKey(), e.getValue()));
}
}
return res;
}
static <K, V> Map.Entry<K, V> entryOf(K key, V val) {
return new AbstractMap.SimpleImmutableEntry<K, V>(key, val);
}
// T9 map
static final Map<Character, String> MAP_T9 = new HashMap<Character, String>(){{
put('1', ",."); put('2', "abc"); put('3', "def");
put('4', "ghi"); put('5', "jkl"); put('6', "mno");
put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");
}};
// T9 reverse<SUF>
static final Map<Character, Character> RMAP_T9 = new HashMap<Character, Character>(){{
for (Character d : MAP_T9.keySet()) {
String cs = MAP_T9.get(d);
for (int i = 0; i < cs.length(); ++i)
put(cs.charAt(i), d);
}
}};
/*
* The T9 reverse map can be built with stream, but it's hard to read
*
* static final Map<Character, Character> RMAP_T9 = MAP_T9.entrySet().stream()
* .flatMap(e -> e.getValue().chars().mapToObj(i -> (char)i)
* .map(c -> entryOf(c, e.getKey())))
* .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
*/
public static String digits(String w) {
StringBuilder d = new StringBuilder();
for(int i = 0; i < w.length(); ++i)
d.append(RMAP_T9.get(w.charAt(i)));
return d.toString();
}
static class Tuple<T> {
String prefix;
String key;
PrefixTree.Node<T> tree;
Tuple(String p, String k, PrefixTree.Node<T> t) {
prefix = p; key = k; tree = t;
}
public static <T> Tuple<T> of(String prefix, String key,
PrefixTree.Node<T> tree) {
return new Tuple<T>(prefix, key, tree);
}
}
static String limit(int n, String s) {
return s.substring(0, Math.min(n, s.length()));
}
public static <T> List<String> lookupT9(PrefixTree.Node<T> t, String key) {
List<String> res = new ArrayList<>();
if (t == null || key.isEmpty())
return res;
Queue<Tuple<T>> q = new LinkedList<>();
q.offer(Tuple.of("", key, t));
while (!q.isEmpty()) {
Tuple<T> elem = q.poll();
for (Map.Entry<String, PrefixTree.Node<T>> e :
elem.tree.subTrees.entrySet()) {
String k = e.getKey();
String ds = digits(k);
if (ds.startsWith(elem.key)) {
res.add(limit(key.length(), elem.prefix + k));
} else if (elem.key.startsWith(ds)) {
q.offer(Tuple.of(elem.prefix + k,
elem.key.substring(k.length()),
e.getValue()));
}
}
}
return res;
}
public static class Test {
final static String[] testKeys =
new String[]{"a", "an", "another", "abandon", "about", "adam", "boy", "body", "zoo"};
final static String[] testVals =
new String[]{"the first letter of English",
"used instead of 'a' when the following word begins witha vowel sound",
"one more person or thing or an extra amount",
"to leave a place, thing or person forever",
"on the subject of; connected with",
"a character in the Bible who was the first man made by God",
"a male child or, more generally, a male of any age",
"the whole physical structure that forms a person or animal",
"an area in which animals, especially wild animals, are kept so that people can go and look at them, or study them"};
static void testEdict() {
PrefixTree.Node<String> t = null;
Map<String, String> m = new HashMap<>();
int n = Math.min(testKeys.length, testVals.length);
for (int i = 0; i < n; ++i) {
t = PrefixTree.insert(t, testKeys[i], testVals[i]);
m.put(testKeys[i], testVals[i]);
}
verifyLookup(m, t, "a", 5);
verifyLookup(m, t, "a", 6);
verifyLookup(m, t, "a", 7);
verifyLookup(m, t, "ab", 2);
verifyLookup(m, t, "ab", 5);
verifyLookup(m, t, "b", 2);
verifyLookup(m, t, "bo", 5);
verifyLookup(m, t, "z", 3);
}
static void verifyLookup(Map<String, String> m, PrefixTree.Node<String> t, String key, int n) {
System.out.format("lookup %s with limit: %d\n", key, n);
SortedMap<String, String> m1 = new TreeMap<>();
for (Map.Entry<String, String> e : lookup(t, key, n)) {
m1.put(e.getKey(), e.getValue());
}
SortedMap<String, String> m2 =
take(n, toSortedMap(m.entrySet().stream()
.filter(e -> e.getKey().startsWith(key))));
if (!m2.equals(m1))
throw new RuntimeException("\n" + m1.toString() + "\n!=\n" + m2.toString());
System.out.println("result:\n" + m1.toString());
}
static <T> SortedMap<String, T> take(int n, SortedMap<String, T> m) {
return toSortedMap(m.entrySet().stream().limit(n));
}
static <K, V> SortedMap<K, V> toSortedMap(Stream<Map.Entry<K, V>> s) {
return new TreeMap<>(s.collect(Collectors.toMap(e -> e.getKey(), e ->e.getValue())));
}
public static void testT9() {
//System.out.println("T9 map: " + MAP_T9);
//System.out.println("reverse T9 map: " + RMAP_T9);
final String txt = "home good gone hood a another an";
final String[] words = txt.split("\\W+");
PrefixTree.Node<Integer> t = PrefixTree.fromString(txt);
for (String testDigits : new String[]{"4663", "22", "2668437"}) {
for (int i = 1; i <= testDigits.length(); ++i) {
String ds = limit(i, testDigits);
SortedSet<String> as = new TreeSet<>(lookupT9(t, ds));
SortedSet<String> bs = new TreeSet<>();
for (String w : words) {
String candidate = limit(i, w);
if (digits(candidate).equals(ds))
bs.add(candidate);
}
//System.out.println("T9 look up: " + as);
//System.out.println("Brute force:" + bs);
if (!as.equals(bs))
throw new RuntimeException("T9 look up " + as + "\n!=\n" +
"Brute force" + bs + "\n");
}
}
System.out.println("T9 verified");
}
public static void test() {
testEdict();
testT9();
}
}
}
|
77246_31 | /**
* Author: [email protected]
* <p>
* Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
* <p>
* http://aws.amazon.com/apache2.0/
* <p>
* or in the "license" file accompanying this file. This file 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 naoremote;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazon.speech.slu.Intent;
import com.amazon.speech.speechlet.IntentRequest;
import com.amazon.speech.speechlet.LaunchRequest;
import com.amazon.speech.speechlet.Session;
import com.amazon.speech.speechlet.SessionEndedRequest;
import com.amazon.speech.speechlet.SessionStartedRequest;
import com.amazon.speech.speechlet.Speechlet;
import com.amazon.speech.speechlet.SpeechletException;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.Reprompt;
import com.amazon.speech.ui.SimpleCard;
import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.amazonaws.util.json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import naoremote.ZeroClient;
/**
* This class implements an Alexa Skill that finds available meals based on the
* desired day and kind of food (vital, vegetarian, meal of the day ...)
*/
public class NaoSpeechlet implements Speechlet {
private static final Logger log = LoggerFactory.getLogger(NaoSpeechlet.class);
private ZeroClient zc = new ZeroClient();
@Override
public void onSessionStarted(final SessionStartedRequest request, final Session session) throws SpeechletException {
log.info("onSessionStarted requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
}
@Override
public SpeechletResponse onLaunch(final LaunchRequest request, final Session session) throws SpeechletException {
log.info("onLaunch requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
return getNewWelcomeResponse();
}
@Override
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException {
log.info("onIntent requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
Intent intent = request.getIntent();
String intentName = (intent != null) ? intent.getName() : null;
String cmd = "";
if ("GetNewNaoIntent".equals(intentName)) {
if (intent.getSlot("Cmd") != null && intent.getSlot("Cmd").getValue() != null) {
cmd = intent.getSlot("Cmd").getValue().toLowerCase();
} else {
cmd = "unknown";
}
}
if ("GetNewNaoIntent".equals(intentName)) {
return getNewNaoResponse(cmd);
} else if ("AMAZON.HelpIntent".equals(intentName)) {
return getHelpResponse();
} else if ("AMAZON.StopIntent".equals(intentName)) {
PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech();
outputSpeech.setText("Goodbye");
return SpeechletResponse.newTellResponse(outputSpeech);
} else if ("AMAZON.CancelIntent".equals(intentName)) {
PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech();
outputSpeech.setText("Goodbye");
return SpeechletResponse.newTellResponse(outputSpeech);
} else {
throw new SpeechletException("Invalid Intent");
}
}
@Override
public void onSessionEnded(final SessionEndedRequest request, final Session session) throws SpeechletException {
log.info("onSessionEnded requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
}
/**
* Generate a String response based on the current slots.
* The mensa plan is provided as JSON on the web.
* @return String
* @param day The desired day of the week
* @param kind The desired menue, e.g., vital, vegetarian, etc.
* @throws IOException
* @see "https://raw.githubusercontent.com/warp1337/ubmensa2json/master/ub_mensa.json"
*/
// private String getMensaPlan(String day, String kind) {
//
// String answer = " ";
// InputStreamReader inputStream = null;
// BufferedReader bufferedReader = null;
// StringBuilder builder = new StringBuilder();
//
// if ("entwickler".equals(day)) {
// return "Florian Lier. Er hat diese Applikation geschrieben. Netter Typ. Ehrlich.";
// }
//
// if ("sonntag".equals(day) || "samstag".equals(day) || "gibt es nicht".equals(day)) {
// return "Easter eggs!";
// }
//
// if ("aktion".equals(kind)) {
// kind = "aktions theke";
// }
//
// if ("vegetarisches".equals(kind)) {
// kind = "vegetarisch";
// }
//
// if ("vital menue".equals(kind)) {
// kind = "vital";
// }
//
// try {
// String line;
// URL url = new URL("https://raw.githubusercontent.com/warp1337/ubmensa2json/master/ub_mensa.json");
// inputStream = new InputStreamReader(url.openStream(), Charset.forName("utf-8"));
// bufferedReader = new BufferedReader(inputStream);
// while ((line = bufferedReader.readLine()) != null) {
// builder.append(line);
// }
// } catch (IOException e) {
// builder.setLength(0);
// } finally {
// IOUtils.closeQuietly(inputStream);
// IOUtils.closeQuietly(bufferedReader);
// }
//
// if (builder.length() == 0) {
// answer = "Entschuldigung, ich konnte keine Informationen zu " + kind + " und " + day + " im Internet finden.";
// } else {
//
// try {
// JSONObject MensaResponseObject = new JSONObject(new JSONTokener(builder.toString()));
//
// if (MensaResponseObject != null) {
//
// JSONArray data = (JSONArray) MensaResponseObject.get(day);
//
// for (int i = 0; i < data.length(); i++) {
// JSONObject item = (JSONObject) data.get(i);
// if (item.has(kind)) {
// answer = item.get(kind).toString();
// }
// }
// }
// } catch (JSONException e) {
// answer = "Entschuldigung, ich konnte keine Informationen im Mensa Plan zu " + kind + " und " + day + " finden.";
// }
// }
//
// return answer;
// }
/**
* Generate a response based on the current slots.
* The mensa plan is provided as JSON on the web.
* @return SpeechletResponse
* @param day The desired day of the week
* @param menue The desired menue, e.g., vital, vegetarian, etc.
*/
private SpeechletResponse getNewNaoResponse(String cmd) {
String speechText = cmd;
speechText = zc.ZSend(cmd);
SimpleCard card = new SimpleCard();
card.setTitle("Nao");
card.setContent(speechText);
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
return SpeechletResponse.newTellResponse(speech, card);
}
/**
* Generate a static help response
* @return SpeechletResponse
*/
private SpeechletResponse getHelpResponse() {
String speechText = "Du kannst fragen welche Menues es heute in der Mensa der Universitaet Bielefeld gibt. Frage zum Beispiel: Mensa Bielefeld Heute Tagesmenue";
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
Reprompt reprompt = new Reprompt();
reprompt.setOutputSpeech(speech);
return SpeechletResponse.newAskResponse(speech, reprompt);
}
/**
* Generate a static welcome response
* @return SpeechletResponse
*/
private SpeechletResponse getNewWelcomeResponse() {
String speechText = "OK";
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
Reprompt reprompt = new Reprompt();
reprompt.setOutputSpeech(speech);
return SpeechletResponse.newAskResponse(speech, reprompt);
}
} | warp1337/alexa-skills-kit-java | samples/src/main/java/naoremote/NaoSpeechlet.java | 2,608 | // JSONObject item = (JSONObject) data.get(i); | line_comment | nl | /**
* Author: [email protected]
* <p>
* Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
* <p>
* http://aws.amazon.com/apache2.0/
* <p>
* or in the "license" file accompanying this file. This file 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 naoremote;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazon.speech.slu.Intent;
import com.amazon.speech.speechlet.IntentRequest;
import com.amazon.speech.speechlet.LaunchRequest;
import com.amazon.speech.speechlet.Session;
import com.amazon.speech.speechlet.SessionEndedRequest;
import com.amazon.speech.speechlet.SessionStartedRequest;
import com.amazon.speech.speechlet.Speechlet;
import com.amazon.speech.speechlet.SpeechletException;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.Reprompt;
import com.amazon.speech.ui.SimpleCard;
import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.amazonaws.util.json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import naoremote.ZeroClient;
/**
* This class implements an Alexa Skill that finds available meals based on the
* desired day and kind of food (vital, vegetarian, meal of the day ...)
*/
public class NaoSpeechlet implements Speechlet {
private static final Logger log = LoggerFactory.getLogger(NaoSpeechlet.class);
private ZeroClient zc = new ZeroClient();
@Override
public void onSessionStarted(final SessionStartedRequest request, final Session session) throws SpeechletException {
log.info("onSessionStarted requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
}
@Override
public SpeechletResponse onLaunch(final LaunchRequest request, final Session session) throws SpeechletException {
log.info("onLaunch requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
return getNewWelcomeResponse();
}
@Override
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException {
log.info("onIntent requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
Intent intent = request.getIntent();
String intentName = (intent != null) ? intent.getName() : null;
String cmd = "";
if ("GetNewNaoIntent".equals(intentName)) {
if (intent.getSlot("Cmd") != null && intent.getSlot("Cmd").getValue() != null) {
cmd = intent.getSlot("Cmd").getValue().toLowerCase();
} else {
cmd = "unknown";
}
}
if ("GetNewNaoIntent".equals(intentName)) {
return getNewNaoResponse(cmd);
} else if ("AMAZON.HelpIntent".equals(intentName)) {
return getHelpResponse();
} else if ("AMAZON.StopIntent".equals(intentName)) {
PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech();
outputSpeech.setText("Goodbye");
return SpeechletResponse.newTellResponse(outputSpeech);
} else if ("AMAZON.CancelIntent".equals(intentName)) {
PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech();
outputSpeech.setText("Goodbye");
return SpeechletResponse.newTellResponse(outputSpeech);
} else {
throw new SpeechletException("Invalid Intent");
}
}
@Override
public void onSessionEnded(final SessionEndedRequest request, final Session session) throws SpeechletException {
log.info("onSessionEnded requestId={}, sessionId={}", request.getRequestId(), session.getSessionId());
}
/**
* Generate a String response based on the current slots.
* The mensa plan is provided as JSON on the web.
* @return String
* @param day The desired day of the week
* @param kind The desired menue, e.g., vital, vegetarian, etc.
* @throws IOException
* @see "https://raw.githubusercontent.com/warp1337/ubmensa2json/master/ub_mensa.json"
*/
// private String getMensaPlan(String day, String kind) {
//
// String answer = " ";
// InputStreamReader inputStream = null;
// BufferedReader bufferedReader = null;
// StringBuilder builder = new StringBuilder();
//
// if ("entwickler".equals(day)) {
// return "Florian Lier. Er hat diese Applikation geschrieben. Netter Typ. Ehrlich.";
// }
//
// if ("sonntag".equals(day) || "samstag".equals(day) || "gibt es nicht".equals(day)) {
// return "Easter eggs!";
// }
//
// if ("aktion".equals(kind)) {
// kind = "aktions theke";
// }
//
// if ("vegetarisches".equals(kind)) {
// kind = "vegetarisch";
// }
//
// if ("vital menue".equals(kind)) {
// kind = "vital";
// }
//
// try {
// String line;
// URL url = new URL("https://raw.githubusercontent.com/warp1337/ubmensa2json/master/ub_mensa.json");
// inputStream = new InputStreamReader(url.openStream(), Charset.forName("utf-8"));
// bufferedReader = new BufferedReader(inputStream);
// while ((line = bufferedReader.readLine()) != null) {
// builder.append(line);
// }
// } catch (IOException e) {
// builder.setLength(0);
// } finally {
// IOUtils.closeQuietly(inputStream);
// IOUtils.closeQuietly(bufferedReader);
// }
//
// if (builder.length() == 0) {
// answer = "Entschuldigung, ich konnte keine Informationen zu " + kind + " und " + day + " im Internet finden.";
// } else {
//
// try {
// JSONObject MensaResponseObject = new JSONObject(new JSONTokener(builder.toString()));
//
// if (MensaResponseObject != null) {
//
// JSONArray data = (JSONArray) MensaResponseObject.get(day);
//
// for (int i = 0; i < data.length(); i++) {
// JSONObject item<SUF>
// if (item.has(kind)) {
// answer = item.get(kind).toString();
// }
// }
// }
// } catch (JSONException e) {
// answer = "Entschuldigung, ich konnte keine Informationen im Mensa Plan zu " + kind + " und " + day + " finden.";
// }
// }
//
// return answer;
// }
/**
* Generate a response based on the current slots.
* The mensa plan is provided as JSON on the web.
* @return SpeechletResponse
* @param day The desired day of the week
* @param menue The desired menue, e.g., vital, vegetarian, etc.
*/
private SpeechletResponse getNewNaoResponse(String cmd) {
String speechText = cmd;
speechText = zc.ZSend(cmd);
SimpleCard card = new SimpleCard();
card.setTitle("Nao");
card.setContent(speechText);
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
return SpeechletResponse.newTellResponse(speech, card);
}
/**
* Generate a static help response
* @return SpeechletResponse
*/
private SpeechletResponse getHelpResponse() {
String speechText = "Du kannst fragen welche Menues es heute in der Mensa der Universitaet Bielefeld gibt. Frage zum Beispiel: Mensa Bielefeld Heute Tagesmenue";
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
Reprompt reprompt = new Reprompt();
reprompt.setOutputSpeech(speech);
return SpeechletResponse.newAskResponse(speech, reprompt);
}
/**
* Generate a static welcome response
* @return SpeechletResponse
*/
private SpeechletResponse getNewWelcomeResponse() {
String speechText = "OK";
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
Reprompt reprompt = new Reprompt();
reprompt.setOutputSpeech(speech);
return SpeechletResponse.newAskResponse(speech, reprompt);
}
} |
109338_8 | package com.gamegards.allinonev3.MyAccountDetails;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.gamegards.allinonev3.R;
import com.gamegards.allinonev3.RedeemCoins.RedeemModel;
import com.gamegards.allinonev3.SampleClasses.Const;
import com.gamegards.allinonev3.Utils.Funtions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.gamegards.allinonev3.MyAccountDetails.MyWinnigmodel.Andhar_Bahar;
import static com.gamegards.allinonev3.MyAccountDetails.MyWinnigmodel.RUMMY;
import static com.gamegards.allinonev3.MyAccountDetails.MyWinnigmodel.TEEN_PATTI;
public class MyWinningAcitivity extends AppCompatActivity {
RecyclerView rec_winning;
MyWinningAdapte myWinningAdapte;
ArrayList<MyWinnigmodel> myWinnigmodelArrayList;
private static final String MY_PREFS_NAME = "Login_data" ;
TextView tb_name,nofound;
ProgressBar progressBar;
Activity context = this;
TextView tvGameRecord;
TextView tvPurchase;
TextView tvGame;
TextView tvRedeemhistory;
// View image_arrow;
// View image_arrow1;
// View image_arrow2;
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_my_winning_acitivity);
progressBar = findViewById(R.id.progressBar);
rec_winning = findViewById(R.id.recylerview_gifts);
rec_winning.setLayoutManager(new LinearLayoutManager(this));
tb_name = findViewById(R.id.txtheader);
nofound = findViewById(R.id.txtnotfound);
tb_name.setText("Game History");
((ImageView) findViewById(R.id.imgclosetop)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
tvGameRecord = findViewById(R.id.tvGameRecord);
tvPurchase = findViewById(R.id.tvPurchase);
tvGame = findViewById(R.id.tvGame);
tvRedeemhistory = findViewById(R.id.tvRedeemhistory);
// image_arrow = findViewById(R.id.image_arrow);
// image_arrow1 = findViewById(R.id.image_arrow1);
// image_arrow2 = findViewById(R.id.image_arrow2);
onClickView();
UserWinnigAPI(TEEN_PATTI);
}
private void onClickView(){
((View) findViewById(R.id.tvRedeemhistory)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ManageTabs(RedeemModel.REDEEM_LIST);
tvGame.setText("Redeem Number");
UsersRedeemList();
}
});
((View) findViewById(R.id.tvGameRecord)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ManageTabs(RedeemModel.GAME_LIST);
tvGame.setText("Game");
UserWinnigAPI(TEEN_PATTI);
}
});
((View) findViewById(R.id.tvPurchase)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ManageTabs(RedeemModel.TRANSACTION_LIST);
tvGame.setText("Pay");
// image_arrow.setVisibility(View.GONE);
// image_arrow1.setVisibility(View.VISIBLE);
getPuchaseListAPI();
}
});
((View) findViewById(R.id.tvTeenpatti)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserWinnigAPI(TEEN_PATTI);
}
});
((View) findViewById(R.id.tvRummy)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserWinnigAPI(RUMMY);
}
});
((View) findViewById(R.id.tvandharbahar)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CALL_API_getANDHAR_BAHAR();
}
});
}
private void ManageGameType(String viewType){
getTextView(R.id.tvTeenpatti).setTextColor(viewType.equalsIgnoreCase(TEEN_PATTI)
? Funtions.getColor(context,R.color.red)
: Funtions.getColor(context,R.color.white)
);
getTextView(R.id.tvRummy).setTextColor(viewType.equalsIgnoreCase(RUMMY)
? Funtions.getColor(context,R.color.red)
: Funtions.getColor(context,R.color.white)
);
getTextView(R.id.tvandharbahar).setTextColor(viewType.equalsIgnoreCase(Andhar_Bahar)
? Funtions.getColor(context,R.color.red)
: Funtions.getColor(context,R.color.white)
);
}
private TextView getTextView(int id){
return ((TextView)findViewById(id));
}
private void ManageTabs(int viewType){
findViewById(R.id.lnrGamesType).setVisibility(viewType == RedeemModel.GAME_LIST
? View.VISIBLE : View.GONE);
tvGameRecord.setBackground(viewType == RedeemModel.GAME_LIST
? getDrawable(R.drawable.d_orange_corner)
: getDrawable(R.drawable.d_white_corner));
tvGameRecord.setTextColor(viewType == RedeemModel.GAME_LIST
? getResources().getColor(R.color.white)
: getResources().getColor(R.color.black));
// image_arrow.setVisibility(viewType == RedeemModel.GAME_LIST
// ? View.VISIBLE
// : View.GONE);
tvPurchase.setBackground(viewType == RedeemModel.TRANSACTION_LIST
? getDrawable(R.drawable.d_orange_corner)
: getDrawable(R.drawable.d_white_corner));
tvPurchase.setTextColor(viewType == RedeemModel.TRANSACTION_LIST
? getResources().getColor(R.color.white)
: getResources().getColor(R.color.black));
// image_arrow1.setVisibility(viewType == RedeemModel.TRANSACTION_LIST
// ? View.VISIBLE
// : View.GONE);
tvRedeemhistory.setBackground(viewType == RedeemModel.REDEEM_LIST
? getDrawable(R.drawable.d_orange_corner)
: getDrawable(R.drawable.d_white_corner));
tvRedeemhistory.setTextColor(viewType == RedeemModel.REDEEM_LIST
? getResources().getColor(R.color.white)
: getResources().getColor(R.color.black));
// image_arrow2.setVisibility(viewType == RedeemModel.REDEEM_LIST
// ? View.VISIBLE
// : View.GONE);
}
@Override
protected void onResume() {
super.onResume();
}
private void UsersRedeemList() {
final ArrayList<RedeemModel> redeemModelArrayList = new ArrayList();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.USER_Redeem_History_LIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Funtions.LOGE("MyWinningActivity",""+Const.USER_Redeem_History_LIST+"\n"+response);
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
Log.d("response", "onResponse: " + response);
if (code.equalsIgnoreCase("200")) {
JSONArray jsonArray = jsonObject.getJSONArray("List");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
RedeemModel model = new RedeemModel();
model.setId(jsonObject1.getString("id"));
model.setCoin(jsonObject1.getString("coin"));
model.setMobile(jsonObject1.getString("mobile"));
model.setUser_name(jsonObject1.getString("user_name"));
model.setUser_mobile(jsonObject1.getString("user_mobile"));
model.setStatus(jsonObject1.getString("status"));
model.setUpdated_date(jsonObject1.getString("updated_date"));
model.ViewType = RedeemModel.REDEEM_LIST;
redeemModelArrayList.add(model);
}
Collections.reverse(redeemModelArrayList);
} else {
if (jsonObject.has("message")) {
Toast.makeText(context, message,
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
UserRedeemHistoryAdapter userWinnerAdapter = new UserRedeemHistoryAdapter(context, redeemModelArrayList);
rec_winning.setAdapter(userWinnerAdapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(context, "Something went wrong", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id", prefs.getString("user_id", ""));
params.put("token", prefs.getString("token", ""));
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
private void UserWinnigAPI(final String type){
ManageGameType(type);
final ProgressDialog progressDialog = new ProgressDialog(MyWinningAcitivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Listing...");
progressDialog.show();
myWinnigmodelArrayList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.USER_WINNIG,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Funtions.LOGE("MyWinningActivity",""+Const.USER_WINNIG+"\n"+response);
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
if(code.equals("200"))
{
JSONArray ListArray = jsonObject.getJSONArray("GameWins");
if(ListArray.length() > 0)
{
JSONArray arraygame_dataa = jsonObject.optJSONArray("GameLog");
if(arraygame_dataa != null)
{
for (int i = 0; i < arraygame_dataa.length(); i++) {
JSONObject welcome_bonusObject = arraygame_dataa.getJSONObject(i);
MyWinnigmodel model = new MyWinnigmodel();
model.setId(welcome_bonusObject.getString("id"));
model.setAnder_baher_id(welcome_bonusObject.getString("ander_baher_id"));
model.setAdded_date(welcome_bonusObject.getString("added_date"));
model.setAmount(welcome_bonusObject.getString("amount"));
model.setWinning_amount(welcome_bonusObject.getString("winning_amount"));
model.amount = welcome_bonusObject.optString("winning_amount");
model.invest = welcome_bonusObject.optInt("invest",0);
model.setBet(welcome_bonusObject.getString("bet"));
model.setRoom_id(welcome_bonusObject.getString("room_id"));
model.game_type = Andhar_Bahar;
model.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(model);
}
}
if(type.equalsIgnoreCase(TEEN_PATTI))
{
JSONArray TeenPattiGameLog = jsonObject.optJSONArray("TeenPattiGameLog");
if(TeenPattiGameLog != null)
{
for (int i = 0; i < TeenPattiGameLog.length() ; i++) {
JSONObject ListObject= TeenPattiGameLog.getJSONObject(i);
MyWinnigmodel usermodel = new MyWinnigmodel();
usermodel.id = ListObject.optString("game_id");
usermodel.table_id = ListObject.optString("game_id");
usermodel.amount = ListObject.optString("winning_amount");
usermodel.invest = ListObject.optInt("invest",0);
usermodel.winner_id = ListObject.optString("winner_id");
usermodel.added_date = ListObject.optString("added_date");
usermodel.game_type = TEEN_PATTI;
usermodel.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(usermodel);
}
}
Collections.reverse(myWinnigmodelArrayList);
}
if(type.equalsIgnoreCase(RUMMY))
{
JSONArray RummyGameLog = jsonObject.optJSONArray("RummyGameLog");
if(RummyGameLog != null)
{
for (int i = 0; i < RummyGameLog.length() ; i++) {
JSONObject ListObject= RummyGameLog.getJSONObject(i);
MyWinnigmodel usermodel = new MyWinnigmodel();
usermodel.id = ListObject.optString("game_id");
usermodel.table_id = ListObject.optString("game_id");
int win_amount = ListObject.optInt("amount",0);
if(win_amount > 0)
usermodel.amount = ListObject.optString("amount");
usermodel.invest = ListObject.optInt("amount",0);
usermodel.winner_id = ListObject.optString("winner_id");
usermodel.added_date = ListObject.optString("added_date");
usermodel.game_type = RUMMY;
usermodel.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(usermodel);
}
}
}
myWinningAdapte = new MyWinningAdapte(MyWinningAcitivity.this,myWinnigmodelArrayList);
rec_winning.setAdapter(myWinningAdapte);
}
else {
nofound.setVisibility(View.VISIBLE);
}
}
else {
nofound.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
nofound.setVisibility(View.VISIBLE);
}
progressDialog.dismiss();
HideProgressBar(true);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
HideProgressBar(true);
Toast.makeText(MyWinningAcitivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
nofound.setVisibility(View.VISIBLE);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id",prefs.getString("user_id", ""));
// params.put("user_id","54");
Funtions.LOGE("MyWinningActivity",""+Const.USER_WINNIG+"\n"+params);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
private void CALL_API_getANDHAR_BAHAR() {
ManageGameType(Andhar_Bahar);
myWinnigmodelArrayList.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.GETHISTORY,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// progressDialog.dismiss();
Funtions.LOGE("CALL_API_getANDHAR_BAHAR",""+Const.GETHISTORY+"\n"+response);
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
if (code.equalsIgnoreCase("200")) {
JSONArray arraygame_dataa = jsonObject.optJSONArray("GameLog");
if(arraygame_dataa != null)
{
for (int i = 0; i < arraygame_dataa.length(); i++) {
JSONObject welcome_bonusObject = arraygame_dataa.getJSONObject(i);
MyWinnigmodel model = new MyWinnigmodel();
model.setId(welcome_bonusObject.getString("id"));
model.setAnder_baher_id(welcome_bonusObject.getString("ander_baher_id"));
model.setAdded_date(welcome_bonusObject.getString("added_date"));
model.setAmount(welcome_bonusObject.getString("amount"));
model.setWinning_amount(welcome_bonusObject.getString("winning_amount"));
model.amount = welcome_bonusObject.optString("winning_amount");
model.invest = welcome_bonusObject.optInt("amount",0);
model.setBet(welcome_bonusObject.getString("bet"));
model.setRoom_id(welcome_bonusObject.getString("room_id"));
model.game_type = Andhar_Bahar;
model.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(model);
}
}
}
Collections.reverse(myWinnigmodelArrayList);
myWinningAdapte = new MyWinningAdapte(MyWinningAcitivity.this,myWinnigmodelArrayList);
rec_winning.setAdapter(myWinningAdapte);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(context, "Something went wrong", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id", prefs.getString("user_id", ""));
params.put("token", prefs.getString("token", ""));
params.put("room_id", "1");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(context).add(stringRequest);
}
private void getPuchaseListAPI(){
final ProgressDialog progressDialog = new ProgressDialog(MyWinningAcitivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Listing...");
progressDialog.show();
final ArrayList<MyWinnigmodel> redeemModelArrayList = new ArrayList();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.USER_WINNIG,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Funtions.LOGE("MyWinningActivity",""+Const.USER_WINNIG+"\n"+response);
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
Log.d("response", "onResponse: " + response);
if (code.equalsIgnoreCase("200")) {
JSONArray jsonArray = jsonObject.getJSONArray("AllPurchase");
// JSONArray WalletLog = jsonObject.getJSONArray("WalletLog");
//
// for (int i = 0; i < WalletLog.length(); i++) {
// JSONObject jsonObject1 = WalletLog.getJSONObject(i);
//
// MyWinnigmodel model = new MyWinnigmodel();
// model.setId(jsonObject1.optString("id"));
// model.setCoin(jsonObject1.optString("coin","-"));
// model.price = jsonObject1.optString("price","admin");
// model.added_date = jsonObject1.optString("added_date","-");
// model.setUpdated_date(jsonObject1.optString("added_date","-"));
// model.ViewType = RedeemModel.TRANSACTION_LIST;
//
//
//// redeemModelArrayList.add(model);
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MyWinnigmodel model = new MyWinnigmodel();
model.setId(jsonObject1.optString("id"));
model.setCoin(jsonObject1.optString("coin","-"));
model.price = jsonObject1.optString("price","admin");
model.added_date = jsonObject1.optString("updated_date");
model.setUpdated_date(jsonObject1.optString("updated_date"));
model.ViewType = RedeemModel.TRANSACTION_LIST;
redeemModelArrayList.add(model);
}
myWinningAdapte = new MyWinningAdapte(MyWinningAcitivity.this,redeemModelArrayList);
rec_winning.setAdapter(myWinningAdapte);
} else {
if (jsonObject.has("message")) {
Toast.makeText(context, message,
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(context, "Something went wrong", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id", prefs.getString("user_id", ""));
params.put("token", prefs.getString("token", ""));
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
private void HideProgressBar(boolean visible){
progressBar.setVisibility(!visible ? View.VISIBLE : View.GONE);
}
}
| warrior7789/androidpatti | app/src/main/java/com/gamegards/allinonev3/MyAccountDetails/MyWinningAcitivity.java | 7,774 | // JSONObject jsonObject1 = WalletLog.getJSONObject(i); | line_comment | nl | package com.gamegards.allinonev3.MyAccountDetails;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.gamegards.allinonev3.R;
import com.gamegards.allinonev3.RedeemCoins.RedeemModel;
import com.gamegards.allinonev3.SampleClasses.Const;
import com.gamegards.allinonev3.Utils.Funtions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.gamegards.allinonev3.MyAccountDetails.MyWinnigmodel.Andhar_Bahar;
import static com.gamegards.allinonev3.MyAccountDetails.MyWinnigmodel.RUMMY;
import static com.gamegards.allinonev3.MyAccountDetails.MyWinnigmodel.TEEN_PATTI;
public class MyWinningAcitivity extends AppCompatActivity {
RecyclerView rec_winning;
MyWinningAdapte myWinningAdapte;
ArrayList<MyWinnigmodel> myWinnigmodelArrayList;
private static final String MY_PREFS_NAME = "Login_data" ;
TextView tb_name,nofound;
ProgressBar progressBar;
Activity context = this;
TextView tvGameRecord;
TextView tvPurchase;
TextView tvGame;
TextView tvRedeemhistory;
// View image_arrow;
// View image_arrow1;
// View image_arrow2;
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_my_winning_acitivity);
progressBar = findViewById(R.id.progressBar);
rec_winning = findViewById(R.id.recylerview_gifts);
rec_winning.setLayoutManager(new LinearLayoutManager(this));
tb_name = findViewById(R.id.txtheader);
nofound = findViewById(R.id.txtnotfound);
tb_name.setText("Game History");
((ImageView) findViewById(R.id.imgclosetop)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
tvGameRecord = findViewById(R.id.tvGameRecord);
tvPurchase = findViewById(R.id.tvPurchase);
tvGame = findViewById(R.id.tvGame);
tvRedeemhistory = findViewById(R.id.tvRedeemhistory);
// image_arrow = findViewById(R.id.image_arrow);
// image_arrow1 = findViewById(R.id.image_arrow1);
// image_arrow2 = findViewById(R.id.image_arrow2);
onClickView();
UserWinnigAPI(TEEN_PATTI);
}
private void onClickView(){
((View) findViewById(R.id.tvRedeemhistory)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ManageTabs(RedeemModel.REDEEM_LIST);
tvGame.setText("Redeem Number");
UsersRedeemList();
}
});
((View) findViewById(R.id.tvGameRecord)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ManageTabs(RedeemModel.GAME_LIST);
tvGame.setText("Game");
UserWinnigAPI(TEEN_PATTI);
}
});
((View) findViewById(R.id.tvPurchase)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ManageTabs(RedeemModel.TRANSACTION_LIST);
tvGame.setText("Pay");
// image_arrow.setVisibility(View.GONE);
// image_arrow1.setVisibility(View.VISIBLE);
getPuchaseListAPI();
}
});
((View) findViewById(R.id.tvTeenpatti)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserWinnigAPI(TEEN_PATTI);
}
});
((View) findViewById(R.id.tvRummy)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserWinnigAPI(RUMMY);
}
});
((View) findViewById(R.id.tvandharbahar)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CALL_API_getANDHAR_BAHAR();
}
});
}
private void ManageGameType(String viewType){
getTextView(R.id.tvTeenpatti).setTextColor(viewType.equalsIgnoreCase(TEEN_PATTI)
? Funtions.getColor(context,R.color.red)
: Funtions.getColor(context,R.color.white)
);
getTextView(R.id.tvRummy).setTextColor(viewType.equalsIgnoreCase(RUMMY)
? Funtions.getColor(context,R.color.red)
: Funtions.getColor(context,R.color.white)
);
getTextView(R.id.tvandharbahar).setTextColor(viewType.equalsIgnoreCase(Andhar_Bahar)
? Funtions.getColor(context,R.color.red)
: Funtions.getColor(context,R.color.white)
);
}
private TextView getTextView(int id){
return ((TextView)findViewById(id));
}
private void ManageTabs(int viewType){
findViewById(R.id.lnrGamesType).setVisibility(viewType == RedeemModel.GAME_LIST
? View.VISIBLE : View.GONE);
tvGameRecord.setBackground(viewType == RedeemModel.GAME_LIST
? getDrawable(R.drawable.d_orange_corner)
: getDrawable(R.drawable.d_white_corner));
tvGameRecord.setTextColor(viewType == RedeemModel.GAME_LIST
? getResources().getColor(R.color.white)
: getResources().getColor(R.color.black));
// image_arrow.setVisibility(viewType == RedeemModel.GAME_LIST
// ? View.VISIBLE
// : View.GONE);
tvPurchase.setBackground(viewType == RedeemModel.TRANSACTION_LIST
? getDrawable(R.drawable.d_orange_corner)
: getDrawable(R.drawable.d_white_corner));
tvPurchase.setTextColor(viewType == RedeemModel.TRANSACTION_LIST
? getResources().getColor(R.color.white)
: getResources().getColor(R.color.black));
// image_arrow1.setVisibility(viewType == RedeemModel.TRANSACTION_LIST
// ? View.VISIBLE
// : View.GONE);
tvRedeemhistory.setBackground(viewType == RedeemModel.REDEEM_LIST
? getDrawable(R.drawable.d_orange_corner)
: getDrawable(R.drawable.d_white_corner));
tvRedeemhistory.setTextColor(viewType == RedeemModel.REDEEM_LIST
? getResources().getColor(R.color.white)
: getResources().getColor(R.color.black));
// image_arrow2.setVisibility(viewType == RedeemModel.REDEEM_LIST
// ? View.VISIBLE
// : View.GONE);
}
@Override
protected void onResume() {
super.onResume();
}
private void UsersRedeemList() {
final ArrayList<RedeemModel> redeemModelArrayList = new ArrayList();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.USER_Redeem_History_LIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Funtions.LOGE("MyWinningActivity",""+Const.USER_Redeem_History_LIST+"\n"+response);
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
Log.d("response", "onResponse: " + response);
if (code.equalsIgnoreCase("200")) {
JSONArray jsonArray = jsonObject.getJSONArray("List");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
RedeemModel model = new RedeemModel();
model.setId(jsonObject1.getString("id"));
model.setCoin(jsonObject1.getString("coin"));
model.setMobile(jsonObject1.getString("mobile"));
model.setUser_name(jsonObject1.getString("user_name"));
model.setUser_mobile(jsonObject1.getString("user_mobile"));
model.setStatus(jsonObject1.getString("status"));
model.setUpdated_date(jsonObject1.getString("updated_date"));
model.ViewType = RedeemModel.REDEEM_LIST;
redeemModelArrayList.add(model);
}
Collections.reverse(redeemModelArrayList);
} else {
if (jsonObject.has("message")) {
Toast.makeText(context, message,
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
UserRedeemHistoryAdapter userWinnerAdapter = new UserRedeemHistoryAdapter(context, redeemModelArrayList);
rec_winning.setAdapter(userWinnerAdapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(context, "Something went wrong", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id", prefs.getString("user_id", ""));
params.put("token", prefs.getString("token", ""));
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
private void UserWinnigAPI(final String type){
ManageGameType(type);
final ProgressDialog progressDialog = new ProgressDialog(MyWinningAcitivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Listing...");
progressDialog.show();
myWinnigmodelArrayList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.USER_WINNIG,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Funtions.LOGE("MyWinningActivity",""+Const.USER_WINNIG+"\n"+response);
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
if(code.equals("200"))
{
JSONArray ListArray = jsonObject.getJSONArray("GameWins");
if(ListArray.length() > 0)
{
JSONArray arraygame_dataa = jsonObject.optJSONArray("GameLog");
if(arraygame_dataa != null)
{
for (int i = 0; i < arraygame_dataa.length(); i++) {
JSONObject welcome_bonusObject = arraygame_dataa.getJSONObject(i);
MyWinnigmodel model = new MyWinnigmodel();
model.setId(welcome_bonusObject.getString("id"));
model.setAnder_baher_id(welcome_bonusObject.getString("ander_baher_id"));
model.setAdded_date(welcome_bonusObject.getString("added_date"));
model.setAmount(welcome_bonusObject.getString("amount"));
model.setWinning_amount(welcome_bonusObject.getString("winning_amount"));
model.amount = welcome_bonusObject.optString("winning_amount");
model.invest = welcome_bonusObject.optInt("invest",0);
model.setBet(welcome_bonusObject.getString("bet"));
model.setRoom_id(welcome_bonusObject.getString("room_id"));
model.game_type = Andhar_Bahar;
model.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(model);
}
}
if(type.equalsIgnoreCase(TEEN_PATTI))
{
JSONArray TeenPattiGameLog = jsonObject.optJSONArray("TeenPattiGameLog");
if(TeenPattiGameLog != null)
{
for (int i = 0; i < TeenPattiGameLog.length() ; i++) {
JSONObject ListObject= TeenPattiGameLog.getJSONObject(i);
MyWinnigmodel usermodel = new MyWinnigmodel();
usermodel.id = ListObject.optString("game_id");
usermodel.table_id = ListObject.optString("game_id");
usermodel.amount = ListObject.optString("winning_amount");
usermodel.invest = ListObject.optInt("invest",0);
usermodel.winner_id = ListObject.optString("winner_id");
usermodel.added_date = ListObject.optString("added_date");
usermodel.game_type = TEEN_PATTI;
usermodel.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(usermodel);
}
}
Collections.reverse(myWinnigmodelArrayList);
}
if(type.equalsIgnoreCase(RUMMY))
{
JSONArray RummyGameLog = jsonObject.optJSONArray("RummyGameLog");
if(RummyGameLog != null)
{
for (int i = 0; i < RummyGameLog.length() ; i++) {
JSONObject ListObject= RummyGameLog.getJSONObject(i);
MyWinnigmodel usermodel = new MyWinnigmodel();
usermodel.id = ListObject.optString("game_id");
usermodel.table_id = ListObject.optString("game_id");
int win_amount = ListObject.optInt("amount",0);
if(win_amount > 0)
usermodel.amount = ListObject.optString("amount");
usermodel.invest = ListObject.optInt("amount",0);
usermodel.winner_id = ListObject.optString("winner_id");
usermodel.added_date = ListObject.optString("added_date");
usermodel.game_type = RUMMY;
usermodel.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(usermodel);
}
}
}
myWinningAdapte = new MyWinningAdapte(MyWinningAcitivity.this,myWinnigmodelArrayList);
rec_winning.setAdapter(myWinningAdapte);
}
else {
nofound.setVisibility(View.VISIBLE);
}
}
else {
nofound.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
nofound.setVisibility(View.VISIBLE);
}
progressDialog.dismiss();
HideProgressBar(true);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
HideProgressBar(true);
Toast.makeText(MyWinningAcitivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
nofound.setVisibility(View.VISIBLE);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id",prefs.getString("user_id", ""));
// params.put("user_id","54");
Funtions.LOGE("MyWinningActivity",""+Const.USER_WINNIG+"\n"+params);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
private void CALL_API_getANDHAR_BAHAR() {
ManageGameType(Andhar_Bahar);
myWinnigmodelArrayList.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.GETHISTORY,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// progressDialog.dismiss();
Funtions.LOGE("CALL_API_getANDHAR_BAHAR",""+Const.GETHISTORY+"\n"+response);
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
if (code.equalsIgnoreCase("200")) {
JSONArray arraygame_dataa = jsonObject.optJSONArray("GameLog");
if(arraygame_dataa != null)
{
for (int i = 0; i < arraygame_dataa.length(); i++) {
JSONObject welcome_bonusObject = arraygame_dataa.getJSONObject(i);
MyWinnigmodel model = new MyWinnigmodel();
model.setId(welcome_bonusObject.getString("id"));
model.setAnder_baher_id(welcome_bonusObject.getString("ander_baher_id"));
model.setAdded_date(welcome_bonusObject.getString("added_date"));
model.setAmount(welcome_bonusObject.getString("amount"));
model.setWinning_amount(welcome_bonusObject.getString("winning_amount"));
model.amount = welcome_bonusObject.optString("winning_amount");
model.invest = welcome_bonusObject.optInt("amount",0);
model.setBet(welcome_bonusObject.getString("bet"));
model.setRoom_id(welcome_bonusObject.getString("room_id"));
model.game_type = Andhar_Bahar;
model.ViewType = RedeemModel.GAME_LIST;
myWinnigmodelArrayList.add(model);
}
}
}
Collections.reverse(myWinnigmodelArrayList);
myWinningAdapte = new MyWinningAdapte(MyWinningAcitivity.this,myWinnigmodelArrayList);
rec_winning.setAdapter(myWinningAdapte);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(context, "Something went wrong", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id", prefs.getString("user_id", ""));
params.put("token", prefs.getString("token", ""));
params.put("room_id", "1");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(context).add(stringRequest);
}
private void getPuchaseListAPI(){
final ProgressDialog progressDialog = new ProgressDialog(MyWinningAcitivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Listing...");
progressDialog.show();
final ArrayList<MyWinnigmodel> redeemModelArrayList = new ArrayList();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.USER_WINNIG,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Funtions.LOGE("MyWinningActivity",""+Const.USER_WINNIG+"\n"+response);
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
Log.d("response", "onResponse: " + response);
if (code.equalsIgnoreCase("200")) {
JSONArray jsonArray = jsonObject.getJSONArray("AllPurchase");
// JSONArray WalletLog = jsonObject.getJSONArray("WalletLog");
//
// for (int i = 0; i < WalletLog.length(); i++) {
// JSONObject jsonObject1<SUF>
//
// MyWinnigmodel model = new MyWinnigmodel();
// model.setId(jsonObject1.optString("id"));
// model.setCoin(jsonObject1.optString("coin","-"));
// model.price = jsonObject1.optString("price","admin");
// model.added_date = jsonObject1.optString("added_date","-");
// model.setUpdated_date(jsonObject1.optString("added_date","-"));
// model.ViewType = RedeemModel.TRANSACTION_LIST;
//
//
//// redeemModelArrayList.add(model);
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MyWinnigmodel model = new MyWinnigmodel();
model.setId(jsonObject1.optString("id"));
model.setCoin(jsonObject1.optString("coin","-"));
model.price = jsonObject1.optString("price","admin");
model.added_date = jsonObject1.optString("updated_date");
model.setUpdated_date(jsonObject1.optString("updated_date"));
model.ViewType = RedeemModel.TRANSACTION_LIST;
redeemModelArrayList.add(model);
}
myWinningAdapte = new MyWinningAdapte(MyWinningAcitivity.this,redeemModelArrayList);
rec_winning.setAdapter(myWinningAdapte);
} else {
if (jsonObject.has("message")) {
Toast.makeText(context, message,
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(context, "Something went wrong", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
params.put("user_id", prefs.getString("user_id", ""));
params.put("token", prefs.getString("token", ""));
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("token", Const.TOKEN);
return headers;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
private void HideProgressBar(boolean visible){
progressBar.setVisibility(!visible ? View.VISIBLE : View.GONE);
}
}
|
128316_0 | // SGU139. Help Needed!
/*
139. Help Needed!
time limit per test: 0.50 sec.
memory limit per test: 4096 KB
Little Johnny likes puzzles a lot! Just a few days ago, he found out about the 'traditional' 4x4 puzzle. For this puzzle, you have all the numbers from 0 to 15 arranged in 4 rows and 4 columns. You are allowed to switch two adjacent elements (horizontally or vertically), only if one of them has the value 0. The purpose of the puzzle is to reach the following final state:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
Given the initial state of the puzzle, you have to decide whether there exists a sequence of moves which brings the puzzle into the final state.
Input
The input will consist of 4 lines, each of them containing 4 integers, describing the initial state of the puzzle.
Output
For every initial state, you should print "YES" if the final state can be reached after several moves or "NO", if such a thing is impossible.
Sample Input #1
1 2 3 4
5 6 7 8
9 10 11 0
13 14 15 12
Sample Output #1
YES
Sample Input #2
2 1 3 4
5 6 7 8
9 10 11 12
0 13 14 15
Sample Output #2
NO
Author : Mugurel Ionut Andreica
Resource : SSU::Online Contester Fall Contest #2
Date : Fall 2002
*/
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num;
int[] a = new int[16];
int dis = 0;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
num = in.nextInt() - 1;
if (num == -1) {
num = 15;
} else {
dis += Math.abs(num / 4 - i) + Math.abs(num % 4 - j);
}
a[i * 4 + j] = num;
}
}
int inv = 0;
for (int i = 0; i < 16; ++i) {
for (int j = 0; j < i; ++j) {
if (a[i] < a[j]) {
++inv;
}
}
}
System.err.println(dis + " " + inv);
System.out.println(((dis & 1) ^ (inv & 1)) == 0 ? "YES" : "NO");
}
}
// ID: Date'n'Time: Name: Task: .Ext: Status: Time: Memory:
// 871681 23.07.09 18:50 watashi 139 .JAVA Accepted 19 ms 2274 kb
| watashi/AlgoSolution | sgu/ac/1/139.java | 802 | // SGU139. Help Needed! | line_comment | nl | // SGU139. Help<SUF>
/*
139. Help Needed!
time limit per test: 0.50 sec.
memory limit per test: 4096 KB
Little Johnny likes puzzles a lot! Just a few days ago, he found out about the 'traditional' 4x4 puzzle. For this puzzle, you have all the numbers from 0 to 15 arranged in 4 rows and 4 columns. You are allowed to switch two adjacent elements (horizontally or vertically), only if one of them has the value 0. The purpose of the puzzle is to reach the following final state:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
Given the initial state of the puzzle, you have to decide whether there exists a sequence of moves which brings the puzzle into the final state.
Input
The input will consist of 4 lines, each of them containing 4 integers, describing the initial state of the puzzle.
Output
For every initial state, you should print "YES" if the final state can be reached after several moves or "NO", if such a thing is impossible.
Sample Input #1
1 2 3 4
5 6 7 8
9 10 11 0
13 14 15 12
Sample Output #1
YES
Sample Input #2
2 1 3 4
5 6 7 8
9 10 11 12
0 13 14 15
Sample Output #2
NO
Author : Mugurel Ionut Andreica
Resource : SSU::Online Contester Fall Contest #2
Date : Fall 2002
*/
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num;
int[] a = new int[16];
int dis = 0;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
num = in.nextInt() - 1;
if (num == -1) {
num = 15;
} else {
dis += Math.abs(num / 4 - i) + Math.abs(num % 4 - j);
}
a[i * 4 + j] = num;
}
}
int inv = 0;
for (int i = 0; i < 16; ++i) {
for (int j = 0; j < i; ++j) {
if (a[i] < a[j]) {
++inv;
}
}
}
System.err.println(dis + " " + inv);
System.out.println(((dis & 1) ^ (inv & 1)) == 0 ? "YES" : "NO");
}
}
// ID: Date'n'Time: Name: Task: .Ext: Status: Time: Memory:
// 871681 23.07.09 18:50 watashi 139 .JAVA Accepted 19 ms 2274 kb
|
172400_24 |
package org.waver.dutchobs.domain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"locatienaam",
"parameternaam",
"par",
"loc",
"net",
"waarde",
"eenheid",
"category",
"iconsubscript",
"meettijd",
"link_wn",
"ids",
"location",
"categoryDescription",
"icon"
})
public class Feature {
@JsonProperty("locatienaam")
private String locatienaam;
@JsonProperty("parameternaam")
private String parameternaam;
@JsonProperty("par")
private String par;
@JsonProperty("loc")
private String loc;
@JsonProperty("net")
private String net;
@JsonProperty("waarde")
private String waarde;
@JsonProperty("eenheid")
private String eenheid;
@JsonProperty("category")
private Integer category;
//@JsonProperty("iconnr")
@JsonIgnore
private Integer iconnr;
//@JsonProperty("popupsize")
@JsonIgnore
private String popupsize;
@JsonIgnore
private String graphsize;
@JsonIgnore
private Object waardeh10a;
@JsonIgnore
private Object waardeh10v;
@JsonIgnore
private Object waardeq10v;
@JsonProperty("iconsubscript")
@JsonIgnore
private String iconsubscript;
@JsonProperty("meettijd")
private String meettijd;
@JsonProperty("link_wn")
@JsonIgnore
private Object linkWn;
@JsonProperty("ids")
private List<String> ids = new ArrayList<String>();
@JsonProperty("location")
private Location location;
@JsonProperty("categoryDescription")
private String categoryDescription;
@JsonProperty("icon")
@JsonIgnore
private Icon icon;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The locatienaam
*/
@JsonProperty("locatienaam")
public String getLocatienaam() {
return locatienaam;
}
/**
*
* @param locatienaam
* The locatienaam
*/
@JsonProperty("locatienaam")
public void setLocatienaam(String locatienaam) {
this.locatienaam = locatienaam;
}
/**
*
* @return
* The parameternaam
*/
@JsonProperty("parameternaam")
public String getParameternaam() {
return parameternaam;
}
/**
*
* @param parameternaam
* The parameternaam
*/
@JsonProperty("parameternaam")
public void setParameternaam(String parameternaam) {
this.parameternaam = parameternaam;
}
/**
*
* @return
* The par
*/
@JsonProperty("par")
public String getPar() {
return par;
}
/**
*
* @param par
* The par
*/
@JsonProperty("par")
public void setPar(String par) {
this.par = par;
}
/**
*
* @return
* The loc
*/
@JsonProperty("loc")
public String getLoc() {
return loc;
}
/**
*
* @param loc
* The loc
*/
@JsonProperty("loc")
public void setLoc(String loc) {
this.loc = loc;
}
/**
*
* @return
* The net
*/
@JsonProperty("net")
public String getNet() {
return net;
}
/**
*
* @param net
* The net
*/
@JsonProperty("net")
public void setNet(String net) {
this.net = net;
}
/**
*
* @return
* The waarde
*/
@JsonProperty("waarde")
public String getWaarde() {
return waarde;
}
/**
*
* @param waarde
* The waarde
*/
@JsonProperty("waarde")
public void setWaarde(String waarde) {
this.waarde = waarde;
}
/**
*
* @return
* The eenheid
*/
@JsonProperty("eenheid")
public String getEenheid() {
return eenheid;
}
/**
*
* @param eenheid
* The eenheid
*/
@JsonProperty("eenheid")
public void setEenheid(String eenheid) {
this.eenheid = eenheid;
}
/**
*
* @return
* The category
*/
@JsonProperty("category")
public Integer getCategory() {
return category;
}
/**
*
* @param category
* The category
*/
@JsonProperty("category")
public void setCategory(Integer category) {
this.category = category;
}
/**
*
* @param iconnr
* The iconnr
*/
@JsonProperty("iconnr")
public void setIconnr(Integer iconnr) {
this.iconnr = iconnr;
}
/**
*
* @param popupsize
* The popupsize
*/
@JsonProperty("popupsize")
public void setPopupsize(String popupsize) {
this.popupsize = popupsize;
}
/**
*
* @param graphsize
* The graphsize
*/
@JsonProperty("graphsize")
public void setGraphsize(String graphsize) {
this.graphsize = graphsize;
}
/**
*
* @param waardeh10a
* The waardeh10a
*/
@JsonProperty("waardeh10a")
public void setWaardeh10a(Object waardeh10a) {
this.waardeh10a = waardeh10a;
}
/**
*
* @param waardeh10v
* The waardeh10v
*/
@JsonProperty("waardeh10v")
public void setWaardeh10v(Object waardeh10v) {
this.waardeh10v = waardeh10v;
}
/**
*
* @param waardeq10v
* The waardeq10v
*/
@JsonProperty("waardeq10v")
public void setWaardeq10v(Object waardeq10v) {
this.waardeq10v = waardeq10v;
}
/**
*
* @return
* The iconsubscript
*/
@JsonProperty("iconsubscript")
public String getIconsubscript() {
return iconsubscript;
}
/**
*
* @param iconsubscript
* The iconsubscript
*/
@JsonProperty("iconsubscript")
public void setIconsubscript(String iconsubscript) {
this.iconsubscript = iconsubscript;
}
/**
*
* @return
* The meettijd
*/
@JsonProperty("meettijd")
public String getMeettijd() {
return meettijd;
}
/**
*
* @param meettijd
* The meettijd
*/
@JsonProperty("meettijd")
public void setMeettijd(String meettijd) {
this.meettijd = meettijd;
}
/**
*
* @param linkWn
* The link_wn
*/
@JsonProperty("link_wn")
public void setLinkWn(Object linkWn) {
this.linkWn = linkWn;
}
/**
*
* @return
* The ids
*/
@JsonProperty("ids")
public List<String> getIds() {
return ids;
}
/**
*
* @param ids
* The ids
*/
@JsonProperty("ids")
public void setIds(List<String> ids) {
this.ids = ids;
}
/**
*
* @return
* The location
*/
@JsonProperty("location")
public Location getLocation() {
return location;
}
/**
*
* @param location
* The location
*/
@JsonProperty("location")
public void setLocation(Location location) {
this.location = location;
}
/**
*
* @return
* The categoryDescription
*/
@JsonProperty("categoryDescription")
public String getCategoryDescription() {
return categoryDescription;
}
/**
*
* @param categoryDescription
* The categoryDescription
*/
@JsonProperty("categoryDescription")
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
/**
*
* @param icon
* The icon
*/
@JsonProperty("icon")
public void setIcon(Icon icon) {
this.icon = icon;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| wavermartijn/nl-weather-obs | src/main/java/org/waver/dutchobs/domain/Feature.java | 2,762 | /**
*
* @return
* The meettijd
*/ | block_comment | nl |
package org.waver.dutchobs.domain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"locatienaam",
"parameternaam",
"par",
"loc",
"net",
"waarde",
"eenheid",
"category",
"iconsubscript",
"meettijd",
"link_wn",
"ids",
"location",
"categoryDescription",
"icon"
})
public class Feature {
@JsonProperty("locatienaam")
private String locatienaam;
@JsonProperty("parameternaam")
private String parameternaam;
@JsonProperty("par")
private String par;
@JsonProperty("loc")
private String loc;
@JsonProperty("net")
private String net;
@JsonProperty("waarde")
private String waarde;
@JsonProperty("eenheid")
private String eenheid;
@JsonProperty("category")
private Integer category;
//@JsonProperty("iconnr")
@JsonIgnore
private Integer iconnr;
//@JsonProperty("popupsize")
@JsonIgnore
private String popupsize;
@JsonIgnore
private String graphsize;
@JsonIgnore
private Object waardeh10a;
@JsonIgnore
private Object waardeh10v;
@JsonIgnore
private Object waardeq10v;
@JsonProperty("iconsubscript")
@JsonIgnore
private String iconsubscript;
@JsonProperty("meettijd")
private String meettijd;
@JsonProperty("link_wn")
@JsonIgnore
private Object linkWn;
@JsonProperty("ids")
private List<String> ids = new ArrayList<String>();
@JsonProperty("location")
private Location location;
@JsonProperty("categoryDescription")
private String categoryDescription;
@JsonProperty("icon")
@JsonIgnore
private Icon icon;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The locatienaam
*/
@JsonProperty("locatienaam")
public String getLocatienaam() {
return locatienaam;
}
/**
*
* @param locatienaam
* The locatienaam
*/
@JsonProperty("locatienaam")
public void setLocatienaam(String locatienaam) {
this.locatienaam = locatienaam;
}
/**
*
* @return
* The parameternaam
*/
@JsonProperty("parameternaam")
public String getParameternaam() {
return parameternaam;
}
/**
*
* @param parameternaam
* The parameternaam
*/
@JsonProperty("parameternaam")
public void setParameternaam(String parameternaam) {
this.parameternaam = parameternaam;
}
/**
*
* @return
* The par
*/
@JsonProperty("par")
public String getPar() {
return par;
}
/**
*
* @param par
* The par
*/
@JsonProperty("par")
public void setPar(String par) {
this.par = par;
}
/**
*
* @return
* The loc
*/
@JsonProperty("loc")
public String getLoc() {
return loc;
}
/**
*
* @param loc
* The loc
*/
@JsonProperty("loc")
public void setLoc(String loc) {
this.loc = loc;
}
/**
*
* @return
* The net
*/
@JsonProperty("net")
public String getNet() {
return net;
}
/**
*
* @param net
* The net
*/
@JsonProperty("net")
public void setNet(String net) {
this.net = net;
}
/**
*
* @return
* The waarde
*/
@JsonProperty("waarde")
public String getWaarde() {
return waarde;
}
/**
*
* @param waarde
* The waarde
*/
@JsonProperty("waarde")
public void setWaarde(String waarde) {
this.waarde = waarde;
}
/**
*
* @return
* The eenheid
*/
@JsonProperty("eenheid")
public String getEenheid() {
return eenheid;
}
/**
*
* @param eenheid
* The eenheid
*/
@JsonProperty("eenheid")
public void setEenheid(String eenheid) {
this.eenheid = eenheid;
}
/**
*
* @return
* The category
*/
@JsonProperty("category")
public Integer getCategory() {
return category;
}
/**
*
* @param category
* The category
*/
@JsonProperty("category")
public void setCategory(Integer category) {
this.category = category;
}
/**
*
* @param iconnr
* The iconnr
*/
@JsonProperty("iconnr")
public void setIconnr(Integer iconnr) {
this.iconnr = iconnr;
}
/**
*
* @param popupsize
* The popupsize
*/
@JsonProperty("popupsize")
public void setPopupsize(String popupsize) {
this.popupsize = popupsize;
}
/**
*
* @param graphsize
* The graphsize
*/
@JsonProperty("graphsize")
public void setGraphsize(String graphsize) {
this.graphsize = graphsize;
}
/**
*
* @param waardeh10a
* The waardeh10a
*/
@JsonProperty("waardeh10a")
public void setWaardeh10a(Object waardeh10a) {
this.waardeh10a = waardeh10a;
}
/**
*
* @param waardeh10v
* The waardeh10v
*/
@JsonProperty("waardeh10v")
public void setWaardeh10v(Object waardeh10v) {
this.waardeh10v = waardeh10v;
}
/**
*
* @param waardeq10v
* The waardeq10v
*/
@JsonProperty("waardeq10v")
public void setWaardeq10v(Object waardeq10v) {
this.waardeq10v = waardeq10v;
}
/**
*
* @return
* The iconsubscript
*/
@JsonProperty("iconsubscript")
public String getIconsubscript() {
return iconsubscript;
}
/**
*
* @param iconsubscript
* The iconsubscript
*/
@JsonProperty("iconsubscript")
public void setIconsubscript(String iconsubscript) {
this.iconsubscript = iconsubscript;
}
/**
*
* @return
<SUF>*/
@JsonProperty("meettijd")
public String getMeettijd() {
return meettijd;
}
/**
*
* @param meettijd
* The meettijd
*/
@JsonProperty("meettijd")
public void setMeettijd(String meettijd) {
this.meettijd = meettijd;
}
/**
*
* @param linkWn
* The link_wn
*/
@JsonProperty("link_wn")
public void setLinkWn(Object linkWn) {
this.linkWn = linkWn;
}
/**
*
* @return
* The ids
*/
@JsonProperty("ids")
public List<String> getIds() {
return ids;
}
/**
*
* @param ids
* The ids
*/
@JsonProperty("ids")
public void setIds(List<String> ids) {
this.ids = ids;
}
/**
*
* @return
* The location
*/
@JsonProperty("location")
public Location getLocation() {
return location;
}
/**
*
* @param location
* The location
*/
@JsonProperty("location")
public void setLocation(Location location) {
this.location = location;
}
/**
*
* @return
* The categoryDescription
*/
@JsonProperty("categoryDescription")
public String getCategoryDescription() {
return categoryDescription;
}
/**
*
* @param categoryDescription
* The categoryDescription
*/
@JsonProperty("categoryDescription")
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
/**
*
* @param icon
* The icon
*/
@JsonProperty("icon")
public void setIcon(Icon icon) {
this.icon = icon;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
79453_0 | package com.ipsene.ipsene.controller;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.*;
import com.google.firebase.cloud.FirestoreClient;
import com.ipsene.ipsene.Globals;
import com.ipsene.ipsene.SceneController;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class AccusationController {
List<String> solutionList = new ArrayList<>();
@FXML
private ChoiceBox<String> whoChoice;
@FXML
private ChoiceBox<String> whatChoice;
@FXML
private ChoiceBox<String> whereChoice;
@FXML
private Button accusationButton;
public static final String lobbyPin = Globals.get_instance().lobbyPin;
Firestore db = FirestoreClient.getFirestore();
SceneController sceneController = new SceneController();
BoardController boardController = new BoardController();
public AccusationController() throws ExecutionException, InterruptedException{
}
public void initialize() {
fillWhatChoice();
fillWhoChoice();
filWhereChoice();
accusationButton.disableProperty().bind(
whoChoice.getSelectionModel().selectedItemProperty().isNull()
.or(whereChoice.getSelectionModel().selectedItemProperty().isNull())
.or(whatChoice.getSelectionModel().selectedItemProperty().isNull()));
}
public void fillWhoChoice(){
List<String> whoList = Arrays.asList("Miss Scarlet", "Colonel Mustard", "Mrs. White", "Mr. Green", "Mrs. Peacock", "Professor Plum");
whoChoice.getItems().addAll(whoList);
}
public void fillWhoChoiceEx() throws ExecutionException, InterruptedException {
List<String> whoList = new ArrayList<>();
CollectionReference docRef = db.collection(lobbyPin);
ApiFuture<QuerySnapshot> query = docRef.get();
QuerySnapshot snapshot = query.get();
snapshot.forEach((doc)-> {
whoList.add(doc.getId());
});
if(whoList.contains("System")){whoList.remove("System");}
whoChoice.getItems().addAll(whoList);
}
public void fillWhatChoice(){
List<String> whatList = Arrays.asList("Candlestick", "Dagger", "Lead pipe", "Revolver", "Rope", "Wrench");
whatChoice.getItems().addAll(whatList);
}
public void filWhereChoice(){
List<String> whereList = Arrays.asList("Kitchen", "Ballroom", "Conservatory", "Dining room", "Billiard room", "Library", "Lounge", "Hall", "Study");
whereChoice.getItems().addAll(whereList);
}
public void closeButtonAction(ActionEvent event) {
sceneController.closeWindow(event);
}
public List<String> getSolution() throws ExecutionException, InterruptedException {
DocumentReference docRef = db.collection(lobbyPin).document("System");
ApiFuture<DocumentSnapshot> future = docRef.get();
DocumentSnapshot document = future.get();
solutionList.add(Objects.requireNonNull(document.getData()).get("solPerson").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solWeapon").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solRoom").toString());
return solutionList;
}
public void accusationButton(ActionEvent event) throws IOException {
try{
String currentPlayer = Globals.get_instance().chosenPlayer;
//haalt de informatie op uit de keuzes
Object who = whoChoice.getSelectionModel().getSelectedItem();
Object what = whatChoice.getSelectionModel().getSelectedItem();
Object where = whereChoice.getSelectionModel().getSelectedItem();
//kijkt wat de solution is
solutionList = getSolution();
//vergelijkt de solution met het antwoord
if(solutionList.get(0).contains(who.toString()) && solutionList.get(1).contains(what.toString()) &&
solutionList.get(2).contains(where.toString())){
DocumentReference docRef = db.collection(lobbyPin).document("System");
Map<String, Object> updates = new HashMap<>();
updates.put("win", currentPlayer);
docRef.set(updates, SetOptions.merge());
boardController.switchPlayer(event);
sceneController.closeWindow(event);
} else {
Alert a = new Alert(Alert.AlertType.WARNING);
a.setContentText("You got it wrong \n Your turn has ended") ;
a.show();
boardController.switchPlayer(event);
sceneController.closeWindow(event);
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
} | wbouhdif/Cluedo-JavaFX | src/main/java/com/ipsene/ipsene/controller/AccusationController.java | 1,366 | //haalt de informatie op uit de keuzes | line_comment | nl | package com.ipsene.ipsene.controller;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.*;
import com.google.firebase.cloud.FirestoreClient;
import com.ipsene.ipsene.Globals;
import com.ipsene.ipsene.SceneController;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class AccusationController {
List<String> solutionList = new ArrayList<>();
@FXML
private ChoiceBox<String> whoChoice;
@FXML
private ChoiceBox<String> whatChoice;
@FXML
private ChoiceBox<String> whereChoice;
@FXML
private Button accusationButton;
public static final String lobbyPin = Globals.get_instance().lobbyPin;
Firestore db = FirestoreClient.getFirestore();
SceneController sceneController = new SceneController();
BoardController boardController = new BoardController();
public AccusationController() throws ExecutionException, InterruptedException{
}
public void initialize() {
fillWhatChoice();
fillWhoChoice();
filWhereChoice();
accusationButton.disableProperty().bind(
whoChoice.getSelectionModel().selectedItemProperty().isNull()
.or(whereChoice.getSelectionModel().selectedItemProperty().isNull())
.or(whatChoice.getSelectionModel().selectedItemProperty().isNull()));
}
public void fillWhoChoice(){
List<String> whoList = Arrays.asList("Miss Scarlet", "Colonel Mustard", "Mrs. White", "Mr. Green", "Mrs. Peacock", "Professor Plum");
whoChoice.getItems().addAll(whoList);
}
public void fillWhoChoiceEx() throws ExecutionException, InterruptedException {
List<String> whoList = new ArrayList<>();
CollectionReference docRef = db.collection(lobbyPin);
ApiFuture<QuerySnapshot> query = docRef.get();
QuerySnapshot snapshot = query.get();
snapshot.forEach((doc)-> {
whoList.add(doc.getId());
});
if(whoList.contains("System")){whoList.remove("System");}
whoChoice.getItems().addAll(whoList);
}
public void fillWhatChoice(){
List<String> whatList = Arrays.asList("Candlestick", "Dagger", "Lead pipe", "Revolver", "Rope", "Wrench");
whatChoice.getItems().addAll(whatList);
}
public void filWhereChoice(){
List<String> whereList = Arrays.asList("Kitchen", "Ballroom", "Conservatory", "Dining room", "Billiard room", "Library", "Lounge", "Hall", "Study");
whereChoice.getItems().addAll(whereList);
}
public void closeButtonAction(ActionEvent event) {
sceneController.closeWindow(event);
}
public List<String> getSolution() throws ExecutionException, InterruptedException {
DocumentReference docRef = db.collection(lobbyPin).document("System");
ApiFuture<DocumentSnapshot> future = docRef.get();
DocumentSnapshot document = future.get();
solutionList.add(Objects.requireNonNull(document.getData()).get("solPerson").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solWeapon").toString());
solutionList.add(Objects.requireNonNull(document.getData()).get("solRoom").toString());
return solutionList;
}
public void accusationButton(ActionEvent event) throws IOException {
try{
String currentPlayer = Globals.get_instance().chosenPlayer;
//haalt de<SUF>
Object who = whoChoice.getSelectionModel().getSelectedItem();
Object what = whatChoice.getSelectionModel().getSelectedItem();
Object where = whereChoice.getSelectionModel().getSelectedItem();
//kijkt wat de solution is
solutionList = getSolution();
//vergelijkt de solution met het antwoord
if(solutionList.get(0).contains(who.toString()) && solutionList.get(1).contains(what.toString()) &&
solutionList.get(2).contains(where.toString())){
DocumentReference docRef = db.collection(lobbyPin).document("System");
Map<String, Object> updates = new HashMap<>();
updates.put("win", currentPlayer);
docRef.set(updates, SetOptions.merge());
boardController.switchPlayer(event);
sceneController.closeWindow(event);
} else {
Alert a = new Alert(Alert.AlertType.WARNING);
a.setContentText("You got it wrong \n Your turn has ended") ;
a.show();
boardController.switchPlayer(event);
sceneController.closeWindow(event);
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
} |
173319_8 | package emu.lunarcore.game.rogue;
import java.util.*;
import emu.lunarcore.data.GameData;
import emu.lunarcore.data.config.AnchorInfo;
import emu.lunarcore.data.excel.RogueAeonExcel;
import emu.lunarcore.data.excel.RogueAreaExcel;
import emu.lunarcore.data.excel.RogueMapExcel;
import emu.lunarcore.game.battle.Battle;
import emu.lunarcore.game.enums.RogueBuffAeonType;
import emu.lunarcore.game.player.Player;
import emu.lunarcore.game.player.lineup.PlayerLineup;
import emu.lunarcore.proto.AvatarTypeOuterClass.AvatarType;
import emu.lunarcore.proto.BattleEndStatusOuterClass.BattleEndStatus;
import emu.lunarcore.proto.BattleStatisticsOuterClass.BattleStatistics;
import emu.lunarcore.proto.ExtraLineupTypeOuterClass.ExtraLineupType;
import emu.lunarcore.proto.RogueAvatarInfoOuterClass.RogueAvatarInfo;
import emu.lunarcore.proto.RogueBuffInfoOuterClass.RogueBuffInfo;
import emu.lunarcore.proto.RogueBuffSourceOuterClass.RogueBuffSource;
import emu.lunarcore.proto.RogueCurrentInfoOuterClass.RogueCurrentInfo;
import emu.lunarcore.proto.RogueFinishInfoOuterClass.RogueFinishInfo;
import emu.lunarcore.proto.RogueMapInfoOuterClass.RogueMapInfo;
import emu.lunarcore.proto.RogueMiracleInfoOuterClass.RogueMiracleInfo;
import emu.lunarcore.proto.RogueMiracleSourceOuterClass.RogueMiracleSource;
import emu.lunarcore.proto.RogueRecordAvatarOuterClass.RogueRecordAvatar;
import emu.lunarcore.proto.RogueRecordInfoOuterClass.RogueRecordInfo;
import emu.lunarcore.proto.RogueRoomStatusOuterClass.RogueRoomStatus;
import emu.lunarcore.proto.RogueStatusOuterClass.RogueStatus;
import emu.lunarcore.server.packet.send.*;
import emu.lunarcore.util.Utils;
import lombok.Getter;
@Getter
public class RogueInstance {
private transient Player player;
private transient RogueAreaExcel excel;
private int areaId;
private int currentRoomProgress;
private int currentSiteId;
private int startSiteId;
private TreeMap<Integer, RogueRoomData> rooms;
private Set<Integer> baseAvatarIds;
private Map<Integer, RogueBuffData> buffs;
private Map<Integer, RogueMiracleData> miracles;
private int pendingBuffSelects;
private RogueBuffSelectMenu buffSelect;
private int pendingMiracleSelects;
private RogueMiracleSelectMenu miracleSelect;
private int baseRerolls;
private int aeonId;
private int aeonBuffType;
private int maxAeonBuffs;
private int roomScore;
private int earnedTalentCoin;
private boolean isWin;
@Deprecated // Morphia only!
public RogueInstance() {}
public RogueInstance(Player player, RogueAreaExcel excel, RogueAeonExcel aeonExcel) {
this.player = player;
this.excel = excel;
this.areaId = excel.getRogueAreaID();
this.currentRoomProgress = 0;
this.baseAvatarIds = new HashSet<>();
this.buffs = new HashMap<>();
this.miracles = new HashMap<>();
this.maxAeonBuffs = 4;
if (aeonExcel != null) {
this.aeonId = aeonExcel.getAeonID();
this.aeonBuffType = aeonExcel.getRogueBuffType();
}
this.initRooms();
this.initTalents();
}
public RogueStatus getStatus() {
return RogueStatus.ROGUE_STATUS_DOING;
}
private void initRooms() {
if (this.rooms != null) return;
this.rooms = new TreeMap<>();
for (var mapExcel : this.getExcel().getSites()) {
var roomData = new RogueRoomData(mapExcel);
this.rooms.put(roomData.getSiteId(), roomData);
if (mapExcel.isIsStart()) {
this.startSiteId = roomData.getSiteId();
}
}
}
private void initTalents() {
// Reset blessings
if (player.getRogueManager().hasTalent(11)) {
this.baseRerolls = 1;
}
// Extra blessings
if (player.getRogueManager().hasTalent(21)) {
this.pendingBuffSelects += 1;
}
}
private RogueRoomData getRoomBySiteId(int siteId) {
return this.rooms.get(siteId);
}
public RogueRoomData getCurrentRoom() {
return this.getRoomBySiteId(this.getCurrentSiteId());
}
private boolean shouldAddAeonBuff() {
int pathBuffs = 0; // Buffs on the current path
int aeonBuffs = 0;
for (var b : this.getBuffs().values()) {
var excel = b.getExcel();
if (excel == null) continue;
if (excel.getRogueBuffType() == this.getAeonBuffType()) {
if (excel.isAeonBuff()) {
aeonBuffs++;
} else {
pathBuffs++;
}
}
}
// Skip if we are already at max aeon buffs
if (aeonBuffs >= this.maxAeonBuffs) {
return false;
}
switch (aeonBuffs) {
case 0:
return pathBuffs >= 3;
case 1:
return pathBuffs >= 6;
case 2:
return pathBuffs >= 10;
case 3:
return pathBuffs >= 14;
default:
return false;
}
}
public synchronized void createBuffSelect(int amount) {
this.pendingBuffSelects += amount;
RogueBuffSelectMenu buffSelect = this.updateBuffSelect();
if (buffSelect != null) {
getPlayer().sendPacket(new PacketSyncRogueBuffSelectInfoScNotify(buffSelect));
}
}
public synchronized RogueBuffSelectMenu updateBuffSelect() {
if (this.getBuffSelect() == null) {
// Creates a new blessing selection menu if we have any pending buff selects
if (this.pendingBuffSelects > 0) {
// Regular blessing selection with 3 random blessings
this.buffSelect = new RogueBuffSelectMenu(this, false);
this.pendingBuffSelects--;
} else if (this.getAeonId() != 0) {
// Check if we should add aeon blessings
if (shouldAddAeonBuff()) {
this.buffSelect = new RogueBuffSelectMenu(this, true);
}
}
return this.buffSelect;
}
return null;
}
public synchronized RogueBuffSelectMenu rollBuffSelect() {
if (getBuffSelect() != null && getBuffSelect().hasRerolls()) {
this.getBuffSelect().reroll();
return this.getBuffSelect();
}
return null;
}
public synchronized RogueBuffData selectBuff(int buffId) {
// Sanity
if (this.getBuffSelect() == null) return null;
// Validate buff from buff select menu
RogueBuffData buff = this.getBuffSelect().getBuffs()
.stream()
.filter(b -> b.getId() == buffId)
.findFirst()
.orElse(null);
if (buff == null) return null;
// Add buff
this.buffSelect = null;
this.getBuffs().put(buff.getId(), buff);
getPlayer().sendPacket(new PacketAddRogueBuffScNotify(buff, RogueBuffSource.ROGUE_BUFF_SOURCE_TYPE_SELECT));
return buff;
}
public synchronized void createMiracleSelect(int amount) {
this.pendingMiracleSelects += amount;
RogueMiracleSelectMenu miracleSelect = this.updateMiracleSelect();
if (miracleSelect != null) {
getPlayer().sendPacket(new PacketSyncRogueMiracleSelectInfoScNotify(miracleSelect));
}
}
public synchronized RogueMiracleSelectMenu updateMiracleSelect() {
if (this.pendingMiracleSelects > 0 && this.getMiracleSelect() == null) {
this.miracleSelect = new RogueMiracleSelectMenu(this);
this.pendingMiracleSelects--;
return this.miracleSelect;
}
return null;
}
public synchronized RogueMiracleData selectMiracle(int miracleId) {
if (this.getMiracleSelect() == null) return null;
RogueMiracleData miracle = this.getMiracleSelect().getMiracles()
.stream()
.filter(b -> b.getId() == miracleId)
.findFirst()
.orElse(null);
if (miracle == null) return null;
this.miracleSelect = null;
this.getMiracles().put(miracle.getId(), miracle);
getPlayer().sendPacket(new PacketAddRogueMiracleScNotify(miracle, RogueMiracleSource.ROGUE_MIRACLE_SOURCE_TYPE_SELECT));
return miracle;
}
public synchronized RogueRoomData enterRoom(int siteId) {
// Set status on previous room
RogueRoomData prevRoom = this.getCurrentRoom();
if (prevRoom != null) {
// Make sure the site we want to go into is connected to the current room we are in
if (!Utils.arrayContains(prevRoom.getNextSiteIds(), siteId)) {
return null;
}
// Update status
prevRoom.setStatus(RogueRoomStatus.ROGUE_ROOM_STATUS_FINISH);
}
// Get next room
RogueRoomData nextRoom = this.getRoomBySiteId(siteId);
if (nextRoom == null) return null;
// Enter room
this.currentRoomProgress++;
this.currentSiteId = nextRoom.getSiteId();
nextRoom.setStatus(RogueRoomStatus.ROGUE_ROOM_STATUS_PLAY);
// Enter scene
boolean success = getPlayer().enterScene(nextRoom.getRoomExcel().getMapEntrance(), 0, false);
if (!success) return null;
// Move player to rogue start position
AnchorInfo anchor = getPlayer().getScene().getFloorInfo().getAnchorInfo(nextRoom.getExcel().getGroupID(), 1);
if (anchor != null) {
getPlayer().getPos().set(anchor.getPos());
getPlayer().getRot().set(anchor.getRot());
}
// Send packet if we are not entering the rogue instance for the first time
if (prevRoom != null) {
getPlayer().sendPacket(new PacketSyncRogueMapRoomScNotify(this, prevRoom));
getPlayer().sendPacket(new PacketSyncRogueMapRoomScNotify(this, nextRoom));
}
return nextRoom;
}
public void onFinish() {
// Calculate completed rooms
int completedRooms = Math.max(this.currentRoomProgress - (this.isWin() ? 0 : 1), 0);
// Calculate score and talent point rewards
this.roomScore = this.getExcel().getScoreMap().get(completedRooms);
this.earnedTalentCoin = this.roomScore / 10;
// Add coins to player
if (this.earnedTalentCoin > 0) {
this.getPlayer().addTalentPoints(this.earnedTalentCoin);
this.getPlayer().save();
}
}
// Dialogue stuff
public void onSelectDialogue(int dialogueEventId) {
}
// Battle
public synchronized void onBattleStart(Battle battle) {
// Add rogue blessings as battle buffs
for (var buff : this.getBuffs().values()) {
// Convert blessing to battle buff
battle.addBuff(buff.toMazeBuff());
// Set battle buff energy to max
if (buff.getExcel().getBattleEventBuffType() == RogueBuffAeonType.BattleEventBuff) {
RogueBuffType type = RogueBuffType.getById(getAeonBuffType());
if (type != null && type.getBattleEventSkill() != 0) {
battle.getTurnSnapshotList().add(type.getBattleEventSkill());
}
}
}
// Set monster level for battle
RogueMapExcel mapExcel = GameData.getRogueMapExcel(this.getExcel().getMapId(), this.getCurrentSiteId());
if (mapExcel != null && mapExcel.getLevelList() != null && mapExcel.getLevelList().length >= 1) {
battle.setCustomLevel(mapExcel.getLevelList()[0]);
}
}
public synchronized void onBattleFinish(Battle battle, BattleEndStatus result, BattleStatistics stats) {
if (result == BattleEndStatus.BATTLE_END_WIN) {
int roomType = this.getCurrentRoom().getExcel().getRogueRoomType();
if (roomType == RogueRoomType.BOSS.getVal()) {
// Final boss
this.isWin = true;
} else {
// Give blessings to player
int amount = battle.getNpcMonsters().size();
this.createBuffSelect(amount);
}
}
}
// Database
public void onLoad(Player player) {
this.player = player;
this.excel = GameData.getRogueAreaExcelMap().get(areaId);
if (this.getBuffSelect() != null) {
this.getBuffSelect().onLoad(this);
}
if (this.getMiracleSelect() != null) {
this.getMiracleSelect().onLoad(this);
}
}
// Serialization
public RogueCurrentInfo toProto() {
var proto = RogueCurrentInfo.newInstance()
.setStatus(this.getStatus())
.setRogueAvatarInfo(this.toAvatarInfoProto())
.setRoomMap(this.toMapInfoProto())
.setRogueBuffInfo(this.toBuffInfoProto())
.setRogueMiracleInfo(this.toMiracleInfoProto());
return proto;
}
public RogueAvatarInfo toAvatarInfoProto() {
var proto = RogueAvatarInfo.newInstance();
for (int id : this.getBaseAvatarIds()) {
proto.addBaseAvatarIdList(id);
}
return proto;
}
public RogueMapInfo toMapInfoProto() {
var room = this.getCurrentRoom();
var proto = RogueMapInfo.newInstance()
.setAreaId(this.getExcel().getId())
.setMapId(this.getExcel().getMapId())
.setCurSiteId(room.getSiteId())
.setCurRoomId(room.getRoomId());
for (var roomData : this.getRooms().values()) {
proto.addRoomList(roomData.toProto());
}
return proto;
}
public RogueBuffInfo toBuffInfoProto() {
var proto = RogueBuffInfo.newInstance();
if (this.getBuffSelect() != null) {
proto.setBuffSelectInfo(this.getBuffSelect().toProto());
} else {
proto.getMutableBuffSelectInfo();
}
for (var buff : this.getBuffs().values()) {
proto.addMazeBuffList(buff.toProto());
}
return proto;
}
public RogueMiracleInfo toMiracleInfoProto() {
var proto = RogueMiracleInfo.newInstance();
if (this.getMiracleSelect() != null) {
proto.setMiracleSelectInfo(this.getMiracleSelect().toProto());
} else {
proto.getMutableMiracleSelectInfo();
}
// Set flag for this so it gets serialized
proto.getMutableRogueMiracleInfo();
for (var miracle : this.getMiracles().values()) {
proto.getMutableRogueMiracleInfo().addRogueMiracleList(miracle.toProto());
}
return proto;
}
public RogueFinishInfo toFinishInfoProto() {
// Rogue record info
var recordInfo = RogueRecordInfo.newInstance();
for (var buff : this.getBuffs().values()) {
recordInfo.addBuffList(buff.toProto());
}
for (var miracle : this.getMiracles().values()) {
recordInfo.addRogueMiracleList(miracle.getId());
}
PlayerLineup lineup = getPlayer().getLineupManager().getExtraLineupByType(ExtraLineupType.LINEUP_ROGUE_VALUE);
if (lineup != null) {
for (int i = 0; i < lineup.getAvatars().size(); i++) {
var recordAvatar = RogueRecordAvatar.newInstance()
.setId(lineup.getAvatars().get(i))
.setSlot(i)
.setAvatarType(AvatarType.AVATAR_FORMAL_TYPE);
recordInfo.addAvatarList(recordAvatar);
}
}
// Create rogue finish info
var proto = RogueFinishInfo.newInstance()
.setTotalScore(this.getRoomScore())
.setTalentCoin(this.getEarnedTalentCoin())
.setAreaId(this.getAreaId())
.setIsWin(this.isWin())
.setPassRoomCount(this.getCurrentSiteId())
.setReachRoomCount(this.getCurrentRoomProgress())
.setRecordInfo(recordInfo);
return proto;
}
} | wcjqwq/LunarCore | src/main/java/emu/lunarcore/game/rogue/RogueInstance.java | 5,211 | // Get next room | line_comment | nl | package emu.lunarcore.game.rogue;
import java.util.*;
import emu.lunarcore.data.GameData;
import emu.lunarcore.data.config.AnchorInfo;
import emu.lunarcore.data.excel.RogueAeonExcel;
import emu.lunarcore.data.excel.RogueAreaExcel;
import emu.lunarcore.data.excel.RogueMapExcel;
import emu.lunarcore.game.battle.Battle;
import emu.lunarcore.game.enums.RogueBuffAeonType;
import emu.lunarcore.game.player.Player;
import emu.lunarcore.game.player.lineup.PlayerLineup;
import emu.lunarcore.proto.AvatarTypeOuterClass.AvatarType;
import emu.lunarcore.proto.BattleEndStatusOuterClass.BattleEndStatus;
import emu.lunarcore.proto.BattleStatisticsOuterClass.BattleStatistics;
import emu.lunarcore.proto.ExtraLineupTypeOuterClass.ExtraLineupType;
import emu.lunarcore.proto.RogueAvatarInfoOuterClass.RogueAvatarInfo;
import emu.lunarcore.proto.RogueBuffInfoOuterClass.RogueBuffInfo;
import emu.lunarcore.proto.RogueBuffSourceOuterClass.RogueBuffSource;
import emu.lunarcore.proto.RogueCurrentInfoOuterClass.RogueCurrentInfo;
import emu.lunarcore.proto.RogueFinishInfoOuterClass.RogueFinishInfo;
import emu.lunarcore.proto.RogueMapInfoOuterClass.RogueMapInfo;
import emu.lunarcore.proto.RogueMiracleInfoOuterClass.RogueMiracleInfo;
import emu.lunarcore.proto.RogueMiracleSourceOuterClass.RogueMiracleSource;
import emu.lunarcore.proto.RogueRecordAvatarOuterClass.RogueRecordAvatar;
import emu.lunarcore.proto.RogueRecordInfoOuterClass.RogueRecordInfo;
import emu.lunarcore.proto.RogueRoomStatusOuterClass.RogueRoomStatus;
import emu.lunarcore.proto.RogueStatusOuterClass.RogueStatus;
import emu.lunarcore.server.packet.send.*;
import emu.lunarcore.util.Utils;
import lombok.Getter;
@Getter
public class RogueInstance {
private transient Player player;
private transient RogueAreaExcel excel;
private int areaId;
private int currentRoomProgress;
private int currentSiteId;
private int startSiteId;
private TreeMap<Integer, RogueRoomData> rooms;
private Set<Integer> baseAvatarIds;
private Map<Integer, RogueBuffData> buffs;
private Map<Integer, RogueMiracleData> miracles;
private int pendingBuffSelects;
private RogueBuffSelectMenu buffSelect;
private int pendingMiracleSelects;
private RogueMiracleSelectMenu miracleSelect;
private int baseRerolls;
private int aeonId;
private int aeonBuffType;
private int maxAeonBuffs;
private int roomScore;
private int earnedTalentCoin;
private boolean isWin;
@Deprecated // Morphia only!
public RogueInstance() {}
public RogueInstance(Player player, RogueAreaExcel excel, RogueAeonExcel aeonExcel) {
this.player = player;
this.excel = excel;
this.areaId = excel.getRogueAreaID();
this.currentRoomProgress = 0;
this.baseAvatarIds = new HashSet<>();
this.buffs = new HashMap<>();
this.miracles = new HashMap<>();
this.maxAeonBuffs = 4;
if (aeonExcel != null) {
this.aeonId = aeonExcel.getAeonID();
this.aeonBuffType = aeonExcel.getRogueBuffType();
}
this.initRooms();
this.initTalents();
}
public RogueStatus getStatus() {
return RogueStatus.ROGUE_STATUS_DOING;
}
private void initRooms() {
if (this.rooms != null) return;
this.rooms = new TreeMap<>();
for (var mapExcel : this.getExcel().getSites()) {
var roomData = new RogueRoomData(mapExcel);
this.rooms.put(roomData.getSiteId(), roomData);
if (mapExcel.isIsStart()) {
this.startSiteId = roomData.getSiteId();
}
}
}
private void initTalents() {
// Reset blessings
if (player.getRogueManager().hasTalent(11)) {
this.baseRerolls = 1;
}
// Extra blessings
if (player.getRogueManager().hasTalent(21)) {
this.pendingBuffSelects += 1;
}
}
private RogueRoomData getRoomBySiteId(int siteId) {
return this.rooms.get(siteId);
}
public RogueRoomData getCurrentRoom() {
return this.getRoomBySiteId(this.getCurrentSiteId());
}
private boolean shouldAddAeonBuff() {
int pathBuffs = 0; // Buffs on the current path
int aeonBuffs = 0;
for (var b : this.getBuffs().values()) {
var excel = b.getExcel();
if (excel == null) continue;
if (excel.getRogueBuffType() == this.getAeonBuffType()) {
if (excel.isAeonBuff()) {
aeonBuffs++;
} else {
pathBuffs++;
}
}
}
// Skip if we are already at max aeon buffs
if (aeonBuffs >= this.maxAeonBuffs) {
return false;
}
switch (aeonBuffs) {
case 0:
return pathBuffs >= 3;
case 1:
return pathBuffs >= 6;
case 2:
return pathBuffs >= 10;
case 3:
return pathBuffs >= 14;
default:
return false;
}
}
public synchronized void createBuffSelect(int amount) {
this.pendingBuffSelects += amount;
RogueBuffSelectMenu buffSelect = this.updateBuffSelect();
if (buffSelect != null) {
getPlayer().sendPacket(new PacketSyncRogueBuffSelectInfoScNotify(buffSelect));
}
}
public synchronized RogueBuffSelectMenu updateBuffSelect() {
if (this.getBuffSelect() == null) {
// Creates a new blessing selection menu if we have any pending buff selects
if (this.pendingBuffSelects > 0) {
// Regular blessing selection with 3 random blessings
this.buffSelect = new RogueBuffSelectMenu(this, false);
this.pendingBuffSelects--;
} else if (this.getAeonId() != 0) {
// Check if we should add aeon blessings
if (shouldAddAeonBuff()) {
this.buffSelect = new RogueBuffSelectMenu(this, true);
}
}
return this.buffSelect;
}
return null;
}
public synchronized RogueBuffSelectMenu rollBuffSelect() {
if (getBuffSelect() != null && getBuffSelect().hasRerolls()) {
this.getBuffSelect().reroll();
return this.getBuffSelect();
}
return null;
}
public synchronized RogueBuffData selectBuff(int buffId) {
// Sanity
if (this.getBuffSelect() == null) return null;
// Validate buff from buff select menu
RogueBuffData buff = this.getBuffSelect().getBuffs()
.stream()
.filter(b -> b.getId() == buffId)
.findFirst()
.orElse(null);
if (buff == null) return null;
// Add buff
this.buffSelect = null;
this.getBuffs().put(buff.getId(), buff);
getPlayer().sendPacket(new PacketAddRogueBuffScNotify(buff, RogueBuffSource.ROGUE_BUFF_SOURCE_TYPE_SELECT));
return buff;
}
public synchronized void createMiracleSelect(int amount) {
this.pendingMiracleSelects += amount;
RogueMiracleSelectMenu miracleSelect = this.updateMiracleSelect();
if (miracleSelect != null) {
getPlayer().sendPacket(new PacketSyncRogueMiracleSelectInfoScNotify(miracleSelect));
}
}
public synchronized RogueMiracleSelectMenu updateMiracleSelect() {
if (this.pendingMiracleSelects > 0 && this.getMiracleSelect() == null) {
this.miracleSelect = new RogueMiracleSelectMenu(this);
this.pendingMiracleSelects--;
return this.miracleSelect;
}
return null;
}
public synchronized RogueMiracleData selectMiracle(int miracleId) {
if (this.getMiracleSelect() == null) return null;
RogueMiracleData miracle = this.getMiracleSelect().getMiracles()
.stream()
.filter(b -> b.getId() == miracleId)
.findFirst()
.orElse(null);
if (miracle == null) return null;
this.miracleSelect = null;
this.getMiracles().put(miracle.getId(), miracle);
getPlayer().sendPacket(new PacketAddRogueMiracleScNotify(miracle, RogueMiracleSource.ROGUE_MIRACLE_SOURCE_TYPE_SELECT));
return miracle;
}
public synchronized RogueRoomData enterRoom(int siteId) {
// Set status on previous room
RogueRoomData prevRoom = this.getCurrentRoom();
if (prevRoom != null) {
// Make sure the site we want to go into is connected to the current room we are in
if (!Utils.arrayContains(prevRoom.getNextSiteIds(), siteId)) {
return null;
}
// Update status
prevRoom.setStatus(RogueRoomStatus.ROGUE_ROOM_STATUS_FINISH);
}
// Get next<SUF>
RogueRoomData nextRoom = this.getRoomBySiteId(siteId);
if (nextRoom == null) return null;
// Enter room
this.currentRoomProgress++;
this.currentSiteId = nextRoom.getSiteId();
nextRoom.setStatus(RogueRoomStatus.ROGUE_ROOM_STATUS_PLAY);
// Enter scene
boolean success = getPlayer().enterScene(nextRoom.getRoomExcel().getMapEntrance(), 0, false);
if (!success) return null;
// Move player to rogue start position
AnchorInfo anchor = getPlayer().getScene().getFloorInfo().getAnchorInfo(nextRoom.getExcel().getGroupID(), 1);
if (anchor != null) {
getPlayer().getPos().set(anchor.getPos());
getPlayer().getRot().set(anchor.getRot());
}
// Send packet if we are not entering the rogue instance for the first time
if (prevRoom != null) {
getPlayer().sendPacket(new PacketSyncRogueMapRoomScNotify(this, prevRoom));
getPlayer().sendPacket(new PacketSyncRogueMapRoomScNotify(this, nextRoom));
}
return nextRoom;
}
public void onFinish() {
// Calculate completed rooms
int completedRooms = Math.max(this.currentRoomProgress - (this.isWin() ? 0 : 1), 0);
// Calculate score and talent point rewards
this.roomScore = this.getExcel().getScoreMap().get(completedRooms);
this.earnedTalentCoin = this.roomScore / 10;
// Add coins to player
if (this.earnedTalentCoin > 0) {
this.getPlayer().addTalentPoints(this.earnedTalentCoin);
this.getPlayer().save();
}
}
// Dialogue stuff
public void onSelectDialogue(int dialogueEventId) {
}
// Battle
public synchronized void onBattleStart(Battle battle) {
// Add rogue blessings as battle buffs
for (var buff : this.getBuffs().values()) {
// Convert blessing to battle buff
battle.addBuff(buff.toMazeBuff());
// Set battle buff energy to max
if (buff.getExcel().getBattleEventBuffType() == RogueBuffAeonType.BattleEventBuff) {
RogueBuffType type = RogueBuffType.getById(getAeonBuffType());
if (type != null && type.getBattleEventSkill() != 0) {
battle.getTurnSnapshotList().add(type.getBattleEventSkill());
}
}
}
// Set monster level for battle
RogueMapExcel mapExcel = GameData.getRogueMapExcel(this.getExcel().getMapId(), this.getCurrentSiteId());
if (mapExcel != null && mapExcel.getLevelList() != null && mapExcel.getLevelList().length >= 1) {
battle.setCustomLevel(mapExcel.getLevelList()[0]);
}
}
public synchronized void onBattleFinish(Battle battle, BattleEndStatus result, BattleStatistics stats) {
if (result == BattleEndStatus.BATTLE_END_WIN) {
int roomType = this.getCurrentRoom().getExcel().getRogueRoomType();
if (roomType == RogueRoomType.BOSS.getVal()) {
// Final boss
this.isWin = true;
} else {
// Give blessings to player
int amount = battle.getNpcMonsters().size();
this.createBuffSelect(amount);
}
}
}
// Database
public void onLoad(Player player) {
this.player = player;
this.excel = GameData.getRogueAreaExcelMap().get(areaId);
if (this.getBuffSelect() != null) {
this.getBuffSelect().onLoad(this);
}
if (this.getMiracleSelect() != null) {
this.getMiracleSelect().onLoad(this);
}
}
// Serialization
public RogueCurrentInfo toProto() {
var proto = RogueCurrentInfo.newInstance()
.setStatus(this.getStatus())
.setRogueAvatarInfo(this.toAvatarInfoProto())
.setRoomMap(this.toMapInfoProto())
.setRogueBuffInfo(this.toBuffInfoProto())
.setRogueMiracleInfo(this.toMiracleInfoProto());
return proto;
}
public RogueAvatarInfo toAvatarInfoProto() {
var proto = RogueAvatarInfo.newInstance();
for (int id : this.getBaseAvatarIds()) {
proto.addBaseAvatarIdList(id);
}
return proto;
}
public RogueMapInfo toMapInfoProto() {
var room = this.getCurrentRoom();
var proto = RogueMapInfo.newInstance()
.setAreaId(this.getExcel().getId())
.setMapId(this.getExcel().getMapId())
.setCurSiteId(room.getSiteId())
.setCurRoomId(room.getRoomId());
for (var roomData : this.getRooms().values()) {
proto.addRoomList(roomData.toProto());
}
return proto;
}
public RogueBuffInfo toBuffInfoProto() {
var proto = RogueBuffInfo.newInstance();
if (this.getBuffSelect() != null) {
proto.setBuffSelectInfo(this.getBuffSelect().toProto());
} else {
proto.getMutableBuffSelectInfo();
}
for (var buff : this.getBuffs().values()) {
proto.addMazeBuffList(buff.toProto());
}
return proto;
}
public RogueMiracleInfo toMiracleInfoProto() {
var proto = RogueMiracleInfo.newInstance();
if (this.getMiracleSelect() != null) {
proto.setMiracleSelectInfo(this.getMiracleSelect().toProto());
} else {
proto.getMutableMiracleSelectInfo();
}
// Set flag for this so it gets serialized
proto.getMutableRogueMiracleInfo();
for (var miracle : this.getMiracles().values()) {
proto.getMutableRogueMiracleInfo().addRogueMiracleList(miracle.toProto());
}
return proto;
}
public RogueFinishInfo toFinishInfoProto() {
// Rogue record info
var recordInfo = RogueRecordInfo.newInstance();
for (var buff : this.getBuffs().values()) {
recordInfo.addBuffList(buff.toProto());
}
for (var miracle : this.getMiracles().values()) {
recordInfo.addRogueMiracleList(miracle.getId());
}
PlayerLineup lineup = getPlayer().getLineupManager().getExtraLineupByType(ExtraLineupType.LINEUP_ROGUE_VALUE);
if (lineup != null) {
for (int i = 0; i < lineup.getAvatars().size(); i++) {
var recordAvatar = RogueRecordAvatar.newInstance()
.setId(lineup.getAvatars().get(i))
.setSlot(i)
.setAvatarType(AvatarType.AVATAR_FORMAL_TYPE);
recordInfo.addAvatarList(recordAvatar);
}
}
// Create rogue finish info
var proto = RogueFinishInfo.newInstance()
.setTotalScore(this.getRoomScore())
.setTalentCoin(this.getEarnedTalentCoin())
.setAreaId(this.getAreaId())
.setIsWin(this.isWin())
.setPassRoomCount(this.getCurrentSiteId())
.setReachRoomCount(this.getCurrentRoomProgress())
.setRecordInfo(recordInfo);
return proto;
}
} |
126750_3 | package com.schooner.MemCached;
import java.io.DataInputStream;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import org.apache.commons.pool2.PooledObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.schooner.MemCached.command.DeletionCommand;
import com.whalin.MemCached.MemCachedClient;
/**
* * {@link AuthSchoonerSockIOFactory} is used to create and destroy socket for connection pool with authorized information.
*
* @author Meng Li
* @since 2.6.1
* @see AuthSchoonerSockIOFactory
*/
public class AuthSchoonerSockIOFactory extends SchoonerSockIOFactory {
private static final Logger LOG = LogManager.getLogger(DeletionCommand.class);
public final static String NTLM = "NTLM";
public final static String PLAIN = "PLAIN";
public final static String LOGIN = "LOGIN";
public final static String DIGEST_MD5 = "DIGEST-MD5";
public final static String CRAM_MD5 = "CRAM-MD5";
public final static String ANONYMOUS = "ANONYMOUS";
public static final byte[] EMPTY_BYTES = new byte[0];
private AuthInfo authInfo;
public AuthSchoonerSockIOFactory(String host, boolean isTcp, int bufferSize, int socketTO, int socketConnectTO, boolean nagle, AuthInfo authInfo) {
super(host, isTcp, bufferSize, socketTO, socketConnectTO, nagle);
this.authInfo = authInfo;
}
@Override
public PooledObject<SchoonerSockIO> makeObject() throws Exception {
SchoonerSockIO socket = createSocket(host);
auth(socket);
return wrap(socket);
}
private void auth(SchoonerSockIO socket) throws Exception {
SaslClient saslClient = Sasl.createSaslClient(authInfo.getMechanisms(), null, "memcached", host, null, this.authInfo.getCallbackHandler());
byte[] authData = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(EMPTY_BYTES) : EMPTY_BYTES;
authData = sendAuthData(socket, MemCachedClient.OPCODE_START_AUTH, saslClient.getMechanismName(), authData);
if (authData == null)
return;
authData = saslClient.evaluateChallenge(authData);
if (sendAuthData(socket, MemCachedClient.OPCODE_AUTH_STEPS, saslClient.getMechanismName(), authData) == null)
return;
LOG.error("Auth Failed: mechanism = " + saslClient.getMechanismName());
throw new Exception();
}
private byte[] sendAuthData(SchoonerSockIO sock, byte opcode, String mechanism, byte[] authData) throws Exception {
sock.writeBuf.clear();
sock.writeBuf.put(MemCachedClient.MAGIC_REQ);
sock.writeBuf.put(opcode);
sock.writeBuf.putShort((short) mechanism.length());
sock.writeBuf.putInt(0);
sock.writeBuf.putInt(mechanism.length() + authData.length);
sock.writeBuf.putInt(0);
sock.writeBuf.putLong(0);
sock.writeBuf.put(mechanism.getBytes());
sock.writeBuf.put(authData);
// write the buffer to server
// now write the data to the cache server
sock.flush();
// get result code
DataInputStream dis = new DataInputStream(new SockInputStream(sock, Integer.MAX_VALUE));
dis.readInt();
dis.readByte();
dis.readByte();
byte[] response = null;
short status = dis.readShort();
if (status == MemCachedClient.FURTHER_AUTH) {
int length = dis.readInt();
response = new byte[length];
dis.readInt();
dis.readLong();
dis.read(response);
} else if (status == MemCachedClient.AUTH_FAILED) {
LOG.error("Auth Failed: mechanism = " + mechanism);
dis.close();
throw new Exception();
}
dis.close();
return response;
}
}
| wdcode/weicoder | memcache/src/main/java/com/schooner/MemCached/AuthSchoonerSockIOFactory.java | 1,184 | // get result code | line_comment | nl | package com.schooner.MemCached;
import java.io.DataInputStream;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import org.apache.commons.pool2.PooledObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.schooner.MemCached.command.DeletionCommand;
import com.whalin.MemCached.MemCachedClient;
/**
* * {@link AuthSchoonerSockIOFactory} is used to create and destroy socket for connection pool with authorized information.
*
* @author Meng Li
* @since 2.6.1
* @see AuthSchoonerSockIOFactory
*/
public class AuthSchoonerSockIOFactory extends SchoonerSockIOFactory {
private static final Logger LOG = LogManager.getLogger(DeletionCommand.class);
public final static String NTLM = "NTLM";
public final static String PLAIN = "PLAIN";
public final static String LOGIN = "LOGIN";
public final static String DIGEST_MD5 = "DIGEST-MD5";
public final static String CRAM_MD5 = "CRAM-MD5";
public final static String ANONYMOUS = "ANONYMOUS";
public static final byte[] EMPTY_BYTES = new byte[0];
private AuthInfo authInfo;
public AuthSchoonerSockIOFactory(String host, boolean isTcp, int bufferSize, int socketTO, int socketConnectTO, boolean nagle, AuthInfo authInfo) {
super(host, isTcp, bufferSize, socketTO, socketConnectTO, nagle);
this.authInfo = authInfo;
}
@Override
public PooledObject<SchoonerSockIO> makeObject() throws Exception {
SchoonerSockIO socket = createSocket(host);
auth(socket);
return wrap(socket);
}
private void auth(SchoonerSockIO socket) throws Exception {
SaslClient saslClient = Sasl.createSaslClient(authInfo.getMechanisms(), null, "memcached", host, null, this.authInfo.getCallbackHandler());
byte[] authData = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(EMPTY_BYTES) : EMPTY_BYTES;
authData = sendAuthData(socket, MemCachedClient.OPCODE_START_AUTH, saslClient.getMechanismName(), authData);
if (authData == null)
return;
authData = saslClient.evaluateChallenge(authData);
if (sendAuthData(socket, MemCachedClient.OPCODE_AUTH_STEPS, saslClient.getMechanismName(), authData) == null)
return;
LOG.error("Auth Failed: mechanism = " + saslClient.getMechanismName());
throw new Exception();
}
private byte[] sendAuthData(SchoonerSockIO sock, byte opcode, String mechanism, byte[] authData) throws Exception {
sock.writeBuf.clear();
sock.writeBuf.put(MemCachedClient.MAGIC_REQ);
sock.writeBuf.put(opcode);
sock.writeBuf.putShort((short) mechanism.length());
sock.writeBuf.putInt(0);
sock.writeBuf.putInt(mechanism.length() + authData.length);
sock.writeBuf.putInt(0);
sock.writeBuf.putLong(0);
sock.writeBuf.put(mechanism.getBytes());
sock.writeBuf.put(authData);
// write the buffer to server
// now write the data to the cache server
sock.flush();
// get result<SUF>
DataInputStream dis = new DataInputStream(new SockInputStream(sock, Integer.MAX_VALUE));
dis.readInt();
dis.readByte();
dis.readByte();
byte[] response = null;
short status = dis.readShort();
if (status == MemCachedClient.FURTHER_AUTH) {
int length = dis.readInt();
response = new byte[length];
dis.readInt();
dis.readLong();
dis.read(response);
} else if (status == MemCachedClient.AUTH_FAILED) {
LOG.error("Auth Failed: mechanism = " + mechanism);
dis.close();
throw new Exception();
}
dis.close();
return response;
}
}
|
22602_16 | /*
Copyright 2020, 2022, 2024 WeAreFrank!, 2018, 2019 Nationale-Nederlanden
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 nl.nn.testtool.echo2.reports;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nextapp.echo2.app.filetransfer.UploadEvent;
import nextapp.echo2.app.filetransfer.UploadListener;
import nl.nn.testtool.echo2.test.TestComponent;
import nl.nn.testtool.echo2.util.Upload;
import nl.nn.testtool.storage.CrudStorage;
import nl.nn.testtool.storage.StorageException;
/**
* @author Jaco de Groot
*/
public class ReportUploadListener implements UploadListener {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
ReportsComponent reportsComponent;
TestComponent testComponent;
CrudStorage storage;
public ReportUploadListener() {
}
public void setReportsComponent(ReportsComponent reportsComponent) {
this.reportsComponent = reportsComponent;
}
public void setTestComponent(TestComponent testComponent) {
this.testComponent = testComponent;
}
public void setStorage(CrudStorage storage) {
this.storage = storage;
}
public void fileUpload(UploadEvent uploadEvent) {
List reports = new ArrayList();
// String errorMessage = DownUpLoad.getReports(uploadEvent.getFileName(), uploadEvent.getInputStream(), reports, log);
// // TODO checken of errorMessage != null?
// for (int i = 0; i < reports.size(); i++) {
// Report report = (Report)reports.get(i);
// if (reportsComponent != null) {
// reportsComponent.openReport(report, true);
// } else {
// try {
// storage.store(report);
// } catch (StorageException e) {
// // TODO iets doen, errorMessage vullen?
// e.printStackTrace();
// }
// }
// }
CrudStorage storage = null;
if (reportsComponent != null) {
// TODO in reportsComponent memory storage bijhouden en gebruiken
// voor download en upload (niet telkens nieuwe aanmaken maar
// synchroon houden met open reports)?
storage = new nl.nn.testtool.storage.memory.Storage();
}
if (testComponent != null) {
storage = this.storage;
}
String errorMessage = Upload.upload(uploadEvent.getFileName(), uploadEvent.getInputStream(), storage, log);
if (reportsComponent != null) {
try {
List storageIds = storage.getStorageIds();
for (int i = storageIds.size() - 1; i > -1; i--) {
reportsComponent.openReport(storage.getReport((Integer)storageIds.get(i)),
ReportsComponent.OPEN_REPORT_ALLOWED, false, true);
}
} catch (StorageException e) {
// TODO iets doen, errorMessage vullen?
e.printStackTrace();
}
}
if (errorMessage != null) {
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayAndLogError(errorMessage);
}
if (testComponent != null) {
testComponent.displayAndLogError(errorMessage);
}
}
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
if (testComponent != null) {
testComponent.getUploadOptionsWindow().setVisible(false);
testComponent.refresh();
}
}
public void invalidFileUpload(UploadEvent uploadEvent) {
String message = "Invalid file upload: " + uploadEvent.getFileName()
+ ", " + uploadEvent.getContentType() + ", " + uploadEvent.getSize();
log.error(message);
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayError(message);
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
}
}
| wearefrank/ladybug | src/main/java/nl/nn/testtool/echo2/reports/ReportUploadListener.java | 1,285 | // TODO generieker maken zodat het ook voor TestComponent werkt | line_comment | nl | /*
Copyright 2020, 2022, 2024 WeAreFrank!, 2018, 2019 Nationale-Nederlanden
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 nl.nn.testtool.echo2.reports;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nextapp.echo2.app.filetransfer.UploadEvent;
import nextapp.echo2.app.filetransfer.UploadListener;
import nl.nn.testtool.echo2.test.TestComponent;
import nl.nn.testtool.echo2.util.Upload;
import nl.nn.testtool.storage.CrudStorage;
import nl.nn.testtool.storage.StorageException;
/**
* @author Jaco de Groot
*/
public class ReportUploadListener implements UploadListener {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
ReportsComponent reportsComponent;
TestComponent testComponent;
CrudStorage storage;
public ReportUploadListener() {
}
public void setReportsComponent(ReportsComponent reportsComponent) {
this.reportsComponent = reportsComponent;
}
public void setTestComponent(TestComponent testComponent) {
this.testComponent = testComponent;
}
public void setStorage(CrudStorage storage) {
this.storage = storage;
}
public void fileUpload(UploadEvent uploadEvent) {
List reports = new ArrayList();
// String errorMessage = DownUpLoad.getReports(uploadEvent.getFileName(), uploadEvent.getInputStream(), reports, log);
// // TODO checken of errorMessage != null?
// for (int i = 0; i < reports.size(); i++) {
// Report report = (Report)reports.get(i);
// if (reportsComponent != null) {
// reportsComponent.openReport(report, true);
// } else {
// try {
// storage.store(report);
// } catch (StorageException e) {
// // TODO iets doen, errorMessage vullen?
// e.printStackTrace();
// }
// }
// }
CrudStorage storage = null;
if (reportsComponent != null) {
// TODO in reportsComponent memory storage bijhouden en gebruiken
// voor download en upload (niet telkens nieuwe aanmaken maar
// synchroon houden met open reports)?
storage = new nl.nn.testtool.storage.memory.Storage();
}
if (testComponent != null) {
storage = this.storage;
}
String errorMessage = Upload.upload(uploadEvent.getFileName(), uploadEvent.getInputStream(), storage, log);
if (reportsComponent != null) {
try {
List storageIds = storage.getStorageIds();
for (int i = storageIds.size() - 1; i > -1; i--) {
reportsComponent.openReport(storage.getReport((Integer)storageIds.get(i)),
ReportsComponent.OPEN_REPORT_ALLOWED, false, true);
}
} catch (StorageException e) {
// TODO iets doen, errorMessage vullen?
e.printStackTrace();
}
}
if (errorMessage != null) {
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayAndLogError(errorMessage);
}
if (testComponent != null) {
testComponent.displayAndLogError(errorMessage);
}
}
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
if (testComponent != null) {
testComponent.getUploadOptionsWindow().setVisible(false);
testComponent.refresh();
}
}
public void invalidFileUpload(UploadEvent uploadEvent) {
String message = "Invalid file upload: " + uploadEvent.getFileName()
+ ", " + uploadEvent.getContentType() + ", " + uploadEvent.getSize();
log.error(message);
// TODO generieker<SUF>
if (reportsComponent != null) {
reportsComponent.displayError(message);
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
}
}
|
143216_7 | /*
* 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.coyote;
import java.io.IOException;
import java.util.Locale;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.http.MimeHeaders;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten <[email protected]>
* @author Remy Maucherat
*/
public final class Response {
// ----------------------------------------------------------- Constructors
public Response() {
}
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
protected int status = 200;
/**
* Status message.
*/
protected String message = null;
/**
* Response headers.
*/
protected MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* Notes.
*/
protected Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
protected boolean commited = false;
/**
* Action hook.
*/
public ActionHook hook;
/**
* HTTP specific fields.
*/
protected String contentType = null;
protected String contentLanguage = null;
protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
protected long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long bytesWritten=0;
/**
* Holds request error exception.
*/
protected Exception errorException = null;
/**
* Has the charset been explicitly set.
*/
protected boolean charsetSet = false;
/**
* Request error URI.
*/
protected String errorURI = null;
protected Request req;
protected int lastWrite = 1;
protected boolean flushLeftovers = true;
protected String sendfilePath = null;
protected long sendfileStart = 0;
protected long sendfileEnd = 0;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public OutputBuffer getOutputBuffer() {
return outputBuffer;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public ActionHook getHook() {
return hook;
}
public void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- State --------------------
public boolean getFlushLeftovers() {
return flushLeftovers;
}
public void setFlushLeftovers(boolean flushLeftovers) {
this.flushLeftovers = flushLeftovers;
}
public int getLastWrite() {
flushLeftovers = false;
return lastWrite;
}
public void setLastWrite(int lastWrite) {
this.lastWrite = lastWrite;
}
public int getStatus() {
return status;
}
/**
* Set the response status
*/
public void setStatus( int status ) {
this.status = status;
}
/**
* Get the status message.
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
this.commited = v;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during
* request processing.
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request
* processing.
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
/**
* Set request URI that caused an error during
* request processing.
*/
public void setErrorURI(String uri) {
errorURI = uri;
}
/** Get the request URI that caused the original error.
*/
public String getErrorURI() {
return errorURI;
}
// -------------------- Methods --------------------
public void reset()
throws IllegalStateException {
if (commited) {
throw new IllegalStateException();
}
recycle();
}
public void finish() throws IOException {
action(ActionCode.ACTION_CLOSE, this);
}
public void acknowledge() throws IOException {
action(ActionCode.ACTION_ACK, this);
}
// -------------------- Headers --------------------
/**
* Warning: This method always returns <code>false<code> for Content-Type
* and Content-Length.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.addValue(name).setString( value );
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
if( name.equalsIgnoreCase( "Content-Language" ) ) {
// XXX XXX Need to construct Locale or something else
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() throws IOException {
action(ActionCode.ACTION_COMMIT, this);
commited = true;
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitely by user to set the Content-Language and
* the default encoding
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.getLanguage();
if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
String country = locale.getCountry();
StringBuilder value = new StringBuilder(contentLanguage);
if ((country != null) && (country.length() > 0)) {
value.append('-');
value.append(country);
}
contentLanguage = value.toString();
}
}
/**
* Return the content language.
*/
public String getContentLanguage() {
return contentLanguage;
}
/*
* Overrides the name of the character encoding used in the body
* of the response. This method must be called prior to writing output
* using getWriter().
*
* @param charset String containing the name of the chararacter encoding.
*/
public void setCharacterEncoding(String charset) {
if (isCommitted())
return;
if (charset == null)
return;
characterEncoding = charset;
charsetSet=true;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
int semicolonIndex = -1;
if (type == null) {
this.contentType = null;
return;
}
/*
* Remove the charset param (if any) from the Content-Type, and use it
* to set the response encoding.
* The most recent response encoding setting will be appended to the
* response's Content-Type (as its charset param) by getContentType();
*/
boolean hasCharset = false;
int len = type.length();
int index = type.indexOf(';');
while (index != -1) {
semicolonIndex = index;
index++;
while (index < len && Character.isSpace(type.charAt(index))) {
index++;
}
if (index+8 < len
&& type.charAt(index) == 'c'
&& type.charAt(index+1) == 'h'
&& type.charAt(index+2) == 'a'
&& type.charAt(index+3) == 'r'
&& type.charAt(index+4) == 's'
&& type.charAt(index+5) == 'e'
&& type.charAt(index+6) == 't'
&& type.charAt(index+7) == '=') {
hasCharset = true;
break;
}
index = type.indexOf(';', index);
}
if (!hasCharset) {
this.contentType = type;
return;
}
this.contentType = type.substring(0, semicolonIndex);
String tail = type.substring(index+8);
int nextParam = tail.indexOf(';');
String charsetValue = null;
if (nextParam != -1) {
this.contentType += tail.substring(nextParam);
charsetValue = tail.substring(0, nextParam);
} else {
charsetValue = tail;
}
// The charset value may be quoted, but must not contain any quotes.
if (charsetValue != null && charsetValue.length() > 0) {
charsetSet=true;
charsetValue = charsetValue.replace('"', ' ');
this.characterEncoding = charsetValue.trim();
}
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& characterEncoding != null
&& charsetSet) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
public String getSendfilePath() {
return sendfilePath;
}
public void setSendfilePath(String sendfilePath) {
this.sendfilePath = sendfilePath;
}
public long getSendfileStart() {
return sendfileStart;
}
public void setSendfileStart(long sendfileStart) {
this.sendfileStart = sendfileStart;
}
public long getSendfileEnd() {
return sendfileEnd;
}
public void setSendfileEnd(long sendfileEnd) {
this.sendfileEnd = sendfileEnd;
}
/**
* Write a chunk of bytes.
*/
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/)
throws IOException
{
outputBuffer.doWrite(chunk, this);
bytesWritten+=chunk.getLength();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
charsetSet = false;
contentLength = -1;
status = 200;
message = null;
commited = false;
errorException = null;
errorURI = null;
headers.clear();
sendfilePath = null;
// update counters
lastWrite = 1;
bytesWritten=0;
}
public long getBytesWritten() {
return bytesWritten;
}
public void setBytesWritten(long bytesWritten) {
this.bytesWritten = bytesWritten;
}
}
| web-servers/jbossweb | java/org/apache/coyote/Response.java | 4,085 | /**
* Response headers.
*/ | block_comment | nl | /*
* 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.coyote;
import java.io.IOException;
import java.util.Locale;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.http.MimeHeaders;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten <[email protected]>
* @author Remy Maucherat
*/
public final class Response {
// ----------------------------------------------------------- Constructors
public Response() {
}
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
protected int status = 200;
/**
* Status message.
*/
protected String message = null;
/**
* Response headers.
<SUF>*/
protected MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* Notes.
*/
protected Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
protected boolean commited = false;
/**
* Action hook.
*/
public ActionHook hook;
/**
* HTTP specific fields.
*/
protected String contentType = null;
protected String contentLanguage = null;
protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
protected long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long bytesWritten=0;
/**
* Holds request error exception.
*/
protected Exception errorException = null;
/**
* Has the charset been explicitly set.
*/
protected boolean charsetSet = false;
/**
* Request error URI.
*/
protected String errorURI = null;
protected Request req;
protected int lastWrite = 1;
protected boolean flushLeftovers = true;
protected String sendfilePath = null;
protected long sendfileStart = 0;
protected long sendfileEnd = 0;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public OutputBuffer getOutputBuffer() {
return outputBuffer;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public ActionHook getHook() {
return hook;
}
public void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- State --------------------
public boolean getFlushLeftovers() {
return flushLeftovers;
}
public void setFlushLeftovers(boolean flushLeftovers) {
this.flushLeftovers = flushLeftovers;
}
public int getLastWrite() {
flushLeftovers = false;
return lastWrite;
}
public void setLastWrite(int lastWrite) {
this.lastWrite = lastWrite;
}
public int getStatus() {
return status;
}
/**
* Set the response status
*/
public void setStatus( int status ) {
this.status = status;
}
/**
* Get the status message.
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
this.commited = v;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during
* request processing.
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request
* processing.
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
/**
* Set request URI that caused an error during
* request processing.
*/
public void setErrorURI(String uri) {
errorURI = uri;
}
/** Get the request URI that caused the original error.
*/
public String getErrorURI() {
return errorURI;
}
// -------------------- Methods --------------------
public void reset()
throws IllegalStateException {
if (commited) {
throw new IllegalStateException();
}
recycle();
}
public void finish() throws IOException {
action(ActionCode.ACTION_CLOSE, this);
}
public void acknowledge() throws IOException {
action(ActionCode.ACTION_ACK, this);
}
// -------------------- Headers --------------------
/**
* Warning: This method always returns <code>false<code> for Content-Type
* and Content-Length.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.addValue(name).setString( value );
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
if( name.equalsIgnoreCase( "Content-Language" ) ) {
// XXX XXX Need to construct Locale or something else
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() throws IOException {
action(ActionCode.ACTION_COMMIT, this);
commited = true;
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitely by user to set the Content-Language and
* the default encoding
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.getLanguage();
if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
String country = locale.getCountry();
StringBuilder value = new StringBuilder(contentLanguage);
if ((country != null) && (country.length() > 0)) {
value.append('-');
value.append(country);
}
contentLanguage = value.toString();
}
}
/**
* Return the content language.
*/
public String getContentLanguage() {
return contentLanguage;
}
/*
* Overrides the name of the character encoding used in the body
* of the response. This method must be called prior to writing output
* using getWriter().
*
* @param charset String containing the name of the chararacter encoding.
*/
public void setCharacterEncoding(String charset) {
if (isCommitted())
return;
if (charset == null)
return;
characterEncoding = charset;
charsetSet=true;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
int semicolonIndex = -1;
if (type == null) {
this.contentType = null;
return;
}
/*
* Remove the charset param (if any) from the Content-Type, and use it
* to set the response encoding.
* The most recent response encoding setting will be appended to the
* response's Content-Type (as its charset param) by getContentType();
*/
boolean hasCharset = false;
int len = type.length();
int index = type.indexOf(';');
while (index != -1) {
semicolonIndex = index;
index++;
while (index < len && Character.isSpace(type.charAt(index))) {
index++;
}
if (index+8 < len
&& type.charAt(index) == 'c'
&& type.charAt(index+1) == 'h'
&& type.charAt(index+2) == 'a'
&& type.charAt(index+3) == 'r'
&& type.charAt(index+4) == 's'
&& type.charAt(index+5) == 'e'
&& type.charAt(index+6) == 't'
&& type.charAt(index+7) == '=') {
hasCharset = true;
break;
}
index = type.indexOf(';', index);
}
if (!hasCharset) {
this.contentType = type;
return;
}
this.contentType = type.substring(0, semicolonIndex);
String tail = type.substring(index+8);
int nextParam = tail.indexOf(';');
String charsetValue = null;
if (nextParam != -1) {
this.contentType += tail.substring(nextParam);
charsetValue = tail.substring(0, nextParam);
} else {
charsetValue = tail;
}
// The charset value may be quoted, but must not contain any quotes.
if (charsetValue != null && charsetValue.length() > 0) {
charsetSet=true;
charsetValue = charsetValue.replace('"', ' ');
this.characterEncoding = charsetValue.trim();
}
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& characterEncoding != null
&& charsetSet) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
public String getSendfilePath() {
return sendfilePath;
}
public void setSendfilePath(String sendfilePath) {
this.sendfilePath = sendfilePath;
}
public long getSendfileStart() {
return sendfileStart;
}
public void setSendfileStart(long sendfileStart) {
this.sendfileStart = sendfileStart;
}
public long getSendfileEnd() {
return sendfileEnd;
}
public void setSendfileEnd(long sendfileEnd) {
this.sendfileEnd = sendfileEnd;
}
/**
* Write a chunk of bytes.
*/
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/)
throws IOException
{
outputBuffer.doWrite(chunk, this);
bytesWritten+=chunk.getLength();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
charsetSet = false;
contentLength = -1;
status = 200;
message = null;
commited = false;
errorException = null;
errorURI = null;
headers.clear();
sendfilePath = null;
// update counters
lastWrite = 1;
bytesWritten=0;
}
public long getBytesWritten() {
return bytesWritten;
}
public void setBytesWritten(long bytesWritten) {
this.bytesWritten = bytesWritten;
}
}
|
152075_5 | package org.dynmap.common;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.dynmap.hdmap.HDBlockModels;
/* Generic biome mapping */
public class BiomeMap {
public static final int NO_INDEX = -2;
private static BiomeMap[] biome_by_index = new BiomeMap[256];
private static Map<String, BiomeMap> biome_by_rl = new HashMap<String, BiomeMap>();
public static final BiomeMap NULL = new BiomeMap(-1, "NULL", 0.5, 0.5, 0xFFFFFF, 0, 0, null);
public static final BiomeMap OCEAN = new BiomeMap(0, "OCEAN", "minecraft:ocean");
public static final BiomeMap PLAINS = new BiomeMap(1, "PLAINS", 0.8, 0.4, "minecraft:plains");
public static final BiomeMap DESERT = new BiomeMap(2, "DESERT", 2.0, 0.0, "minecraft:desert");
public static final BiomeMap EXTREME_HILLS = new BiomeMap(3, "EXTREME_HILLS", 0.2, 0.3, "minecraft:mountains");
public static final BiomeMap FOREST = new BiomeMap(4, "FOREST", 0.7, 0.8, "minecraft:forest");
public static final BiomeMap TAIGA = new BiomeMap(5, "TAIGA", 0.05, 0.8, "minecraft:taiga");
public static final BiomeMap SWAMPLAND = new BiomeMap(6, "SWAMPLAND", 0.8, 0.9, 0xE0FFAE, 0x2e282a, 0x902c52, "minecraft:swamp");
public static final BiomeMap RIVER = new BiomeMap(7, "RIVER", "minecraft:river");
public static final BiomeMap HELL = new BiomeMap(8, "HELL", 2.0, 0.0, "minecraft:nether");
public static final BiomeMap SKY = new BiomeMap(9, "SKY", "minecraft:the_end");
public static final BiomeMap FROZEN_OCEAN = new BiomeMap(10, "FROZEN_OCEAN", 0.0, 0.5, "minecraft:frozen_ocean");
public static final BiomeMap FROZEN_RIVER = new BiomeMap(11, "FROZEN_RIVER", 0.0, 0.5, "minecraft:frozen_river");
public static final BiomeMap ICE_PLAINS = new BiomeMap(12, "ICE_PLAINS", 0.0, 0.5, "minecraft:snowy_tundra");
public static final BiomeMap ICE_MOUNTAINS = new BiomeMap(13, "ICE_MOUNTAINS", 0.0, 0.5, "minecraft:snowy_mountains");
public static final BiomeMap MUSHROOM_ISLAND = new BiomeMap(14, "MUSHROOM_ISLAND", 0.9, 1.0, "minecraft:mushroom_fields");
public static final BiomeMap MUSHROOM_SHORE = new BiomeMap(15, "MUSHROOM_SHORE", 0.9, 1.0, "minecraft:mushroom_field_shore");
public static final BiomeMap BEACH = new BiomeMap(16, "BEACH", 0.8, 0.4, "minecraft:beach");
public static final BiomeMap DESERT_HILLS = new BiomeMap(17, "DESERT_HILLS", 2.0, 0.0, "minecraft:desert_hills");
public static final BiomeMap FOREST_HILLS = new BiomeMap(18, "FOREST_HILLS", 0.7, 0.8, "minecraft:wooded_hills");
public static final BiomeMap TAIGA_HILLS = new BiomeMap(19, "TAIGA_HILLS", 0.05, 0.8, "minecraft:taiga_hills");
public static final BiomeMap SMALL_MOUNTAINS = new BiomeMap(20, "SMALL_MOUNTAINS", 0.2, 0.8, "minecraft:mountain_edge");
public static final BiomeMap JUNGLE = new BiomeMap(21, "JUNGLE", 1.2, 0.9, "minecraft:jungle");
public static final BiomeMap JUNGLE_HILLS = new BiomeMap(22, "JUNGLE_HILLS", 1.2, 0.9, "minecraft:jungle_hills");
public static final int LAST_WELL_KNOWN = 175;
private double tmp;
private double rain;
private int watercolormult;
private int grassmult;
private int foliagemult;
private Optional<?> biomeObj = Optional.empty();
private final String id;
private final String resourcelocation;
private final int index;
private int biomeindex256; // Standard biome mapping index (for 256 x 256)
private boolean isDef;
private static boolean loadDone = false;
public static void loadWellKnownByVersion(String mcver) {
if (loadDone) return;
if (HDBlockModels.checkVersionRange(mcver, "1.7.0-")) {
new BiomeMap(23, "JUNGLE_EDGE", 0.95, 0.8, "minecraft:jungle_edge");
new BiomeMap(24, "DEEP_OCEAN", "minecraft:deep_ocean");
new BiomeMap(25, "STONE_BEACH", 0.2, 0.3, "minecraft:stone_shore");
new BiomeMap(26, "COLD_BEACH", 0.05, 0.3, "minecraft:snowy_beach");
new BiomeMap(27, "BIRCH_FOREST", 0.6, 0.6, "minecraft:birch_forest");
new BiomeMap(28, "BIRCH_FOREST_HILLS", 0.6, 0.6, "minecraft:birch_forest_hills");
new BiomeMap(29, "ROOFED_FOREST", 0.7, 0.8, 0xFFFFFF, 0x28340A, 0, "minecraft:dark_forest");
new BiomeMap(30, "COLD_TAIGA", -0.5, 0.4, "minecraft:snowy_taiga");
new BiomeMap(31, "COLD_TAIGA_HILLS", -0.5, 0.4, "minecraft:snowy_taiga_hills");
new BiomeMap(32, "MEGA_TAIGA", 0.3, 0.8, "minecraft:giant_tree_taiga");
new BiomeMap(33, "MEGA_TAIGA_HILLS", 0.3, 0.8, "minecraft:giant_tree_taiga_hills");
new BiomeMap(34, "EXTREME_HILLS_PLUS", 0.2, 0.3, "minecraft:wooded_mountains");
new BiomeMap(35, "SAVANNA", 1.2, 0.0, "minecraft:savanna");
new BiomeMap(36, "SAVANNA_PLATEAU", 1.0, 0.0, "minecraft:savanna_plateau");
new BiomeMap(37, "MESA", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:badlands");
new BiomeMap(129, "SUNFLOWER_PLAINS", 0.8, 0.4, "minecraft:sunflower_plains");
new BiomeMap(130, "DESERT_MOUNTAINS", 2.0, 0.0, "minecraft:desert_lakes");
new BiomeMap(131, "EXTREME_HILLS_MOUNTAINS", 0.2, 0.3, "minecraft:gravelly_mountains");
new BiomeMap(132, "FLOWER_FOREST", 0.7, 0.8, "minecraft:flower_forest");
new BiomeMap(133, "TAIGA_MOUNTAINS", 0.05, 0.8, "minecraft:taiga_mountains");
new BiomeMap(140, "ICE_PLAINS_SPIKES", 0.0, 0.5, "minecraft:ice_spikes");
new BiomeMap(149, "JUNGLE_MOUNTAINS", 1.2, 0.9, "minecraft:modified_jungle");
new BiomeMap(151, "JUNGLE_EDGE_MOUNTAINS", 0.95, 0.8, "minecraft:modified_jungle_edge");
new BiomeMap(155, "BIRCH_FOREST_MOUNTAINS", 0.6, 0.6, "minecraft:tall_birch_forest");
new BiomeMap(156, "BIRCH_FOREST_HILLS_MOUNTAINS", 0.6, 0.6, "minecraft:tall_birch_hills");
new BiomeMap(157, "ROOFED_FOREST_MOUNTAINS", 0.7, 0.8, 0xFFFFFF, 0x28340A, 0, "minecraft:dark_forest_hills");
new BiomeMap(158, "COLD_TAIGA_MOUNTAINS", -0.5, 0.4, "minecraft:snowy_taiga_mountains");
new BiomeMap(160, "MEGA_SPRUCE_TAIGA", 0.25, 0.8, "minecraft:giant_spruce_taiga");
new BiomeMap(161, "MEGA_SPRUCE_TAIGA_HILLS", 0.3, 0.8, "minecraft:giant_spruce_taiga_hills");
new BiomeMap(162, "EXTREME_HILLS_PLUS_MOUNTAINS", 0.2, 0.3, "minecraft:modified_gravelly_mountains");
new BiomeMap(163, "SAVANNA_MOUNTAINS", 1.2, 0.0, "minecraft:shattered_savanna");
new BiomeMap(164, "SAVANNA_PLATEAU_MOUNTAINS", 1.0, 0.0, "minecraft:shattered_savanna_plateau");
new BiomeMap(165, "MESA_BRYCE", 2.0, 0.0,0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:eroded_badlands");
}
if (HDBlockModels.checkVersionRange(mcver, "1.7.0-1.17.1")) {
new BiomeMap(38, "MESA_PLATEAU_FOREST", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:wooded_badlands_plateau");
new BiomeMap(39, "MESA_PLATEAU", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:badlands_plateau");
new BiomeMap(134, "SWAMPLAND_MOUNTAINS", 0.8, 0.9, 0xE0FFAE, 0x2e282a, 0x902c52, "minecraft:swamp_hills");
new BiomeMap(166, "MESA_PLATEAU_FOREST_MOUNTAINS", 2.0, 0.0,0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:modified_wooded_badlands_plateau");
new BiomeMap(167, "MESA_PLATEAU_MOUNTAINS", 2.0, 0.0,0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:modified_badlands_plateau");
}
if (HDBlockModels.checkVersionRange(mcver, "1.9.0-")) {
new BiomeMap(127, "THE_VOID", "minecraft:the_void");
}
if (HDBlockModels.checkVersionRange(mcver, "1.13.0-")) {
new BiomeMap(40, "SMALL_END_ISLANDS", "minecraft:small_end_islands");
new BiomeMap(41, "END_MIDLANDS", "minecraft:end_midlands");
new BiomeMap(42, "END_HIGHLANDS", "minecraft:end_highlands");
new BiomeMap(43, "END_BARRENS", "minecraft:end_barrens");
new BiomeMap(44, "WARM_OCEAN", "minecraft:warm_ocean");
new BiomeMap(45, "LUKEWARM_OCEAN", "minecraft:lukewarm_ocean");
new BiomeMap(46, "COLD_OCEAN", "minecraft:cold_ocean");
new BiomeMap(47, "DEEP_WARM_OCEAN", "minecraft:deep_warm_ocean");
new BiomeMap(48, "DEEP_LUKEWARM_OCEAN", "minecraft:deep_lukewarm_ocean");
new BiomeMap(49, "DEEP_COLD_OCEAN", "minecraft:deep_cold_ocean");
new BiomeMap(50, "DEEP_FROZEN_OCEAN", "minecraft:deep_frozen_ocean");
}
if (HDBlockModels.checkVersionRange(mcver, "1.14.0-")) {
new BiomeMap(168, "BAMBOO_JUNGLE", "minecraft:bamboo_jungle");
new BiomeMap(169, "BAMBOO_JUNGLE_HILLS", "minecraft:bamboo_jungle_hills");
}
if (HDBlockModels.checkVersionRange(mcver, "1.16.0-")) {
new BiomeMap(170, "SOUL_SAND_VALLEY", "minecraft:soul_sand_valley");
new BiomeMap(171, "CRIMSON_FOREST", "minecraft:crimson_forest");
new BiomeMap(172, "WARPED_FOREST", "minecraft:warped_forest");
new BiomeMap(173, "BASALT_DELTAS", "minecraft:basalt_deltas");
}
if (HDBlockModels.checkVersionRange(mcver, "1.17.0-")) {
new BiomeMap(174, "DRIPSTONE_CAVES", "minecraft:dripstone_caves");
new BiomeMap(175, "LUSH_CAVES", "minecraft:lush_caves");
}
if (HDBlockModels.checkVersionRange(mcver, "1.18.0-")) {
new BiomeMap(38, "MESA_FOREST", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:wooded_badlands");
}
loadDone = true;
}
static {
for (int i = 0; i < biome_by_index.length; i++) {
BiomeMap bm = BiomeMap.byBiomeID(i-1);
if (bm == null) {
bm = new BiomeMap(i-1, "BIOME_" + (i-1));
bm.isDef = true;
}
}
}
private static boolean isUniqueID(String id) {
for(int i = 0; i < biome_by_index.length; i++) {
if(biome_by_index[i] == null) continue;
if(biome_by_index[i].id.equals(id))
return false;
}
return true;
}
private static void resizeIfNeeded(int idx) {
if ((idx >= biome_by_index.length) ) {
int oldlen = biome_by_index.length;
biome_by_index = Arrays.copyOf(biome_by_index, idx * 3 / 2);
for (int i = oldlen; i < biome_by_index.length; i++) {
if (biome_by_index[i] == null) {
BiomeMap bm = new BiomeMap(i-1, "BIOME_" + (i-1));
bm.isDef = true;
}
}
}
}
private BiomeMap(int idx, String id, double tmp, double rain, int waterColorMultiplier, int grassmult, int foliagemult, String rl) {
/* Clamp values : we use raw values from MC code, which are clamped during color mapping only */
setTemperature(tmp);
setRainfall(rain);
this.watercolormult = waterColorMultiplier;
this.grassmult = grassmult;
this.foliagemult = foliagemult;
// Handle null biome
if (id == null) { id = "biome_" + idx; }
id = id.toUpperCase().replace(' ', '_');
if (isUniqueID(id) == false) {
id = id + "_" + idx;
}
this.id = id;
// If index is NO_INDEX, find one after the well known ones
if (idx == NO_INDEX) {
idx = LAST_WELL_KNOWN;
while (true) {
idx++;
resizeIfNeeded(idx);
if (biome_by_index[idx].isDef) {
break;
}
}
}
else {
idx++; /* Insert one after ID value - null is zero index */
}
this.index = idx;
if (idx >= 0) {
resizeIfNeeded(idx);
biome_by_index[idx] = this;
}
this.resourcelocation = rl;
if (rl != null) {
biome_by_rl.put(rl, this);
}
}
public BiomeMap(int idx, String id) {
this(idx, id, 0.5, 0.5, 0xFFFFFF, 0, 0, null);
}
public BiomeMap(int idx, String id, String rl) {
this(idx, id, 0.5, 0.5, 0xFFFFFF, 0, 0, rl);
}
public BiomeMap(int idx, String id, double tmp, double rain) {
this(idx, id, tmp, rain, 0xFFFFFF, 0, 0, null);
}
public BiomeMap(int idx, String id, double tmp, double rain, String rl) {
this(idx, id, tmp, rain, 0xFFFFFF, 0, 0, rl);
}
public BiomeMap(String id, double tmp, double rain, String rl) {
this(NO_INDEX, id, tmp, rain, 0xFFFFFF, 0, 0, rl); // No index
}
private final int biomeLookup(int width) {
int w = width-1;
int t = (int)((1.0-tmp)*w);
int h = (int)((1.0 - (tmp*rain))*w);
return width*h + t;
}
public final int biomeLookup() {
return this.biomeindex256;
}
public final int getModifiedGrassMultiplier(int rawgrassmult) {
if(grassmult == 0)
return rawgrassmult;
else if(grassmult > 0xFFFFFF)
return grassmult & 0xFFFFFF;
else
return ((rawgrassmult & 0xfefefe) + grassmult) / 2;
}
public final int getModifiedFoliageMultiplier(int rawfoliagemult) {
if(foliagemult == 0)
return rawfoliagemult;
else if(foliagemult > 0xFFFFFF)
return foliagemult & 0xFFFFFF;
else
return ((rawfoliagemult & 0xfefefe) + foliagemult) / 2;
}
public final int getWaterColorMult() {
return watercolormult;
}
public final int ordinal() {
return index;
}
public static final BiomeMap byBiomeID(int idx) {
idx++;
if((idx >= 0) && (idx < biome_by_index.length))
return biome_by_index[idx];
else
return NULL;
}
public static final BiomeMap byBiomeResourceLocation(String resloc) {
BiomeMap b = biome_by_rl.get(resloc);
return (b != null) ? b : NULL;
}
public int getBiomeID() {
return index - 1; // Index of biome in MC biome table
}
public static final BiomeMap[] values() {
return biome_by_index;
}
public void setWaterColorMultiplier(int watercolormult) {
this.watercolormult = watercolormult;
}
public void setGrassColorMultiplier(int grassmult) {
this.grassmult = grassmult;
}
public void setFoliageColorMultiplier(int foliagemult) {
this.foliagemult = foliagemult;
}
public void setTemperature(double tmp) {
if(tmp < 0.0) tmp = 0.0;
if(tmp > 1.0) tmp = 1.0;
this.tmp = tmp;
this.biomeindex256 = this.biomeLookup(256);
}
public void setRainfall(double rain) {
if(rain < 0.0) rain = 0.0;
if(rain > 1.0) rain = 1.0;
this.rain = rain;
this.biomeindex256 = this.biomeLookup(256);
}
public final double getTemperature() {
return this.tmp;
}
public final double getRainfall() {
return this.rain;
}
public boolean isDefault() {
return isDef;
}
public String getId() {
return id;
}
public String toString() {
return String.format("%s(%s)", id, resourcelocation);
}
public @SuppressWarnings("unchecked") <T> Optional<T> getBiomeObject() {
return (Optional<T>) biomeObj;
}
public void setBiomeObject(Object biomeObj) {
this.biomeObj = Optional.of(biomeObj);
}
}
| webbukkit/dynmap | DynmapCore/src/main/java/org/dynmap/common/BiomeMap.java | 6,101 | /* Insert one after ID value - null is zero index */ | block_comment | nl | package org.dynmap.common;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.dynmap.hdmap.HDBlockModels;
/* Generic biome mapping */
public class BiomeMap {
public static final int NO_INDEX = -2;
private static BiomeMap[] biome_by_index = new BiomeMap[256];
private static Map<String, BiomeMap> biome_by_rl = new HashMap<String, BiomeMap>();
public static final BiomeMap NULL = new BiomeMap(-1, "NULL", 0.5, 0.5, 0xFFFFFF, 0, 0, null);
public static final BiomeMap OCEAN = new BiomeMap(0, "OCEAN", "minecraft:ocean");
public static final BiomeMap PLAINS = new BiomeMap(1, "PLAINS", 0.8, 0.4, "minecraft:plains");
public static final BiomeMap DESERT = new BiomeMap(2, "DESERT", 2.0, 0.0, "minecraft:desert");
public static final BiomeMap EXTREME_HILLS = new BiomeMap(3, "EXTREME_HILLS", 0.2, 0.3, "minecraft:mountains");
public static final BiomeMap FOREST = new BiomeMap(4, "FOREST", 0.7, 0.8, "minecraft:forest");
public static final BiomeMap TAIGA = new BiomeMap(5, "TAIGA", 0.05, 0.8, "minecraft:taiga");
public static final BiomeMap SWAMPLAND = new BiomeMap(6, "SWAMPLAND", 0.8, 0.9, 0xE0FFAE, 0x2e282a, 0x902c52, "minecraft:swamp");
public static final BiomeMap RIVER = new BiomeMap(7, "RIVER", "minecraft:river");
public static final BiomeMap HELL = new BiomeMap(8, "HELL", 2.0, 0.0, "minecraft:nether");
public static final BiomeMap SKY = new BiomeMap(9, "SKY", "minecraft:the_end");
public static final BiomeMap FROZEN_OCEAN = new BiomeMap(10, "FROZEN_OCEAN", 0.0, 0.5, "minecraft:frozen_ocean");
public static final BiomeMap FROZEN_RIVER = new BiomeMap(11, "FROZEN_RIVER", 0.0, 0.5, "minecraft:frozen_river");
public static final BiomeMap ICE_PLAINS = new BiomeMap(12, "ICE_PLAINS", 0.0, 0.5, "minecraft:snowy_tundra");
public static final BiomeMap ICE_MOUNTAINS = new BiomeMap(13, "ICE_MOUNTAINS", 0.0, 0.5, "minecraft:snowy_mountains");
public static final BiomeMap MUSHROOM_ISLAND = new BiomeMap(14, "MUSHROOM_ISLAND", 0.9, 1.0, "minecraft:mushroom_fields");
public static final BiomeMap MUSHROOM_SHORE = new BiomeMap(15, "MUSHROOM_SHORE", 0.9, 1.0, "minecraft:mushroom_field_shore");
public static final BiomeMap BEACH = new BiomeMap(16, "BEACH", 0.8, 0.4, "minecraft:beach");
public static final BiomeMap DESERT_HILLS = new BiomeMap(17, "DESERT_HILLS", 2.0, 0.0, "minecraft:desert_hills");
public static final BiomeMap FOREST_HILLS = new BiomeMap(18, "FOREST_HILLS", 0.7, 0.8, "minecraft:wooded_hills");
public static final BiomeMap TAIGA_HILLS = new BiomeMap(19, "TAIGA_HILLS", 0.05, 0.8, "minecraft:taiga_hills");
public static final BiomeMap SMALL_MOUNTAINS = new BiomeMap(20, "SMALL_MOUNTAINS", 0.2, 0.8, "minecraft:mountain_edge");
public static final BiomeMap JUNGLE = new BiomeMap(21, "JUNGLE", 1.2, 0.9, "minecraft:jungle");
public static final BiomeMap JUNGLE_HILLS = new BiomeMap(22, "JUNGLE_HILLS", 1.2, 0.9, "minecraft:jungle_hills");
public static final int LAST_WELL_KNOWN = 175;
private double tmp;
private double rain;
private int watercolormult;
private int grassmult;
private int foliagemult;
private Optional<?> biomeObj = Optional.empty();
private final String id;
private final String resourcelocation;
private final int index;
private int biomeindex256; // Standard biome mapping index (for 256 x 256)
private boolean isDef;
private static boolean loadDone = false;
public static void loadWellKnownByVersion(String mcver) {
if (loadDone) return;
if (HDBlockModels.checkVersionRange(mcver, "1.7.0-")) {
new BiomeMap(23, "JUNGLE_EDGE", 0.95, 0.8, "minecraft:jungle_edge");
new BiomeMap(24, "DEEP_OCEAN", "minecraft:deep_ocean");
new BiomeMap(25, "STONE_BEACH", 0.2, 0.3, "minecraft:stone_shore");
new BiomeMap(26, "COLD_BEACH", 0.05, 0.3, "minecraft:snowy_beach");
new BiomeMap(27, "BIRCH_FOREST", 0.6, 0.6, "minecraft:birch_forest");
new BiomeMap(28, "BIRCH_FOREST_HILLS", 0.6, 0.6, "minecraft:birch_forest_hills");
new BiomeMap(29, "ROOFED_FOREST", 0.7, 0.8, 0xFFFFFF, 0x28340A, 0, "minecraft:dark_forest");
new BiomeMap(30, "COLD_TAIGA", -0.5, 0.4, "minecraft:snowy_taiga");
new BiomeMap(31, "COLD_TAIGA_HILLS", -0.5, 0.4, "minecraft:snowy_taiga_hills");
new BiomeMap(32, "MEGA_TAIGA", 0.3, 0.8, "minecraft:giant_tree_taiga");
new BiomeMap(33, "MEGA_TAIGA_HILLS", 0.3, 0.8, "minecraft:giant_tree_taiga_hills");
new BiomeMap(34, "EXTREME_HILLS_PLUS", 0.2, 0.3, "minecraft:wooded_mountains");
new BiomeMap(35, "SAVANNA", 1.2, 0.0, "minecraft:savanna");
new BiomeMap(36, "SAVANNA_PLATEAU", 1.0, 0.0, "minecraft:savanna_plateau");
new BiomeMap(37, "MESA", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:badlands");
new BiomeMap(129, "SUNFLOWER_PLAINS", 0.8, 0.4, "minecraft:sunflower_plains");
new BiomeMap(130, "DESERT_MOUNTAINS", 2.0, 0.0, "minecraft:desert_lakes");
new BiomeMap(131, "EXTREME_HILLS_MOUNTAINS", 0.2, 0.3, "minecraft:gravelly_mountains");
new BiomeMap(132, "FLOWER_FOREST", 0.7, 0.8, "minecraft:flower_forest");
new BiomeMap(133, "TAIGA_MOUNTAINS", 0.05, 0.8, "minecraft:taiga_mountains");
new BiomeMap(140, "ICE_PLAINS_SPIKES", 0.0, 0.5, "minecraft:ice_spikes");
new BiomeMap(149, "JUNGLE_MOUNTAINS", 1.2, 0.9, "minecraft:modified_jungle");
new BiomeMap(151, "JUNGLE_EDGE_MOUNTAINS", 0.95, 0.8, "minecraft:modified_jungle_edge");
new BiomeMap(155, "BIRCH_FOREST_MOUNTAINS", 0.6, 0.6, "minecraft:tall_birch_forest");
new BiomeMap(156, "BIRCH_FOREST_HILLS_MOUNTAINS", 0.6, 0.6, "minecraft:tall_birch_hills");
new BiomeMap(157, "ROOFED_FOREST_MOUNTAINS", 0.7, 0.8, 0xFFFFFF, 0x28340A, 0, "minecraft:dark_forest_hills");
new BiomeMap(158, "COLD_TAIGA_MOUNTAINS", -0.5, 0.4, "minecraft:snowy_taiga_mountains");
new BiomeMap(160, "MEGA_SPRUCE_TAIGA", 0.25, 0.8, "minecraft:giant_spruce_taiga");
new BiomeMap(161, "MEGA_SPRUCE_TAIGA_HILLS", 0.3, 0.8, "minecraft:giant_spruce_taiga_hills");
new BiomeMap(162, "EXTREME_HILLS_PLUS_MOUNTAINS", 0.2, 0.3, "minecraft:modified_gravelly_mountains");
new BiomeMap(163, "SAVANNA_MOUNTAINS", 1.2, 0.0, "minecraft:shattered_savanna");
new BiomeMap(164, "SAVANNA_PLATEAU_MOUNTAINS", 1.0, 0.0, "minecraft:shattered_savanna_plateau");
new BiomeMap(165, "MESA_BRYCE", 2.0, 0.0,0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:eroded_badlands");
}
if (HDBlockModels.checkVersionRange(mcver, "1.7.0-1.17.1")) {
new BiomeMap(38, "MESA_PLATEAU_FOREST", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:wooded_badlands_plateau");
new BiomeMap(39, "MESA_PLATEAU", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:badlands_plateau");
new BiomeMap(134, "SWAMPLAND_MOUNTAINS", 0.8, 0.9, 0xE0FFAE, 0x2e282a, 0x902c52, "minecraft:swamp_hills");
new BiomeMap(166, "MESA_PLATEAU_FOREST_MOUNTAINS", 2.0, 0.0,0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:modified_wooded_badlands_plateau");
new BiomeMap(167, "MESA_PLATEAU_MOUNTAINS", 2.0, 0.0,0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:modified_badlands_plateau");
}
if (HDBlockModels.checkVersionRange(mcver, "1.9.0-")) {
new BiomeMap(127, "THE_VOID", "minecraft:the_void");
}
if (HDBlockModels.checkVersionRange(mcver, "1.13.0-")) {
new BiomeMap(40, "SMALL_END_ISLANDS", "minecraft:small_end_islands");
new BiomeMap(41, "END_MIDLANDS", "minecraft:end_midlands");
new BiomeMap(42, "END_HIGHLANDS", "minecraft:end_highlands");
new BiomeMap(43, "END_BARRENS", "minecraft:end_barrens");
new BiomeMap(44, "WARM_OCEAN", "minecraft:warm_ocean");
new BiomeMap(45, "LUKEWARM_OCEAN", "minecraft:lukewarm_ocean");
new BiomeMap(46, "COLD_OCEAN", "minecraft:cold_ocean");
new BiomeMap(47, "DEEP_WARM_OCEAN", "minecraft:deep_warm_ocean");
new BiomeMap(48, "DEEP_LUKEWARM_OCEAN", "minecraft:deep_lukewarm_ocean");
new BiomeMap(49, "DEEP_COLD_OCEAN", "minecraft:deep_cold_ocean");
new BiomeMap(50, "DEEP_FROZEN_OCEAN", "minecraft:deep_frozen_ocean");
}
if (HDBlockModels.checkVersionRange(mcver, "1.14.0-")) {
new BiomeMap(168, "BAMBOO_JUNGLE", "minecraft:bamboo_jungle");
new BiomeMap(169, "BAMBOO_JUNGLE_HILLS", "minecraft:bamboo_jungle_hills");
}
if (HDBlockModels.checkVersionRange(mcver, "1.16.0-")) {
new BiomeMap(170, "SOUL_SAND_VALLEY", "minecraft:soul_sand_valley");
new BiomeMap(171, "CRIMSON_FOREST", "minecraft:crimson_forest");
new BiomeMap(172, "WARPED_FOREST", "minecraft:warped_forest");
new BiomeMap(173, "BASALT_DELTAS", "minecraft:basalt_deltas");
}
if (HDBlockModels.checkVersionRange(mcver, "1.17.0-")) {
new BiomeMap(174, "DRIPSTONE_CAVES", "minecraft:dripstone_caves");
new BiomeMap(175, "LUSH_CAVES", "minecraft:lush_caves");
}
if (HDBlockModels.checkVersionRange(mcver, "1.18.0-")) {
new BiomeMap(38, "MESA_FOREST", 2.0, 0.0, 0xFFFFFF, 0x624c46, 0x8e5e70, "minecraft:wooded_badlands");
}
loadDone = true;
}
static {
for (int i = 0; i < biome_by_index.length; i++) {
BiomeMap bm = BiomeMap.byBiomeID(i-1);
if (bm == null) {
bm = new BiomeMap(i-1, "BIOME_" + (i-1));
bm.isDef = true;
}
}
}
private static boolean isUniqueID(String id) {
for(int i = 0; i < biome_by_index.length; i++) {
if(biome_by_index[i] == null) continue;
if(biome_by_index[i].id.equals(id))
return false;
}
return true;
}
private static void resizeIfNeeded(int idx) {
if ((idx >= biome_by_index.length) ) {
int oldlen = biome_by_index.length;
biome_by_index = Arrays.copyOf(biome_by_index, idx * 3 / 2);
for (int i = oldlen; i < biome_by_index.length; i++) {
if (biome_by_index[i] == null) {
BiomeMap bm = new BiomeMap(i-1, "BIOME_" + (i-1));
bm.isDef = true;
}
}
}
}
private BiomeMap(int idx, String id, double tmp, double rain, int waterColorMultiplier, int grassmult, int foliagemult, String rl) {
/* Clamp values : we use raw values from MC code, which are clamped during color mapping only */
setTemperature(tmp);
setRainfall(rain);
this.watercolormult = waterColorMultiplier;
this.grassmult = grassmult;
this.foliagemult = foliagemult;
// Handle null biome
if (id == null) { id = "biome_" + idx; }
id = id.toUpperCase().replace(' ', '_');
if (isUniqueID(id) == false) {
id = id + "_" + idx;
}
this.id = id;
// If index is NO_INDEX, find one after the well known ones
if (idx == NO_INDEX) {
idx = LAST_WELL_KNOWN;
while (true) {
idx++;
resizeIfNeeded(idx);
if (biome_by_index[idx].isDef) {
break;
}
}
}
else {
idx++; /* Insert one after<SUF>*/
}
this.index = idx;
if (idx >= 0) {
resizeIfNeeded(idx);
biome_by_index[idx] = this;
}
this.resourcelocation = rl;
if (rl != null) {
biome_by_rl.put(rl, this);
}
}
public BiomeMap(int idx, String id) {
this(idx, id, 0.5, 0.5, 0xFFFFFF, 0, 0, null);
}
public BiomeMap(int idx, String id, String rl) {
this(idx, id, 0.5, 0.5, 0xFFFFFF, 0, 0, rl);
}
public BiomeMap(int idx, String id, double tmp, double rain) {
this(idx, id, tmp, rain, 0xFFFFFF, 0, 0, null);
}
public BiomeMap(int idx, String id, double tmp, double rain, String rl) {
this(idx, id, tmp, rain, 0xFFFFFF, 0, 0, rl);
}
public BiomeMap(String id, double tmp, double rain, String rl) {
this(NO_INDEX, id, tmp, rain, 0xFFFFFF, 0, 0, rl); // No index
}
private final int biomeLookup(int width) {
int w = width-1;
int t = (int)((1.0-tmp)*w);
int h = (int)((1.0 - (tmp*rain))*w);
return width*h + t;
}
public final int biomeLookup() {
return this.biomeindex256;
}
public final int getModifiedGrassMultiplier(int rawgrassmult) {
if(grassmult == 0)
return rawgrassmult;
else if(grassmult > 0xFFFFFF)
return grassmult & 0xFFFFFF;
else
return ((rawgrassmult & 0xfefefe) + grassmult) / 2;
}
public final int getModifiedFoliageMultiplier(int rawfoliagemult) {
if(foliagemult == 0)
return rawfoliagemult;
else if(foliagemult > 0xFFFFFF)
return foliagemult & 0xFFFFFF;
else
return ((rawfoliagemult & 0xfefefe) + foliagemult) / 2;
}
public final int getWaterColorMult() {
return watercolormult;
}
public final int ordinal() {
return index;
}
public static final BiomeMap byBiomeID(int idx) {
idx++;
if((idx >= 0) && (idx < biome_by_index.length))
return biome_by_index[idx];
else
return NULL;
}
public static final BiomeMap byBiomeResourceLocation(String resloc) {
BiomeMap b = biome_by_rl.get(resloc);
return (b != null) ? b : NULL;
}
public int getBiomeID() {
return index - 1; // Index of biome in MC biome table
}
public static final BiomeMap[] values() {
return biome_by_index;
}
public void setWaterColorMultiplier(int watercolormult) {
this.watercolormult = watercolormult;
}
public void setGrassColorMultiplier(int grassmult) {
this.grassmult = grassmult;
}
public void setFoliageColorMultiplier(int foliagemult) {
this.foliagemult = foliagemult;
}
public void setTemperature(double tmp) {
if(tmp < 0.0) tmp = 0.0;
if(tmp > 1.0) tmp = 1.0;
this.tmp = tmp;
this.biomeindex256 = this.biomeLookup(256);
}
public void setRainfall(double rain) {
if(rain < 0.0) rain = 0.0;
if(rain > 1.0) rain = 1.0;
this.rain = rain;
this.biomeindex256 = this.biomeLookup(256);
}
public final double getTemperature() {
return this.tmp;
}
public final double getRainfall() {
return this.rain;
}
public boolean isDefault() {
return isDef;
}
public String getId() {
return id;
}
public String toString() {
return String.format("%s(%s)", id, resourcelocation);
}
public @SuppressWarnings("unchecked") <T> Optional<T> getBiomeObject() {
return (Optional<T>) biomeObj;
}
public void setBiomeObject(Object biomeObj) {
this.biomeObj = Optional.of(biomeObj);
}
}
|
34051_3 | package de.aitools.ie.uima.io;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
*
* An {@link InputStream} that can open {@link ClassLoader} resources, as well
* as files.
*
* @author [email protected]
*
*/
public class ResourceInputStream extends InputStream implements Closeable, AutoCloseable {
private InputStream wrapped;
/**
* Creates an {@link InputStream} to the resource identified by the given
* path, which can be either a {@link ClassLoader} system resource, or an
* object on the local file system.
*
* @param resourcePath
* a path to a {@link ClassLoader} resource with the lexicon
* file, or a path on the local file system. If the parameter can
* be interpreted as either, {@link ClassLoader} resources take
* precedence
* @throws FileNotFoundException
*/
public ResourceInputStream(String resourcePath) throws FileNotFoundException {
wrapped = ClassLoader.getSystemResourceAsStream(resourcePath);
if (wrapped == null) {
String absolutePath = PathTools.getAbsolutePath(resourcePath);
try {
wrapped = new FileInputStream(absolutePath);
} catch (Exception e) {
throw new FileNotFoundException(String
.format("Resource '%s' could not be located on the classpath or file system.", resourcePath));
}
}
}
/**
* @return
* @throws IOException
* @see java.io.InputStream#read()
*/
public int read() throws IOException {
return wrapped.read();
}
/**
* @return
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return wrapped.hashCode();
}
/**
* @param b
* @return
* @throws IOException
* @see java.io.InputStream#read(byte[])
*/
public int read(byte[] b) throws IOException {
return wrapped.read(b);
}
/**
* @param obj
* @return
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return wrapped.equals(obj);
}
/**
* @param b
* @param off
* @param len
* @return
* @throws IOException
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException {
return wrapped.read(b, off, len);
}
/**
* @param n
* @return
* @throws IOException
* @see java.io.InputStream#skip(long)
*/
public long skip(long n) throws IOException {
return wrapped.skip(n);
}
/**
* @return
* @see java.lang.Object#toString()
*/
public String toString() {
return wrapped.toString();
}
/**
* @return
* @throws IOException
* @see java.io.InputStream#available()
*/
public int available() throws IOException {
return wrapped.available();
}
/**
* @throws IOException
* @see java.io.InputStream#close()
*/
public void close() throws IOException {
wrapped.close();
}
/**
* @param readlimit
* @see java.io.InputStream#mark(int)
*/
public void mark(int readlimit) {
wrapped.mark(readlimit);
}
/**
* @throws IOException
* @see java.io.InputStream#reset()
*/
public void reset() throws IOException {
wrapped.reset();
}
/**
* @return
* @see java.io.InputStream#markSupported()
*/
public boolean markSupported() {
return wrapped.markSupported();
}
}
| webis-de/argmining20-rhetorical-devices | src/de/aitools/ie/uima/io/ResourceInputStream.java | 1,047 | /**
* @return
* @see java.lang.Object#hashCode()
*/ | block_comment | nl | package de.aitools.ie.uima.io;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
*
* An {@link InputStream} that can open {@link ClassLoader} resources, as well
* as files.
*
* @author [email protected]
*
*/
public class ResourceInputStream extends InputStream implements Closeable, AutoCloseable {
private InputStream wrapped;
/**
* Creates an {@link InputStream} to the resource identified by the given
* path, which can be either a {@link ClassLoader} system resource, or an
* object on the local file system.
*
* @param resourcePath
* a path to a {@link ClassLoader} resource with the lexicon
* file, or a path on the local file system. If the parameter can
* be interpreted as either, {@link ClassLoader} resources take
* precedence
* @throws FileNotFoundException
*/
public ResourceInputStream(String resourcePath) throws FileNotFoundException {
wrapped = ClassLoader.getSystemResourceAsStream(resourcePath);
if (wrapped == null) {
String absolutePath = PathTools.getAbsolutePath(resourcePath);
try {
wrapped = new FileInputStream(absolutePath);
} catch (Exception e) {
throw new FileNotFoundException(String
.format("Resource '%s' could not be located on the classpath or file system.", resourcePath));
}
}
}
/**
* @return
* @throws IOException
* @see java.io.InputStream#read()
*/
public int read() throws IOException {
return wrapped.read();
}
/**
* @return
<SUF>*/
public int hashCode() {
return wrapped.hashCode();
}
/**
* @param b
* @return
* @throws IOException
* @see java.io.InputStream#read(byte[])
*/
public int read(byte[] b) throws IOException {
return wrapped.read(b);
}
/**
* @param obj
* @return
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return wrapped.equals(obj);
}
/**
* @param b
* @param off
* @param len
* @return
* @throws IOException
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException {
return wrapped.read(b, off, len);
}
/**
* @param n
* @return
* @throws IOException
* @see java.io.InputStream#skip(long)
*/
public long skip(long n) throws IOException {
return wrapped.skip(n);
}
/**
* @return
* @see java.lang.Object#toString()
*/
public String toString() {
return wrapped.toString();
}
/**
* @return
* @throws IOException
* @see java.io.InputStream#available()
*/
public int available() throws IOException {
return wrapped.available();
}
/**
* @throws IOException
* @see java.io.InputStream#close()
*/
public void close() throws IOException {
wrapped.close();
}
/**
* @param readlimit
* @see java.io.InputStream#mark(int)
*/
public void mark(int readlimit) {
wrapped.mark(readlimit);
}
/**
* @throws IOException
* @see java.io.InputStream#reset()
*/
public void reset() throws IOException {
wrapped.reset();
}
/**
* @return
* @see java.io.InputStream#markSupported()
*/
public boolean markSupported() {
return wrapped.markSupported();
}
}
|
180580_42 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package org.ow2.proactive.scheduler.util.process;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jvnet.winp.WinProcess;
import org.jvnet.winp.WinpException;
import org.ow2.proactive.utils.FileToBytesConverter;
/**
* Kills a process tree to clean up the mess left by a build.
*
* @author Kohsuke Kawaguchi
* @since 1.201
*/
public abstract class ProcessTreeKiller {
/**
* Kills the given process (like {@link Process#destroy()}
* but also attempts to kill descendant processes created from the given
* process.
*
* <p>
* The implementation is obviously OS-dependent.
*
* <p>
* The execution doesn't have to be blocking; the method may return
* before processes are actually killed.
* @param proc the process to kill.
*/
public abstract void kill(Process proc);
/**
* In addition to what {@link #kill(Process)} does, also tries to
* kill all the daemon processes launched.
*
* <p>
* Daemon processes are hard to find because they normally detach themselves
* from the parent process. In this method, the method is given a
* "model environment variables", which is a list of environment variables
* and their values that are characteristic to the launched process.
* The implementation is expected to find processes
* in the system that inherit these environment variables, and kill
* them even if the {@code proc} and such processes do not have direct
* ancestor/descendant relationship.
* @param proc the process to kill.
* @param modelEnvVars the model environment variables characterizing the process.
*/
public abstract void kill(Process proc, Map<String, String> modelEnvVars);
/**
* Creates a magic cookie that can be used as the model environment variable
* when we later kill the processes.
*
* @return the magic cookie.
*/
public static String createCookie() {
return UUID.randomUUID().toString();
}
/**
* Gets the {@link ProcessTreeKiller} suitable for the current system
* that JVM runs in, or in the worst case return the default one
* that's not capable of killing descendants at all.
* @return the Process Tree Killer.
*/
public static ProcessTreeKiller get() {
if (File.pathSeparatorChar == ';')
return new Windows();
String os = fixNull(System.getProperty("os.name"));
if (os.equals("Linux"))
return new Linux();
if (os.equals("SunOS"))
return new Solaris();
return DEFAULT;
}
/**
* Given the environment variable of a process and the "model environment variable" that Hudson
* used for launching the build, returns true if there's a match (which means the process should
* be considered a descendant of a build.)
*/
protected boolean hasMatchingEnvVars(Map<String, String> envVar, Map<String, String> modelEnvVar) {
if (modelEnvVar.isEmpty())
// sanity check so that we don't start rampage.
return false;
for (Entry<String, String> e : modelEnvVar.entrySet()) {
String v = envVar.get(e.getKey());
if (v == null || !v.equals(e.getValue()))
return false; // no match
}
return true;
}
/**
* Fallback implementation that doesn't do anything clever.
*/
private static final ProcessTreeKiller DEFAULT = new ProcessTreeKiller() {
@Override
public void kill(Process proc) {
proc.destroy();
}
@Override
public void kill(Process proc, Map<String, String> modelEnvVars) {
proc.destroy();
}
};
/**
* Implementation for Windows.
*
* <p>
* Not a singleton pattern because loading this class requires Windows specific library.
*/
private static final class Windows extends ProcessTreeKiller {
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process)
*/
@Override
public void kill(Process proc) {
new WinProcess(proc).killRecursively();
}
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process, java.util.Map)
*/
@Override
public void kill(Process proc, Map<String, String> modelEnvVars) {
kill(proc);
for (WinProcess p : WinProcess.all()) {
if (p.getPid() < 10)
continue; // ignore system processes like "idle process"
boolean matched;
try {
matched = hasMatchingEnvVars(p.getEnvironmentVariables(), modelEnvVars);
} catch (WinpException e) {
// likely a missing privilege
continue;
}
if (matched)
p.killRecursively();
}
}
static {
WinProcess.enableDebugPrivilege();
}
}
/**
* Implementation for Unix that supports reasonably powerful <tt>/proc</tt> FS.
*/
private static abstract class Unix<S extends Unix.UnixSystem<?>> extends ProcessTreeKiller {
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process)
*/
@Override
public void kill(Process proc) {
kill(proc, null);
}
protected abstract S createSystem();
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process, java.util.Map)
*/
@Override
public void kill(Process proc, Map<String, String> modelEnvVars) {
S system = createSystem();
UnixProcess p;
try {
p = system.get((Integer) PID_FIELD.get(proc));
} catch (IllegalAccessException e) { // impossible
IllegalAccessError x = new IllegalAccessError();
x.initCause(e);
throw x;
}
if (modelEnvVars == null) {
p.killRecursively();
} else {
for (UnixProcess lp : system) {
if (hasMatchingEnvVars(lp.getEnvVars(), modelEnvVars))
lp.kill();
}
}
}
/**
* Field to access the PID of the process.
*/
private static final Field PID_FIELD;
/**
* Method to destroy a process, given pid.
*/
private static final Method DESTROY_PROCESS;
static {
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
PID_FIELD = clazz.getDeclaredField("pid");
PID_FIELD.setAccessible(true);
DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess", int.class);
DESTROY_PROCESS.setAccessible(true);
} catch (ClassNotFoundException e) {
LinkageError x = new LinkageError();
x.initCause(e);
throw x;
} catch (NoSuchFieldException e) {
LinkageError x = new LinkageError();
x.initCause(e);
throw x;
} catch (NoSuchMethodException e) {
LinkageError x = new LinkageError();
x.initCause(e);
throw x;
}
}
/**
* Represents a single Unix system, which hosts multiple processes.
*
* <p>
* The object represents a snapshot of the system state.
*/
static abstract class UnixSystem<P extends UnixProcess<P>> implements Iterable<P> {
private final Map<Integer/*pid*/, P> processes = new HashMap<Integer, P>();
UnixSystem() {
File[] processes = new File("/proc").listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
});
if (processes == null) {
LOGGER.info("No /proc");
return;
}
for (File p : processes) {
int pid;
try {
pid = Integer.parseInt(p.getName());
} catch (NumberFormatException e) {
// other sub-directories
continue;
}
try {
this.processes.put(pid, createProcess(pid));
} catch (IOException e) {
// perhaps the process status has changed since we obtained a directory listing
}
}
}
protected abstract P createProcess(int pid) throws IOException;
public P get(int pid) {
return processes.get(pid);
}
public Iterator<P> iterator() {
return processes.values().iterator();
}
}
/**
* A process.
*/
public static abstract class UnixProcess<P extends UnixProcess<P>> {
public final UnixSystem<P> system;
protected UnixProcess(UnixSystem<P> system) {
this.system = system;
}
public abstract int getPid();
/**
* Gets the parent process. This method may return null, because
* there's no guarantee that we are getting a consistent snapshot
* of the whole system state.
*/
public abstract P getParent();
protected final File getFile(String relativePath) {
return new File(new File("/proc/" + getPid()), relativePath);
}
/**
* Immediate child processes.
*/
public List<P> getChildren() {
List<P> r = new ArrayList<P>();
for (P p : system)
if (p.getParent() == this)
r.add(p);
return r;
}
/**
* Tries to kill this process.
*/
public void kill() {
try {
DESTROY_PROCESS.invoke(null, getPid());
} catch (IllegalAccessException e) {
// this is impossible
IllegalAccessError x = new IllegalAccessError();
x.initCause(e);
throw x;
} catch (InvocationTargetException e) {
// tunnel serious errors
if (e.getTargetException() instanceof Error)
throw (Error) e.getTargetException();
// otherwise log and let go. I need to see when this happens
LOGGER.log(Level.INFO, "Failed to terminate pid=" + getPid(), e);
}
}
public void killRecursively() {
for (P p : getChildren())
p.killRecursively();
kill();
}
/**
* Obtains the environment variables of this process.
*
* @return
* empty map if failed (for example because the process is already dead,
* or the permission was denied.)
*/
public abstract EnvVars getEnvVars();
}
}
/**
* Implementation for Linux that uses <tt>/proc</tt>.
*/
private static final class Linux extends Unix<Linux.LinuxSystem> {
@Override
protected LinuxSystem createSystem() {
return new LinuxSystem();
}
static class LinuxSystem extends Unix.UnixSystem<LinuxProcess> {
@Override
protected LinuxProcess createProcess(int pid) throws IOException {
return new LinuxProcess(this, pid);
}
}
static class LinuxProcess extends Unix.UnixProcess<LinuxProcess> {
private final int pid;
private int ppid = -1;
private EnvVars envVars;
LinuxProcess(LinuxSystem system, int pid) throws IOException {
super(system);
this.pid = pid;
BufferedReader r = new BufferedReader(new FileReader(getFile("status")));
try {
String line;
while ((line = r.readLine()) != null) {
line = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("ppid:")) {
ppid = Integer.parseInt(line.substring(5).trim());
break;
}
}
} finally {
r.close();
}
if (ppid == -1)
throw new IOException("Failed to parse PPID from /proc/" + pid + "/status");
}
@Override
public int getPid() {
return pid;
}
@Override
public LinuxProcess getParent() {
return system.get(ppid);
}
@Override
public synchronized EnvVars getEnvVars() {
if (envVars != null)
return envVars;
envVars = new EnvVars();
try {
byte[] environ = FileToBytesConverter.convertFileToByteArray(getFile("environ"));
int pos = 0;
for (int i = 0; i < environ.length; i++) {
byte b = environ[i];
if (b == 0) {
envVars.addLine(new String(environ, pos, i - pos));
pos = i + 1;
}
}
} catch (Exception e) {
// failed to read. this can happen under normal circumstances (most notably permission denied)
// so don't report this as an error.
}
return envVars;
}
}
}
/**
* Implementation for Solaris that uses <tt>/proc</tt>.
*
* Amazingly, this single code works for both 32bit and 64bit Solaris, despite the fact
* that does a lot of pointer manipulation and what not.
*/
private static final class Solaris extends Unix<Solaris.SolarisSystem> {
@Override
protected SolarisSystem createSystem() {
return new SolarisSystem();
}
static class SolarisSystem extends Unix.UnixSystem<SolarisProcess> {
@Override
protected SolarisProcess createProcess(int pid) throws IOException {
return new SolarisProcess(this, pid);
}
}
static class SolarisProcess extends Unix.UnixProcess<SolarisProcess> {
private final int pid;
private final int ppid;
/**
* Address of the environment vector. Even on 64bit Solaris this is still 32bit pointer.
*/
private final int envp;
private EnvVars envVars;
SolarisProcess(SolarisSystem system, int pid) throws IOException {
super(system);
this.pid = pid;
RandomAccessFile psinfo = new RandomAccessFile(getFile("psinfo"), "r");
try {
//typedef struct psinfo {
// int pr_flag; /* process flags */
// int pr_nlwp; /* number of lwps in the process */
// pid_t pr_pid; /* process id */
// pid_t pr_ppid; /* process id of parent */
// pid_t pr_pgid; /* process id of process group leader */
// pid_t pr_sid; /* session id */
// uid_t pr_uid; /* real user id */
// uid_t pr_euid; /* effective user id */
// gid_t pr_gid; /* real group id */
// gid_t pr_egid; /* effective group id */
// uintptr_t pr_addr; /* address of process */
// size_t pr_size; /* size of process image in Kbytes */
// size_t pr_rssize; /* resident set size in Kbytes */
// dev_t pr_ttydev; /* controlling tty device (or PRNODEV) */
// ushort_t pr_pctcpu; /* % of recent cpu time used by all lwps */
// ushort_t pr_pctmem; /* % of system memory used by process */
// timestruc_t pr_start; /* process start time, from the epoch */
// timestruc_t pr_time; /* cpu time for this process */
// timestruc_t pr_ctime; /* cpu time for reaped children */
// char pr_fname[PRFNSZ]; /* name of exec'ed file */
// char pr_psargs[PRARGSZ]; /* initial characters of arg list */
// int pr_wstat; /* if zombie, the wait() status */
// int pr_argc; /* initial argument count */
// uintptr_t pr_argv; /* address of initial argument vector */
// uintptr_t pr_envp; /* address of initial environment vector */
// char pr_dmodel; /* data model of the process */
// lwpsinfo_t pr_lwp; /* information for representative lwp */
//} psinfo_t;
// see http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/sys/types.h
// for the size of the various datatype.
psinfo.seek(8);
if (adjust(psinfo.readInt()) != pid)
throw new IOException("psinfo PID mismatch"); // sanity check
ppid = adjust(psinfo.readInt());
psinfo.seek(196); // now jump to pr_envp
envp = adjust(psinfo.readInt());
} finally {
psinfo.close();
}
if (ppid == -1)
throw new IOException("Failed to parse PPID from /proc/" + pid + "/status");
}
/**
* {@link DataInputStream} reads a value in big-endian, so
* convert it to the correct value on little-endian systems.
*/
private int adjust(int i) {
if (IS_LITTLE_ENDIAN)
return (i << 24) | ((i << 8) & 0x00FF0000) | ((i >> 8) & 0x0000FF00) | (i >>> 24);
else
return i;
}
@Override
public int getPid() {
return pid;
}
@Override
public SolarisProcess getParent() {
return system.get(ppid);
}
@Override
public synchronized EnvVars getEnvVars() {
if (envVars != null)
return envVars;
envVars = new EnvVars();
try {
RandomAccessFile as = new RandomAccessFile(getFile("as"), "r");
try {
for (int n = 0;; n++) {
// read a pointer to one entry
as.seek(to64(envp + n * 4));
int p = as.readInt();
if (p == 0)
break; // completed the walk
// now read the null-terminated string
as.seek(to64(p));
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int ch;
while ((ch = as.read()) != 0)
buf.write(ch);
envVars.addLine(buf.toString());
}
} finally {
// failed to read. this can happen under normal circumstances,
// so don't report this as an error.
as.close();
}
} catch (IOException e) {
// failed to read. this can happen under normal circumstances (most notably permission denied)
// so don't report this as an error.
}
return envVars;
}
/**
* int to long conversion with zero-padding.
*/
private static long to64(int i) {
return i & 0xFFFFFFFFL;
}
}
}
/*
On MacOS X, there's no procfs <http://www.osxbook.com/book/bonus/chapter11/procfs/>
instead you'd do it with the sysctl <http://search.cpan.org/src/DURIST/Proc-ProcessTable-0.42/os/darwin.c>
<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html>
There's CLI but that doesn't seem to offer the access to per-process info
<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man8/sysctl.8.html>
On HP-UX, pstat_getcommandline get you command line, but I'm not seeing any environment variables.
*/
private static final boolean IS_LITTLE_ENDIAN = "little".equals(System.getProperty("sun.cpu.endian"));
private static final Logger LOGGER = Logger.getLogger(ProcessTreeKiller.class.getName());
/**
* Convert null to "".
* @param s the string to fix.
* @return The string if not null, empty string if null.
*/
public static String fixNull(String s) {
if (s == null)
return "";
else
return s;
}
}
| weichaoguo/Anaconda | src/scheduler/src/org/ow2/proactive/scheduler/util/process/ProcessTreeKiller.java | 6,264 | // uid_t pr_euid; /* effective user id */ | line_comment | nl | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package org.ow2.proactive.scheduler.util.process;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jvnet.winp.WinProcess;
import org.jvnet.winp.WinpException;
import org.ow2.proactive.utils.FileToBytesConverter;
/**
* Kills a process tree to clean up the mess left by a build.
*
* @author Kohsuke Kawaguchi
* @since 1.201
*/
public abstract class ProcessTreeKiller {
/**
* Kills the given process (like {@link Process#destroy()}
* but also attempts to kill descendant processes created from the given
* process.
*
* <p>
* The implementation is obviously OS-dependent.
*
* <p>
* The execution doesn't have to be blocking; the method may return
* before processes are actually killed.
* @param proc the process to kill.
*/
public abstract void kill(Process proc);
/**
* In addition to what {@link #kill(Process)} does, also tries to
* kill all the daemon processes launched.
*
* <p>
* Daemon processes are hard to find because they normally detach themselves
* from the parent process. In this method, the method is given a
* "model environment variables", which is a list of environment variables
* and their values that are characteristic to the launched process.
* The implementation is expected to find processes
* in the system that inherit these environment variables, and kill
* them even if the {@code proc} and such processes do not have direct
* ancestor/descendant relationship.
* @param proc the process to kill.
* @param modelEnvVars the model environment variables characterizing the process.
*/
public abstract void kill(Process proc, Map<String, String> modelEnvVars);
/**
* Creates a magic cookie that can be used as the model environment variable
* when we later kill the processes.
*
* @return the magic cookie.
*/
public static String createCookie() {
return UUID.randomUUID().toString();
}
/**
* Gets the {@link ProcessTreeKiller} suitable for the current system
* that JVM runs in, or in the worst case return the default one
* that's not capable of killing descendants at all.
* @return the Process Tree Killer.
*/
public static ProcessTreeKiller get() {
if (File.pathSeparatorChar == ';')
return new Windows();
String os = fixNull(System.getProperty("os.name"));
if (os.equals("Linux"))
return new Linux();
if (os.equals("SunOS"))
return new Solaris();
return DEFAULT;
}
/**
* Given the environment variable of a process and the "model environment variable" that Hudson
* used for launching the build, returns true if there's a match (which means the process should
* be considered a descendant of a build.)
*/
protected boolean hasMatchingEnvVars(Map<String, String> envVar, Map<String, String> modelEnvVar) {
if (modelEnvVar.isEmpty())
// sanity check so that we don't start rampage.
return false;
for (Entry<String, String> e : modelEnvVar.entrySet()) {
String v = envVar.get(e.getKey());
if (v == null || !v.equals(e.getValue()))
return false; // no match
}
return true;
}
/**
* Fallback implementation that doesn't do anything clever.
*/
private static final ProcessTreeKiller DEFAULT = new ProcessTreeKiller() {
@Override
public void kill(Process proc) {
proc.destroy();
}
@Override
public void kill(Process proc, Map<String, String> modelEnvVars) {
proc.destroy();
}
};
/**
* Implementation for Windows.
*
* <p>
* Not a singleton pattern because loading this class requires Windows specific library.
*/
private static final class Windows extends ProcessTreeKiller {
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process)
*/
@Override
public void kill(Process proc) {
new WinProcess(proc).killRecursively();
}
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process, java.util.Map)
*/
@Override
public void kill(Process proc, Map<String, String> modelEnvVars) {
kill(proc);
for (WinProcess p : WinProcess.all()) {
if (p.getPid() < 10)
continue; // ignore system processes like "idle process"
boolean matched;
try {
matched = hasMatchingEnvVars(p.getEnvironmentVariables(), modelEnvVars);
} catch (WinpException e) {
// likely a missing privilege
continue;
}
if (matched)
p.killRecursively();
}
}
static {
WinProcess.enableDebugPrivilege();
}
}
/**
* Implementation for Unix that supports reasonably powerful <tt>/proc</tt> FS.
*/
private static abstract class Unix<S extends Unix.UnixSystem<?>> extends ProcessTreeKiller {
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process)
*/
@Override
public void kill(Process proc) {
kill(proc, null);
}
protected abstract S createSystem();
/**
* @see org.ow2.proactive.scheduler.util.process.ProcessTreeKiller#kill(java.lang.Process, java.util.Map)
*/
@Override
public void kill(Process proc, Map<String, String> modelEnvVars) {
S system = createSystem();
UnixProcess p;
try {
p = system.get((Integer) PID_FIELD.get(proc));
} catch (IllegalAccessException e) { // impossible
IllegalAccessError x = new IllegalAccessError();
x.initCause(e);
throw x;
}
if (modelEnvVars == null) {
p.killRecursively();
} else {
for (UnixProcess lp : system) {
if (hasMatchingEnvVars(lp.getEnvVars(), modelEnvVars))
lp.kill();
}
}
}
/**
* Field to access the PID of the process.
*/
private static final Field PID_FIELD;
/**
* Method to destroy a process, given pid.
*/
private static final Method DESTROY_PROCESS;
static {
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
PID_FIELD = clazz.getDeclaredField("pid");
PID_FIELD.setAccessible(true);
DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess", int.class);
DESTROY_PROCESS.setAccessible(true);
} catch (ClassNotFoundException e) {
LinkageError x = new LinkageError();
x.initCause(e);
throw x;
} catch (NoSuchFieldException e) {
LinkageError x = new LinkageError();
x.initCause(e);
throw x;
} catch (NoSuchMethodException e) {
LinkageError x = new LinkageError();
x.initCause(e);
throw x;
}
}
/**
* Represents a single Unix system, which hosts multiple processes.
*
* <p>
* The object represents a snapshot of the system state.
*/
static abstract class UnixSystem<P extends UnixProcess<P>> implements Iterable<P> {
private final Map<Integer/*pid*/, P> processes = new HashMap<Integer, P>();
UnixSystem() {
File[] processes = new File("/proc").listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
});
if (processes == null) {
LOGGER.info("No /proc");
return;
}
for (File p : processes) {
int pid;
try {
pid = Integer.parseInt(p.getName());
} catch (NumberFormatException e) {
// other sub-directories
continue;
}
try {
this.processes.put(pid, createProcess(pid));
} catch (IOException e) {
// perhaps the process status has changed since we obtained a directory listing
}
}
}
protected abstract P createProcess(int pid) throws IOException;
public P get(int pid) {
return processes.get(pid);
}
public Iterator<P> iterator() {
return processes.values().iterator();
}
}
/**
* A process.
*/
public static abstract class UnixProcess<P extends UnixProcess<P>> {
public final UnixSystem<P> system;
protected UnixProcess(UnixSystem<P> system) {
this.system = system;
}
public abstract int getPid();
/**
* Gets the parent process. This method may return null, because
* there's no guarantee that we are getting a consistent snapshot
* of the whole system state.
*/
public abstract P getParent();
protected final File getFile(String relativePath) {
return new File(new File("/proc/" + getPid()), relativePath);
}
/**
* Immediate child processes.
*/
public List<P> getChildren() {
List<P> r = new ArrayList<P>();
for (P p : system)
if (p.getParent() == this)
r.add(p);
return r;
}
/**
* Tries to kill this process.
*/
public void kill() {
try {
DESTROY_PROCESS.invoke(null, getPid());
} catch (IllegalAccessException e) {
// this is impossible
IllegalAccessError x = new IllegalAccessError();
x.initCause(e);
throw x;
} catch (InvocationTargetException e) {
// tunnel serious errors
if (e.getTargetException() instanceof Error)
throw (Error) e.getTargetException();
// otherwise log and let go. I need to see when this happens
LOGGER.log(Level.INFO, "Failed to terminate pid=" + getPid(), e);
}
}
public void killRecursively() {
for (P p : getChildren())
p.killRecursively();
kill();
}
/**
* Obtains the environment variables of this process.
*
* @return
* empty map if failed (for example because the process is already dead,
* or the permission was denied.)
*/
public abstract EnvVars getEnvVars();
}
}
/**
* Implementation for Linux that uses <tt>/proc</tt>.
*/
private static final class Linux extends Unix<Linux.LinuxSystem> {
@Override
protected LinuxSystem createSystem() {
return new LinuxSystem();
}
static class LinuxSystem extends Unix.UnixSystem<LinuxProcess> {
@Override
protected LinuxProcess createProcess(int pid) throws IOException {
return new LinuxProcess(this, pid);
}
}
static class LinuxProcess extends Unix.UnixProcess<LinuxProcess> {
private final int pid;
private int ppid = -1;
private EnvVars envVars;
LinuxProcess(LinuxSystem system, int pid) throws IOException {
super(system);
this.pid = pid;
BufferedReader r = new BufferedReader(new FileReader(getFile("status")));
try {
String line;
while ((line = r.readLine()) != null) {
line = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("ppid:")) {
ppid = Integer.parseInt(line.substring(5).trim());
break;
}
}
} finally {
r.close();
}
if (ppid == -1)
throw new IOException("Failed to parse PPID from /proc/" + pid + "/status");
}
@Override
public int getPid() {
return pid;
}
@Override
public LinuxProcess getParent() {
return system.get(ppid);
}
@Override
public synchronized EnvVars getEnvVars() {
if (envVars != null)
return envVars;
envVars = new EnvVars();
try {
byte[] environ = FileToBytesConverter.convertFileToByteArray(getFile("environ"));
int pos = 0;
for (int i = 0; i < environ.length; i++) {
byte b = environ[i];
if (b == 0) {
envVars.addLine(new String(environ, pos, i - pos));
pos = i + 1;
}
}
} catch (Exception e) {
// failed to read. this can happen under normal circumstances (most notably permission denied)
// so don't report this as an error.
}
return envVars;
}
}
}
/**
* Implementation for Solaris that uses <tt>/proc</tt>.
*
* Amazingly, this single code works for both 32bit and 64bit Solaris, despite the fact
* that does a lot of pointer manipulation and what not.
*/
private static final class Solaris extends Unix<Solaris.SolarisSystem> {
@Override
protected SolarisSystem createSystem() {
return new SolarisSystem();
}
static class SolarisSystem extends Unix.UnixSystem<SolarisProcess> {
@Override
protected SolarisProcess createProcess(int pid) throws IOException {
return new SolarisProcess(this, pid);
}
}
static class SolarisProcess extends Unix.UnixProcess<SolarisProcess> {
private final int pid;
private final int ppid;
/**
* Address of the environment vector. Even on 64bit Solaris this is still 32bit pointer.
*/
private final int envp;
private EnvVars envVars;
SolarisProcess(SolarisSystem system, int pid) throws IOException {
super(system);
this.pid = pid;
RandomAccessFile psinfo = new RandomAccessFile(getFile("psinfo"), "r");
try {
//typedef struct psinfo {
// int pr_flag; /* process flags */
// int pr_nlwp; /* number of lwps in the process */
// pid_t pr_pid; /* process id */
// pid_t pr_ppid; /* process id of parent */
// pid_t pr_pgid; /* process id of process group leader */
// pid_t pr_sid; /* session id */
// uid_t pr_uid; /* real user id */
// uid_t pr_euid;<SUF>
// gid_t pr_gid; /* real group id */
// gid_t pr_egid; /* effective group id */
// uintptr_t pr_addr; /* address of process */
// size_t pr_size; /* size of process image in Kbytes */
// size_t pr_rssize; /* resident set size in Kbytes */
// dev_t pr_ttydev; /* controlling tty device (or PRNODEV) */
// ushort_t pr_pctcpu; /* % of recent cpu time used by all lwps */
// ushort_t pr_pctmem; /* % of system memory used by process */
// timestruc_t pr_start; /* process start time, from the epoch */
// timestruc_t pr_time; /* cpu time for this process */
// timestruc_t pr_ctime; /* cpu time for reaped children */
// char pr_fname[PRFNSZ]; /* name of exec'ed file */
// char pr_psargs[PRARGSZ]; /* initial characters of arg list */
// int pr_wstat; /* if zombie, the wait() status */
// int pr_argc; /* initial argument count */
// uintptr_t pr_argv; /* address of initial argument vector */
// uintptr_t pr_envp; /* address of initial environment vector */
// char pr_dmodel; /* data model of the process */
// lwpsinfo_t pr_lwp; /* information for representative lwp */
//} psinfo_t;
// see http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/sys/types.h
// for the size of the various datatype.
psinfo.seek(8);
if (adjust(psinfo.readInt()) != pid)
throw new IOException("psinfo PID mismatch"); // sanity check
ppid = adjust(psinfo.readInt());
psinfo.seek(196); // now jump to pr_envp
envp = adjust(psinfo.readInt());
} finally {
psinfo.close();
}
if (ppid == -1)
throw new IOException("Failed to parse PPID from /proc/" + pid + "/status");
}
/**
* {@link DataInputStream} reads a value in big-endian, so
* convert it to the correct value on little-endian systems.
*/
private int adjust(int i) {
if (IS_LITTLE_ENDIAN)
return (i << 24) | ((i << 8) & 0x00FF0000) | ((i >> 8) & 0x0000FF00) | (i >>> 24);
else
return i;
}
@Override
public int getPid() {
return pid;
}
@Override
public SolarisProcess getParent() {
return system.get(ppid);
}
@Override
public synchronized EnvVars getEnvVars() {
if (envVars != null)
return envVars;
envVars = new EnvVars();
try {
RandomAccessFile as = new RandomAccessFile(getFile("as"), "r");
try {
for (int n = 0;; n++) {
// read a pointer to one entry
as.seek(to64(envp + n * 4));
int p = as.readInt();
if (p == 0)
break; // completed the walk
// now read the null-terminated string
as.seek(to64(p));
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int ch;
while ((ch = as.read()) != 0)
buf.write(ch);
envVars.addLine(buf.toString());
}
} finally {
// failed to read. this can happen under normal circumstances,
// so don't report this as an error.
as.close();
}
} catch (IOException e) {
// failed to read. this can happen under normal circumstances (most notably permission denied)
// so don't report this as an error.
}
return envVars;
}
/**
* int to long conversion with zero-padding.
*/
private static long to64(int i) {
return i & 0xFFFFFFFFL;
}
}
}
/*
On MacOS X, there's no procfs <http://www.osxbook.com/book/bonus/chapter11/procfs/>
instead you'd do it with the sysctl <http://search.cpan.org/src/DURIST/Proc-ProcessTable-0.42/os/darwin.c>
<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html>
There's CLI but that doesn't seem to offer the access to per-process info
<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man8/sysctl.8.html>
On HP-UX, pstat_getcommandline get you command line, but I'm not seeing any environment variables.
*/
private static final boolean IS_LITTLE_ENDIAN = "little".equals(System.getProperty("sun.cpu.endian"));
private static final Logger LOGGER = Logger.getLogger(ProcessTreeKiller.class.getName());
/**
* Convert null to "".
* @param s the string to fix.
* @return The string if not null, empty string if null.
*/
public static String fixNull(String s) {
if (s == null)
return "";
else
return s;
}
}
|
52694_0 | package InfobordSysteem.infoborden;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import Tijdtools.tijdtools.InfobordTijdFuncties;
public class Infobord extends Application{
private String titel = "Bushalte XX in richting YY";
private Text tijdRegel = new Text("00:00:00");
private Text infoRegel1 = new Text("De eestevolgende bus");
private Text infoRegel2 = new Text("De tweede bus");
private Text infoRegel3 = new Text("De derde bus");
private Text infoRegel4 = new Text("De vierde bus");
private String halte;
private String richting;
private Berichten berichten;
public Infobord(String halte, String richting) {
this.titel = "Bushalte " + halte + " in richting " + richting;
this.halte=halte;
this.richting=richting;
this.berichten=new Berichten();
}
public void verwerkBericht() {
if (berichten.hetBordMoetVerverst()) {
String[] infoTekstRegels = berichten.repaintInfoBordValues();
//Deze code hoort bij opdracht 3
InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties();
String tijd = tijdfuncties.getCentralTime().toString();
tijdRegel.setText(tijd);
infoRegel1.setText(infoTekstRegels[0]);
infoRegel2.setText(infoTekstRegels[1]);
infoRegel3.setText(infoTekstRegels[2]);
infoRegel4.setText(infoTekstRegels[3]);
};
}
public void updateBord() {
Runnable updater = new Runnable() {
@Override
public void run() {
verwerkBericht();
}
};
Platform.runLater(updater);
}
@Override
public void start(Stage primaryStage) {
String selector = "(HALTE = '"+ halte + "') AND (RICHTING='"+ richting + "')";
thread(new ListenerStarter(selector, this, berichten),false);
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER_LEFT);
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setHgap(5.5);
pane.setVgap(5.5);
// Place nodes in the pane
pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0);
pane.add(tijdRegel, 1, 0);
pane.add(new Label("1:"), 0, 1);
pane.add(infoRegel1, 1, 1);
pane.add(new Label("2:"), 0, 2);
pane.add(infoRegel2, 1, 2);
pane.add(new Label("3:"), 0, 3);
pane.add(infoRegel3, 1, 3);
pane.add(new Label("4:"), 0, 4);
pane.add(infoRegel4, 1, 4);
// Create a scene and place it in the stage
Scene scene = new Scene(pane,500,150);
primaryStage.setTitle(titel); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
} | welmaris/BusSimulator_SQ_DUO23 | InfobordSysteem/infoborden/Infobord.java | 1,107 | //Deze code hoort bij opdracht 3 | line_comment | nl | package InfobordSysteem.infoborden;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import Tijdtools.tijdtools.InfobordTijdFuncties;
public class Infobord extends Application{
private String titel = "Bushalte XX in richting YY";
private Text tijdRegel = new Text("00:00:00");
private Text infoRegel1 = new Text("De eestevolgende bus");
private Text infoRegel2 = new Text("De tweede bus");
private Text infoRegel3 = new Text("De derde bus");
private Text infoRegel4 = new Text("De vierde bus");
private String halte;
private String richting;
private Berichten berichten;
public Infobord(String halte, String richting) {
this.titel = "Bushalte " + halte + " in richting " + richting;
this.halte=halte;
this.richting=richting;
this.berichten=new Berichten();
}
public void verwerkBericht() {
if (berichten.hetBordMoetVerverst()) {
String[] infoTekstRegels = berichten.repaintInfoBordValues();
//Deze code<SUF>
InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties();
String tijd = tijdfuncties.getCentralTime().toString();
tijdRegel.setText(tijd);
infoRegel1.setText(infoTekstRegels[0]);
infoRegel2.setText(infoTekstRegels[1]);
infoRegel3.setText(infoTekstRegels[2]);
infoRegel4.setText(infoTekstRegels[3]);
};
}
public void updateBord() {
Runnable updater = new Runnable() {
@Override
public void run() {
verwerkBericht();
}
};
Platform.runLater(updater);
}
@Override
public void start(Stage primaryStage) {
String selector = "(HALTE = '"+ halte + "') AND (RICHTING='"+ richting + "')";
thread(new ListenerStarter(selector, this, berichten),false);
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER_LEFT);
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setHgap(5.5);
pane.setVgap(5.5);
// Place nodes in the pane
pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0);
pane.add(tijdRegel, 1, 0);
pane.add(new Label("1:"), 0, 1);
pane.add(infoRegel1, 1, 1);
pane.add(new Label("2:"), 0, 2);
pane.add(infoRegel2, 1, 2);
pane.add(new Label("3:"), 0, 3);
pane.add(infoRegel3, 1, 3);
pane.add(new Label("4:"), 0, 4);
pane.add(infoRegel4, 1, 4);
// Create a scene and place it in the stage
Scene scene = new Scene(pane,500,150);
primaryStage.setTitle(titel); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
} |
22086_6 | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays van knoppen, 1 voor iedere panel.
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | wennhao/project3-4 | guiold_OUTDATED/gui.java | 765 | //Drie arrays van knoppen, 1 voor iedere panel. | line_comment | nl | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays<SUF>
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} |
196460_8 | package spelling;
import java.util.List;
public class BuildHTML {
public static String getHtml(List<WordBean> wordBeanList) {
String htmlStr = getHTMLHead();
htmlStr = htmlStr + getScript_Checkall(wordBeanList);
htmlStr = htmlStr + getScript(wordBeanList);
htmlStr = htmlStr + getContent_Checkall();
htmlStr = htmlStr + getContent(wordBeanList);
// htmlStr = htmlStr + getcontent2(wordBeanList);
htmlStr = htmlStr + getHTMLEnd();
return htmlStr;
}
public static String getHTMLHead() {
String htmlHeadStr = "<html><head>\n";
// htmlHeadStr = htmlHeadStr +
// "<script type=\"text/javascript\" src=\"js/jquery-1.4.2.js\"></script>";
// htmlHeadStr = htmlHeadStr +
// "<script type=\"text/javascript\">" +
// "$(document).ready(function(){" +
// "if( $(\"#show_word\").is(\":visible\")){" +
// "$(\"#show_word\").click(function(){" +
// "$(\"#show_wordAAA\").slideToggle(\"slow\");" +
// "});" +
// "}" +
// "});" +
// "</script>";
htmlHeadStr = htmlHeadStr + "<style> \n";
htmlHeadStr = htmlHeadStr + "body {\n" +
"background-color:lightblue; \n" +
"background-image:url('img/pencil.gif'); \n" +
"background-repeat:no-repeat; \n " +
"background-attachment:fixed; \n " +
"background-position:center; \n " +
"}" +
"h1 {font-size:36pt;}" +
"h2 {color:blue;}" +
"p {margin-left:50px;}" +
"</style>";
htmlHeadStr = htmlHeadStr + "</head><body bgcolor=\"#OOFFCC\"> <h6>2.6</h6> <center> <h1><i>Spelling<i></h1> <br> <i><h6>Wensen Zhang</h6></i> \n";
return htmlHeadStr;
}
public static String getContent(List<WordBean> wordBeanList) {
String s = new String();
s = s + "<br><ol>\n";
int ii = 1;
for (WordBean wb : wordBeanList) {
String mp3Url = "Non";
if (wb.getMp3List().size() != 0 && wb.getMp3List() != null) {
mp3Url = getHtmlEmbed(wb.getMp3List().get(0));
}
// htmlContent = htmlContent +
// " <div id=\"show_word\">Show Word</div>";
// htmlContent = htmlContent +
// " <div id=\"show_wordAAA\"><a href=\"" + wb.getWordURL() +
// "\" target=\"new\">" + wb.getWord() + "</a></div>\n";
// htmlContent = htmlContent + "<p></p>\n";
s = s
+ "<FORM NAME=\"form" + ii + "\"> \n"
+ "<li>" + mp3Url + " "
+ " <a href=\"" + wb.getWordURL() + "\">Definition</a> <br>\n"
+ "<INPUT type=\"text\" value=\"\" name=\"Answer\" size=25> \n"
+ "<INPUT type=\"hidden\" value=\""
+ wb.getWord()
+ "\" name=\"Word\" size=5> \n"
+ "<input type=\"button\" value=\"Check\" name=\"Submit\" onClick=\"check"
+ ii
+ "()\"> <br> \n"
+ "<INPUT type=\"text\" value=\"Input Word Then Click Submit Button \" name=\"Result\" size=35> \n"
+ " <br> \n"
+ "<INPUT type=\"text\" value=\" \" name=\"ShowAnswer\" size=25> \n"
+ " <input type=\"button\" value=\"Show Answer\" name=\"Show\" onClick=\"show" + ii + "()\"> \n"
+ "</FORM>";
s = s + "\n";
ii++;
}
s = s + "</ol> \n";
return s;
}
public static String getContent_Checkall() {
String s = "<FORM NAME=\"formall\"> \n"
+ "<input type=\"button\" value=\"Check Test\" name=\"Check All\" onClick=\"checkall()\"> \n"
+ " <input type=\"button\" value=\"See Answers\" name=\"Show\" onClick=\"showall()\"> \n"
+ " <input type=\"button\" value=\"Restart\" name=\"Reset All\" onClick=\"resetall()\"> \n"
+ "</FORM>";
return s;
}
public static String getScript_Checkall(List<WordBean> wordBeanList) {
int nword = wordBeanList.size();
String s = "<script type=\"text/javascript\">\n";
s = s + "function checkall(){\n";
for (int ii = 0; ii < nword; ii++) {
int ip = ii + 1;
s = s + "check" + ip + "(); \n";
}
s = s + "} \n";
s = s + "function showall(){\n";
for (int ii = 0; ii < nword; ii++) {
int ip = ii + 1;
s = s + "show" + ip + "(); \n";
}
s = s + "} \n";
s = s + "function resetall(){\n";
for (int ii = 0; ii < nword; ii++) {
int ip = ii + 1;
s = s + "document.form" + ip + ".Answer.value = \"\"; \n";
s = s + "document.form" + ip + ".Result.value = \"Input Word Then Click Submit Button \"; \n";
s = s + "document.form" + ip + ".ShowAnswer.value = \"\"; \n";
}
s = s + "} \n";
s = s + "</script>\n";
return s;
}
public static String getScript(List<WordBean> wordBeanList) {
String s = "<script type=\"text/javascript\">\n";
int ii = 1;
for (WordBean wb : wordBeanList) {
s = s + "function check" + ii + "(){\n";
s = s + "if (document.form" + ii + ".Word.value == document.form" + ii
+ ".Answer.value){\n" + "document.form" + ii + ".Result.value = document.form"
+ ii + ".Word.value + \" is Correct!\"; \n" + "}else{ \n" + " document.form"
+ ii + ".Result.value = document.form" + ii
+ ".Answer.value + \" is Incorrect!\"; \n" + "} \n" + "} \n" +
" function show" + ii + "(){ \n" + "document.form" + ii
+ ".ShowAnswer.value = document.form" + ii
+ ".Word.value; \n" + "} \n";
ii++;
}
s = s + "</script>\n";
return s;
}
public static String getcontent2(List<WordBean> wordBeanList) {
String htmlContent = new String();
htmlContent = htmlContent + "<br>\n";
htmlContent = htmlContent + "<hr>\n";
htmlContent = htmlContent + "<p></p>\n";
for (int i = 0; i < 20; i++) {
htmlContent = htmlContent + ".<br>\n";
}
int ii = 0;
htmlContent = htmlContent + "<ul><ol>\n";
for (WordBean wb : wordBeanList) {
String mp3Url = "Non";
if (wb.getMp3List().size() != 0 && wb.getMp3List() != null) {
mp3Url = getHtmlEmbed(wb.getMp3List().get(0));
}
htmlContent = htmlContent + "<li>" + mp3Url;
htmlContent = htmlContent + " <a href=\"" + wb.getWordURL() + "\" target=\"new\">"
+ wb.getWord() + "</a>\n";
// htmlContent = htmlContent + "<p></p>\n";
ii++;
}
htmlContent = htmlContent + "</ol></ul>\n";
return htmlContent;
}
public static String getHtmlEmbed(String mp3Url) {
String htmlEmbed = "<span><embed type=\"application/x-shockwave-flash\" src=\"http://static.sfdict.com/dictstatic/d/g/speaker.swf\" id=\"speaker\" quality=\"high\" loop=\"false\" menu=\"false\" salign=\"t\" allowscriptaccess=\"sameDomain\" wmode=\"transparent\" flashvars=\"soundUrl="
+ mp3Url + "\"" + " align=\"texttop\" height=\"15\" width=\"17\"></span>";
// <embed type="application/x-shockwave-flash"
// src="http://static.sfdict.com/dictstatic/d/g/speaker.swf"
// id="speaker" quality="high" loop="false" menu="false" salign="t"
// allowscriptaccess="sameDomain" wmode="transparent"
// flashvars="soundUrl=http://static.sfdict.com/dictstatic/dictionary/audio/luna/E03/E0398500.mp3"
// align="texttop" height="15" width="17"></span>
return htmlEmbed;
}
public static String getHTMLEnd() {
String htmlEndStr = " </center> </body>\n";
htmlEndStr = htmlEndStr + "</html>\n";
return htmlEndStr;
}
}
| wenszhang/MAD-Project-2015-2016 | src/spelling/BuildHTML.java | 2,779 | // htmlContent = htmlContent +
| line_comment | nl | package spelling;
import java.util.List;
public class BuildHTML {
public static String getHtml(List<WordBean> wordBeanList) {
String htmlStr = getHTMLHead();
htmlStr = htmlStr + getScript_Checkall(wordBeanList);
htmlStr = htmlStr + getScript(wordBeanList);
htmlStr = htmlStr + getContent_Checkall();
htmlStr = htmlStr + getContent(wordBeanList);
// htmlStr = htmlStr + getcontent2(wordBeanList);
htmlStr = htmlStr + getHTMLEnd();
return htmlStr;
}
public static String getHTMLHead() {
String htmlHeadStr = "<html><head>\n";
// htmlHeadStr = htmlHeadStr +
// "<script type=\"text/javascript\" src=\"js/jquery-1.4.2.js\"></script>";
// htmlHeadStr = htmlHeadStr +
// "<script type=\"text/javascript\">" +
// "$(document).ready(function(){" +
// "if( $(\"#show_word\").is(\":visible\")){" +
// "$(\"#show_word\").click(function(){" +
// "$(\"#show_wordAAA\").slideToggle(\"slow\");" +
// "});" +
// "}" +
// "});" +
// "</script>";
htmlHeadStr = htmlHeadStr + "<style> \n";
htmlHeadStr = htmlHeadStr + "body {\n" +
"background-color:lightblue; \n" +
"background-image:url('img/pencil.gif'); \n" +
"background-repeat:no-repeat; \n " +
"background-attachment:fixed; \n " +
"background-position:center; \n " +
"}" +
"h1 {font-size:36pt;}" +
"h2 {color:blue;}" +
"p {margin-left:50px;}" +
"</style>";
htmlHeadStr = htmlHeadStr + "</head><body bgcolor=\"#OOFFCC\"> <h6>2.6</h6> <center> <h1><i>Spelling<i></h1> <br> <i><h6>Wensen Zhang</h6></i> \n";
return htmlHeadStr;
}
public static String getContent(List<WordBean> wordBeanList) {
String s = new String();
s = s + "<br><ol>\n";
int ii = 1;
for (WordBean wb : wordBeanList) {
String mp3Url = "Non";
if (wb.getMp3List().size() != 0 && wb.getMp3List() != null) {
mp3Url = getHtmlEmbed(wb.getMp3List().get(0));
}
// htmlContent = htmlContent +
// " <div id=\"show_word\">Show Word</div>";
// htmlContent =<SUF>
// " <div id=\"show_wordAAA\"><a href=\"" + wb.getWordURL() +
// "\" target=\"new\">" + wb.getWord() + "</a></div>\n";
// htmlContent = htmlContent + "<p></p>\n";
s = s
+ "<FORM NAME=\"form" + ii + "\"> \n"
+ "<li>" + mp3Url + " "
+ " <a href=\"" + wb.getWordURL() + "\">Definition</a> <br>\n"
+ "<INPUT type=\"text\" value=\"\" name=\"Answer\" size=25> \n"
+ "<INPUT type=\"hidden\" value=\""
+ wb.getWord()
+ "\" name=\"Word\" size=5> \n"
+ "<input type=\"button\" value=\"Check\" name=\"Submit\" onClick=\"check"
+ ii
+ "()\"> <br> \n"
+ "<INPUT type=\"text\" value=\"Input Word Then Click Submit Button \" name=\"Result\" size=35> \n"
+ " <br> \n"
+ "<INPUT type=\"text\" value=\" \" name=\"ShowAnswer\" size=25> \n"
+ " <input type=\"button\" value=\"Show Answer\" name=\"Show\" onClick=\"show" + ii + "()\"> \n"
+ "</FORM>";
s = s + "\n";
ii++;
}
s = s + "</ol> \n";
return s;
}
public static String getContent_Checkall() {
String s = "<FORM NAME=\"formall\"> \n"
+ "<input type=\"button\" value=\"Check Test\" name=\"Check All\" onClick=\"checkall()\"> \n"
+ " <input type=\"button\" value=\"See Answers\" name=\"Show\" onClick=\"showall()\"> \n"
+ " <input type=\"button\" value=\"Restart\" name=\"Reset All\" onClick=\"resetall()\"> \n"
+ "</FORM>";
return s;
}
public static String getScript_Checkall(List<WordBean> wordBeanList) {
int nword = wordBeanList.size();
String s = "<script type=\"text/javascript\">\n";
s = s + "function checkall(){\n";
for (int ii = 0; ii < nword; ii++) {
int ip = ii + 1;
s = s + "check" + ip + "(); \n";
}
s = s + "} \n";
s = s + "function showall(){\n";
for (int ii = 0; ii < nword; ii++) {
int ip = ii + 1;
s = s + "show" + ip + "(); \n";
}
s = s + "} \n";
s = s + "function resetall(){\n";
for (int ii = 0; ii < nword; ii++) {
int ip = ii + 1;
s = s + "document.form" + ip + ".Answer.value = \"\"; \n";
s = s + "document.form" + ip + ".Result.value = \"Input Word Then Click Submit Button \"; \n";
s = s + "document.form" + ip + ".ShowAnswer.value = \"\"; \n";
}
s = s + "} \n";
s = s + "</script>\n";
return s;
}
public static String getScript(List<WordBean> wordBeanList) {
String s = "<script type=\"text/javascript\">\n";
int ii = 1;
for (WordBean wb : wordBeanList) {
s = s + "function check" + ii + "(){\n";
s = s + "if (document.form" + ii + ".Word.value == document.form" + ii
+ ".Answer.value){\n" + "document.form" + ii + ".Result.value = document.form"
+ ii + ".Word.value + \" is Correct!\"; \n" + "}else{ \n" + " document.form"
+ ii + ".Result.value = document.form" + ii
+ ".Answer.value + \" is Incorrect!\"; \n" + "} \n" + "} \n" +
" function show" + ii + "(){ \n" + "document.form" + ii
+ ".ShowAnswer.value = document.form" + ii
+ ".Word.value; \n" + "} \n";
ii++;
}
s = s + "</script>\n";
return s;
}
public static String getcontent2(List<WordBean> wordBeanList) {
String htmlContent = new String();
htmlContent = htmlContent + "<br>\n";
htmlContent = htmlContent + "<hr>\n";
htmlContent = htmlContent + "<p></p>\n";
for (int i = 0; i < 20; i++) {
htmlContent = htmlContent + ".<br>\n";
}
int ii = 0;
htmlContent = htmlContent + "<ul><ol>\n";
for (WordBean wb : wordBeanList) {
String mp3Url = "Non";
if (wb.getMp3List().size() != 0 && wb.getMp3List() != null) {
mp3Url = getHtmlEmbed(wb.getMp3List().get(0));
}
htmlContent = htmlContent + "<li>" + mp3Url;
htmlContent = htmlContent + " <a href=\"" + wb.getWordURL() + "\" target=\"new\">"
+ wb.getWord() + "</a>\n";
// htmlContent = htmlContent + "<p></p>\n";
ii++;
}
htmlContent = htmlContent + "</ol></ul>\n";
return htmlContent;
}
public static String getHtmlEmbed(String mp3Url) {
String htmlEmbed = "<span><embed type=\"application/x-shockwave-flash\" src=\"http://static.sfdict.com/dictstatic/d/g/speaker.swf\" id=\"speaker\" quality=\"high\" loop=\"false\" menu=\"false\" salign=\"t\" allowscriptaccess=\"sameDomain\" wmode=\"transparent\" flashvars=\"soundUrl="
+ mp3Url + "\"" + " align=\"texttop\" height=\"15\" width=\"17\"></span>";
// <embed type="application/x-shockwave-flash"
// src="http://static.sfdict.com/dictstatic/d/g/speaker.swf"
// id="speaker" quality="high" loop="false" menu="false" salign="t"
// allowscriptaccess="sameDomain" wmode="transparent"
// flashvars="soundUrl=http://static.sfdict.com/dictstatic/dictionary/audio/luna/E03/E0398500.mp3"
// align="texttop" height="15" width="17"></span>
return htmlEmbed;
}
public static String getHTMLEnd() {
String htmlEndStr = " </center> </body>\n";
htmlEndStr = htmlEndStr + "</html>\n";
return htmlEndStr;
}
}
|
10424_0 | // http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop-p1.html
package main;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Connection extends JLabel implements DragGestureListener, DragSourceListener, DropTargetListener, Transferable, Serializable {
private int index, type;
private String name;
private boolean input;
private int conX, conY;
private boolean open; // Of er een kabel in zit...
private Module module;
private ImageIcon icon;
private Connection _this = null;
public final static int imageWidth = 13/2; // DE HELFT ERVAN!!!
Cables cables = null;
private static boolean moving = false;
//--- drag
private DragSource dragSource = null;
private int dragAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- drop
private DropTarget dropTarget = null;
private int dropAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- data
public static final DataFlavor inConnectionFlavor = new DataFlavor("jmod/inConnection", "jMod In Connection");
public static final DataFlavor outConnectionFlavor = new DataFlavor("jmod/outConnection", "jMod Out Connection");
private static final DataFlavor[] inFlavors = {inConnectionFlavor, outConnectionFlavor};
private static final DataFlavor[] outFlavors = {outConnectionFlavor, inConnectionFlavor};
private DataFlavor[] flavors = null;
private int oldDragX = -1, oldDragY = -1;
// endDrag zorgt ervoor dat de kabel die zojuist gedropt is, opnieuw getekend wordt met een curve.
// Volgens mij worden alle kabels opnieuw getekend na een drop... ach ja...
private boolean endDrag = true;
Connection(Module newModule, boolean bInput, int newIndex, String newName, int newType, int newX, int newY) {
_this = this;
index = newIndex;
type = newType;
input = bInput;
name = newName;
conX = newX;
conY = newY;
open = true;
module = newModule;
if (input){
if (type == 0)
icon = new ImageIcon("./grafix/_con_in_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_in_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_in_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_in.gif");
flavors = inFlavors;
}
else {
if (type == 0)
icon = new ImageIcon("./grafix/_con_out_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_out_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_out_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_out.gif");
flavors = outFlavors;
}
this.setIcon(icon);
this.setLocation(conX, conY);
this.setSize(icon.getIconWidth(), icon.getIconHeight());
this.setToolTipText(name);
module.add(this);
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this, dragAction, this);
dropTarget = new DropTarget(this, dropAction, this, true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moving = false;
// TODO ?Replace lgic to Cables
Cable cab = null;
int modIndex = module.getModuleData().getModIndex();
int conIndex = _this.getConnectionIndex();
int inpIndex = _this.input?0:1;
boolean poly = module.getModuleData().getPoly();
int loopSize = poly?module.getModules().getCables().getPolySize():module.getModules().getCables().getCommonSize();
if (loopSize > 0) {
for (int i=0; i < loopSize; i++) {
cab = module.getModules().getCables().getCable(poly, i);
if (((cab.getBeginModule() == modIndex) && (cab.getBeginConnector() == conIndex) && (cab.getBeginConnectorType() == inpIndex)) ||
((cab.getEndModule() == modIndex) && (cab.getEndConnector() == conIndex) && (cab.getEndConnectorType() == inpIndex))) {
Cables.setDragCable(cab);
Cables.getDragCable().setSelectColor1();
break;
}
}
}
if (e.isAltDown()) {
module.getModules().getCables().selectChain(cab, poly);
}
if (e.getClickCount() > 1 || e.isControlDown()) {
moving = true;
Cables.determBeginWindowDrag(module.getX() + conX, module.getY() + conY);
Cables.determBeginCableDrag(modIndex, conIndex, inpIndex);
Cables.getDragCable().setSelectColor2();
}
}
public void mouseReleased(MouseEvent e)
{
if (e.isAltDown()) {
Cable cab = Cables.getDragCable();
module.getModules().getCables().unSelectChain(cab, module.getModuleData().getPoly());
}
if (!e.isAltDown()) {
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
}
}
});
}
// Getters
public Module getModule() {
return module;
}
public String getConnectionName() {
return name;
}
public int getConnectionType() {
return type;
}
public int getConnectionIndex() {
return index;
}
public int getConnectionLocationX() {
return conX;
}
public int getConnectionLocationY() {
return conY;
}
public String getConnectionTypeName() {
String returnType;
switch (type) {
case 0: returnType = "Audio"; break; // 24bit, min = -64, max = +64 - 96kHz.
case 1: returnType = "Control"; break; // 24bit, min = -64, max = +64 - 24kHz.
case 2: returnType = "Logic"; break; // 1bit, low = 0, high = +64.
case 3: returnType = "Slave"; break; // frequentie referentie tussen master en slave modulen
default: returnType = "Wrong type..."; break;
}
return returnType;
}
//--- drag
public void setEndDrag(boolean newEndDrag) {
endDrag = newEndDrag;
}
public void dragGestureRecognized(DragGestureEvent e) {
endDrag = false;
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
if (Cables.getDragCable() != null) module.getModules().getCables().unSelectChain(Cables.getDragCable(), module.getModuleData().getPoly());
// Het ligt aan de Action (shift/control) wat we gaan doen...
if (e.getDragAction() == 2 && !moving) { // new
moving = false;
e.startDrag(DragSource.DefaultCopyDrop, this, this);
Cables.newDragCable(module.getX() + conX, module.getY() + conY, Cable.SELECTCOLOR1, input?0:1);
module.getDesktopPane().add(Cables.getDragCable());
}
else { // dan is de kabel die in de mousePressed gevonden is de juiste.
moving = true;
e.startDrag(DragSource.DefaultMoveDrop, this, this);
Cables.setTempCable(Cables.getDragCable());
Cables.getDragCable().setSelectColor2();
}
module.getDesktopPane().setLayer(Cables.getDragCable(), JLayeredPane.DEFAULT_LAYER.intValue() + 10); // Ietskes hoger
// Debug.println("Connection dragGestureRecognized(source)");
}
public void dragEnter(DragSourceDragEvent e) {
// Debug.println("dragEnter(source)?");
}
public void dragOver(DragSourceDragEvent e) {
// Debug.println("dragOver(source)?");
}
public void dragExit(DragSourceEvent e) {
// Debug.println("Connection dragExit(source)");
}
public void dragDropEnd(DragSourceDropEvent e) {
if (e.getDropSuccess() == false) {
if (moving) {
if (e.getDropAction() == 2) { // rejected by wron connection
module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getTempCable(Cables.getDragCable()));
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else { // rejected by 'module' -> delete
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
}
else {
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
return;
}
int dropAction = e.getDropAction();
if (dropAction == DnDConstants.ACTION_MOVE) {
// wat te doen als het een move was... etc
}
this.open = false; // dit moet ook in de target gebeuren
}
public void dropActionChanged(DragSourceDragEvent e) {
//Bij het indrukken van Shift en Ctrl
//Debug.println("dropActionChanged(source)");
// DragSourceContext context = e.getDragSourceContext();
// context.setCursor(DragSource.DefaultCopyNoDrop);
}
// --- drop
private boolean isDragOk(DropTargetDragEvent e) {
DataFlavor chosen = null;
// do we need this anymore?
for (int i = 0; i < flavors.length; i++) {
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
/* if the src does not support any of the Connection flavors */
if (chosen == null) {
return false;
}
// the actions specified when the source
// created the DragGestureRecognizer
int sa = e.getSourceActions(); // Copy or Move
// we're saying that these actions are necessary
if ((sa & dragAction) == 0)
return false;
return true;
}
public void dragEnter(DropTargetDragEvent e) {
// Debug.println("dragEnter(target)");
}
public void dragOver(DropTargetDragEvent e) {
if(!isDragOk(e)) {
e.rejectDrag();
return;
}
int newDragX = e.getLocation().x - Connection.imageWidth;
int newDragY = e.getLocation().y - Connection.imageWidth;
if ((newDragX != oldDragX) || (newDragY != oldDragY)) {
if (Cables.getDragCable() != null) {
Cables.getDragCable().setNewDragWindowLayout((module.getX() + conX) + (newDragX), (module.getY() + conY) + (newDragY));
Cables.getDragCable().repaint();
oldDragX = newDragX;
oldDragY = newDragY;
}
}
e.acceptDrag(dragAction);
}
public void dragExit(DropTargetEvent e)
{
// Debug.println("dragExit(target)");
}
public void dropActionChanged(DropTargetDragEvent e) {
// Debug.println(new Integer(e.getDropAction()).toString());
}
public void drop(DropTargetDropEvent e) {
DataFlavor chosen = null;
if (e.isLocalTransfer() == false) {
// chosen = StringTransferable.plainTextFlavor;
}
else {
for (int i = 0; i < flavors.length; i++)
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
if (chosen == null) {
e.rejectDrop();
return;
}
// the actions that the source has specified with DragGestureRecognizer
int sa = e.getSourceActions();
if ((sa & dropAction) == 0 ) { // Als een Move op Copy niet mag...
e.rejectDrop();
return;
}
Object data = null;
try {
e.acceptDrop(dropAction);
data = e.getTransferable().getTransferData(chosen);
if (data == null)
throw new NullPointerException();
}
catch (Throwable t) {
t.printStackTrace();
e.dropComplete(false);
return;
}
if (data instanceof Connection) {
Connection con = (Connection) data;
int newColour = 6;
con.endDrag = true;
if (_this.equals(con)) {
e.dropComplete(false);
return;
}
int modIndex = module.getModuleData().getModIndex();
int conModIndex = con.getModule().getModuleData().getModIndex();
if (!moving) {
if (con.input)
Cables.getDragCable().setCableData(conModIndex, con.index, 0, modIndex, index, input?0:1, newColour);
else
Cables.getDragCable().setCableData(modIndex, index, this.input?0:1, conModIndex, con.index, con.input?0:1, newColour);
}
else {
if (Cables.getDragBeginCable())
// if (input) {
// Debug.println("a");
Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
// else {
// Debug.println("b");
// Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
else {
// if (con.input) {
// Debug.println("c");
Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
// else {
// Debug.println("d");
// Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
}
}
// Dragged to other end of cable
if ((Cables.getDragCable().getBeginModule() == Cables.getDragCable().getEndModule()) &&
(Cables.getDragCable().getBeginConnector() == Cables.getDragCable().getEndConnector()) &&
(Cables.getDragCable().getBeginConnectorType() == Cables.getDragCable().getEndConnectorType())) {
e.dropComplete(false);
return;
}
newColour = module.getModules().getCables().checkChain(Cables.getDragCable(), module.getModuleData().getPoly());
if (newColour < 0) // reject cable;
{
e.dropComplete(false);
return;
}
Cables.getDragCable().setColor(newColour);
if (!moving) module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getDragCable());
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else {
e.dropComplete(false);
return;
}
e.dropComplete(true);
}
//--- data
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor targetFlavor) {
// het dataobject (nu zichzelf) krijgt flavours mee van de source.
return true;
}
public synchronized Object getTransferData(DataFlavor flavor) {
// afhankelijk van welke flavour de target(?) graag wil, geven we het juiste terug
// if (flavor.equals(inConnectionFlavor))
// return this;
// if (flavor.equals(outConnectionFlavor))
// return this;
// throw new UnsupportedFlavorException(flavor);
// we vinden alles goed
return this;
}
public String toString() {
return (input?"input ":"output ") + index + " " + getConnectionTypeName() + "(" + type + ") " + name;
}
}
| wesen/nmedit | jMod/src/main/Connection.java | 5,185 | // Of er een kabel in zit... | line_comment | nl | // http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop-p1.html
package main;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Connection extends JLabel implements DragGestureListener, DragSourceListener, DropTargetListener, Transferable, Serializable {
private int index, type;
private String name;
private boolean input;
private int conX, conY;
private boolean open; // Of er<SUF>
private Module module;
private ImageIcon icon;
private Connection _this = null;
public final static int imageWidth = 13/2; // DE HELFT ERVAN!!!
Cables cables = null;
private static boolean moving = false;
//--- drag
private DragSource dragSource = null;
private int dragAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- drop
private DropTarget dropTarget = null;
private int dropAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- data
public static final DataFlavor inConnectionFlavor = new DataFlavor("jmod/inConnection", "jMod In Connection");
public static final DataFlavor outConnectionFlavor = new DataFlavor("jmod/outConnection", "jMod Out Connection");
private static final DataFlavor[] inFlavors = {inConnectionFlavor, outConnectionFlavor};
private static final DataFlavor[] outFlavors = {outConnectionFlavor, inConnectionFlavor};
private DataFlavor[] flavors = null;
private int oldDragX = -1, oldDragY = -1;
// endDrag zorgt ervoor dat de kabel die zojuist gedropt is, opnieuw getekend wordt met een curve.
// Volgens mij worden alle kabels opnieuw getekend na een drop... ach ja...
private boolean endDrag = true;
Connection(Module newModule, boolean bInput, int newIndex, String newName, int newType, int newX, int newY) {
_this = this;
index = newIndex;
type = newType;
input = bInput;
name = newName;
conX = newX;
conY = newY;
open = true;
module = newModule;
if (input){
if (type == 0)
icon = new ImageIcon("./grafix/_con_in_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_in_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_in_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_in.gif");
flavors = inFlavors;
}
else {
if (type == 0)
icon = new ImageIcon("./grafix/_con_out_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_out_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_out_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_out.gif");
flavors = outFlavors;
}
this.setIcon(icon);
this.setLocation(conX, conY);
this.setSize(icon.getIconWidth(), icon.getIconHeight());
this.setToolTipText(name);
module.add(this);
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this, dragAction, this);
dropTarget = new DropTarget(this, dropAction, this, true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moving = false;
// TODO ?Replace lgic to Cables
Cable cab = null;
int modIndex = module.getModuleData().getModIndex();
int conIndex = _this.getConnectionIndex();
int inpIndex = _this.input?0:1;
boolean poly = module.getModuleData().getPoly();
int loopSize = poly?module.getModules().getCables().getPolySize():module.getModules().getCables().getCommonSize();
if (loopSize > 0) {
for (int i=0; i < loopSize; i++) {
cab = module.getModules().getCables().getCable(poly, i);
if (((cab.getBeginModule() == modIndex) && (cab.getBeginConnector() == conIndex) && (cab.getBeginConnectorType() == inpIndex)) ||
((cab.getEndModule() == modIndex) && (cab.getEndConnector() == conIndex) && (cab.getEndConnectorType() == inpIndex))) {
Cables.setDragCable(cab);
Cables.getDragCable().setSelectColor1();
break;
}
}
}
if (e.isAltDown()) {
module.getModules().getCables().selectChain(cab, poly);
}
if (e.getClickCount() > 1 || e.isControlDown()) {
moving = true;
Cables.determBeginWindowDrag(module.getX() + conX, module.getY() + conY);
Cables.determBeginCableDrag(modIndex, conIndex, inpIndex);
Cables.getDragCable().setSelectColor2();
}
}
public void mouseReleased(MouseEvent e)
{
if (e.isAltDown()) {
Cable cab = Cables.getDragCable();
module.getModules().getCables().unSelectChain(cab, module.getModuleData().getPoly());
}
if (!e.isAltDown()) {
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
}
}
});
}
// Getters
public Module getModule() {
return module;
}
public String getConnectionName() {
return name;
}
public int getConnectionType() {
return type;
}
public int getConnectionIndex() {
return index;
}
public int getConnectionLocationX() {
return conX;
}
public int getConnectionLocationY() {
return conY;
}
public String getConnectionTypeName() {
String returnType;
switch (type) {
case 0: returnType = "Audio"; break; // 24bit, min = -64, max = +64 - 96kHz.
case 1: returnType = "Control"; break; // 24bit, min = -64, max = +64 - 24kHz.
case 2: returnType = "Logic"; break; // 1bit, low = 0, high = +64.
case 3: returnType = "Slave"; break; // frequentie referentie tussen master en slave modulen
default: returnType = "Wrong type..."; break;
}
return returnType;
}
//--- drag
public void setEndDrag(boolean newEndDrag) {
endDrag = newEndDrag;
}
public void dragGestureRecognized(DragGestureEvent e) {
endDrag = false;
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
if (Cables.getDragCable() != null) module.getModules().getCables().unSelectChain(Cables.getDragCable(), module.getModuleData().getPoly());
// Het ligt aan de Action (shift/control) wat we gaan doen...
if (e.getDragAction() == 2 && !moving) { // new
moving = false;
e.startDrag(DragSource.DefaultCopyDrop, this, this);
Cables.newDragCable(module.getX() + conX, module.getY() + conY, Cable.SELECTCOLOR1, input?0:1);
module.getDesktopPane().add(Cables.getDragCable());
}
else { // dan is de kabel die in de mousePressed gevonden is de juiste.
moving = true;
e.startDrag(DragSource.DefaultMoveDrop, this, this);
Cables.setTempCable(Cables.getDragCable());
Cables.getDragCable().setSelectColor2();
}
module.getDesktopPane().setLayer(Cables.getDragCable(), JLayeredPane.DEFAULT_LAYER.intValue() + 10); // Ietskes hoger
// Debug.println("Connection dragGestureRecognized(source)");
}
public void dragEnter(DragSourceDragEvent e) {
// Debug.println("dragEnter(source)?");
}
public void dragOver(DragSourceDragEvent e) {
// Debug.println("dragOver(source)?");
}
public void dragExit(DragSourceEvent e) {
// Debug.println("Connection dragExit(source)");
}
public void dragDropEnd(DragSourceDropEvent e) {
if (e.getDropSuccess() == false) {
if (moving) {
if (e.getDropAction() == 2) { // rejected by wron connection
module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getTempCable(Cables.getDragCable()));
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else { // rejected by 'module' -> delete
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
}
else {
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
return;
}
int dropAction = e.getDropAction();
if (dropAction == DnDConstants.ACTION_MOVE) {
// wat te doen als het een move was... etc
}
this.open = false; // dit moet ook in de target gebeuren
}
public void dropActionChanged(DragSourceDragEvent e) {
//Bij het indrukken van Shift en Ctrl
//Debug.println("dropActionChanged(source)");
// DragSourceContext context = e.getDragSourceContext();
// context.setCursor(DragSource.DefaultCopyNoDrop);
}
// --- drop
private boolean isDragOk(DropTargetDragEvent e) {
DataFlavor chosen = null;
// do we need this anymore?
for (int i = 0; i < flavors.length; i++) {
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
/* if the src does not support any of the Connection flavors */
if (chosen == null) {
return false;
}
// the actions specified when the source
// created the DragGestureRecognizer
int sa = e.getSourceActions(); // Copy or Move
// we're saying that these actions are necessary
if ((sa & dragAction) == 0)
return false;
return true;
}
public void dragEnter(DropTargetDragEvent e) {
// Debug.println("dragEnter(target)");
}
public void dragOver(DropTargetDragEvent e) {
if(!isDragOk(e)) {
e.rejectDrag();
return;
}
int newDragX = e.getLocation().x - Connection.imageWidth;
int newDragY = e.getLocation().y - Connection.imageWidth;
if ((newDragX != oldDragX) || (newDragY != oldDragY)) {
if (Cables.getDragCable() != null) {
Cables.getDragCable().setNewDragWindowLayout((module.getX() + conX) + (newDragX), (module.getY() + conY) + (newDragY));
Cables.getDragCable().repaint();
oldDragX = newDragX;
oldDragY = newDragY;
}
}
e.acceptDrag(dragAction);
}
public void dragExit(DropTargetEvent e)
{
// Debug.println("dragExit(target)");
}
public void dropActionChanged(DropTargetDragEvent e) {
// Debug.println(new Integer(e.getDropAction()).toString());
}
public void drop(DropTargetDropEvent e) {
DataFlavor chosen = null;
if (e.isLocalTransfer() == false) {
// chosen = StringTransferable.plainTextFlavor;
}
else {
for (int i = 0; i < flavors.length; i++)
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
if (chosen == null) {
e.rejectDrop();
return;
}
// the actions that the source has specified with DragGestureRecognizer
int sa = e.getSourceActions();
if ((sa & dropAction) == 0 ) { // Als een Move op Copy niet mag...
e.rejectDrop();
return;
}
Object data = null;
try {
e.acceptDrop(dropAction);
data = e.getTransferable().getTransferData(chosen);
if (data == null)
throw new NullPointerException();
}
catch (Throwable t) {
t.printStackTrace();
e.dropComplete(false);
return;
}
if (data instanceof Connection) {
Connection con = (Connection) data;
int newColour = 6;
con.endDrag = true;
if (_this.equals(con)) {
e.dropComplete(false);
return;
}
int modIndex = module.getModuleData().getModIndex();
int conModIndex = con.getModule().getModuleData().getModIndex();
if (!moving) {
if (con.input)
Cables.getDragCable().setCableData(conModIndex, con.index, 0, modIndex, index, input?0:1, newColour);
else
Cables.getDragCable().setCableData(modIndex, index, this.input?0:1, conModIndex, con.index, con.input?0:1, newColour);
}
else {
if (Cables.getDragBeginCable())
// if (input) {
// Debug.println("a");
Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
// else {
// Debug.println("b");
// Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
else {
// if (con.input) {
// Debug.println("c");
Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
// else {
// Debug.println("d");
// Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
}
}
// Dragged to other end of cable
if ((Cables.getDragCable().getBeginModule() == Cables.getDragCable().getEndModule()) &&
(Cables.getDragCable().getBeginConnector() == Cables.getDragCable().getEndConnector()) &&
(Cables.getDragCable().getBeginConnectorType() == Cables.getDragCable().getEndConnectorType())) {
e.dropComplete(false);
return;
}
newColour = module.getModules().getCables().checkChain(Cables.getDragCable(), module.getModuleData().getPoly());
if (newColour < 0) // reject cable;
{
e.dropComplete(false);
return;
}
Cables.getDragCable().setColor(newColour);
if (!moving) module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getDragCable());
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else {
e.dropComplete(false);
return;
}
e.dropComplete(true);
}
//--- data
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor targetFlavor) {
// het dataobject (nu zichzelf) krijgt flavours mee van de source.
return true;
}
public synchronized Object getTransferData(DataFlavor flavor) {
// afhankelijk van welke flavour de target(?) graag wil, geven we het juiste terug
// if (flavor.equals(inConnectionFlavor))
// return this;
// if (flavor.equals(outConnectionFlavor))
// return this;
// throw new UnsupportedFlavorException(flavor);
// we vinden alles goed
return this;
}
public String toString() {
return (input?"input ":"output ") + index + " " + getConnectionTypeName() + "(" + type + ") " + name;
}
}
|
131308_13 | package hotel.userinterface;
import hotel.model.Hotel;
import hotel.model.KamerType;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.time.LocalDate;
import javafx.stage.Stage;
public class BoekingenController {
@FXML private Label errorLabel;
@FXML private TextField naamTextField;
@FXML private TextField adresTextField;
@FXML private DatePicker aankomstDatePicker;
@FXML private DatePicker vertrekDatePicker;
@FXML private ComboBox<KamerType> kamertypeComboBox;
private HotelOverzichtController hotelOverzichtController;
private Stage stage; // Add a field to store the reference to the stage
// Setter method to set the stage
public void setStage(Stage stage) {
this.stage = stage;
}
private Hotel hotel = Hotel.getHotel();
public void setHotelOverzichtController(HotelOverzichtController hotelOverzichtController) {
this.hotelOverzichtController = hotelOverzichtController;
}
@FXML
private void initialize() {
// Initialize the kamertypeComboBox with available KamerTypes
ObservableList<KamerType> kamerTypes = FXCollections.observableArrayList(hotel.getKamerTypen());
kamertypeComboBox.setItems(kamerTypes);
System.out.println("BoekingenController initialized!");
}
@FXML
private void resetForm() {
// Reset all fields to their initial state
naamTextField.clear();
adresTextField.clear();
aankomstDatePicker.setValue(null);
vertrekDatePicker.setValue(null);
kamertypeComboBox.getSelectionModel().clearSelection();
if (errorLabel != null) {
errorLabel.setText("");
}
}
@FXML
private void handleBoekButtonAction() {
System.out.println("Boek button clicked!");
// Ensure that errorLabel is not null before invoking setText
if (errorLabel != null) {
errorLabel.setText(""); // Clear any previous error messages
}
try {
// Get the selected values from the form
String naam = naamTextField.getText();
String adres = adresTextField.getText();
LocalDate aankomstDatum = aankomstDatePicker.getValue();
LocalDate vertrekDatum = vertrekDatePicker.getValue();
KamerType selectedKamerType = kamertypeComboBox.getValue();
// Perform basic validation
if (naam.isEmpty() || adres.isEmpty() || aankomstDatum == null || vertrekDatum == null || selectedKamerType == null) {
throw new Exception("Vul alle velden in");
}
// Perform validation for enddate
if (aankomstDatum.isBefore(LocalDate.now())) {
throw new Exception("De aankomstdatum moet vandaag of later zijn");
}
// Perform validation for end date being later than the arrival date
if (aankomstDatum.isAfter(vertrekDatum)) {
throw new Exception("De vertrekdatum moet later zijn dan de aankomstdatum");
}
// Try to create a new booking
hotel.voegBoekingToe(aankomstDatum, vertrekDatum, naam, adres, selectedKamerType);
// Reset the form after a successful booking
resetForm();
// Call a method on HotelOverzichtController to update UI
if (hotelOverzichtController != null) {
hotelOverzichtController.updateBoekingen();
}
// Close the Boekingen screen
if (stage != null) {
stage.close();
}
} catch (Exception e) {
// Handle the exception, display an error message
if (errorLabel != null) {
errorLabel.setText("Fout bij het maken van de boeking: " + e.getMessage());
System.out.println(e.getMessage());
}
}
}
}
| wesselvandenijssel/Oop-les-7 | Practicum 10/src/hotel/userinterface/BoekingenController.java | 1,131 | // Close the Boekingen screen | line_comment | nl | package hotel.userinterface;
import hotel.model.Hotel;
import hotel.model.KamerType;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.time.LocalDate;
import javafx.stage.Stage;
public class BoekingenController {
@FXML private Label errorLabel;
@FXML private TextField naamTextField;
@FXML private TextField adresTextField;
@FXML private DatePicker aankomstDatePicker;
@FXML private DatePicker vertrekDatePicker;
@FXML private ComboBox<KamerType> kamertypeComboBox;
private HotelOverzichtController hotelOverzichtController;
private Stage stage; // Add a field to store the reference to the stage
// Setter method to set the stage
public void setStage(Stage stage) {
this.stage = stage;
}
private Hotel hotel = Hotel.getHotel();
public void setHotelOverzichtController(HotelOverzichtController hotelOverzichtController) {
this.hotelOverzichtController = hotelOverzichtController;
}
@FXML
private void initialize() {
// Initialize the kamertypeComboBox with available KamerTypes
ObservableList<KamerType> kamerTypes = FXCollections.observableArrayList(hotel.getKamerTypen());
kamertypeComboBox.setItems(kamerTypes);
System.out.println("BoekingenController initialized!");
}
@FXML
private void resetForm() {
// Reset all fields to their initial state
naamTextField.clear();
adresTextField.clear();
aankomstDatePicker.setValue(null);
vertrekDatePicker.setValue(null);
kamertypeComboBox.getSelectionModel().clearSelection();
if (errorLabel != null) {
errorLabel.setText("");
}
}
@FXML
private void handleBoekButtonAction() {
System.out.println("Boek button clicked!");
// Ensure that errorLabel is not null before invoking setText
if (errorLabel != null) {
errorLabel.setText(""); // Clear any previous error messages
}
try {
// Get the selected values from the form
String naam = naamTextField.getText();
String adres = adresTextField.getText();
LocalDate aankomstDatum = aankomstDatePicker.getValue();
LocalDate vertrekDatum = vertrekDatePicker.getValue();
KamerType selectedKamerType = kamertypeComboBox.getValue();
// Perform basic validation
if (naam.isEmpty() || adres.isEmpty() || aankomstDatum == null || vertrekDatum == null || selectedKamerType == null) {
throw new Exception("Vul alle velden in");
}
// Perform validation for enddate
if (aankomstDatum.isBefore(LocalDate.now())) {
throw new Exception("De aankomstdatum moet vandaag of later zijn");
}
// Perform validation for end date being later than the arrival date
if (aankomstDatum.isAfter(vertrekDatum)) {
throw new Exception("De vertrekdatum moet later zijn dan de aankomstdatum");
}
// Try to create a new booking
hotel.voegBoekingToe(aankomstDatum, vertrekDatum, naam, adres, selectedKamerType);
// Reset the form after a successful booking
resetForm();
// Call a method on HotelOverzichtController to update UI
if (hotelOverzichtController != null) {
hotelOverzichtController.updateBoekingen();
}
// Close the<SUF>
if (stage != null) {
stage.close();
}
} catch (Exception e) {
// Handle the exception, display an error message
if (errorLabel != null) {
errorLabel.setText("Fout bij het maken van de boeking: " + e.getMessage());
System.out.println(e.getMessage());
}
}
}
}
|
143222_27 | /*
* 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.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.WriteListener;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaType;
import org.apache.tomcat.util.res.StringManager;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten [[email protected]]
* @author Remy Maucherat
*/
public final class Response {
private static final StringManager sm =
StringManager.getManager(Constants.Package);
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
protected int status = 200;
/**
* Status message.
*/
protected String message = null;
/**
* Response headers.
*/
protected final MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* Notes.
*/
protected final Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
protected boolean commited = false;
/**
* Action hook.
*/
public ActionHook hook;
/**
* HTTP specific fields.
*/
protected String contentType = null;
protected String contentLanguage = null;
protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
protected long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
protected Exception errorException = null;
/**
* Has the charset been explicitly set.
*/
protected boolean charsetSet = false;
protected Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public ActionHook getHook() {
return hook;
}
public void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status
*/
public void setStatus( int status ) {
this.status = status;
}
/**
* Get the status message.
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
if (v && !this.commited) {
this.commitTime = System.currentTimeMillis();
}
this.commited = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during
* request processing.
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request
* processing.
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
// -------------------- Methods --------------------
public void reset() throws IllegalStateException {
if (commited) {
throw new IllegalStateException();
}
recycle();
// Reset the stream
action(ActionCode.RESET, this);
}
// -------------------- Headers --------------------
/**
* Warning: This method always returns <code>false</code> for Content-Type
* and Content-Length.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
public void addHeader(String name, String value, Charset charset) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
MessageBytes mb = headers.addValue(name);
if (charset != null) {
mb.setCharset(charset);
}
mb.setString(value);
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and
* the default encoding
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.getLanguage();
if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
String country = locale.getCountry();
StringBuilder value = new StringBuilder(contentLanguage);
if ((country != null) && (country.length() > 0)) {
value.append('-');
value.append(country);
}
contentLanguage = value.toString();
}
}
/**
* Return the content language.
*/
public String getContentLanguage() {
return contentLanguage;
}
/*
* Overrides the name of the character encoding used in the body
* of the response. This method must be called prior to writing output
* using getWriter().
*
* @param charset String containing the name of the character encoding.
*/
public void setCharacterEncoding(String charset) {
if (isCommitted())
return;
if (charset == null)
return;
characterEncoding = charset;
charsetSet=true;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = MediaType.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
charsetSet = true;
this.characterEncoding = charsetValue;
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& characterEncoding != null
&& charsetSet) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*/
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/)
throws IOException
{
outputBuffer.doWrite(chunk, this);
contentWritten+=chunk.getLength();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
charsetSet = false;
contentLength = -1;
status = 200;
message = null;
commited = false;
commitTime = -1;
errorException = null;
headers.clear();
// Servlet 3.1 non-blocking write listener
listener = null;
fireListener = false;
registeredForWrite = false;
// update counters
contentWritten=0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
/*
* State for non-blocking output is maintained here as it is the one point
* easily reachable from the CoyoteOutputStream and the Processor which both
* need access to state.
*/
protected volatile WriteListener listener;
private boolean fireListener = false;
private boolean registeredForWrite = false;
private final Object nonBlockingStateLock = new Object();
public WriteListener getWriteListener() {
return listener;
}
public void setWriteListener(WriteListener listener) {
if (listener == null) {
throw new NullPointerException(
sm.getString("response.nullWriteListener"));
}
if (getWriteListener() != null) {
throw new IllegalStateException(
sm.getString("response.writeListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
// for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
throw new IllegalStateException(
sm.getString("response.notAsync"));
}
this.listener = listener;
// The container is responsible for the first call to
// listener.onWritePossible(). If isReady() returns true, the container
// needs to call listener.onWritePossible() from a new thread. If
// isReady() returns false, the socket will be registered for write and
// the container will call listener.onWritePossible() once data can be
// written.
if (isReady()) {
action(ActionCode.DISPATCH_WRITE, null);
// Need to set the fireListener flag otherwise when the container
// tries to trigger onWritePossible, nothing will happen
synchronized (nonBlockingStateLock) {
fireListener = true;
}
}
}
public boolean isReady() {
if (listener == null) {
// TODO i18n
throw new IllegalStateException("not in non blocking mode.");
}
// Assume write is not possible
boolean ready = false;
synchronized (nonBlockingStateLock) {
if (registeredForWrite) {
fireListener = true;
return false;
}
ready = checkRegisterForWrite(false);
fireListener = !ready;
}
return ready;
}
public boolean checkRegisterForWrite(boolean internal) {
AtomicBoolean ready = new AtomicBoolean(false);
synchronized (nonBlockingStateLock) {
if (!registeredForWrite || internal) {
action(ActionCode.NB_WRITE_INTEREST, ready);
registeredForWrite = !ready.get();
}
}
return ready.get();
}
public void onWritePossible() throws IOException {
// Any buffered data left over from a previous non-blocking write is
// written in the Processor so if this point is reached the app is able
// to write data.
boolean fire = false;
synchronized (nonBlockingStateLock) {
registeredForWrite = false;
if (fireListener) {
fireListener = false;
fire = true;
}
}
if (fire) {
listener.onWritePossible();
}
}
}
| wgoulet/tomcat | java/org/apache/coyote/Response.java | 4,355 | // -------------------- Headers -------------------- | line_comment | nl | /*
* 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.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.WriteListener;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaType;
import org.apache.tomcat.util.res.StringManager;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten [[email protected]]
* @author Remy Maucherat
*/
public final class Response {
private static final StringManager sm =
StringManager.getManager(Constants.Package);
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
protected int status = 200;
/**
* Status message.
*/
protected String message = null;
/**
* Response headers.
*/
protected final MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* Notes.
*/
protected final Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
protected boolean commited = false;
/**
* Action hook.
*/
public ActionHook hook;
/**
* HTTP specific fields.
*/
protected String contentType = null;
protected String contentLanguage = null;
protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
protected long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
protected Exception errorException = null;
/**
* Has the charset been explicitly set.
*/
protected boolean charsetSet = false;
protected Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest( Request req ) {
this.req=req;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public ActionHook getHook() {
return hook;
}
public void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status
*/
public void setStatus( int status ) {
this.status = status;
}
/**
* Get the status message.
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return commited;
}
public void setCommitted(boolean v) {
if (v && !this.commited) {
this.commitTime = System.currentTimeMillis();
}
this.commited = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during
* request processing.
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request
* processing.
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return ( errorException != null );
}
// -------------------- Methods --------------------
public void reset() throws IllegalStateException {
if (commited) {
throw new IllegalStateException();
}
recycle();
// Reset the stream
action(ActionCode.RESET, this);
}
// -------------------- Headers<SUF>
/**
* Warning: This method always returns <code>false</code> for Content-Type
* and Content-Length.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
headers.setValue(name).setString( value);
}
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
public void addHeader(String name, String value, Charset charset) {
char cc=name.charAt(0);
if( cc=='C' || cc=='c' ) {
if( checkSpecialHeader(name, value) )
return;
}
MessageBytes mb = headers.addValue(name);
if (charset != null) {
mb.setCharset(charset);
}
mb.setString(value);
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader( String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if( name.equalsIgnoreCase( "Content-Type" ) ) {
setContentType( value );
return true;
}
if( name.equalsIgnoreCase( "Content-Length" ) ) {
try {
long cL=Long.parseLong( value );
setContentLength( cL );
return true;
} catch( NumberFormatException ex ) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
return false;
}
/** Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and
* the default encoding
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.getLanguage();
if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
String country = locale.getCountry();
StringBuilder value = new StringBuilder(contentLanguage);
if ((country != null) && (country.length() > 0)) {
value.append('-');
value.append(country);
}
contentLanguage = value.toString();
}
}
/**
* Return the content language.
*/
public String getContentLanguage() {
return contentLanguage;
}
/*
* Overrides the name of the character encoding used in the body
* of the response. This method must be called prior to writing output
* using getWriter().
*
* @param charset String containing the name of the character encoding.
*/
public void setCharacterEncoding(String charset) {
if (isCommitted())
return;
if (charset == null)
return;
characterEncoding = charset;
charsetSet=true;
}
public String getCharacterEncoding() {
return characterEncoding;
}
/**
* Sets the content type.
*
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = MediaType.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
charsetSet = true;
this.characterEncoding = charsetValue;
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null
&& characterEncoding != null
&& charsetSet) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*/
public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/)
throws IOException
{
outputBuffer.doWrite(chunk, this);
contentWritten+=chunk.getLength();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING;
charsetSet = false;
contentLength = -1;
status = 200;
message = null;
commited = false;
commitTime = -1;
errorException = null;
headers.clear();
// Servlet 3.1 non-blocking write listener
listener = null;
fireListener = false;
registeredForWrite = false;
// update counters
contentWritten=0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
/*
* State for non-blocking output is maintained here as it is the one point
* easily reachable from the CoyoteOutputStream and the Processor which both
* need access to state.
*/
protected volatile WriteListener listener;
private boolean fireListener = false;
private boolean registeredForWrite = false;
private final Object nonBlockingStateLock = new Object();
public WriteListener getWriteListener() {
return listener;
}
public void setWriteListener(WriteListener listener) {
if (listener == null) {
throw new NullPointerException(
sm.getString("response.nullWriteListener"));
}
if (getWriteListener() != null) {
throw new IllegalStateException(
sm.getString("response.writeListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
// for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
throw new IllegalStateException(
sm.getString("response.notAsync"));
}
this.listener = listener;
// The container is responsible for the first call to
// listener.onWritePossible(). If isReady() returns true, the container
// needs to call listener.onWritePossible() from a new thread. If
// isReady() returns false, the socket will be registered for write and
// the container will call listener.onWritePossible() once data can be
// written.
if (isReady()) {
action(ActionCode.DISPATCH_WRITE, null);
// Need to set the fireListener flag otherwise when the container
// tries to trigger onWritePossible, nothing will happen
synchronized (nonBlockingStateLock) {
fireListener = true;
}
}
}
public boolean isReady() {
if (listener == null) {
// TODO i18n
throw new IllegalStateException("not in non blocking mode.");
}
// Assume write is not possible
boolean ready = false;
synchronized (nonBlockingStateLock) {
if (registeredForWrite) {
fireListener = true;
return false;
}
ready = checkRegisterForWrite(false);
fireListener = !ready;
}
return ready;
}
public boolean checkRegisterForWrite(boolean internal) {
AtomicBoolean ready = new AtomicBoolean(false);
synchronized (nonBlockingStateLock) {
if (!registeredForWrite || internal) {
action(ActionCode.NB_WRITE_INTEREST, ready);
registeredForWrite = !ready.get();
}
}
return ready.get();
}
public void onWritePossible() throws IOException {
// Any buffered data left over from a previous non-blocking write is
// written in the Processor so if this point is reached the app is able
// to write data.
boolean fire = false;
synchronized (nonBlockingStateLock) {
registeredForWrite = false;
if (fireListener) {
fireListener = false;
fire = true;
}
}
if (fire) {
listener.onWritePossible();
}
}
}
|
19569_2 | /*
* 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 power.api.assignment;
import java.io.IOException;
import java.util.Random;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
*
* @author raymond
*/
public class SmallFacts {
private static Random generator = new Random();
public static String randomQuest() {
try {
int page = generator.nextInt(9) + 1;
Document doc = Jsoup.connect("https://www.quest.nl/weetjes/" + page).get();
Elements facts = doc.select(".list-container .list-item p");
int factnum = generator.nextInt(facts.size());
return facts.get(factnum).text();
} catch (IOException ex) {
return null;
}
}
private static String[] facts = new String[]{
"Per 1 april 2014 waren bijna 2,5 miljoen woningen voorzien van een energielabel. Circa 20% van de woningen heeft een groen label (A, A+en A++, B). De meerderheid van de woningen heeft energielabel C (30%) of D (25%).",
"Na de invoering van het Europees energie-etiketteringssysteem in 1996 zijn de marktaandelen van producten die voorzien zijn van energielabel A sterk gestegen, ten koste van de relatief energie-onzuinige apparaten (klasse C en hoger). Bij de meeste apparatuur had enkele jaren later het A-segment een dominante positie op de markt bereikt. Sinds 2001 zijn de aanvullende categorieën A+, A++ en A+++ geïntroduceerd. De aandelen hiervan zijn anno 2013 aanzienlijk. Bij koel- en vriesapparatuur maken deze categorieën samen al 95% van de verkopen uit. Hierin is categorie A+ met 70% het belangrijkst. Bij wasmachines is het aandeel A+ 25%, A++ 25% en A+++ 44%. Bij vaatwassers is het aandeel A+ 39%, A++ 24% en A+++ 4%. Uitzondering op dit verloop zijn de wasdrogers. Bij de wasdrogers werd het A-segment gevormd door de relatief dure warmtepompdrogers. De afgelopen jaren zijn deze relatief goedkoper geworden, (en de stroom steeds duurder) waardoor het aandeel A label en beter nu 29% bedraagt. Het aandeel hierin van A+ is 20%, en van A++ 4%.",
"Voor lichtbronnen geldt sinds 1998 eveneens een etiketteringsplicht. Uit bovenstaande figuur blijkt dat bij de huishoudens het aandeel van de onzuinige gloeilampen en halogeenlampen (C- t/m G-labels) nog steeds hoog is. De energiezuinige LED-, TL- en spaarlampen (A- en B-labels) maken samen 41% uit. Wel is binnen de onzuinige typen een verschuiving richting halogeen opgetreden, en binnen de zuinige typen een verschuiving richting spaarlampen en LED verlichting. Was het aandeel LED in 2009 nog verwaarloosbaar, in 2011 had een gemiddeld huishouden al 5 LED lampen in huis, op een totaal van 44 lampen.",
"Het huishoudelijk energieverbruik per inwoner is de laatste jaren stabiel. Het verbruik betreft vooral aardgas en elektriciteit. Het verbruik van aardgas per inwoner is sinds 1980 door energiebesparende maatregelen met bijna 30 procent gedaald.",
"Het huishoudelijk elektriciteitsverbruik per inwoner, omgerekend naar de hoeveelheid fossiele brandstoffen nodig voor de elektriciteitsopwekking, is in 2013 bijna vier keer zo hoog als in 1950. Vooral in de jaren zestig en zeventig van de vorige eeuw nam het verbruik flink toe. Het elektriciteitsverbruik in de jaren tachtig is stabiel, in de jaren negentig groeide het verbruik en sinds 2005 is het stabiel. In Nederland wordt vooral elektriciteit geproduceerd met behulp van de primaire brandstoffen aardgas en steenkool.",
"Het aardgasverbruik per inwoner (gecorrigeerd voor de gemiddelde jaartemperatuur) is tussen 1965 en 1975 zeer sterk gestegen. Vanaf begin jaren tachtig treedt een daling op door energiebesparende maatregelen, zoals isolatie en de installatie van HR-ketels. In 2013 is het aardgasverbruik per inwoner bijna 30 procent lager dan in 1980.",
"Het verbruik van hernieuwbare elektriciteit daalde in 2013 met 5 procent. Dit kwam doordat er minder biomassa werd meegestookt in elektriciteitscentrales. Het verbruik van windenergie nam juist toe door het bijplaatsen van nieuwe windmolens. Deze toename was echter niet genoeg om de daling van het meestoken te compenseren.",
"Het belang van hernieuwbare energie is in 2013 niet toegenomen. In 2013 maakte hernieuwbare energie 4,5 procent van het totale Nederlandse energieverbruik uit. Dat is evenveel als in 2012. Volgens Europese afspraken moet het Nederlandse aandeel hernieuwbare energie in 2020 naar 14 procent."
};
public static String random() {
int fact = generator.nextInt(facts.length);
return facts[fact];
}
}
| where-is-your-power/power-api | src/main/java/power/api/assignment/SmallFacts.java | 1,505 | //www.quest.nl/weetjes/" + page).get(); | line_comment | nl | /*
* 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 power.api.assignment;
import java.io.IOException;
import java.util.Random;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
*
* @author raymond
*/
public class SmallFacts {
private static Random generator = new Random();
public static String randomQuest() {
try {
int page = generator.nextInt(9) + 1;
Document doc = Jsoup.connect("https://www.quest.nl/weetjes/" +<SUF>
Elements facts = doc.select(".list-container .list-item p");
int factnum = generator.nextInt(facts.size());
return facts.get(factnum).text();
} catch (IOException ex) {
return null;
}
}
private static String[] facts = new String[]{
"Per 1 april 2014 waren bijna 2,5 miljoen woningen voorzien van een energielabel. Circa 20% van de woningen heeft een groen label (A, A+en A++, B). De meerderheid van de woningen heeft energielabel C (30%) of D (25%).",
"Na de invoering van het Europees energie-etiketteringssysteem in 1996 zijn de marktaandelen van producten die voorzien zijn van energielabel A sterk gestegen, ten koste van de relatief energie-onzuinige apparaten (klasse C en hoger). Bij de meeste apparatuur had enkele jaren later het A-segment een dominante positie op de markt bereikt. Sinds 2001 zijn de aanvullende categorieën A+, A++ en A+++ geïntroduceerd. De aandelen hiervan zijn anno 2013 aanzienlijk. Bij koel- en vriesapparatuur maken deze categorieën samen al 95% van de verkopen uit. Hierin is categorie A+ met 70% het belangrijkst. Bij wasmachines is het aandeel A+ 25%, A++ 25% en A+++ 44%. Bij vaatwassers is het aandeel A+ 39%, A++ 24% en A+++ 4%. Uitzondering op dit verloop zijn de wasdrogers. Bij de wasdrogers werd het A-segment gevormd door de relatief dure warmtepompdrogers. De afgelopen jaren zijn deze relatief goedkoper geworden, (en de stroom steeds duurder) waardoor het aandeel A label en beter nu 29% bedraagt. Het aandeel hierin van A+ is 20%, en van A++ 4%.",
"Voor lichtbronnen geldt sinds 1998 eveneens een etiketteringsplicht. Uit bovenstaande figuur blijkt dat bij de huishoudens het aandeel van de onzuinige gloeilampen en halogeenlampen (C- t/m G-labels) nog steeds hoog is. De energiezuinige LED-, TL- en spaarlampen (A- en B-labels) maken samen 41% uit. Wel is binnen de onzuinige typen een verschuiving richting halogeen opgetreden, en binnen de zuinige typen een verschuiving richting spaarlampen en LED verlichting. Was het aandeel LED in 2009 nog verwaarloosbaar, in 2011 had een gemiddeld huishouden al 5 LED lampen in huis, op een totaal van 44 lampen.",
"Het huishoudelijk energieverbruik per inwoner is de laatste jaren stabiel. Het verbruik betreft vooral aardgas en elektriciteit. Het verbruik van aardgas per inwoner is sinds 1980 door energiebesparende maatregelen met bijna 30 procent gedaald.",
"Het huishoudelijk elektriciteitsverbruik per inwoner, omgerekend naar de hoeveelheid fossiele brandstoffen nodig voor de elektriciteitsopwekking, is in 2013 bijna vier keer zo hoog als in 1950. Vooral in de jaren zestig en zeventig van de vorige eeuw nam het verbruik flink toe. Het elektriciteitsverbruik in de jaren tachtig is stabiel, in de jaren negentig groeide het verbruik en sinds 2005 is het stabiel. In Nederland wordt vooral elektriciteit geproduceerd met behulp van de primaire brandstoffen aardgas en steenkool.",
"Het aardgasverbruik per inwoner (gecorrigeerd voor de gemiddelde jaartemperatuur) is tussen 1965 en 1975 zeer sterk gestegen. Vanaf begin jaren tachtig treedt een daling op door energiebesparende maatregelen, zoals isolatie en de installatie van HR-ketels. In 2013 is het aardgasverbruik per inwoner bijna 30 procent lager dan in 1980.",
"Het verbruik van hernieuwbare elektriciteit daalde in 2013 met 5 procent. Dit kwam doordat er minder biomassa werd meegestookt in elektriciteitscentrales. Het verbruik van windenergie nam juist toe door het bijplaatsen van nieuwe windmolens. Deze toename was echter niet genoeg om de daling van het meestoken te compenseren.",
"Het belang van hernieuwbare energie is in 2013 niet toegenomen. In 2013 maakte hernieuwbare energie 4,5 procent van het totale Nederlandse energieverbruik uit. Dat is evenveel als in 2012. Volgens Europese afspraken moet het Nederlandse aandeel hernieuwbare energie in 2020 naar 14 procent."
};
public static String random() {
int fact = generator.nextInt(facts.length);
return facts[fact];
}
}
|
56464_3 | /**
*
*/
package jazmin.driver.mq;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* @author yama
*
*/
public abstract class TopicQueue {
//
protected String id;
protected String type;
protected LongAdder publishCount;
protected List<TopicSubscriber> topicSubscribers;
protected long maxTtl;
protected long redelieverInterval;
protected long accpetRejectExpiredTime=1000*60*10;
protected Map<Short,TopicChannel>topicChannels;
//
public TopicQueue(String id,String type){
this.id=id;
this.type=type;
topicSubscribers=new LinkedList<TopicSubscriber>();
publishCount=new LongAdder();
topicChannels=new HashMap<>();
maxTtl=1000*3600*24;//1 day
redelieverInterval=1000*5;//5 seconds redeliever
}
/**
*
*/
public List<TopicChannel>getChannels(){
return new LinkedList<TopicChannel>(topicChannels.values());
}
/**
*
* @return
*/
public long getRedelieverInterval() {
return redelieverInterval;
}
/**
*
* @param redelieverInterval
*/
public void setRedelieverInterval(long redelieverInterval) {
if(redelieverInterval<=0){
throw new IllegalArgumentException("redelieverInterval should >0");
}
this.redelieverInterval = redelieverInterval;
}
/**
*
* @return
*/
public long getMaxTtl() {
return maxTtl;
}
/**
*
* @param maxTtl
*/
public void setMaxTtl(long maxTtl) {
if(maxTtl<=0){
throw new IllegalArgumentException("maxTtl should >0");
}
this.maxTtl = maxTtl;
}
/**
*
* @return
*/
public String getId(){
return id;
}
/**
*
* @return
*/
public String getType() {
return type;
}
/**
*
*/
public void start(){
}
/**
*
*/
public void stop(){
}
//
public long getPublishedCount(){
return publishCount.longValue();
}
/**
*
* @param name
*/
public void subscribe(TopicSubscriber ts){
if(topicSubscribers.contains(ts)){
throw new IllegalArgumentException(ts.name+" already exists");
}
topicSubscribers.add(ts);
}
/**
*
* @param obj
*/
public void publish(Object obj){
if(obj==null){
throw new NullPointerException("publish message can not be null");
}
if(topicSubscribers.isEmpty()){
throw new IllegalArgumentException("no topic subscriber");
}
publishCount.increment();
}
//
public Message take(short subscriberId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException(
"can not find subscriber ["+subscriberId+"] on topic queue:"+id);
}
Message message= channel.take();
if(message!=null&&message!=MessageQueueDriver.takeNext){
message.topic=id;
channel.delieverCount.increment();
}
return message;
}
//
public void accept(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.accept(messageId);
}
//
public void reject(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.reject(messageId);
}
}
| whx0123/JazminServer | JazminServer/src/jazmin/driver/mq/TopicQueue.java | 1,159 | /**
*
* @param redelieverInterval
*/ | block_comment | nl | /**
*
*/
package jazmin.driver.mq;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* @author yama
*
*/
public abstract class TopicQueue {
//
protected String id;
protected String type;
protected LongAdder publishCount;
protected List<TopicSubscriber> topicSubscribers;
protected long maxTtl;
protected long redelieverInterval;
protected long accpetRejectExpiredTime=1000*60*10;
protected Map<Short,TopicChannel>topicChannels;
//
public TopicQueue(String id,String type){
this.id=id;
this.type=type;
topicSubscribers=new LinkedList<TopicSubscriber>();
publishCount=new LongAdder();
topicChannels=new HashMap<>();
maxTtl=1000*3600*24;//1 day
redelieverInterval=1000*5;//5 seconds redeliever
}
/**
*
*/
public List<TopicChannel>getChannels(){
return new LinkedList<TopicChannel>(topicChannels.values());
}
/**
*
* @return
*/
public long getRedelieverInterval() {
return redelieverInterval;
}
/**
*
* @param redelieverInterval
<SUF>*/
public void setRedelieverInterval(long redelieverInterval) {
if(redelieverInterval<=0){
throw new IllegalArgumentException("redelieverInterval should >0");
}
this.redelieverInterval = redelieverInterval;
}
/**
*
* @return
*/
public long getMaxTtl() {
return maxTtl;
}
/**
*
* @param maxTtl
*/
public void setMaxTtl(long maxTtl) {
if(maxTtl<=0){
throw new IllegalArgumentException("maxTtl should >0");
}
this.maxTtl = maxTtl;
}
/**
*
* @return
*/
public String getId(){
return id;
}
/**
*
* @return
*/
public String getType() {
return type;
}
/**
*
*/
public void start(){
}
/**
*
*/
public void stop(){
}
//
public long getPublishedCount(){
return publishCount.longValue();
}
/**
*
* @param name
*/
public void subscribe(TopicSubscriber ts){
if(topicSubscribers.contains(ts)){
throw new IllegalArgumentException(ts.name+" already exists");
}
topicSubscribers.add(ts);
}
/**
*
* @param obj
*/
public void publish(Object obj){
if(obj==null){
throw new NullPointerException("publish message can not be null");
}
if(topicSubscribers.isEmpty()){
throw new IllegalArgumentException("no topic subscriber");
}
publishCount.increment();
}
//
public Message take(short subscriberId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException(
"can not find subscriber ["+subscriberId+"] on topic queue:"+id);
}
Message message= channel.take();
if(message!=null&&message!=MessageQueueDriver.takeNext){
message.topic=id;
channel.delieverCount.increment();
}
return message;
}
//
public void accept(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.accept(messageId);
}
//
public void reject(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.reject(messageId);
}
}
|
10440_7 | import Game.Settings;
import Gui.Control;
import Gui.MainGUI;
import Gui.SelectSerial;
import Log.Logger;
import SerialPort.Port;
class PBControl {
public static void main(String[] arg) {
PBControl pb = new PBControl();
}
public PBControl() {
/* Voordat we beginnen halen we eerst het OS op ��n de beschikbare compoorten */
String os = System.getProperty("os.name").toLowerCase();
String serialPort = null;
/* Onder windows kiezen we standaard COM1 */
if (os.startsWith("windows")) {
serialPort = "COM1";
}
/* En onder Linux ttyS0 */
if (os.startsWith("linux")) {
serialPort = "/dev/ttyS0";
}
Logger.msg("Info", "Detected OS: " + os);
Logger.msg("Info", "Default serial port: " + serialPort);
/* Er zijn serie��le poorten aanwezig, dus we spawnen een GUI */
try {
/* Voor dat we verder gaan, laten we eerst de serie��le poort selecteren */
String[] availablePorts = Port.listPorts();
/* Als er maar ����n serie��le poort is, selecteren we die */
if (availablePorts[0] != null && availablePorts[1] == null) {
serialPort = availablePorts[0];
} else {
if (availablePorts != null) {
if (availablePorts.length > 0) {
SelectSerial selectSerial = new SelectSerial(availablePorts);
SelectSerial.run(selectSerial);
/* We wachten tot de thread klaar is om ons een selectie terug te geven */
while(!selectSerial.isReady()) {
try {
Thread.sleep(50);
} catch (Exception e) {}
}
serialPort = selectSerial.getSelection();
}
} else {
Logger.msg("Warn", "No serial ports available, continuing anyway.");
}
}
} catch (java.lang.UnsatisfiedLinkError e) {
Logger.msg("Error", "RXTX library could not be loaded, please install before running again.");
System.exit(1);
} catch (Exception e) {}
Logger.msg("Info", "Selected serial port: " + serialPort);
/* Settings laden en daarbij ook twee default waarden zetten */
Settings settings = new Settings();
Logger.msg("Info", "Initializing settings");
settings.setBaudRate(4800);
settings.setSender(0);
settings.setRoundTime(60);
settings.setRespawnTime(10);
settings.setCountdownTime(10);
settings.load();
Logger.msg("Info", "Game settings loaded. RoundTime: (" + settings.getRoundTime() + "), RespawnTime: (" + settings.getRespawnTime() + ")");
Control control = new Control(settings, new Port(serialPort, settings.getBaudRate(), settings.getSender()));
MainGUI maingui = new MainGUI();
maingui.run(maingui, control);
}
}
| wido/pbcontrol | src/PBControl.java | 835 | /* Settings laden en daarbij ook twee default waarden zetten */ | block_comment | nl | import Game.Settings;
import Gui.Control;
import Gui.MainGUI;
import Gui.SelectSerial;
import Log.Logger;
import SerialPort.Port;
class PBControl {
public static void main(String[] arg) {
PBControl pb = new PBControl();
}
public PBControl() {
/* Voordat we beginnen halen we eerst het OS op ��n de beschikbare compoorten */
String os = System.getProperty("os.name").toLowerCase();
String serialPort = null;
/* Onder windows kiezen we standaard COM1 */
if (os.startsWith("windows")) {
serialPort = "COM1";
}
/* En onder Linux ttyS0 */
if (os.startsWith("linux")) {
serialPort = "/dev/ttyS0";
}
Logger.msg("Info", "Detected OS: " + os);
Logger.msg("Info", "Default serial port: " + serialPort);
/* Er zijn serie��le poorten aanwezig, dus we spawnen een GUI */
try {
/* Voor dat we verder gaan, laten we eerst de serie��le poort selecteren */
String[] availablePorts = Port.listPorts();
/* Als er maar ����n serie��le poort is, selecteren we die */
if (availablePorts[0] != null && availablePorts[1] == null) {
serialPort = availablePorts[0];
} else {
if (availablePorts != null) {
if (availablePorts.length > 0) {
SelectSerial selectSerial = new SelectSerial(availablePorts);
SelectSerial.run(selectSerial);
/* We wachten tot de thread klaar is om ons een selectie terug te geven */
while(!selectSerial.isReady()) {
try {
Thread.sleep(50);
} catch (Exception e) {}
}
serialPort = selectSerial.getSelection();
}
} else {
Logger.msg("Warn", "No serial ports available, continuing anyway.");
}
}
} catch (java.lang.UnsatisfiedLinkError e) {
Logger.msg("Error", "RXTX library could not be loaded, please install before running again.");
System.exit(1);
} catch (Exception e) {}
Logger.msg("Info", "Selected serial port: " + serialPort);
/* Settings laden en<SUF>*/
Settings settings = new Settings();
Logger.msg("Info", "Initializing settings");
settings.setBaudRate(4800);
settings.setSender(0);
settings.setRoundTime(60);
settings.setRespawnTime(10);
settings.setCountdownTime(10);
settings.load();
Logger.msg("Info", "Game settings loaded. RoundTime: (" + settings.getRoundTime() + "), RespawnTime: (" + settings.getRespawnTime() + ")");
Control control = new Control(settings, new Port(serialPort, settings.getBaudRate(), settings.getSender()));
MainGUI maingui = new MainGUI();
maingui.run(maingui, control);
}
}
|
210751_12 | import java.util.ArrayList;
/*
* Nev: INVERTER
* Tipus: Class
* Interfacek: iComponent
* Szulok DigitalObject-->Gate
*
*********** Leiras **********
* Logikai invertert megvalosito objektum. Egyetlen egy bemenettel rendelkezik,
* es kimenetere ennek inverzet adja, ha annak van ertelme.
* Igazsagtablaja a kovetkezo:
*
* bemenet kimenet
* A NOT A
* 0 1
* 1 0
* X X
* Jelentesek: 0: logikai HAMIS ertek | 1: logikai IGAZ ertek | X: don't care
*/
public class INVERTER extends Gate{
/* ATTRIBUTUMOK */
private static int INVERTERCounts;
/* KONSTRUKTOR */
public INVERTER(Wire wirein1){
wireIn = new ArrayList<Wire>();
wireOut = new ArrayList<Wire>();
ID = "INVERTER" + INVERTERCounts++;
PreviousValue = -1;
wireIn.add(wirein1);
}
/* METODUSOK */
public int Count(){
// Leiras: Kiszamolja egy DigitalObject erteket
int Result=0;
_TEST stack = new _TEST();
stack.PrintHeader(ID,"",Result +":int");
/* Lekerdezzuk a bemenetek ertekeit */
wireIn.get(0).GetValue();
// Eredmeny kiszamitasa
//if(wireIn.get(0).GetValue() ==0)Result =1;
//if(wireIn.get(0).GetValue() ==1)Result =0;
//if(wireIn.get(0).GetValue() ==-1)Result =-1
/* Az oSSZES kimenetre kiadjuk a kiszamitott eredmenyt. Skeletonnal csak egyre */
/*for(Wire OutPut:wireOut){
OutPut.SetValue(Result);
}
*/
Wire wire_out = new Wire();
wire_out.SetValue(0);
stack.PrintTail(ID,"",Result +":int");
return Result;
};
public boolean Step(){
/* Leiras: Feladata az adott elem ertekenek kiszamitasa,
* ill. annak eldontese, hogy a DigitalObject stabil-e
*/
boolean Result = true; // A vegso eredmeny: Stabil-e az aramkor
_TEST stack = new _TEST(); /* TEST */
stack.PrintHeader(ID,"","true:boolean"); /* TEST */
PreviousValue = Count(); // Megnezzuk az elso futas erredmenyet
if(Feedbacks != null && !Feedbacks.isEmpty()){// Ha nem ures a Feedback tomb
int NewValue ; // Lokalis valtozo
for(DigitalObject obj:Feedbacks){ // Feedback ossezs elemen vegig
obj.Count();
}
NewValue = Count(); // Megnezzuk ujol az eredmenyt
Result = (PreviousValue==NewValue); // Elter-e a ketto?( Prev es a mostani)
for(DigitalObject obj:Feedbacks){
obj.Count();
}
NewValue = Count();
Result = (PreviousValue==NewValue);
for(DigitalObject obj:Feedbacks){
obj.Count();
}
NewValue = Count();
Result = (PreviousValue==NewValue);
}
stack.PrintTail(ID,"",Result + ":boolean"); /* TEST */
return Result;
};
} | widteam/project | 01_skeleton/src/INVERTER.java | 1,053 | // Feedback ossezs elemen vegig | line_comment | nl | import java.util.ArrayList;
/*
* Nev: INVERTER
* Tipus: Class
* Interfacek: iComponent
* Szulok DigitalObject-->Gate
*
*********** Leiras **********
* Logikai invertert megvalosito objektum. Egyetlen egy bemenettel rendelkezik,
* es kimenetere ennek inverzet adja, ha annak van ertelme.
* Igazsagtablaja a kovetkezo:
*
* bemenet kimenet
* A NOT A
* 0 1
* 1 0
* X X
* Jelentesek: 0: logikai HAMIS ertek | 1: logikai IGAZ ertek | X: don't care
*/
public class INVERTER extends Gate{
/* ATTRIBUTUMOK */
private static int INVERTERCounts;
/* KONSTRUKTOR */
public INVERTER(Wire wirein1){
wireIn = new ArrayList<Wire>();
wireOut = new ArrayList<Wire>();
ID = "INVERTER" + INVERTERCounts++;
PreviousValue = -1;
wireIn.add(wirein1);
}
/* METODUSOK */
public int Count(){
// Leiras: Kiszamolja egy DigitalObject erteket
int Result=0;
_TEST stack = new _TEST();
stack.PrintHeader(ID,"",Result +":int");
/* Lekerdezzuk a bemenetek ertekeit */
wireIn.get(0).GetValue();
// Eredmeny kiszamitasa
//if(wireIn.get(0).GetValue() ==0)Result =1;
//if(wireIn.get(0).GetValue() ==1)Result =0;
//if(wireIn.get(0).GetValue() ==-1)Result =-1
/* Az oSSZES kimenetre kiadjuk a kiszamitott eredmenyt. Skeletonnal csak egyre */
/*for(Wire OutPut:wireOut){
OutPut.SetValue(Result);
}
*/
Wire wire_out = new Wire();
wire_out.SetValue(0);
stack.PrintTail(ID,"",Result +":int");
return Result;
};
public boolean Step(){
/* Leiras: Feladata az adott elem ertekenek kiszamitasa,
* ill. annak eldontese, hogy a DigitalObject stabil-e
*/
boolean Result = true; // A vegso eredmeny: Stabil-e az aramkor
_TEST stack = new _TEST(); /* TEST */
stack.PrintHeader(ID,"","true:boolean"); /* TEST */
PreviousValue = Count(); // Megnezzuk az elso futas erredmenyet
if(Feedbacks != null && !Feedbacks.isEmpty()){// Ha nem ures a Feedback tomb
int NewValue ; // Lokalis valtozo
for(DigitalObject obj:Feedbacks){ // Feedback ossezs<SUF>
obj.Count();
}
NewValue = Count(); // Megnezzuk ujol az eredmenyt
Result = (PreviousValue==NewValue); // Elter-e a ketto?( Prev es a mostani)
for(DigitalObject obj:Feedbacks){
obj.Count();
}
NewValue = Count();
Result = (PreviousValue==NewValue);
for(DigitalObject obj:Feedbacks){
obj.Count();
}
NewValue = Count();
Result = (PreviousValue==NewValue);
}
stack.PrintTail(ID,"",Result + ":boolean"); /* TEST */
return Result;
};
} |
69092_4 | import data.AdresDAOHibernate;
import data.OVChipkaartDAOHibernate;
import data.ProductDAOHibernate;
import data.ReizigerDAOHibernate;
import data.interfaces.AdresDAO;
import data.interfaces.OVChipkaartDAO;
import data.interfaces.ProductDAO;
import data.interfaces.ReizigerDAO;
import domain.Adres;
import domain.OVChipkaart;
import domain.Product;
import domain.Reiziger;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.Metamodel;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
//testFetchAll();
testDAO();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
private static void testDAO() {
Session session = getSession();
Transaction transaction = session.getTransaction();
try {
// make DAO
OVChipkaartDAO ovChipkaartDAO = new OVChipkaartDAOHibernate(session);
AdresDAO adresDAO = new AdresDAOHibernate(session);
ReizigerDAO reizigerDAO = new ReizigerDAOHibernate(session);
ProductDAO productDAO = new ProductDAOHibernate(session);
// test DAO
testReizigerDAO(reizigerDAO);
testAdresDAO(adresDAO, reizigerDAO);
testOVChipDAO(ovChipkaartDAO, reizigerDAO);
testProductDAO(productDAO, reizigerDAO);
}
catch (Exception e){
e.printStackTrace();
System.out.println("ROLLBACK!!!");
transaction.rollback();
}
finally {
session.close();
}
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testReizigerDAO----------");
Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"));
List<Reiziger> reizigers= rdao.findAll();
System.out.println("findAll gives:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println("\nfindByGbdatum gives:");
for (Reiziger r : rdao.findByGbdatum("2002-12-03")) {
System.out.println(r);
}
// test save
System.out.println("\nsave before: " + reizigers.size());
rdao.save(reiziger);
reizigers = rdao.findAll();
System.out.println("after: " + reizigers.size());
System.out.println("\nupdate before: " + rdao.findById(100));
reiziger.setVoorletters("jag");
rdao.update(reiziger);
System.out.println("update after: " + rdao.findById(100));
// test delete
System.out.println("\ndelete before: " + reizigers.size());
rdao.delete(reiziger);
reizigers = rdao.findAll();
System.out.println("after: " + reizigers.size());
}
private static void testAdresDAO(AdresDAO adao, ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testAdresDAO----------");
Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht");
Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"), adres);
adres.setReiziger(reiziger);
List<Adres> adresList = adao.findAll();
System.out.println("\nfindAll gives:");
for (Adres a : adresList) {
System.out.println(a);
}
// test save
System.out.println("\nsave before: " + adresList.size());
rdao.save(reiziger);
adresList = adao.findAll();
System.out.println("after: " + adresList.size());
System.out.println("\nfindById gives: " + adao.findById(reiziger.getId()));
System.out.println("\nfindByReiziger gives: " + adao.findByReiziger(reiziger));
// test update
System.out.println("\nupdate before: " + rdao.findById(100));
adres.setHuisnummer("3B");
rdao.update(reiziger);
System.out.println("update after: " + rdao.findById(100));
// test delete
System.out.println("\ndelete before: " + adresList.size());
rdao.delete(reiziger);
adresList = adao.findAll();
System.out.println("delete after: " + adresList.size());
}
private static void testOVChipDAO(OVChipkaartDAO odao, ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testOVChipkaartDAO----------");
OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100);
OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100);
Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht");
Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres);
adres.setReiziger(reiziger);
ovChipkaart.setReiziger(reiziger);
reiziger.addOVChipkaart(ovChipkaart);
List<OVChipkaart> kaartList = odao.findAll();
System.out.println("\nfindAll gives:");
for (OVChipkaart o : kaartList) {
System.out.println(o);
}
// test save
System.out.println("\nsave before: " + kaartList.size());
rdao.save(reiziger);
kaartList = odao.findAll();
System.out.println("after: " + kaartList.size());
System.out.println("\nfindById gives: " + odao.findById(reiziger.getId()));
System.out.println("\nfindByReiziger gives: " + odao.findByReiziger(reiziger));
// test update
System.out.println("\nupdate before: " + rdao.findById(100));
ovChipkaart.setSaldo(69);
reiziger.addOVChipkaart(ovChipkaart2);
ovChipkaart2.setReiziger(reiziger);
rdao.update(reiziger);
System.out.println("update after: " + rdao.findById(100));
// test delete
System.out.println("\ndelete before: " + kaartList.size());
rdao.delete(reiziger);
kaartList = odao.findAll();
System.out.println("delete after: " + kaartList.size());
}
private static void testProductDAO(ProductDAO pdao, ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testProductDAO----------");
OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100);
OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100);
Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht");
Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres);
Product product = new Product(100,"test","test",100);
adres.setReiziger(reiziger);
ovChipkaart.setReiziger(reiziger);
ovChipkaart2.setReiziger(reiziger);
product.addOvChip(ovChipkaart);
rdao.save(reiziger);
List<Product> productList = pdao.findAll();
System.out.println("\nfindAll gives:");
for (Product p : productList) {
System.out.println(p);
}
// test save
System.out.println("\nsave before: " + productList.size());
pdao.save(product);
productList = pdao.findAll();
System.out.println("after: " + productList.size());
System.out.println("\nfindById gives: " + pdao.findById(product.getProductNummer()));
System.out.println("\nfindByOVChipkaart gives: " + pdao.findByOvChipkaart(ovChipkaart));
// test update
System.out.println("\nupdate before: " + pdao.findById(product.getProductNummer()));
product.addOvChip(ovChipkaart2);
product.setBeschrijving("tset");
pdao.update(product);
System.out.println("update after: " + pdao.findById(product.getProductNummer()));
// test delete
System.out.println("\ndelete before: " + productList.size());
pdao.delete(product);
productList = pdao.findAll();
System.out.println("delete after: " + productList.size());
rdao.delete(reiziger);
}
} | wiemanboy/DataPersistency-Hibernate | src/main/java/Main.java | 3,208 | /**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/ | block_comment | nl | import data.AdresDAOHibernate;
import data.OVChipkaartDAOHibernate;
import data.ProductDAOHibernate;
import data.ReizigerDAOHibernate;
import data.interfaces.AdresDAO;
import data.interfaces.OVChipkaartDAO;
import data.interfaces.ProductDAO;
import data.interfaces.ReizigerDAO;
import domain.Adres;
import domain.OVChipkaart;
import domain.Product;
import domain.Reiziger;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.Metamodel;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
//testFetchAll();
testDAO();
}
/**
* P6. Haal alle<SUF>*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
private static void testDAO() {
Session session = getSession();
Transaction transaction = session.getTransaction();
try {
// make DAO
OVChipkaartDAO ovChipkaartDAO = new OVChipkaartDAOHibernate(session);
AdresDAO adresDAO = new AdresDAOHibernate(session);
ReizigerDAO reizigerDAO = new ReizigerDAOHibernate(session);
ProductDAO productDAO = new ProductDAOHibernate(session);
// test DAO
testReizigerDAO(reizigerDAO);
testAdresDAO(adresDAO, reizigerDAO);
testOVChipDAO(ovChipkaartDAO, reizigerDAO);
testProductDAO(productDAO, reizigerDAO);
}
catch (Exception e){
e.printStackTrace();
System.out.println("ROLLBACK!!!");
transaction.rollback();
}
finally {
session.close();
}
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testReizigerDAO----------");
Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"));
List<Reiziger> reizigers= rdao.findAll();
System.out.println("findAll gives:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println("\nfindByGbdatum gives:");
for (Reiziger r : rdao.findByGbdatum("2002-12-03")) {
System.out.println(r);
}
// test save
System.out.println("\nsave before: " + reizigers.size());
rdao.save(reiziger);
reizigers = rdao.findAll();
System.out.println("after: " + reizigers.size());
System.out.println("\nupdate before: " + rdao.findById(100));
reiziger.setVoorletters("jag");
rdao.update(reiziger);
System.out.println("update after: " + rdao.findById(100));
// test delete
System.out.println("\ndelete before: " + reizigers.size());
rdao.delete(reiziger);
reizigers = rdao.findAll();
System.out.println("after: " + reizigers.size());
}
private static void testAdresDAO(AdresDAO adao, ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testAdresDAO----------");
Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht");
Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"), adres);
adres.setReiziger(reiziger);
List<Adres> adresList = adao.findAll();
System.out.println("\nfindAll gives:");
for (Adres a : adresList) {
System.out.println(a);
}
// test save
System.out.println("\nsave before: " + adresList.size());
rdao.save(reiziger);
adresList = adao.findAll();
System.out.println("after: " + adresList.size());
System.out.println("\nfindById gives: " + adao.findById(reiziger.getId()));
System.out.println("\nfindByReiziger gives: " + adao.findByReiziger(reiziger));
// test update
System.out.println("\nupdate before: " + rdao.findById(100));
adres.setHuisnummer("3B");
rdao.update(reiziger);
System.out.println("update after: " + rdao.findById(100));
// test delete
System.out.println("\ndelete before: " + adresList.size());
rdao.delete(reiziger);
adresList = adao.findAll();
System.out.println("delete after: " + adresList.size());
}
private static void testOVChipDAO(OVChipkaartDAO odao, ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testOVChipkaartDAO----------");
OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100);
OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100);
Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht");
Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres);
adres.setReiziger(reiziger);
ovChipkaart.setReiziger(reiziger);
reiziger.addOVChipkaart(ovChipkaart);
List<OVChipkaart> kaartList = odao.findAll();
System.out.println("\nfindAll gives:");
for (OVChipkaart o : kaartList) {
System.out.println(o);
}
// test save
System.out.println("\nsave before: " + kaartList.size());
rdao.save(reiziger);
kaartList = odao.findAll();
System.out.println("after: " + kaartList.size());
System.out.println("\nfindById gives: " + odao.findById(reiziger.getId()));
System.out.println("\nfindByReiziger gives: " + odao.findByReiziger(reiziger));
// test update
System.out.println("\nupdate before: " + rdao.findById(100));
ovChipkaart.setSaldo(69);
reiziger.addOVChipkaart(ovChipkaart2);
ovChipkaart2.setReiziger(reiziger);
rdao.update(reiziger);
System.out.println("update after: " + rdao.findById(100));
// test delete
System.out.println("\ndelete before: " + kaartList.size());
rdao.delete(reiziger);
kaartList = odao.findAll();
System.out.println("delete after: " + kaartList.size());
}
private static void testProductDAO(ProductDAO pdao, ReizigerDAO rdao) throws SQLException {
System.out.println("\n----------testProductDAO----------");
OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100);
OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100);
Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht");
Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres);
Product product = new Product(100,"test","test",100);
adres.setReiziger(reiziger);
ovChipkaart.setReiziger(reiziger);
ovChipkaart2.setReiziger(reiziger);
product.addOvChip(ovChipkaart);
rdao.save(reiziger);
List<Product> productList = pdao.findAll();
System.out.println("\nfindAll gives:");
for (Product p : productList) {
System.out.println(p);
}
// test save
System.out.println("\nsave before: " + productList.size());
pdao.save(product);
productList = pdao.findAll();
System.out.println("after: " + productList.size());
System.out.println("\nfindById gives: " + pdao.findById(product.getProductNummer()));
System.out.println("\nfindByOVChipkaart gives: " + pdao.findByOvChipkaart(ovChipkaart));
// test update
System.out.println("\nupdate before: " + pdao.findById(product.getProductNummer()));
product.addOvChip(ovChipkaart2);
product.setBeschrijving("tset");
pdao.update(product);
System.out.println("update after: " + pdao.findById(product.getProductNummer()));
// test delete
System.out.println("\ndelete before: " + productList.size());
pdao.delete(product);
productList = pdao.findAll();
System.out.println("delete after: " + productList.size());
rdao.delete(reiziger);
}
} |
54537_1 | package model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import security.PasswordHashing;
import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
public class Werknemer implements Serializable, Principal {
private String naam;
private double uurloon;
private String role;
private StringBuilder hash;
private byte[] salt;
private static ArrayList<Werknemer> allWerknemers = new ArrayList<>();
public Werknemer(String naam, double uurloon, String role){
this.naam = naam;
this.role = role;
if (uurloon < 0) {
this.uurloon = 0;
}
else {
this.uurloon = uurloon;
}
// Auto generate password: 1234
salt = PasswordHashing.generateSalt();
hash = PasswordHashing.hashPassword("1234", salt);
// add de aangemaakte werknemer aan allewerknemers
if (!allWerknemers.contains(this)) {
allWerknemers.add(this);
Klus.getKlusById(1).addWerknemer(this);
}
}
public boolean checkPassword(String password){
return PasswordHashing.checkPassword(hash, salt, password);
}
public void generateNewPassword(String password){
salt = PasswordHashing.generateSalt();
hash = PasswordHashing.hashPassword(password, salt);
}
public void changeUurloon(double uurloon){
this.uurloon = uurloon;
}
public void changeRole(String role){
this.role = role;
}
public double getUurloon(){
return uurloon;
}
public String getNaam(){
return naam;
}
public String getRole(){
return role;
}
public boolean equals(Object andereObject) {
boolean equal = false;
if (andereObject instanceof Werknemer) {
Werknemer werknemer2 = (Werknemer) andereObject;
if (this.naam.equals(werknemer2.naam) &&
this.uurloon == werknemer2.uurloon &&
this.role.equals(werknemer2.role)) {
equal = true;
}
}
return equal;
}
@Override
@JsonIgnore
public String getName() {
return null;
}
public static Werknemer getWerknemerByNaam(String naam) {
for (Werknemer w : getAllWerknemers()) {
if (w.getNaam().equals(naam)) {
return w;
}
}
return null;
}
public static ArrayList<Werknemer> getAllWerknemers(){
return allWerknemers;
}
public static void addWerknemers(Werknemer werknemer){
allWerknemers.add(werknemer);
}
public static void removeWerknemer(Werknemer werknemer){
allWerknemers.remove(werknemer);
}
}
| wiemanboy/IPASS-WerknemerSysteem | src/main/java/model/Werknemer.java | 838 | // add de aangemaakte werknemer aan allewerknemers | line_comment | nl | package model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import security.PasswordHashing;
import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
public class Werknemer implements Serializable, Principal {
private String naam;
private double uurloon;
private String role;
private StringBuilder hash;
private byte[] salt;
private static ArrayList<Werknemer> allWerknemers = new ArrayList<>();
public Werknemer(String naam, double uurloon, String role){
this.naam = naam;
this.role = role;
if (uurloon < 0) {
this.uurloon = 0;
}
else {
this.uurloon = uurloon;
}
// Auto generate password: 1234
salt = PasswordHashing.generateSalt();
hash = PasswordHashing.hashPassword("1234", salt);
// add de<SUF>
if (!allWerknemers.contains(this)) {
allWerknemers.add(this);
Klus.getKlusById(1).addWerknemer(this);
}
}
public boolean checkPassword(String password){
return PasswordHashing.checkPassword(hash, salt, password);
}
public void generateNewPassword(String password){
salt = PasswordHashing.generateSalt();
hash = PasswordHashing.hashPassword(password, salt);
}
public void changeUurloon(double uurloon){
this.uurloon = uurloon;
}
public void changeRole(String role){
this.role = role;
}
public double getUurloon(){
return uurloon;
}
public String getNaam(){
return naam;
}
public String getRole(){
return role;
}
public boolean equals(Object andereObject) {
boolean equal = false;
if (andereObject instanceof Werknemer) {
Werknemer werknemer2 = (Werknemer) andereObject;
if (this.naam.equals(werknemer2.naam) &&
this.uurloon == werknemer2.uurloon &&
this.role.equals(werknemer2.role)) {
equal = true;
}
}
return equal;
}
@Override
@JsonIgnore
public String getName() {
return null;
}
public static Werknemer getWerknemerByNaam(String naam) {
for (Werknemer w : getAllWerknemers()) {
if (w.getNaam().equals(naam)) {
return w;
}
}
return null;
}
public static ArrayList<Werknemer> getAllWerknemers(){
return allWerknemers;
}
public static void addWerknemers(Werknemer werknemer){
allWerknemers.add(werknemer);
}
public static void removeWerknemer(Werknemer werknemer){
allWerknemers.remove(werknemer);
}
}
|