hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
6bc970e784c3ac71570375e1ef5d8f3a45fb001d | 1,842 | /*******************************************************************************
* Copyright 2019 T-Mobile, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
/**
*
*/
package com.tmobile.kardio.bean;
/**
*
*
*/
public class ApiStatus extends KardioStatus {
private long totalContainers;
private long totalApis;
private int deltaValue;
private long totalPods;
/**
* @return the totalPods
*/
public long getTotalPods() {
return totalPods;
}
/**
* @param totalPods the totalPods to set
*/
public void setTotalPods(long totalPods) {
this.totalPods = totalPods;
}
/**
* @return the totalApis
*/
public long getTotalApis() {
return totalApis;
}
/**
* @param totalApis the totalApis to set
*/
public void setTotalApis(long totalApis) {
this.totalApis = totalApis;
}
/**
* @return the deltaValue
*/
public int getDeltaValue() {
return deltaValue;
}
/**
* @param deltaValue the deltaValue to set
*/
public void setDeltaValue(int deltaValue) {
this.deltaValue = deltaValue;
}
public long getTotalContainers() {
return totalContainers;
}
public void setTotalContainers(long totalContainers) {
this.totalContainers = totalContainers;
}
}
| 24.236842 | 80 | 0.645494 |
593e6b64499e77d22b96d4541857c59343b8f24f | 382 | package codewars.kyu7;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @name Scoring Tests
* @rank 7
* @id 55d2aee99f30dbbf8b000001
* @url https://www.codewars.com/kata/55d2aee99f30dbbf8b000001
*/
public class ScoringTestsTest {
@Test
public void testScore() {
assertEquals(12, ScoringTests.sol(new int[] {0,0,0,1,1,2}, 5, 0, 3));
}
}
| 20.105263 | 77 | 0.664921 |
f065b618d928a235be4c1445035260d0040c0a1f | 572 | package ca.ulaval.glo2003.transactions.rest;
import ca.ulaval.glo2003.interfaces.domain.AbstractMapper;
import ca.ulaval.glo2003.transactions.rest.serializers.TransactionDeserializingModule;
import ca.ulaval.glo2003.transactions.rest.serializers.TransactionSerializingModule;
import javax.inject.Inject;
public class TransactionMapper extends AbstractMapper {
@Inject
public TransactionMapper(
TransactionSerializingModule serializingModule,
TransactionDeserializingModule deserializingModule) {
super(serializingModule, deserializingModule);
}
}
| 33.647059 | 86 | 0.837413 |
6d3b82d1beae645b064c008ae4f0e2166244ae50 | 728 | package com.liuhuachao.springbootaop.service.proxy;
import com.liuhuachao.springbootaop.service.impl.CacheServiceImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* CacheServiceProxy Tester.
* @author <liuhuachao>
* @version 1.0
* @since <pre>12/27/2021</pre>
*/
public class CacheServiceProxyTest {
private CacheServiceProxy proxy;
@Before
public void before() throws Exception {
proxy = new CacheServiceProxy(new CacheServiceImpl());
}
@After
public void after() throws Exception {
}
/**
* Method: m1()
*/
@Test
public void testM1() throws Exception {
proxy.m1();
}
/**
* Method: m2()
*/
@Test
public void testM2() throws Exception {
proxy.m2();
}
}
| 16.177778 | 66 | 0.693681 |
8cf744b84eb6b8376e01e45b4ac20240f66e630a | 662 | package redstone.multimeter.block.chest;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.ChestBlockEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import redstone.multimeter.block.PowerSource;
public class TrappedChestHelper {
public static int getPower(World world, BlockPos pos, BlockState state) {
return getPowerFromViewerCount(ChestBlockEntity.getPlayersLookingInChestCount(world, pos));
}
public static int getPowerFromViewerCount(int viewerCount) {
return MathHelper.clamp(viewerCount, PowerSource.MIN_POWER, PowerSource.MAX_POWER);
}
}
| 31.52381 | 93 | 0.823263 |
c02c62043c9e507fb35ff8654bbadb46b8ba8f1b | 3,682 | /*
* Copyright 2004-2013 ICEsoft Technologies Canada Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icemobile.component.meta;
import org.icefaces.ace.meta.annotation.Component;
import org.icefaces.ace.meta.annotation.Facet;
import org.icefaces.ace.meta.annotation.Facets;
import org.icefaces.ace.meta.annotation.JSP;
import org.icefaces.ace.meta.annotation.Property;
import org.icemobile.component.baseMeta.PanelMeta;
import javax.faces.application.ResourceDependency;
import javax.faces.component.UIComponent;
@Component(
tagName = "splitPane",
componentClass = "org.icefaces.mobi.component.splitpane.SplitPane",
rendererClass = "org.icefaces.mobi.component.splitpane.SplitPaneRenderer",
generatedClass = "org.icefaces.mobi.component.splitpane.SplitPaneBase",
componentType = "org.icefaces.SplitPane",
rendererType = "org.icefaces.SplitPaneRenderer",
extendsClass = "javax.faces.component.UIPanel",
componentFamily = "org.icefaces.SplitPane",
tlddoc = "splitPane renders a div with two children that can be defined for " +
"page layout. It can be scrollable, have columnDivider at certain location. " +
" Requires a left and right facet for two, side by side, panels." +
" Eventually will also be resizable.")
@JSP(tagName = "splitPane",
tagClass = "org.icemobile.jsp.tags.layout.SplitPaneTag",
generatedTagClass = "org.icemobile.jsp.tags.layout.SplitPaneBaseTag",
generatedInterfaceClass = "org.icemobile.component.ISplitPane",
generatedInterfaceExtendsClass = "org.icemobile.component.IMobiComponent",
tlddoc = "SplitPane must be used with 2 children that are " +
"fragment. The first will represent the left and the " +
"second the right side, as only vertical split is currently " +
"supported. The user may determine the width of the first or " +
"left column with an integer % value with the remainder " +
"being assigned to the right column or inner div. both " +
"inner children will be scrollable by default unless " +
"scrollable attribute is set to false.")
@ResourceDependency(library = "org.icefaces.component.util", name = "component.js")
public class SplitPaneMeta extends PanelMeta {
@Property(defaultValue="true",
tlddoc="Determines if the contents of this panel are both scrollable.")
private boolean scrollable;
@Property(defaultValue="25",
tlddoc="An integer value representing the % of the total width assigned to the left pane.")
private int columnDivider;
@Facets
class FacetsMeta {
@Facet
UIComponent left;
@Facet
UIComponent right;
}
/* @Property(defaultValue="none",
tlddoc = " TODO resize needs to be further defined, but initially will be 2 adjacent panes " +
"sharing a common border which can move. Will also provide a button to collapse left pane" )
private String resizable; */
}
| 47.818182 | 108 | 0.687127 |
44782890ef0bb637053ff4f28737fc3fc7c16590 | 18,065 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.marshal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.util.Objects;
import com.google.common.primitives.Ints;
import org.apache.cassandra.cql3.CQL3Type;
import org.apache.cassandra.cql3.Constants;
import org.apache.cassandra.cql3.Term;
import org.apache.cassandra.serializers.TypeSerializer;
import org.apache.cassandra.serializers.DecimalSerializer;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.transport.ProtocolVersion;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.bytecomparable.ByteComparable;
import org.apache.cassandra.utils.bytecomparable.ByteSource;
public class DecimalType extends NumberType<BigDecimal>
{
public static final DecimalType instance = new DecimalType();
private static final int MIN_SCALE = 32;
private static final int MIN_SIGNIFICANT_DIGITS = MIN_SCALE;
private static final int MAX_SCALE = 1000;
private static final MathContext MAX_PRECISION = new MathContext(10000);
// Constants or escaping values needed to encode/decode variable-length floating point numbers (decimals) in our
// custom byte-ordered encoding scheme.
private static final int POSITIVE_DECIMAL_HEADER_MASK = 0x80;
private static final int NEGATIVE_DECIMAL_HEADER_MASK = 0x00;
private static final int DECIMAL_EXPONENT_LENGTH_HEADER_MASK = 0x40;
private static final byte DECIMAL_LAST_BYTE = (byte) 0x00;
private static final BigInteger HUNDRED = BigInteger.valueOf(100);
private static final ByteBuffer ZERO_BUFFER = instance.decompose(BigDecimal.ZERO);
DecimalType() {super(ComparisonType.CUSTOM);} // singleton
public boolean isEmptyValueMeaningless()
{
return true;
}
@Override
public boolean isFloatingPoint()
{
return true;
}
public <VL, VR> int compareCustom(VL left, ValueAccessor<VL> accessorL, VR right, ValueAccessor<VR> accessorR)
{
return compareComposed(left, accessorL, right, accessorR, this);
}
/**
* Constructs a byte-comparable representation.
* This is rather difficult and involves reconstructing the decimal.
*
* To compare, we need a normalized value, i.e. one with a sign, exponent and (0,1) mantissa. To avoid
* loss of precision, both exponent and mantissa need to be base-100. We can't get this directly off the serialized
* bytes, as they have base-10 scale and base-256 unscaled part.
*
* We store:
* - sign bit inverted * 0x80 + 0x40 + signed exponent length, where exponent is negated if value is negative
* - zero or more exponent bytes (as given by length)
* - 0x80 + first pair of decimal digits, negative is value is negative, rounded to -inf
* - zero or more 0x80 + pair of decimal digits, always positive
* - trailing 0x00
* Zero is special-cased as 0x80.
*
* Because the trailing 00 cannot be produced from a pair of decimal digits (positive or not), no value can be
* a prefix of another.
*
* Encoding examples:
* 1.1 as c1 = 0x80 (positive number) + 0x40 + (positive exponent) 0x01 (exp length 1)
* 01 = exponent 1 (100^1)
* 81 = 0x80 + 01 (0.01)
* 8a = 0x80 + 10 (....10) 0.0110e2
* 00
* -1 as 3f = 0x00 (negative number) + 0x40 - (negative exponent) 0x01 (exp length 1)
* ff = exponent -1. negative number, thus 100^1
* 7f = 0x80 - 01 (-0.01) -0.01e2
* 00
* -99.9 as 3f = 0x00 (negative number) + 0x40 - (negative exponent) 0x01 (exp length 1)
* ff = exponent -1. negative number, thus 100^1
* 1c = 0x80 - 100 (-1.00)
* 8a = 0x80 + 10 (+....10) -0.999e2
* 00
*
*/
@Override
public <V> ByteSource asComparableBytes(ValueAccessor<V> accessor, V data, ByteComparable.Version version)
{
BigDecimal value = compose(data, accessor);
if (value == null)
return null;
if (value.compareTo(BigDecimal.ZERO) == 0) // Note: 0.equals(0.0) returns false!
return ByteSource.oneByte(POSITIVE_DECIMAL_HEADER_MASK);
long scale = (((long) value.scale()) - value.precision()) & ~1;
boolean negative = value.signum() < 0;
// Make a base-100 exponent (this will always fit in an int).
int exponent = Math.toIntExact(-scale >> 1);
// Flip the exponent sign for negative numbers, so that ones with larger magnitudes are propely treated as smaller.
final int modulatedExponent = negative ? -exponent : exponent;
// We should never have scale > Integer.MAX_VALUE, as we're always subtracting the non-negative precision of
// the encoded BigDecimal, and furthermore we're rounding to negative infinity.
assert scale <= Integer.MAX_VALUE;
// However, we may end up overflowing on the negative side.
if (scale < Integer.MIN_VALUE)
{
// As scaleByPowerOfTen needs an int scale, do the scaling in two steps.
int mv = Integer.MIN_VALUE;
value = value.scaleByPowerOfTen(mv);
scale -= mv;
}
final BigDecimal mantissa = value.scaleByPowerOfTen(Ints.checkedCast(scale)).stripTrailingZeros();
// We now have a smaller-than-one signed mantissa, and a signed and modulated base-100 exponent.
assert mantissa.abs().compareTo(BigDecimal.ONE) < 0;
return new ByteSource()
{
// Start with up to 5 bytes for sign + exponent.
int exponentBytesLeft = 5;
BigDecimal current = mantissa;
@Override
public int next()
{
if (exponentBytesLeft > 0)
{
--exponentBytesLeft;
if (exponentBytesLeft == 4)
{
// Skip leading zero bytes in the modulatedExponent.
exponentBytesLeft -= Integer.numberOfLeadingZeros(Math.abs(modulatedExponent)) / 8;
// Now prepare the leading byte which includes the sign of the number plus the sign and length of the modulatedExponent.
int explen = DECIMAL_EXPONENT_LENGTH_HEADER_MASK + (modulatedExponent < 0 ? -exponentBytesLeft : exponentBytesLeft);
return explen + (negative ? NEGATIVE_DECIMAL_HEADER_MASK : POSITIVE_DECIMAL_HEADER_MASK);
}
else
return (modulatedExponent >> (exponentBytesLeft * 8)) & 0xFF;
}
else if (current == null)
{
return END_OF_STREAM;
}
else if (current.compareTo(BigDecimal.ZERO) == 0)
{
current = null;
return 0x00;
}
else
{
BigDecimal v = current.scaleByPowerOfTen(2);
BigDecimal floor = v.setScale(0, BigDecimal.ROUND_FLOOR);
current = v.subtract(floor);
return floor.byteValueExact() + 0x80;
}
}
};
}
@Override
public <V> V fromComparableBytes(ValueAccessor<V> accessor, ByteSource.Peekable comparableBytes, ByteComparable.Version version)
{
if (comparableBytes == null)
return accessor.empty();
int headerBits = comparableBytes.next();
if (headerBits == POSITIVE_DECIMAL_HEADER_MASK)
return accessor.valueOf(ZERO_BUFFER);
// I. Extract the exponent.
// The sign of the decimal, and the sign and the length (in bytes) of the decimal exponent, are all encoded in
// the first byte.
// Get the sign of the decimal...
boolean isNegative = headerBits < POSITIVE_DECIMAL_HEADER_MASK;
headerBits -= isNegative ? NEGATIVE_DECIMAL_HEADER_MASK : POSITIVE_DECIMAL_HEADER_MASK;
headerBits -= DECIMAL_EXPONENT_LENGTH_HEADER_MASK;
// Get the sign and the length of the exponent (the latter is encoded as its negative if the sign of the
// exponent is negative)...
boolean isExponentNegative = headerBits < 0;
headerBits = isExponentNegative ? -headerBits : headerBits;
// Now consume the exponent bytes. If the exponent is negative and uses less than 4 bytes, the remaining bytes
// should be padded with 1s, in order for the constructed int to contain the correct (negative) exponent value.
// So, if the exponent is negative, we can just start with all bits set to 1 (i.e. we can start with -1).
int exponent = isExponentNegative ? -1 : 0;
for (int i = 0; i < headerBits; ++i)
exponent = (exponent << 8) | comparableBytes.next();
// The encoded exponent also contains the decimal sign, in order to correctly compare exponents in case of
// negative decimals (e.g. x * 10^y > x * 10^z if x < 0 && y < z). After the decimal sign is "removed", what's
// left is a base-100 exponent following BigDecimal's convention for the exponent sign.
exponent = isNegative ? -exponent : exponent;
// II. Extract the mantissa as a BigInteger value. It was encoded as a BigDecimal value between 0 and 1, in
// order to be used for comparison (after the sign of the decimal and the sign and the value of the exponent),
// but when decoding we don't need that property on the transient mantissa value.
BigInteger mantissa = BigInteger.ZERO;
int curr = comparableBytes.next();
while (curr != DECIMAL_LAST_BYTE)
{
// The mantissa value is constructed by a standard positional notation value calculation.
// The value of the next digit is the next most-significant mantissa byte as an unsigned integer,
// offset by a predetermined value (in this case, 0x80)...
int currModified = curr - 0x80;
// ...multiply the current value by the base (in this case, 100)...
mantissa = mantissa.multiply(HUNDRED);
// ...then add the next digit to the modified current value...
mantissa = mantissa.add(BigInteger.valueOf(currModified));
// ...and finally, adjust the base-100, BigDecimal format exponent accordingly.
--exponent;
curr = comparableBytes.next();
}
// III. Construct the final BigDecimal value, by combining the mantissa and the exponent, guarding against
// underflow or overflow when exponents are close to their boundary values.
long base10NonBigDecimalFormatExp = 2L * exponent;
// When expressing a sufficiently big decimal, BigDecimal's internal scale value will be negative with very
// big absolute value. To compute the encoded exponent, this internal scale has the number of digits of the
// unscaled value subtracted from it, after which it's divided by 2, rounding down to negative infinity
// (before accounting for the decimal sign). When decoding, this exponent is converted to a base-10 exponent in
// non-BigDecimal format, which means that it can very well overflow Integer.MAX_VALUE.
// For example, see how <code>new BigDecimal(BigInteger.TEN, Integer.MIN_VALUE)</code> is encoded and decoded.
if (base10NonBigDecimalFormatExp > Integer.MAX_VALUE)
{
// If the base-10 exponent will result in an overflow, some of its powers of 10 need to be absorbed by the
// mantissa. How much exactly? As little as needed, in order to avoid complex BigInteger operations, which
// means exactly as much as to have a scale of -Integer.MAX_VALUE.
int exponentReduction = (int) (base10NonBigDecimalFormatExp - Integer.MAX_VALUE);
mantissa = mantissa.multiply(BigInteger.TEN.pow(exponentReduction));
base10NonBigDecimalFormatExp = Integer.MAX_VALUE;
}
assert base10NonBigDecimalFormatExp >= Integer.MIN_VALUE && base10NonBigDecimalFormatExp <= Integer.MAX_VALUE;
// Here we negate the exponent, as we are not using BigDecimal.scaleByPowerOfTen, where a positive number means
// "multiplying by a positive power of 10", but to BigDecimal's internal scale representation, where a positive
// number means "dividing by a positive power of 10".
byte[] mantissaBytes = mantissa.toByteArray();
V resultBuf = accessor.allocate(4 + mantissaBytes.length);
accessor.putInt(resultBuf, 0, (int) -base10NonBigDecimalFormatExp);
accessor.copyByteArrayTo(mantissaBytes, 0, resultBuf, 4, mantissaBytes.length);
return resultBuf;
}
public ByteBuffer fromString(String source) throws MarshalException
{
// Return an empty ByteBuffer for an empty string.
if (source.isEmpty()) return ByteBufferUtil.EMPTY_BYTE_BUFFER;
BigDecimal decimal;
try
{
decimal = new BigDecimal(source);
}
catch (Exception e)
{
throw new MarshalException(String.format("unable to make BigDecimal from '%s'", source), e);
}
return decompose(decimal);
}
@Override
public Term fromJSONObject(Object parsed) throws MarshalException
{
try
{
return new Constants.Value(fromString(Objects.toString(parsed)));
}
catch (NumberFormatException | MarshalException exc)
{
throw new MarshalException(String.format("Value '%s' is not a valid representation of a decimal value", parsed));
}
}
@Override
public String toJSONString(ByteBuffer buffer, ProtocolVersion protocolVersion)
{
return Objects.toString(getSerializer().deserialize(buffer), "\"\"");
}
public CQL3Type asCQL3Type()
{
return CQL3Type.Native.DECIMAL;
}
public TypeSerializer<BigDecimal> getSerializer()
{
return DecimalSerializer.instance;
}
@Override
protected int toInt(ByteBuffer value)
{
throw new UnsupportedOperationException();
}
@Override
protected float toFloat(ByteBuffer value)
{
throw new UnsupportedOperationException();
}
@Override
protected long toLong(ByteBuffer value)
{
throw new UnsupportedOperationException();
}
@Override
protected double toDouble(ByteBuffer value)
{
throw new UnsupportedOperationException();
}
@Override
protected BigInteger toBigInteger(ByteBuffer value)
{
throw new UnsupportedOperationException();
}
@Override
protected BigDecimal toBigDecimal(ByteBuffer value)
{
return compose(value);
}
public ByteBuffer add(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right)
{
return decompose(leftType.toBigDecimal(left).add(rightType.toBigDecimal(right), MAX_PRECISION));
}
public ByteBuffer substract(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right)
{
return decompose(leftType.toBigDecimal(left).subtract(rightType.toBigDecimal(right), MAX_PRECISION));
}
public ByteBuffer multiply(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right)
{
return decompose(leftType.toBigDecimal(left).multiply(rightType.toBigDecimal(right), MAX_PRECISION));
}
public ByteBuffer divide(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right)
{
BigDecimal leftOperand = leftType.toBigDecimal(left);
BigDecimal rightOperand = rightType.toBigDecimal(right);
// Predict position of first significant digit in the quotient.
// Note: it is possible to improve prediction accuracy by comparing first significant digits in operands
// but it requires additional computations so this step is omitted
int quotientFirstDigitPos = (leftOperand.precision() - leftOperand.scale()) - (rightOperand.precision() - rightOperand.scale());
int scale = MIN_SIGNIFICANT_DIGITS - quotientFirstDigitPos;
scale = Math.max(scale, leftOperand.scale());
scale = Math.max(scale, rightOperand.scale());
scale = Math.max(scale, MIN_SCALE);
scale = Math.min(scale, MAX_SCALE);
return decompose(leftOperand.divide(rightOperand, scale, RoundingMode.HALF_UP).stripTrailingZeros());
}
public ByteBuffer mod(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right)
{
return decompose(leftType.toBigDecimal(left).remainder(rightType.toBigDecimal(right)));
}
public ByteBuffer negate(ByteBuffer input)
{
return decompose(toBigDecimal(input).negate());
}
}
| 45.850254 | 144 | 0.65375 |
4def384ff8472326f0a64a5101ca3efc114d448f | 273 | package com.github.lianjiatech.retrofit.spring.boot.annotation;
import java.lang.annotation.*;
/**
* 拦截标记注解
* Intercept mark
*
* @author 陈添明
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@Documented
public @interface InterceptMark {
}
| 16.058824 | 63 | 0.761905 |
d0d7ee351b7041eef513c6b71bb2855b0001ddf3 | 803 | class Solution {
public String XXX(String s, int numRows) {
if(s == null || s.length() == 0) return "";
StringBuilder[] sb = new StringBuilder[numRows];
for(int i = 0; i < numRows; i++) {
sb[i] = new StringBuilder();
}
int i = 0;
while(i < s.length()) {
// 往下走
for(int j = 0; i < s.length() && j < numRows; j ++) {
sb[j].append(s.charAt(i++));
}
// 往上走
for(int j = numRows - 2; i < s.length() && j > 0; j--) {
sb[j].append(s.charAt(i++));
}
}
StringBuilder ret = new StringBuilder();
for(i = 0; i < numRows; i++) {
ret.append(sb[i]);
}
return ret.toString();
}
}
| 27.689655 | 68 | 0.403487 |
2bf88f525a425560a12fc77eaa28c2f71b779ece | 12,662 | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
import java.nio.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Native bindings to the <a href="http://www.opengl.org/registry/specs/ARB/draw_instanced.txt">ARB_draw_instanced</a> extension.
*
* <p>A common use case in GL for some applications is to be able to draw the same object, or groups of similar objects that share vertex data, primitive
* count and type, multiple times. This extension provides a means of accelerating such use cases while restricting the number of API calls, and keeping
* the amount of duplicate data to a minimum.</p>
*
* <p>This extension introduces two draw calls which are conceptually equivalent to a series of draw calls. Each conceptual call in this series is considered
* an "instance" of the actual draw call.</p>
*
* <p>This extension also introduces a read-only built-in variable to GLSL which contains the "instance ID." This variable initially contains 0, but increases
* by one after each conceptual draw call.</p>
*
* <p>By using the instance ID or multiples thereof as an index into a uniform array containing transform data, vertex shaders can draw multiple instances of
* an object with a single draw call.</p>
*
* <p>Requires {@link GL30 OpenGL 3.0} or <a href="http://www.opengl.org/registry/specs/EXT/gpu_shader4.txt">EXT_gpu_shader4</a> or <a href="http://www.opengl.org/registry/specs/NV/vertex_program4.txt">NV_vertex_program4</a>. Promoted to core in {@link GL31 OpenGL 3.1}.</p>
*/
public class ARBDrawInstanced {
protected ARBDrawInstanced() {
throw new UnsupportedOperationException();
}
static boolean isAvailable(GLCapabilities caps) {
return checkFunctions(
caps.glDrawArraysInstancedARB, caps.glDrawElementsInstancedARB
);
}
// --- [ glDrawArraysInstancedARB ] ---
/**
* Draw multiple instances of a range of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param first the starting index in the enabled arrays
* @param count the number of indices to be rendered
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void glDrawArraysInstancedARB(int mode, int first, int count, int primcount) {
long __functionAddress = GL.getCapabilities().glDrawArraysInstancedARB;
if ( CHECKS )
checkFunctionAddress(__functionAddress);
callV(__functionAddress, mode, first, count, primcount);
}
// --- [ glDrawElementsInstancedARB ] ---
/**
* Draws multiple instances of a set of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param count the number of elements to be rendered
* @param type the type of the values in {@code indices}. One of:<br><table><tr><td>{@link GL11#GL_UNSIGNED_BYTE UNSIGNED_BYTE}</td><td>{@link GL11#GL_UNSIGNED_SHORT UNSIGNED_SHORT}</td><td>{@link GL11#GL_UNSIGNED_INT UNSIGNED_INT}</td></tr></table>
* @param indices a pointer to the location where the indices are stored
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void nglDrawElementsInstancedARB(int mode, int count, int type, long indices, int primcount) {
long __functionAddress = GL.getCapabilities().glDrawElementsInstancedARB;
if ( CHECKS )
checkFunctionAddress(__functionAddress);
callPV(__functionAddress, mode, count, type, indices, primcount);
}
/**
* Draws multiple instances of a set of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param count the number of elements to be rendered
* @param type the type of the values in {@code indices}. One of:<br><table><tr><td>{@link GL11#GL_UNSIGNED_BYTE UNSIGNED_BYTE}</td><td>{@link GL11#GL_UNSIGNED_SHORT UNSIGNED_SHORT}</td><td>{@link GL11#GL_UNSIGNED_INT UNSIGNED_INT}</td></tr></table>
* @param indices a pointer to the location where the indices are stored
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void glDrawElementsInstancedARB(int mode, int count, int type, long indices, int primcount) {
if ( CHECKS )
GLChecks.ensureBufferObject(GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING, true);
nglDrawElementsInstancedARB(mode, count, type, indices, primcount);
}
/**
* Draws multiple instances of a set of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param type the type of the values in {@code indices}. One of:<br><table><tr><td>{@link GL11#GL_UNSIGNED_BYTE UNSIGNED_BYTE}</td><td>{@link GL11#GL_UNSIGNED_SHORT UNSIGNED_SHORT}</td><td>{@link GL11#GL_UNSIGNED_INT UNSIGNED_INT}</td></tr></table>
* @param indices a pointer to the location where the indices are stored
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void glDrawElementsInstancedARB(int mode, int type, ByteBuffer indices, int primcount) {
if ( CHECKS )
GLChecks.ensureBufferObject(GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING, false);
nglDrawElementsInstancedARB(mode, indices.remaining() >> GLChecks.typeToByteShift(type), type, memAddress(indices), primcount);
}
/**
* Draws multiple instances of a set of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param indices a pointer to the location where the indices are stored
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void glDrawElementsInstancedARB(int mode, ByteBuffer indices, int primcount) {
if ( CHECKS )
GLChecks.ensureBufferObject(GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING, false);
nglDrawElementsInstancedARB(mode, indices.remaining(), GL11.GL_UNSIGNED_BYTE, memAddress(indices), primcount);
}
/**
* Draws multiple instances of a set of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param indices a pointer to the location where the indices are stored
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void glDrawElementsInstancedARB(int mode, ShortBuffer indices, int primcount) {
if ( CHECKS )
GLChecks.ensureBufferObject(GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING, false);
nglDrawElementsInstancedARB(mode, indices.remaining(), GL11.GL_UNSIGNED_SHORT, memAddress(indices), primcount);
}
/**
* Draws multiple instances of a set of elements.
*
* @param mode the kind of primitives to render. One of:<br><table><tr><td>{@link GL11#GL_POINTS POINTS}</td><td>{@link GL11#GL_LINE_STRIP LINE_STRIP}</td><td>{@link GL11#GL_LINE_LOOP LINE_LOOP}</td><td>{@link GL11#GL_LINES LINES}</td><td>{@link GL11#GL_POLYGON POLYGON}</td><td>{@link GL11#GL_TRIANGLE_STRIP TRIANGLE_STRIP}</td><td>{@link GL11#GL_TRIANGLE_FAN TRIANGLE_FAN}</td></tr><tr><td>{@link GL11#GL_TRIANGLES TRIANGLES}</td><td>{@link GL11#GL_QUAD_STRIP QUAD_STRIP}</td><td>{@link GL11#GL_QUADS QUADS}</td><td>{@link GL32#GL_LINES_ADJACENCY LINES_ADJACENCY}</td><td>{@link GL32#GL_LINE_STRIP_ADJACENCY LINE_STRIP_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLES_ADJACENCY TRIANGLES_ADJACENCY}</td><td>{@link GL32#GL_TRIANGLE_STRIP_ADJACENCY TRIANGLE_STRIP_ADJACENCY}</td></tr><tr><td>{@link GL40#GL_PATCHES PATCHES}</td></tr></table>
* @param indices a pointer to the location where the indices are stored
* @param primcount the number of instances of the specified range of indices to be rendered
*/
public static void glDrawElementsInstancedARB(int mode, IntBuffer indices, int primcount) {
if ( CHECKS )
GLChecks.ensureBufferObject(GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING, false);
nglDrawElementsInstancedARB(mode, indices.remaining(), GL11.GL_UNSIGNED_INT, memAddress(indices), primcount);
}
} | 86.136054 | 842 | 0.750987 |
ddda1def46361f2ae3b098236213cd2eb53f3513 | 4,187 | package com.apphoa.tuanh.projectandroid.Admin;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.apphoa.tuanh.projectandroid.Database.MySqlHelper;
import com.apphoa.tuanh.projectandroid.Database.UserAction;
import com.apphoa.tuanh.projectandroid.Model.Flower;
import com.apphoa.tuanh.projectandroid.Model.SessionManagement;
import com.apphoa.tuanh.projectandroid.Model.User;
import com.apphoa.tuanh.projectandroid.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class add_flowerActivity extends AppCompatActivity {
DatabaseReference ref;
SessionManagement sessionManagement ;
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_flower);
Intent intent = this.getIntent();
sessionManagement= new SessionManagement(this);
sessionManagement.checkLogin();
if(sessionManagement.isLoggedIn()){
// ktra quyền của user
MySqlHelper mySqlHelper = new MySqlHelper(this);
UserAction userAction = new UserAction(mySqlHelper);
String UserID = sessionManagement.getUserID();
User u = userAction.GetUserById(UserID);
if (u.equals(null)) finish();
if(u.getPermission() == 0) {
Toast.makeText(this,"You do not have Permission!",Toast.LENGTH_SHORT).show();
finish();
}
}
ref = FirebaseDatabase.getInstance().getReference("Flower");
}
public void add (View v)
{
EditText name = (EditText) findViewById(R.id.edittext_name_addflower);
EditText price = (EditText) findViewById(R.id.edittext_price_addflower);
EditText image = (EditText) findViewById(R.id.edittext_image_addflower);
EditText status = (EditText) findViewById(R.id.edittext_status_addflower);
EditText species = (EditText) findViewById(R.id.edittext_species_addflower);
EditText detail = (EditText) findViewById(R.id.edittext_detail_addflower);
String name_text = name.getText().toString();
String price_text = price.getText().toString();
String image_text = image.getText().toString();
String status_text = status.getText().toString();
String species_text = species.getText().toString();
String detail_text = detail.getText().toString();
final Flower flower = new Flower();
flower.setTenHoa(name_text);
flower.setHinhAnh(image_text);
flower.setGia(price_text);
flower.setStatus(status_text);
flower.setLoai(species_text);
flower.setMoTa(detail_text);
if(name_text.isEmpty()==true||price_text.isEmpty()==true||image_text.isEmpty()==true||status_text.isEmpty()==true||species_text.isEmpty()==true)
{
showAlertDialog("bạn cần điền đầy đủ thông tin hoa!");
}
else
{
String id = ref.push().getKey().toString();
flower.setID(id);
ref.child(id).setValue(flower);
showAlertDialog("thêm hoa thành công!");
Intent sucess = new Intent(add_flowerActivity.this, FlowerManagerActivity.class);
startActivity(sucess);
}
}
public void showAlertDialog(String s)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("FlowerShop");
builder.setMessage(s);
builder.setCancelable(false);
builder.setNegativeButton("OK!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public void back (View v)
{
this.onBackPressed();
}
}
| 40.259615 | 152 | 0.673036 |
f70f8380eca16e144909fd7f6d8ff9d5c2b2e2ff | 423 | package cn.cerc.db;
import cn.cerc.db.core.DataSet;
/**
* 专用于建立测试类数据
*
* @author 张弓
*/
public class SampleData {
public static DataSet getDataSet() {
DataSet ds = new DataSet();
for (int i = 1; i < 10; i++) {
ds.append();
ds.setValue("code", "code" + i);
ds.setValue("name", "name" + i);
ds.setValue("num", i);
}
return ds;
}
}
| 18.391304 | 44 | 0.489362 |
b601b9d31eb6dc7e10c9f85a8725273143181e7e | 267 | package com.chess.backend.restController.objects;
import com.chess.backend.gamemodel.constants.GameMode;
import lombok.Data;
@Data
public class NewGameObject {
private GameMode type;
private Integer numberOfPlayers;
private NewPlayerObject[] players;
}
| 22.25 | 54 | 0.790262 |
aceffb9e0ae0560818ee977c54b1cb1606b65cb9 | 538 | package test;
import act.Act;
import act.util.PropertySpec;
import org.osgl.mvc.annotation.GetAction;
import java.util.ArrayList;
import java.util.List;
public class AppEntry {
@GetAction("/query")
@PropertySpec("mfield.test.a as 测试")
public List<Bean> query() {
List<Bean> beans = new ArrayList<>();
beans.add(new Bean("a1"));
beans.add(new Bean("a2"));
return beans;
}
public static void main(String[] args) throws Exception{
Act.start();
}
}
| 21.52 | 61 | 0.605948 |
883e6d00d59719ebf9ddb47ee3007c58341c7043 | 3,327 | /**
* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6380849
* @summary Tests BeanInfo finder
* @author Sergey Malenkov
*/
import beans.FirstBean;
import beans.FirstBeanBeanInfo;
import beans.SecondBean;
import beans.ThirdBean;
import infos.SecondBeanBeanInfo;
import infos.ThirdBeanBeanInfo;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.lang.reflect.Method;
public class TestBeanInfo implements Runnable {
private static final String[] SEARCH_PATH = { "infos" }; // NON-NLS: package name
public static void main(String[] args) throws InterruptedException {
TestBeanInfo test = new TestBeanInfo();
test.run();
// the following tests fails on previous build
ThreadGroup group = new ThreadGroup("$$$"); // NON-NLS: unique thread name
Thread thread = new Thread(group, test);
thread.start();
thread.join();
}
private static void test(Class<?> type, Class<? extends BeanInfo> expected) {
BeanInfo actual;
try {
actual = Introspector.getBeanInfo(type);
type = actual.getClass();
Method method = type.getDeclaredMethod("getTargetBeanInfo"); // NON-NLS: method name
method.setAccessible(true);
actual = (BeanInfo) method.invoke(actual);
}
catch (Exception exception) {
throw new Error("unexpected error", exception);
}
if ((actual == null) && (expected != null)) {
throw new Error("expected info is not found");
}
if ((actual != null) && !actual.getClass().equals(expected)) {
throw new Error("found unexpected info");
}
}
private boolean passed;
public void run() {
Introspector.flushCaches();
test(FirstBean.class, FirstBeanBeanInfo.class);
test(SecondBean.class, null);
test(ThirdBean.class, null);
test(ThirdBeanBeanInfo.class, ThirdBeanBeanInfo.class);
Introspector.setBeanInfoSearchPath(SEARCH_PATH);
Introspector.flushCaches();
test(FirstBean.class, FirstBeanBeanInfo.class);
test(SecondBean.class, SecondBeanBeanInfo.class);
test(ThirdBean.class, null);
test(ThirdBeanBeanInfo.class, ThirdBeanBeanInfo.class);
}
}
| 34.65625 | 96 | 0.676886 |
aa0a0e01233b82d4162c978948ed2e55fcae1bb2 | 51,626 | /*
HumanDetectProfile.java
Copyright (c) 2015 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.profile;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.deviceconnect.android.message.MessageUtils;
import android.content.Intent;
import android.os.Bundle;
/**
* Human Detect Profile.
*
* <p>
* API that provides Setting, the Detection feature for Human Detect Device.<br/>
*
* DevicePlugin that provides a HumanDetect operation function of for smart device inherits an
* equivalent class, and implements the corresponding API thing. <br/>
* </p>
*
* <h1>API provides methods</h1>
* <p>
* For requests to each API of HumanDetectProfile, following callback method group is automatically
* invoked.<br/>
* Subclasses override the methods for API provided by the DevicePlugin from the following methods
* group, to implement the functionality that.<br/>
* Features that are not overridden automatically return the response as non-compliant API.
* </p>
* @author NTT DOCOMO, INC.
*/
public abstract class HumanDetectProfile extends DConnectProfile {
/**
* profile name: {@value} .
*/
public static final String PROFILE_NAME = "humandetect";
/**
* interface: {@value} .
*/
public static final String INTERFACE_DETECTION = "detection";
/**
* attribute: {@value} .
*/
public static final String ATTRIBUTE_BODY_DETECTION = "body";
/**
* attribute: {@value} .
*/
public static final String ATTRIBUTE_HAND_DETECTION = "hand";
/**
* attribute: {@value} .
*/
public static final String ATTRIBUTE_FACE_DETECTION = "face";
/**
* attribute: {@value} .
*/
public static final String ATTRIBUTE_ON_BODY_DETECTION = "onbodydetection";
/**
* attribute: {@value} .
*/
public static final String ATTRIBUTE_ON_HAND_DETECTION = "onhanddetection";
/**
* attribute: {@value} .
*/
public static final String ATTRIBUTE_ON_FACE_DETECTION = "onfacedetection";
/**
* path: {@value}.
*/
public static final String PATH_PROFILE = PATH_ROOT + SEPARATOR + PROFILE_NAME;
/**
* path: {@value} .
*/
public static final String PATH_BODY_DETECTION = PATH_PROFILE + SEPARATOR + INTERFACE_DETECTION
+ SEPARATOR + ATTRIBUTE_BODY_DETECTION;
/**
* path: {@value} .
*/
public static final String PATH_HAND_DETECTION = PATH_PROFILE + SEPARATOR + INTERFACE_DETECTION
+ SEPARATOR + ATTRIBUTE_HAND_DETECTION;
/**
* path: {@value} .
*/
public static final String PATH_FACE_DETECTION = PATH_PROFILE + SEPARATOR + INTERFACE_DETECTION
+ SEPARATOR + ATTRIBUTE_FACE_DETECTION;
/**
* path: {@value} .
*/
public static final String PATH_ON_BODY_DETECTION = PATH_PROFILE + SEPARATOR + ATTRIBUTE_ON_BODY_DETECTION;
/**
* path: {@value} .
*/
public static final String PATH_ON_HAND_DETECTION = PATH_PROFILE + SEPARATOR + ATTRIBUTE_ON_HAND_DETECTION;
/**
* path: {@value} .
*/
public static final String PATH_ON_FACE_DETECTION = PATH_PROFILE + SEPARATOR + ATTRIBUTE_ON_FACE_DETECTION;
/*--- request ---*/
/**
* parameter: {@value} .
*/
public static final String PARAM_THRESHOLD = "threshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_MINWIDTH = "minWidth";
/**
* parameter: {@value} .
*/
public static final String PARAM_MINHEIGHT = "minHeight";
/**
* parameter: {@value} .
*/
public static final String PARAM_MAXWIDTH = "maxWidth";
/**
* parameter: {@value} .
*/
public static final String PARAM_MAXHEIGHT = "maxHeight";
/**
* parameter: {@value} .
*/
public static final String PARAM_OPTIONS = "options";
/**
* parameter: {@value} .
*/
public static final String PARAM_INTERVAL = "interval";
/**
* parameter: {@value} .
*/
public static final String PARAM_EYE_THRESHOLD = "eyeThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_NOSE_THRESHOLD = "noseThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_MOUTH_THRESHOLD = "mouthThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_BLINK_THRESHOLD = "blinkThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_AGE_THRESHOLD = "ageThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_GENDER_THRESHOLD = "genderThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_FACE_DIRECTION_THRESHOLD = "faceDirectionThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_GAZE_THRESHOLD = "gazeThreshold";
/**
* parameter: {@value} .
*/
public static final String PARAM_EXPRESSION_THRESHOLD = "expressionThreshold";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_EYE = "eye";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_NOSE = "nose";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_MOUTH = "mouth";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_BLINK = "blink";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_AGE = "age";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_GENDER = "gender";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_FACE_DIRECTION = "faceDirection";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_GAZE = "gaze";
/**
* value: {@value} .
*/
public static final String VALUE_OPTION_EXPRESSION = "expression";
/*--- response ---*/
/**
* parameter: {@value} .
*/
public static final String PARAM_BODYDETECTS = "bodyDetects";
/**
* parameter: {@value} .
*/
public static final String PARAM_HANDDETECTS = "handDetects";
/**
* parameter: {@value} .
*/
public static final String PARAM_FACEDETECTS = "faceDetects";
/**
* parameter: {@value} .
*/
public static final String PARAM_X = "x";
/**
* parameter: {@value} .
*/
public static final String PARAM_Y = "y";
/**
* parameter: {@value} .
*/
public static final String PARAM_WIDTH = "width";
/**
* parameter: {@value} .
*/
public static final String PARAM_HEIGHT = "height";
/**
* parameter: {@value} .
*/
public static final String PARAM_CONFIDENCE = "confidence";
/**
* parameter: {@value} .
*/
public static final String PARAM_EYEPOINTS = "eyePoints";
/**
* parameter: {@value} .
*/
public static final String PARAM_LEFTEYE_X = "leftEyeX";
/**
* parameter: {@value} .
*/
public static final String PARAM_LEFTEYE_Y = "leftEyeY";
/**
* parameter: {@value} .
*/
public static final String PARAM_LEFTEYE_WIDTH = "leftEyeWidth";
/**
* parameter: {@value} .
*/
public static final String PARAM_LEFTEYE_HEIGHT = "leftEyeHeight";
/**
* parameter: {@value} .
*/
public static final String PARAM_RIGHTEYE_X = "rightEyeX";
/**
* parameter: {@value} .
*/
public static final String PARAM_RIGHTEYE_Y = "rightEyeY";
/**
* parameter: {@value} .
*/
public static final String PARAM_RIGHTEYE_WIDTH = "rightEyeWidth";
/**
* parameter: {@value} .
*/
public static final String PARAM_RIGHTEYE_HEIGHT = "rightEyeHeight";
/**
* parameter: {@value} .
*/
public static final String PARAM_NOSEPOINTS = "nosePoints";
/**
* parameter: {@value} .
*/
public static final String PARAM_NOSE_X = "noseX";
/**
* parameter: {@value} .
*/
public static final String PARAM_NOSE_Y = "noseY";
/**
* parameter: {@value} .
*/
public static final String PARAM_NOSE_WIDTH = "noseWidth";
/**
* parameter: {@value} .
*/
public static final String PARAM_NOSE_HEIGHT = "noseHeight";
/**
* parameter: {@value} .
*/
public static final String PARAM_MOUTHPOINTS = "mouthPoints";
/**
* parameter: {@value} .
*/
public static final String PARAM_MOUTH_X = "mouthX";
/**
* parameter: {@value} .
*/
public static final String PARAM_MOUTH_Y = "mouthY";
/**
* parameter: {@value} .
*/
public static final String PARAM_MOUTH_WIDTH = "mouthWidth";
/**
* parameter: {@value} .
*/
public static final String PARAM_MOUTH_HEIGHT = "mouthHeight";
/**
* parameter: {@value} .
*/
public static final String PARAM_BLINKRESULTS = "blinkResults";
/**
* parameter: {@value} .
*/
public static final String PARAM_LEFTEYE = "leftEye";
/**
* parameter: {@value} .
*/
public static final String PARAM_RIGHTEYE = "rightEye";
/**
* parameter: {@value} .
*/
public static final String PARAM_AGERESULTS = "ageResults";
/**
* parameter: {@value} .
*/
public static final String PARAM_AGE = "age";
/**
* parameter: {@value} .
*/
public static final String PARAM_GENDERRESULTS = "genderResults";
/**
* parameter: {@value} .
*/
public static final String PARAM_GENDER = "gender";
/**
* parameter: {@value} .
*/
public static final String VALUE_GENDER_MALE = "male";
/**
* parameter: {@value} .
*/
public static final String VALUE_GENDER_FEMALE = "female";
/**
* parameter: {@value} .
*/
public static final String PARAM_FACEDIRECTIONRESULTS = "faceDirectionResults";
/**
* parameter: {@value} .
*/
public static final String PARAM_YAW = "yaw";
/**
* parameter: {@value} .
*/
public static final String PARAM_PITCH = "pitch";
/**
* parameter: {@value} .
*/
public static final String PARAM_ROLL = "roll";
/**
* parameter: {@value} .
*/
public static final String PARAM_GAZERESULTS = "gazeResults";
/**
* parameter: {@value} .
*/
public static final String PARAM_GAZE_LR = "gazeLR";
/**
* parameter: {@value} .
*/
public static final String PARAM_GAZE_UD = "gazeUD";
/**
* parameter: {@value} .
*/
public static final String PARAM_EXPRESSIONRESULTS = "expressionResults";
/**
* parameter: {@value} .
*/
public static final String PARAM_EXPRESSION = "expression";
/**
* value: {@value} .
*/
public static final String VALUE_EXPRESSION_UNKNOWN = "unknown";
/**
* value: {@value} .
*/
public static final String VALUE_EXPRESSION_SMILE = "smile";
/**
* value: {@value} .
*/
public static final String VALUE_EXPRESSION_SURPRISE = "surprise";
/**
* value: {@value} .
*/
public static final String VALUE_EXPRESSION_MAD = "mad";
/**
* value: {@value} .
*/
public static final String VALUE_EXPRESSION_SAD = "sad";
/**
* normalize min value.
*/
public static final double NORMALIZE_VALUE_MIN = 0.0;
/**
* normalize max value.
*/
public static final double NORMALIZE_VALUE_MAX = 1.0;
/**
* error: {@value} .
*/
private static final String ERROR_THRESHOLD_DIFFERENT_TYPE = "threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_THRESHOLD_OUT_OF_RANGE =
"threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_MINWIDTH_DIFFERENT_TYPE = "minWidth is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_MINWIDTH_OUT_OF_RANGE =
"minWidth is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_MAXWIDTH_DIFFERENT_TYPE = "maxWidth is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_MAXWIDTH_OUT_OF_RANGE =
"maxWidth is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_MINHEIGHT_DIFFERENT_TYPE = "minHeight is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_MINHEIGHT_OUT_OF_RANGE =
"minHeight is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_MAXHEIGHT_DIFFERENT_TYPE = "maxHeight is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_MAXHEIGHT_OUT_OF_RANGE =
"maxHeight is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_INTERVAL_DIFFERENT_TYPE = "interval is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_INTERVAL_OUT_OF_RANGE =
"interval is out of range. range:{ %d - %d } [msec]";
/**
* error: {@value} .
*/
private static final String ERROR_EYE_THRESHOLD_DIFFERENT_TYPE = "eye threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_EYE_THRESHOLD_OUT_OF_RANGE =
"eye threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_NOSE_THRESHOLD_DIFFERENT_TYPE = "nose threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_NOSE_THRESHOLD_OUT_OF_RANGE =
"nose threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_MOUTH_THRESHOLD_DIFFERENT_TYPE = "mouth threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_MOUTH_THRESHOLD_OUT_OF_RANGE =
"mouth threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_BLINK_THRESHOLD_DIFFERENT_TYPE = "blink threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_BLINK_THRESHOLD_OUT_OF_RANGE =
"blink threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_AGE_THRESHOLD_DIFFERENT_TYPE = "age threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_AGE_THRESHOLD_OUT_OF_RANGE =
"age threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_GENDER_THRESHOLD_DIFFERENT_TYPE = "gender threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_GENDER_THRESHOLD_OUT_OF_RANGE =
"gender threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_FACE_DIRECTION_THRESHOLD_DIFFERENT_TYPE =
"face direction threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_FACE_DIRECTION_THRESHOLD_OUT_OF_RANGE =
"face direction threshold is out of range. range:{ "
+ NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_GAZE_THRESHOLD_DIFFERENT_TYPE = "gaze threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_GAZE_THRESHOLD_OUT_OF_RANGE =
"gaze threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* error: {@value} .
*/
private static final String ERROR_EXPRESSION_THRESHOLD_DIFFERENT_TYPE = "expression threshold is different type.";
/**
* error: {@value} .
*/
private static final String ERROR_EXPRESSION_THRESHOLD_OUT_OF_RANGE =
"expression threshold is out of range. range:{ " + NORMALIZE_VALUE_MIN + " - " + NORMALIZE_VALUE_MAX + " }";
/**
* Constructor.
*/
public HumanDetectProfile() {
}
@Override
public final String getProfileName() {
return PROFILE_NAME;
}
@Override
protected boolean onGetRequest(final Intent request, final Intent response) {
String interfac = getInterface(request);
String attribute = getAttribute(request);
boolean result = true;
if (INTERFACE_DETECTION.equals(interfac) && ATTRIBUTE_BODY_DETECTION.equals(attribute)) {
String serviceId = getServiceID(request);
List<String> options = getOptions(request);
result = onGetBodyDetection(request, response, serviceId, options);
} else if (INTERFACE_DETECTION.equals(interfac) && ATTRIBUTE_HAND_DETECTION.equals(attribute)) {
String serviceId = getServiceID(request);
List<String> options = getOptions(request);
result = onGetHandDetection(request, response, serviceId, options);
} else if (INTERFACE_DETECTION.equals(interfac) && ATTRIBUTE_FACE_DETECTION.equals(attribute)) {
String serviceId = getServiceID(request);
List<String> options = getOptions(request);
result = onGetFaceDetection(request, response, serviceId, options);
} else {
MessageUtils.setUnknownAttributeError(response);
}
return result;
}
@Override
protected boolean onPostRequest(final Intent request, final Intent response) {
String interfac = getInterface(request);
String attribute = getAttribute(request);
boolean result = true;
if (INTERFACE_DETECTION.equals(interfac) && ATTRIBUTE_BODY_DETECTION.equals(attribute)) {
String serviceId = getServiceID(request);
List<String> options = getOptions(request);
result = onPostBodyDetection(request, response, serviceId, options);
} else if (INTERFACE_DETECTION.equals(interfac) && ATTRIBUTE_HAND_DETECTION.equals(attribute)) {
String serviceId = getServiceID(request);
List<String> options = getOptions(request);
result = onPostHandDetection(request, response, serviceId, options);
} else if (INTERFACE_DETECTION.equals(interfac) && ATTRIBUTE_FACE_DETECTION.equals(attribute)) {
String serviceId = getServiceID(request);
List<String> options = getOptions(request);
result = onPostFaceDetection(request, response, serviceId, options);
} else {
MessageUtils.setUnknownAttributeError(response);
}
return result;
}
@Override
protected boolean onPutRequest(final Intent request, final Intent response) {
boolean result = true;
String attribute = getAttribute(request);
if (ATTRIBUTE_ON_BODY_DETECTION.equals(attribute)) {
result = onPutOnBodyDetection(request, response, getServiceID(request), getSessionKey(request));
} else if (ATTRIBUTE_ON_HAND_DETECTION.equals(attribute)) {
result = onPutOnHandDetection(request, response, getServiceID(request), getSessionKey(request));
} else if (ATTRIBUTE_ON_FACE_DETECTION.equals(attribute)) {
result = onPutOnFaceDetection(request, response, getServiceID(request), getSessionKey(request));
} else {
MessageUtils.setUnknownAttributeError(response);
}
return result;
}
@Override
protected boolean onDeleteRequest(final Intent request, final Intent response) {
boolean result = true;
String attribute = getAttribute(request);
if (ATTRIBUTE_ON_BODY_DETECTION.equals(attribute)) {
result = onDeleteOnBodyDetection(request, response, getServiceID(request), getSessionKey(request));
} else if (ATTRIBUTE_ON_HAND_DETECTION.equals(attribute)) {
result = onDeleteOnHandDetection(request, response, getServiceID(request), getSessionKey(request));
} else if (ATTRIBUTE_ON_FACE_DETECTION.equals(attribute)) {
result = onDeleteOnFaceDetection(request, response, getServiceID(request), getSessionKey(request));
} else {
MessageUtils.setUnknownAttributeError(response);
}
return result;
}
// ------------------------------------
// PUT
// ------------------------------------
/**
* onbodydetectionコールバック登録リクエストハンドラー.<br/>
* onbodydetectionコールバックを登録し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param serviceId サービスID
* @param sessionKey セッションキー
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onPutOnBodyDetection(final Intent request, final Intent response,
final String serviceId, final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* onhanddetectionコールバック登録リクエストハンドラー.<br/>
* onhanddetectionコールバックを登録し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param serviceId サービスID
* @param sessionKey セッションキー
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onPutOnHandDetection(final Intent request, final Intent response,
final String serviceId, final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* onfacedetectionコールバック登録リクエストハンドラー.<br/>
* onfacedetectionコールバックを登録し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param serviceId サービスID
* @param sessionKey セッションキー
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onPutOnFaceDetection(final Intent request, final Intent response,
final String serviceId, final String sessionKey) {
setUnsupportedError(response);
return true;
}
// ------------------------------------
// DELETE
// ------------------------------------
/**
* onbodydetectionコールバック解除リクエストハンドラー.<br/>
* onbodydetectionコールバックを解除し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param serviceId サービスID
* @param sessionKey セッションキー
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onDeleteOnBodyDetection(final Intent request, final Intent response,
final String serviceId, final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* onhanddetectionコールバック解除リクエストハンドラー.<br/>
* onhanddetectionコールバックを解除し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param serviceId サービスID
* @param sessionKey セッションキー
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onDeleteOnHandDetection(final Intent request, final Intent response,
final String serviceId, final String sessionKey) {
setUnsupportedError(response);
return true;
}
/**
* onfacedetectionコールバック解除リクエストハンドラー.<br/>
* onfacedetectionコールバックを解除し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param serviceId サービスID
* @param sessionKey セッションキー
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onDeleteOnFaceDetection(final Intent request, final Intent response,
final String serviceId, final String sessionKey) {
setUnsupportedError(response);
return true;
}
// ------------------------------------
// GET
// ------------------------------------
/**
* body detection attribute request handler.<br/>
* And ask the human body detection, and the result is stored in the response parameters.
* If the response parameter is ready, please return true.
* If you are not ready, please return false to start the process in the thread.
* Once the thread is complete, send the response parameters.
* @param request request parameter
* @param response response parameter.
* @param serviceId serviceID
* @param options options.
* @return send response flag.(true:sent / unsent (Send after the thread has been completed))
*/
protected boolean onGetBodyDetection(final Intent request, final Intent response,
final String serviceId, final List<String> options) {
setUnsupportedError(response);
return true;
}
/**
* hand detection attribute request handler.<br/>
* And ask the human hand detection, and the result is stored in the response parameters.
* If the response parameter is ready, please return true.
* If you are not ready, please return false to start the process in the thread.
* Once the thread is complete, send the response parameters.
* @param request request parameter
* @param response response parameter.
* @param serviceId serviceID
* @param options options.
* @return send response flag.(true:sent / unsent (Send after the thread has been completed))
*/
protected boolean onGetHandDetection(final Intent request, final Intent response,
final String serviceId, final List<String> options) {
setUnsupportedError(response);
return true;
}
/**
* face detection attribute request handler.<br/>
* And ask the human face detection, and the result is stored in the response parameters.
* If the response parameter is ready, please return true.
* If you are not ready, please return false to start the process in the thread.
* Once the thread is complete, send the response parameters.
* @param request request parameter
* @param response response parameter.
* @param serviceId serviceID
* @param options options.
* @return send response flag.(true:sent / unsent (Send after the thread has been completed))
*/
protected boolean onGetFaceDetection(final Intent request, final Intent response,
final String serviceId, final List<String> options) {
setUnsupportedError(response);
return true;
}
// ------------------------------------
// POST
// ------------------------------------
/**
* body detection attribute request handler.<br/>
* And ask the human body detection, and the result is stored in the response parameters.
* If the response parameter is ready, please return true.
* If you are not ready, please return false to start the process in the thread.
* Once the thread is complete, send the response parameters.
* @param request request parameter
* @param response response parameter.
* @param serviceId serviceID
* @param options options.
* @return send response flag.(true:sent / unsent (Send after the thread has been completed))
*/
protected boolean onPostBodyDetection(final Intent request, final Intent response,
final String serviceId, final List<String> options) {
setUnsupportedError(response);
return true;
}
/**
* hand detection attribute request handler.<br/>
* And ask the human hand detection, and the result is stored in the response parameters.
* If the response parameter is ready, please return true.
* If you are not ready, please return false to start the process in the thread.
* Once the thread is complete, send the response parameters.
* @param request request parameter
* @param response response parameter.
* @param serviceId serviceID
* @param options options.
* @return send response flag.(true:sent / unsent (Send after the thread has been completed))
*/
protected boolean onPostHandDetection(final Intent request, final Intent response,
final String serviceId, final List<String> options) {
setUnsupportedError(response);
return true;
}
/**
* face detection attribute request handler.<br/>
* And ask the human face detection, and the result is stored in the response parameters.
* If the response parameter is ready, please return true.
* If you are not ready, please return false to start the process in the thread.
* Once the thread is complete, send the response parameters.
* @param request request parameter
* @param response response parameter.
* @param serviceId serviceID
* @param options options.
* @return send response flag.(true:sent / unsent (Send after the thread has been completed))
*/
protected boolean onPostFaceDetection(final Intent request, final Intent response,
final String serviceId, final List<String> options) {
setUnsupportedError(response);
return true;
}
// ------------------------------------
// Getter methods.
// ------------------------------------
/**
* get options string array list from request.
*
* @param request request parameter.
* @return options. if nothing, null.
*/
public static List<String> getOptions(final Intent request) {
List<String> optionList = null;
String strOptions = request.getStringExtra(PARAM_OPTIONS);
if (strOptions != null) {
String[] options = strOptions.split(",", 0);
if (options != null) {
optionList = Arrays.asList(options);
}
}
return optionList;
}
/**
* get threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_THRESHOLD)) {
return null;
}
Double threshold = parseDouble(request, PARAM_THRESHOLD);
if (threshold == null) {
throw new NumberFormatException(ERROR_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= threshold && threshold <= NORMALIZE_VALUE_MAX) {
return threshold;
} else {
throw new NumberFormatException(ERROR_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get minWidth from request.
*
* @param request request parameter.
* @return minWidth(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getMinWidth(final Intent request) {
if (!checkExistRequestData(request, PARAM_MINWIDTH)) {
return null;
}
Double minWidth = parseDouble(request, PARAM_MINWIDTH);
if (minWidth == null) {
throw new NumberFormatException(ERROR_MINWIDTH_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= minWidth && minWidth <= NORMALIZE_VALUE_MAX) {
return minWidth;
} else {
throw new NumberFormatException(ERROR_MINWIDTH_OUT_OF_RANGE);
}
}
/**
* get maxWidth from request.
*
* @param request request parameter.
* @return maxWidth(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getMaxWidth(final Intent request) {
if (!checkExistRequestData(request, PARAM_MAXWIDTH)) {
return null;
}
Double maxWidth = parseDouble(request, PARAM_MAXWIDTH);
if (maxWidth == null) {
throw new NumberFormatException(ERROR_MAXWIDTH_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= maxWidth && maxWidth <= NORMALIZE_VALUE_MAX) {
return maxWidth;
} else {
throw new NumberFormatException(ERROR_MAXWIDTH_OUT_OF_RANGE);
}
}
/**
* get minHeight from request.
*
* @param request request parameter.
* @return minHeight(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getMinHeight(final Intent request) {
if (!checkExistRequestData(request, PARAM_MINHEIGHT)) {
return null;
}
Double minHeight = parseDouble(request, PARAM_MINHEIGHT);
if (minHeight == null) {
throw new NumberFormatException(ERROR_MINHEIGHT_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= minHeight && minHeight <= NORMALIZE_VALUE_MAX) {
return minHeight;
} else {
throw new NumberFormatException(ERROR_MINHEIGHT_OUT_OF_RANGE);
}
}
/**
* get maxHeight from request.
*
* @param request request parameter.
* @return maxHeight(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getMaxHeight(final Intent request) {
if (!checkExistRequestData(request, PARAM_MAXHEIGHT)) {
return null;
}
Double maxHeight = parseDouble(request, PARAM_MAXHEIGHT);
if (maxHeight == null) {
throw new NumberFormatException(ERROR_MAXHEIGHT_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= maxHeight && maxHeight <= NORMALIZE_VALUE_MAX) {
return maxHeight;
} else {
throw new NumberFormatException(ERROR_MAXHEIGHT_OUT_OF_RANGE);
}
}
/**
* get interval from request.
*
* @param request request parameter.
* @param minInterval minimum interval[msec]
* @param maxInterval maximum interval[msec]
* @return interval[msec]. if nothing, null.
* @throws NumberFormatException exception
*/
public static Long getInterval(final Intent request,
final long minInterval, final long maxInterval) {
if (!checkExistRequestData(request, PARAM_INTERVAL)) {
return null;
}
Long interval = parseLong(request, PARAM_INTERVAL);
if (interval == null) {
throw new NumberFormatException(ERROR_INTERVAL_DIFFERENT_TYPE);
}
if (interval == 0 || minInterval <= interval && interval <= maxInterval) {
return interval;
} else {
String error = String.format(Locale.ENGLISH,
ERROR_INTERVAL_OUT_OF_RANGE, minInterval, maxInterval);
throw new NumberFormatException(error);
}
}
/**
* get eye threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getEyeThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_EYE_THRESHOLD)) {
return null;
}
Double eyeThreshold = parseDouble(request, PARAM_EYE_THRESHOLD);
if (eyeThreshold == null) {
throw new NumberFormatException(ERROR_EYE_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= eyeThreshold && eyeThreshold <= NORMALIZE_VALUE_MAX) {
return eyeThreshold;
} else {
throw new NumberFormatException(ERROR_EYE_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get nose threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getNoseThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_NOSE_THRESHOLD)) {
return null;
}
Double noseThreshold = parseDouble(request, PARAM_EYE_THRESHOLD);
if (noseThreshold == null) {
throw new NumberFormatException(ERROR_NOSE_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= noseThreshold && noseThreshold <= NORMALIZE_VALUE_MAX) {
return noseThreshold;
} else {
throw new NumberFormatException(ERROR_NOSE_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get mouth threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getMouthThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_MOUTH_THRESHOLD)) {
return null;
}
Double mouthThreshold = parseDouble(request, PARAM_MOUTH_THRESHOLD);
if (mouthThreshold == null) {
throw new NumberFormatException(ERROR_MOUTH_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= mouthThreshold && mouthThreshold <= NORMALIZE_VALUE_MAX) {
return mouthThreshold;
} else {
throw new NumberFormatException(ERROR_MOUTH_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get blink threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getBlinkThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_BLINK_THRESHOLD)) {
return null;
}
Double blinkThreshold = parseDouble(request, PARAM_BLINK_THRESHOLD);
if (blinkThreshold == null) {
throw new NumberFormatException(ERROR_BLINK_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= blinkThreshold && blinkThreshold <= NORMALIZE_VALUE_MAX) {
return blinkThreshold;
} else {
throw new NumberFormatException(ERROR_BLINK_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get age threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getAgeThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_AGE_THRESHOLD)) {
return null;
}
Double ageThreshold = parseDouble(request, PARAM_AGE_THRESHOLD);
if (ageThreshold == null) {
throw new NumberFormatException(ERROR_AGE_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= ageThreshold && ageThreshold <= NORMALIZE_VALUE_MAX) {
return ageThreshold;
} else {
throw new NumberFormatException(ERROR_AGE_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get gender threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getGenderThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_GENDER_THRESHOLD)) {
return null;
}
Double genderThreshold = parseDouble(request, PARAM_AGE_THRESHOLD);
if (genderThreshold == null) {
throw new NumberFormatException(ERROR_GENDER_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= genderThreshold && genderThreshold <= NORMALIZE_VALUE_MAX) {
return genderThreshold;
} else {
throw new NumberFormatException(ERROR_GENDER_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get face direction threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getFaceDirectionThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_FACE_DIRECTION_THRESHOLD)) {
return null;
}
Double faceDirectionThreshold = parseDouble(request, PARAM_FACE_DIRECTION_THRESHOLD);
if (faceDirectionThreshold == null) {
throw new NumberFormatException(ERROR_FACE_DIRECTION_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= faceDirectionThreshold && faceDirectionThreshold <= NORMALIZE_VALUE_MAX) {
return faceDirectionThreshold;
} else {
throw new NumberFormatException(ERROR_FACE_DIRECTION_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get gaze threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getGazeThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_GAZE_THRESHOLD)) {
return null;
}
Double gazeThreshold = parseDouble(request, PARAM_GAZE_THRESHOLD);
if (gazeThreshold == null) {
throw new NumberFormatException(ERROR_GAZE_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= gazeThreshold && gazeThreshold <= NORMALIZE_VALUE_MAX) {
return gazeThreshold;
} else {
throw new NumberFormatException(ERROR_GAZE_THRESHOLD_OUT_OF_RANGE);
}
}
/**
* get expression threshold from request.
*
* @param request request parameter.
* @return threshold(0.0 ... 1.0). if nothing, null.
* @throws NumberFormatException
*/
public static Double getExpressionThreshold(final Intent request) {
if (!checkExistRequestData(request, PARAM_EXPRESSION_THRESHOLD)) {
return null;
}
Double expressionThreshold = parseDouble(request, PARAM_EXPRESSION_THRESHOLD);
if (expressionThreshold == null) {
throw new NumberFormatException(ERROR_EXPRESSION_THRESHOLD_DIFFERENT_TYPE);
}
if (NORMALIZE_VALUE_MIN <= expressionThreshold && expressionThreshold <= NORMALIZE_VALUE_MAX) {
return expressionThreshold;
} else {
throw new NumberFormatException(ERROR_EXPRESSION_THRESHOLD_OUT_OF_RANGE);
}
}
// ------------------------------------
// Setter methods.
// ------------------------------------
/**
* set body detects data to response.
*
* @param response response
* @param bodyDetects body detects data.
*/
public static void setBodyDetects(final Intent response, final Bundle[] bodyDetects) {
response.putExtra(PARAM_BODYDETECTS, bodyDetects);
}
/**
* set hand detects data to response.
*
* @param response response
* @param handDetects hand detects data.
*/
public static void setHandDetects(final Intent response, final Bundle[] handDetects) {
response.putExtra(PARAM_HANDDETECTS, handDetects);
}
/**
* set face detects data to response.
*
* @param response response
* @param faceDetects face detects data.
*/
public static void setFaceDetects(final Intent response, final Bundle[] faceDetects) {
response.putExtra(PARAM_FACEDETECTS, faceDetects);
}
/**
* set normalize x value to bundle.
* @param bundle bundle
* @param normalizeX normalize X value.
*/
public static void setParamX(final Bundle bundle, final double normalizeX) {
bundle.putDouble(PARAM_X, normalizeX);
}
/**
* set normalize y value to bundle.
* @param bundle bundle
* @param normalizeY normalize Y value.
*/
public static void setParamY(final Bundle bundle, final double normalizeY) {
bundle.putDouble(PARAM_Y, normalizeY);
}
/**
* set normalize width value to bundle.
* @param bundle bundle
* @param normalizeWidth normalize width value
*/
public static void setParamWidth(final Bundle bundle, final double normalizeWidth) {
bundle.putDouble(PARAM_WIDTH, normalizeWidth);
}
/**
* set normalize height value to bundle.
* @param bundle bundle
* @param normalizeHeight normalize height value
*/
public static void setParamHeight(final Bundle bundle, final double normalizeHeight) {
bundle.putDouble(PARAM_HEIGHT, normalizeHeight);
}
/**
* set normalize confidence value to bundle.
* @param bundle bundle
* @param normalizeConfidence normalize confidence value
*/
public static void setParamConfidence(final Bundle bundle, final double normalizeConfidence) {
bundle.putDouble(PARAM_CONFIDENCE, normalizeConfidence);
}
/**
* set yaw degree value to bundle.
* @param bundle bundle
* @param yawDegree yaw Degree value.
*/
public static void setParamYaw(final Bundle bundle, final double yawDegree) {
bundle.putDouble(PARAM_YAW, yawDegree);
}
/**
* set roll degree value to bundle.
* @param bundle bundle
* @param rollDegree roll Degree value.
*/
public static void setParamRoll(final Bundle bundle, final double rollDegree) {
bundle.putDouble(PARAM_ROLL, rollDegree);
}
/**
* set pitch degree value to bundle.
* @param bundle bundle
* @param pitchDegree pitch Degree value.
*/
public static void setParamPitch(final Bundle bundle, final double pitchDegree) {
bundle.putDouble(PARAM_PITCH, pitchDegree);
}
/**
* set age value to bundle.
* @param bundle bundle
* @param age age value.
*/
public static void setParamAge(final Bundle bundle, final int age) {
bundle.putInt(PARAM_AGE, age);
}
/**
* set gender value to bundle.
* @param bundle bundle
* @param gender gender value.
*/
public static void setParamGender(final Bundle bundle, final String gender) {
bundle.putString(PARAM_GENDER, gender);
}
/**
* set gazeLR value to bundle.
* @param bundle bundle
* @param gazeLR gazeLR value.
*/
public static void setParamGazeLR(final Bundle bundle, final double gazeLR) {
bundle.putDouble(PARAM_GAZE_LR, gazeLR);
}
/**
* set gazeUD value to bundle.
* @param bundle bundle
* @param gazeUD gazeUD value.
*/
public static void setParamGazeUD(final Bundle bundle, final double gazeUD) {
bundle.putDouble(PARAM_GAZE_UD, gazeUD);
}
/**
* set left eye value to bundle.
* @param bundle bundle
* @param leftEye left eye value.
*/
public static void setParamLeftEye(final Bundle bundle, final double leftEye) {
bundle.putDouble(PARAM_LEFTEYE, leftEye);
}
/**
* set right eye value to bundle.
* @param bundle bundle
* @param rightEye right eye value.
*/
public static void setParamRightEye(final Bundle bundle, final double rightEye) {
bundle.putDouble(PARAM_RIGHTEYE, rightEye);
}
/**
* set expression value to bundle.
* @param bundle bundle
* @param expression expression value.
*/
public static void setParamExpression(final Bundle bundle, final String expression) {
bundle.putString(PARAM_EXPRESSION, expression);
}
/**
* set face direction result to bundle.
* @param bundle bundle
* @param faceDirectionResults face direction results.
*/
public static void setParamFaceDirectionResults(final Bundle bundle, final Bundle faceDirectionResults) {
bundle.putParcelable(PARAM_FACEDIRECTIONRESULTS, faceDirectionResults);
}
/**
* set age value to bundle.
* @param bundle bundle
* @param ageResults age results.
*/
public static void setParamAgeResults(final Bundle bundle, final Bundle ageResults) {
bundle.putParcelable(PARAM_AGERESULTS, ageResults);
}
/**
* set gender value to bundle.
* @param bundle bundle
* @param genderResults gender results.
*/
public static void setParamGenderResults(final Bundle bundle, final Bundle genderResults) {
bundle.putParcelable(PARAM_GENDERRESULTS, genderResults);
}
/**
* set gaze value to bundle.
* @param bundle bundle
* @param gazeResults gaze results.
*/
public static void setParamGazeResults(final Bundle bundle, final Bundle gazeResults) {
bundle.putParcelable(PARAM_GAZERESULTS, gazeResults);
}
/**
* set blink value to bundle.
* @param bundle bundle
* @param blinkResults blink results.
*/
public static void setParamBlinkResults(final Bundle bundle, final Bundle blinkResults) {
bundle.putParcelable(PARAM_BLINKRESULTS, blinkResults);
}
/**
* set expression value to bundle.
* @param bundle bundle
* @param expressionResults expression result.
*/
public static void setParamExpressionResults(final Bundle bundle, final Bundle expressionResults) {
bundle.putParcelable(PARAM_EXPRESSIONRESULTS, expressionResults);
}
/**
* check exist request data.
* @param request request
* @param param param
* @return true: exist / false: not exist
*/
private static boolean checkExistRequestData(final Intent request, final String param) {
Bundle b = request.getExtras();
return b != null && b.get(param) != null;
}
}
| 31.460085 | 120 | 0.623852 |
e66203cadcbaa0960a244b9dc69767d5f95cf3b3 | 4,400 | package com.stripe.example.activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.stripe.android.CustomerSession;
import com.stripe.android.model.Customer;
import com.stripe.android.model.Source;
import com.stripe.android.model.SourceCardData;
import com.stripe.android.view.PaymentMethodsActivity;
import com.stripe.example.R;
import com.stripe.example.controller.ErrorDialogHandler;
import com.stripe.example.service.ExampleEphemeralKeyProvider;
/**
* An example activity that handles working with a {@link CustomerSession}, allowing you to
* add and select sources for the current customer.
*/
public class CustomerSessionActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SELECT_SOURCE = 55;
private Button mSelectSourceButton;
private TextView mSelectedSourceTextView;
private ProgressBar mProgressBar;
private ErrorDialogHandler mErrorDialogHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_session);
setTitle(R.string.customer_payment_data_example);
mProgressBar = findViewById(R.id.customer_progress_bar);
mSelectedSourceTextView = findViewById(R.id.tv_customer_default_source_acs);
mSelectSourceButton = findViewById(R.id.btn_launch_payment_methods_acs);
mSelectSourceButton.setEnabled(false);
mErrorDialogHandler = new ErrorDialogHandler(getSupportFragmentManager());
CustomerSession.initCustomerSession(
new ExampleEphemeralKeyProvider(
new ExampleEphemeralKeyProvider.ProgressListener() {
@Override
public void onStringResponse(String string) {
if (string.startsWith("Error: ")) {
mErrorDialogHandler.showError(string);
}
}
}));
mProgressBar.setVisibility(View.VISIBLE);
CustomerSession.getInstance().retrieveCurrentCustomer(
new CustomerSession.CustomerRetrievalListener() {
@Override
public void onCustomerRetrieved(@NonNull Customer customer) {
mSelectSourceButton.setEnabled(true);
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onError(int errorCode, @Nullable String errorMessage) {
mSelectSourceButton.setEnabled(false);
mErrorDialogHandler.showError(errorMessage);
mProgressBar.setVisibility(View.INVISIBLE);
}
});
mSelectSourceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launchWithCustomer();
}
});
}
private void launchWithCustomer() {
Intent payIntent = PaymentMethodsActivity.newIntent(this);
startActivityForResult(payIntent, REQUEST_CODE_SELECT_SOURCE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SELECT_SOURCE && resultCode == RESULT_OK) {
String selectedSource = data.getStringExtra(PaymentMethodsActivity.EXTRA_SELECTED_PAYMENT);
Source source = Source.fromString(selectedSource);
// Note: it isn't possible for a null or non-card source to be returned.
if (source != null && Source.CARD.equals(source.getType())) {
SourceCardData cardData = (SourceCardData) source.getSourceTypeModel();
mSelectedSourceTextView.setText(buildCardString(cardData));
}
}
}
private String buildCardString(@NonNull SourceCardData data) {
return data.getBrand() + getString(R.string.ending_in) + data.getLast4();
}
}
| 42.307692 | 103 | 0.669773 |
f2fb09f31f4535a5ebfa1e107f39298298958dad | 3,135 | package unit.com.bitdubai.fermat_cry_plugin.layer.crypto_network.bitcoin.developer.bitdubai.version_1.structure.BitcoinEventListeners;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogManager;
import com.bitdubai.fermat_cry_plugin.layer.crypto_network.bitcoin.developer.bitdubai.version_1.structure.BitcoinEventListeners;
import org.bitcoinj.core.AbstractBlockChain;
import org.bitcoinj.core.AbstractBlockChain.NewBlockType;
import org.bitcoinj.core.GetDataMessage;
import org.bitcoinj.core.Message;
import org.bitcoinj.core.Peer;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Created by rodrigo on 2015.07.15..
*/
@RunWith(MockitoJUnitRunner.class)
public class GenereateEventTests {
@Mock
Transaction tx;
@Mock
StoredBlock storedBlock;
NewBlockType newBlockType;
@Mock
LogManager logManager;
@Mock
Peer peer;
@Mock
Message message;
@Mock
GetDataMessage getDataMessage;
@Mock
Sha256Hash sha256Hash;
@Test
public void testReceiveFromBlock(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
newBlockType = NewBlockType.BEST_CHAIN;
bitcoinEventListeners.receiveFromBlock(tx, storedBlock, newBlockType, 1);
}
@Test
public void testOnChainDownloadStart(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
bitcoinEventListeners.onChainDownloadStarted(peer, 2);
}
@Test
public void testOnPeerDisconected(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
bitcoinEventListeners.onPeerDisconnected(peer, 2);
}
@Test
public void testisTransactionRelevant(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
bitcoinEventListeners.isTransactionRelevant(tx);
}
@Test
public void testonPreMessageReceived(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
bitcoinEventListeners.onPreMessageReceived(peer, message);
}
@Test
public void testGetData(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
bitcoinEventListeners.getData(peer, getDataMessage);
}
@Test
public void testnotifyTransactionIsInBlock(){
BitcoinEventListeners bitcoinEventListeners = new BitcoinEventListeners();
bitcoinEventListeners.setLogManager(logManager);
bitcoinEventListeners.notifyTransactionIsInBlock(sha256Hash, storedBlock, newBlockType, 1);
}
}
| 28.761468 | 134 | 0.759171 |
7d213cef9cc4846a95544fcbd9c945bf0ac2408f | 2,618 | package jetbrains.mps.lang.behavior.migration;
/*Generated by MPS */
import jetbrains.mps.lang.migration.runtime.base.MigrationScriptBase;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.module.SModule;
import org.jetbrains.mps.openapi.module.SearchScope;
import jetbrains.mps.lang.smodel.query.runtime.CommandUtil;
import jetbrains.mps.project.EditableFilteringScope;
import jetbrains.mps.lang.smodel.query.runtime.QueryExecutionContext;
import jetbrains.mps.internal.collections.runtime.CollectionSequence;
import jetbrains.mps.internal.collections.runtime.IVisitor;
import jetbrains.mps.lang.migration.runtime.base.MigrationScriptReference;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SConcept;
import org.jetbrains.mps.openapi.language.SProperty;
public class Remove_ConceptMethodDeclaration_IsPrivate_Property extends MigrationScriptBase {
private final String description = "Remove ConceptMethodDeclaration.isPrivate property ";
public String getCaption() {
return description;
}
@Override
public boolean isRerunnable() {
return true;
}
public SNode execute(final SModule m) {
doExecute(m);
return null;
}
public void doExecute(final SModule m) {
{
SearchScope scope_65f75z_a0e = CommandUtil.createScope(m);
final SearchScope scope_65f75z_a0e_0 = new EditableFilteringScope(scope_65f75z_a0e);
QueryExecutionContext context = new QueryExecutionContext() {
public SearchScope getDefaultSearchScope() {
return scope_65f75z_a0e_0;
}
};
CollectionSequence.fromCollection(CommandUtil.instances(CommandUtil.selectScope(null, context), CONCEPTS.ConceptMethodDeclaration$N0, false)).visitAll(new IVisitor<SNode>() {
public void visit(SNode it) {
it.setProperty(PROPS.isPrivate$qveJ, null);
}
});
}
}
public MigrationScriptReference getReference() {
return new MigrationScriptReference(MetaAdapterFactory.getLanguage(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, "jetbrains.mps.lang.behavior"), 1);
}
private static final class CONCEPTS {
/*package*/ static final SConcept ConceptMethodDeclaration$N0 = MetaAdapterFactory.getConcept(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d4348057eL, "jetbrains.mps.lang.behavior.structure.ConceptMethodDeclaration");
}
private static final class PROPS {
/*package*/ static final SProperty isPrivate$qveJ = MetaAdapterFactory.getProperty(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d4348057eL, 0x11d43480581L, "isPrivate");
}
}
| 43.633333 | 222 | 0.785332 |
efd24de06cd6d1d97b80654686c5f2ba88429d61 | 809 | import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet(urlPatterns = {"/EvenNumber"})
public class EvenNumber extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
String number = request.getParameter("aNumber");
int num = Integer.parseInt(number);
if(num%2==0){
out.println("<h1>Even</h1>");
}
else{
out.println("<h1>Odd</h1>");
}
}
catch(Exception e){}
}
} | 26.966667 | 121 | 0.561187 |
7be7cf2fecf9ba65fc320855e89bdf0c742f52a8 | 2,689 | package base.dto;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Arrays;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author csieflyman
*/
public class MyConstraints {
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = EnumValidator.class)
public @interface Enumerated {
String message() default EnumValidator.messageKey;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] stringValues() default {};
int[] intValues() default {};
boolean ignoreCase() default false;
}
public static class EnumValidator extends DefaultValidator<Enumerated, Object> {
final static public String messageKey = "base.enum";
private String[] stringValues;
private int[] intValues;
private boolean ignoreCase;
public EnumValidator() {
super(messageKey);
}
@Override
public void initialize(Enumerated constraintAnnotation) {
this.stringValues = constraintAnnotation.stringValues();
this.intValues = constraintAnnotation.intValues();
this.ignoreCase = constraintAnnotation.ignoreCase();
}
@Override
public boolean isValid(Object input) {
if(input == null)
return true;
if(stringValues != null && stringValues.length > 0) {
for(String validString: stringValues) {
if(ignoreCase && validString.equalsIgnoreCase((String)input))
return true;
else if(!ignoreCase && validString.equals(input))
return true;
}
}
else if(intValues != null && intValues.length > 0) {
for(int validInteger: intValues) {
if(validInteger == (Integer)input)
return true;
}
}
String enumValues = getEnumValueString();
messageParameters.put("enumValues", enumValues);
return false;
}
private String getEnumValueString() {
String joinedValueString = "";
if(stringValues != null) {
joinedValueString = Arrays.toString(stringValues);
}
else if(intValues != null) {
joinedValueString = Arrays.toString(intValues);
}
return joinedValueString;
}
}
}
| 32.011905 | 84 | 0.584976 |
4f6a8b0f08b7372f9be1000f6d6aa5bbff025c68 | 5,804 | /*
* Copyright 2015 Rodrigo Agerri
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 eus.ixa.ixa.pipe.nerc;
import ixa.kaflib.KAFDocument;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import org.jdom2.JDOMException;
import com.google.common.io.Files;
public class TargetExtractorServer {
/**
* Get dynamically the version of ixa-pipe-nerc by looking at the MANIFEST
* file.
*/
private final String version = CLI.class.getPackage().getImplementationVersion();
/**
* Get the git commit of the ixa-pipe-nerc compiled by looking at the MANIFEST
* file.
*/
private final String commit = CLI.class.getPackage().getSpecificationVersion();
/**
* The model.
*/
private String model = null;
/**
* The annotation output format, one of NAF (default), CoNLL 2002, CoNLL 2003
* and OpenNLP.
*/
private String outputFormat = null;
/**
* Construct an OTE server.
*
* @param properties
* the properties
*/
public TargetExtractorServer(Properties properties) {
Integer port = Integer.parseInt(properties.getProperty("port"));
model = properties.getProperty("model");
outputFormat = properties.getProperty("outputFormat");
ServerSocket socketServer = null;
try {
OpinionTargetExtractor annotator = new OpinionTargetExtractor(properties);
System.out.println("-> Trying to listen port... " + port);
socketServer = new ServerSocket(port);
while (true) {
System.out.println("-> Connected and listening to port " + port);
try (Socket activeSocket = socketServer.accept();
DataInputStream inFromClient = new DataInputStream(
activeSocket.getInputStream());
DataOutputStream outToClient = new DataOutputStream(new BufferedOutputStream(
activeSocket.getOutputStream()));) {
System.out.println("-> Received a connection from: " + activeSocket);
//get data from client
String stringFromClient = getClientData(inFromClient);
// annotate
String kafToString = getAnnotations(annotator, stringFromClient);
// send to server
sendDataToServer(outToClient, kafToString);
}
}
} catch (IOException | JDOMException e) {
e.printStackTrace();
} finally {
System.out.println("closing tcp socket...");
try {
socketServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Read data from the client and output to a String.
* @param inFromClient the client inputstream
* @return the string from the client
*/
private String getClientData(DataInputStream inFromClient) {
//get data from client and build a string with it
StringBuilder stringFromClient = new StringBuilder();
try {
boolean endOfClientFile = inFromClient.readBoolean();
String line = "";
while (!endOfClientFile) {
line = inFromClient.readUTF();
stringFromClient.append(line).append("\n");
endOfClientFile = inFromClient.readBoolean();
}
}catch (IOException e) {
e.printStackTrace();
}
return stringFromClient.toString();
}
/**
* Send data back to server after annotation.
* @param outToClient the outputstream to the client
* @param kafToString the string to be processed
* @throws IOException if io error
*/
private void sendDataToServer(DataOutputStream outToClient, String kafToString) throws IOException {
byte[] kafByteArray = kafToString.getBytes("UTF-8");
outToClient.write(kafByteArray);
}
/**
* OTE annotator.
*
* @param annotator
* the annotator
* @param stringFromClient
* the string to be annotated
* @return the annotation result
* @throws IOException
* if io error
* @throws JDOMException
* if xml error
*/
private String getAnnotations(OpinionTargetExtractor annotator, String stringFromClient)
throws IOException, JDOMException {
// get a breader from the string coming from the client
BufferedReader clientReader = new BufferedReader(new StringReader(
stringFromClient));
KAFDocument kaf = KAFDocument.createFromStream(clientReader);
KAFDocument.LinguisticProcessor newLp = kaf.addLinguisticProcessor(
"entities", "ixa-pipe-nerc-" + Files.getNameWithoutExtension(model),
version + "-" + commit);
newLp.setBeginTimestamp();
annotator.annotateOTE(kaf);
newLp.setEndTimestamp();
// get outputFormat
String kafToString = null;
if (outputFormat.equalsIgnoreCase("conll03")) {
kafToString = annotator.annotateOTEsToKAF(kaf);
} else if (outputFormat.equalsIgnoreCase("conll02")) {
kafToString = annotator.annotateOTEsToKAF(kaf);
} else if (outputFormat.equalsIgnoreCase("opennlp")) {
kafToString = annotator.annotateOTEsToOpenNLP(kaf);
} else {
kafToString = annotator.annotateOTEsToKAF(kaf);
}
return kafToString;
}
}
| 32.79096 | 102 | 0.681082 |
4caad3e5121709c8eaf792cf8dce037bcdce2d6a | 320 | package com.smn.it.taotaomall.sso.util;
public class TokenUtils {
private static final String TOKEN_PREFIX="token_";
public static final long DEAFAULT_TOKEN_EXPIRED_TIME=300000;
public static String getToken(String userAccount){
return TOKEN_PREFIX+userAccount+System.currentTimeMillis();
}
}
| 26.666667 | 67 | 0.7625 |
75b86f562a393755b2687aad6366bc8454da38b5 | 11,362 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|minihms
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FSDataOutputStream
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileSystem
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|TrashPolicy
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|HiveMetaStoreClient
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|IMetaStoreClient
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|Warehouse
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|api
operator|.
name|MetaException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|metastore
operator|.
name|conf
operator|.
name|MetastoreConf
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_comment
comment|/** * The tests should use this abstract class to access the MetaStore services. * This abstract class ensures, that the same tests could be run against the different MetaStore * configurations. */
end_comment
begin_class
specifier|public
specifier|abstract
class|class
name|AbstractMetaStoreService
block|{
specifier|private
name|Configuration
name|configuration
decl_stmt|;
specifier|private
name|Warehouse
name|warehouse
decl_stmt|;
specifier|private
name|FileSystem
name|warehouseRootFs
decl_stmt|;
specifier|private
name|Path
name|trashDir
decl_stmt|;
specifier|public
name|AbstractMetaStoreService
parameter_list|(
name|Configuration
name|configuration
parameter_list|)
block|{
name|this
operator|.
name|configuration
operator|=
operator|new
name|Configuration
argument_list|(
name|configuration
argument_list|)
expr_stmt|;
block|}
comment|/** * Returns the actual configuration of the MetaStore. * @return The actual configuration */
specifier|protected
name|Configuration
name|getConfiguration
parameter_list|()
block|{
return|return
name|configuration
return|;
block|}
comment|/** * Starts the MetaStoreService. Be aware, as the current MetaStore does not implement clean * shutdown, starting MetaStoreService is possible only once per test. * * @throws Exception if any Exception occurs */
specifier|public
name|void
name|start
parameter_list|()
throws|throws
name|Exception
block|{
name|warehouse
operator|=
operator|new
name|Warehouse
argument_list|(
name|configuration
argument_list|)
expr_stmt|;
name|warehouseRootFs
operator|=
name|warehouse
operator|.
name|getFs
argument_list|(
name|warehouse
operator|.
name|getWhRoot
argument_list|()
argument_list|)
expr_stmt|;
name|TrashPolicy
name|trashPolicy
init|=
name|TrashPolicy
operator|.
name|getInstance
argument_list|(
name|configuration
argument_list|,
name|warehouseRootFs
argument_list|)
decl_stmt|;
name|trashDir
operator|=
name|trashPolicy
operator|.
name|getCurrentTrashDir
argument_list|()
expr_stmt|;
block|}
comment|/** * Starts the service with adding extra configuration to the default ones. Be aware, as the * current MetaStore does not implement clean shutdown, starting MetaStoreService is possible only * once per test. * * @param metastoreOverlay The extra metastore parameters which should be set before starting the * service * @param configurationOverlay The extra other parameters which should be set before starting the * service * @throws Exception if any Exception occurs */
specifier|public
name|void
name|start
parameter_list|(
name|Map
argument_list|<
name|MetastoreConf
operator|.
name|ConfVars
argument_list|,
name|String
argument_list|>
name|metastoreOverlay
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|configurationOverlay
parameter_list|)
throws|throws
name|Exception
block|{
comment|// Set metastoreOverlay parameters
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|MetastoreConf
operator|.
name|ConfVars
argument_list|,
name|String
argument_list|>
name|entry
range|:
name|metastoreOverlay
operator|.
name|entrySet
argument_list|()
control|)
block|{
name|MetastoreConf
operator|.
name|setVar
argument_list|(
name|configuration
argument_list|,
name|entry
operator|.
name|getKey
argument_list|()
argument_list|,
name|entry
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|// Set other configurationOverlay parameters
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|entry
range|:
name|configurationOverlay
operator|.
name|entrySet
argument_list|()
control|)
block|{
name|configuration
operator|.
name|set
argument_list|(
name|entry
operator|.
name|getKey
argument_list|()
argument_list|,
name|entry
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|// Start the service
name|start
argument_list|()
expr_stmt|;
block|}
comment|/** * Returns the MetaStoreClient for this MetaStoreService. * * @return The client connected to this service * @throws MetaException if any Exception occurs during client configuration */
specifier|public
name|IMetaStoreClient
name|getClient
parameter_list|()
throws|throws
name|MetaException
block|{
return|return
operator|new
name|HiveMetaStoreClient
argument_list|(
name|configuration
argument_list|)
return|;
block|}
comment|/** * Returns the MetaStore Warehouse root directory name. * * @return The warehouse root directory * @throws MetaException IO failure */
specifier|public
name|Path
name|getWarehouseRoot
parameter_list|()
throws|throws
name|MetaException
block|{
return|return
name|warehouse
operator|.
name|getWhRoot
argument_list|()
return|;
block|}
comment|/** * Returns the External MetaStore Warehouse root directory name. * * @return The external warehouse root directory * @throws MetaException IO failure */
specifier|public
name|Path
name|getExternalWarehouseRoot
parameter_list|()
throws|throws
name|MetaException
block|{
return|return
name|warehouse
operator|.
name|getWhRootExternal
argument_list|()
return|;
block|}
comment|/** * Check if a path exists. * * @param path The path to check * @return true if the path exists * @throws IOException IO failure */
specifier|public
name|boolean
name|isPathExists
parameter_list|(
name|Path
name|path
parameter_list|)
throws|throws
name|IOException
block|{
return|return
name|warehouseRootFs
operator|.
name|exists
argument_list|(
name|path
argument_list|)
return|;
block|}
comment|/** * Check if a path exists in the thrash directory. * * @param path The path to check * @return True if the path exists * @throws IOException IO failure */
specifier|public
name|boolean
name|isPathExistsInTrash
parameter_list|(
name|Path
name|path
parameter_list|)
throws|throws
name|IOException
block|{
name|Path
name|pathInTrash
init|=
operator|new
name|Path
argument_list|(
name|trashDir
operator|.
name|toUri
argument_list|()
operator|.
name|getScheme
argument_list|()
argument_list|,
name|trashDir
operator|.
name|toUri
argument_list|()
operator|.
name|getAuthority
argument_list|()
argument_list|,
name|trashDir
operator|.
name|toUri
argument_list|()
operator|.
name|getPath
argument_list|()
operator|+
name|path
operator|.
name|toUri
argument_list|()
operator|.
name|getPath
argument_list|()
argument_list|)
decl_stmt|;
return|return
name|isPathExists
argument_list|(
name|pathInTrash
argument_list|)
return|;
block|}
comment|/** * Creates a file on the given path. * * @param path Destination path * @param content The content of the file * @throws IOException IO failure */
specifier|public
name|void
name|createFile
parameter_list|(
name|Path
name|path
parameter_list|,
name|String
name|content
parameter_list|)
throws|throws
name|IOException
block|{
name|FSDataOutputStream
name|outputStream
init|=
name|warehouseRootFs
operator|.
name|create
argument_list|(
name|path
argument_list|)
decl_stmt|;
name|outputStream
operator|.
name|write
argument_list|(
name|content
operator|.
name|getBytes
argument_list|()
argument_list|)
expr_stmt|;
name|outputStream
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
comment|/** * Cleans the warehouse and the thrash dirs in preparation for the tests. * * @throws MetaException IO failure */
specifier|public
name|void
name|cleanWarehouseDirs
parameter_list|()
throws|throws
name|MetaException
block|{
name|warehouse
operator|.
name|deleteDir
argument_list|(
name|getWarehouseRoot
argument_list|()
argument_list|,
literal|true
argument_list|,
literal|true
argument_list|,
literal|false
argument_list|)
expr_stmt|;
name|warehouse
operator|.
name|deleteDir
argument_list|(
name|trashDir
argument_list|,
literal|true
argument_list|,
literal|true
argument_list|,
literal|false
argument_list|)
expr_stmt|;
block|}
comment|/** * Stops the MetaStoreService. When MetaStore will implement clean shutdown, this method will * call shutdown on MetaStore. Currently this does nothing :( */
specifier|public
name|void
name|stop
parameter_list|()
block|{ }
specifier|public
name|Configuration
name|getConf
parameter_list|()
block|{
return|return
name|configuration
return|;
block|}
block|}
end_class
end_unit
| 18.266881 | 813 | 0.786833 |
6fd9fc98ca5a95c35164dc5a39f20ae594a602d9 | 3,255 | /*
* Copyright 2020 Xiaomi
*
* 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.xiaomi.youpin.gwdash.bo;
import lombok.Data;
import java.util.Objects;
/**
* @author [email protected]
*/
@Data
public class ListParam {
private int pageNo;
private int pageSize;
private String urlString;
private String name;
private String pathString;
private String serviceName;
private int groupType;
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getUrlString() {
return urlString;
}
public void setUrlString(String urlString) {
this.urlString = urlString;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPathString() {
return pathString;
}
public void setPathString(String pathString) {
this.pathString = pathString;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getGroupType() {
return groupType;
}
public void setGroupType(int groupType) {
this.groupType = groupType;
}
@Override
public String toString() {
return "ListParam{" +
"pageNo=" + pageNo +
", pageSize=" + pageSize +
", urlString='" + urlString + '\'' +
", name='" + name + '\'' +
", pathString='" + pathString + '\'' +
", serviceName='" + serviceName + '\'' +
", groupType=" + groupType +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ListParam listParam = (ListParam) o;
return pageNo == listParam.pageNo &&
pageSize == listParam.pageSize &&
Objects.equals(urlString, listParam.urlString) &&
Objects.equals(name, listParam.name) &&
Objects.equals(pathString, listParam.pathString) &&
Objects.equals(serviceName, listParam.serviceName) &&
Objects.equals(groupType, listParam.groupType);
}
@Override
public int hashCode() {
return Objects.hash(pageNo, pageSize, urlString, name, pathString, serviceName, groupType);
}
}
| 24.473684 | 99 | 0.594163 |
54c4e60a40b14a2d1d6441196b31d4499388786f | 1,807 | package com.excilys.cdb.binding.utils;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAmount;
import java.util.Date;
public class DateUtils {
private static DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private DateUtils(){}
public static Timestamp stringToTimestamp(String toBeParsed) {
return Timestamp.valueOf(toBeParsed);
}
public static String stringToDateString(Timestamp toBeParsed) {
return toBeParsed.toLocalDateTime().format(dateFormatter);
}
public static Timestamp getNowTimestamp() {
LocalDateTime dateTime = LocalDateTime.now();
String textDate = dateTime.format(timestampFormatter);
LocalDateTime now = LocalDateTime.parse(textDate, timestampFormatter);
return Timestamp.valueOf(now);
}
public static Timestamp getAfterNowTimestamp(TemporalAmount amountToAdd) {
LocalDateTime dateTime = LocalDateTime.now().plus(amountToAdd);
String textDate = dateTime.format(timestampFormatter);
LocalDateTime now = LocalDateTime.parse(textDate, timestampFormatter);
return Timestamp.valueOf(now);
}
public static Timestamp getBeforeNowTimestamp(TemporalAmount amountToTake) {
LocalDateTime dateTime = LocalDateTime.now().minus(amountToTake);
String textDate = dateTime.format(timestampFormatter);
LocalDateTime now = LocalDateTime.parse(textDate, timestampFormatter);
return Timestamp.valueOf(now);
}
public static Date timestampToDate(String timeString) {
return Date.from(stringToTimestamp(timeString).toInstant());
}
}
| 31.701754 | 107 | 0.756502 |
cac5ab1d37d8271a4d0fd24f46dfb2edc58a64a1 | 4,971 | package com.krish.linked.list;
public class SinglyLinkedList {
private ListNode head;
public static void main(String[] args) {
SinglyLinkedList sll = new SinglyLinkedList();
sll.head = new ListNode(10);
ListNode second = new ListNode(6);
ListNode third = new ListNode(4);
ListNode fourth = new ListNode(1);
sll.head.next = second;
second.next = third;
third.next = fourth;
sll.display(sll.head);
System.out.println("Length = " + sll.length());
sll.addFirst(5);
sll.display(sll.head);
sll.addFirst(8);
sll.display(sll.head);
sll.addLast(19);
sll.display(sll.head);
sll.addLast(9);
sll.display(sll.head);
ListNode middelNode = sll.middleNode(sll.head);
System.out.println("Middle Node = " + middelNode.data);
System.out.println(sll.searchData(19));
System.out.println(sll.searchData(190));
int number = 2;
ListNode nthNodeFromLast = sll.nthNodeFromLast(number);
System.out.println(number + " Node from the last is = " + nthNodeFromLast.data);
int number1 = 4;
ListNode nthNodeFromLast1 = sll.nthNodeFromLast(number1);
System.out.println(number + " Node from the last is = " + nthNodeFromLast1.data);
ListNode reverse = sll.reverse(sll.head);
sll.display(reverse);
SinglyLinkedList sll1 = new SinglyLinkedList();
sll1.head = new ListNode(1);
ListNode second1 = new ListNode(8);
ListNode third1 = new ListNode(11);
ListNode fourth1 = new ListNode(16);
sll1.head.next = second1;
second1.next = third1;
third1.next = fourth1;
sll1.display(sll1.head);
ListNode resultHead = sll1.insertNodeSortedSinglyLinkedList(10);
sll1.display(resultHead);
sll1.removeKey(16);
sll1.display(sll1.head);
}
public void addFirst(int value) {
ListNode newNode = new ListNode(value);
newNode.next = head;
head = newNode;
}
public void addLast(int value) {
ListNode newNode = new ListNode(value);
if(null == head) {
head = newNode;
return;
}
ListNode current = head;
while(null != current.next) {
current = current.next;
}
current.next = newNode;
}
public boolean searchData(int data) {
if(null == head)
return false;
ListNode current = head;
while(null != current) {
if(current.data == data)
return true;
current = current.next;
}
return false;
}
public ListNode reverse(ListNode head) {
if(null == head)
return head;
ListNode current = head;
ListNode previous = null;
ListNode next = null;
while(null != current) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public ListNode middleNode(ListNode head) {
ListNode slowPointer = head;
ListNode fastPointer = head;
while(null != fastPointer && null != fastPointer.next) {
slowPointer = slowPointer.next;
fastPointer = fastPointer.next.next;
}
return slowPointer;
}
public ListNode nthNodeFromLast(int number) {
if(null == head)
return null;
if(number <= 0)
throw new IllegalArgumentException("Invalid value = " + number);
ListNode mainPointer = head;
ListNode refPointer = head;
int count = 0;
while(count < number) {
refPointer = refPointer.next;
count++;
}
while(null != refPointer) {
refPointer = refPointer.next;
mainPointer = mainPointer.next;
}
return mainPointer;
}
public ListNode insertNodeSortedSinglyLinkedList(int value) {
ListNode newNode = new ListNode(value);
if(null == head)
return newNode;
ListNode current = head;
ListNode temp = head;
while(null != current && current.data < newNode.data) {
temp = current;
current = current.next;
}
newNode.next = current;
temp.next = newNode;
return head;
}
public void removeKey(int data) {
ListNode current = head;
ListNode temp = head;
if(current != null && current.data == data) {
head = current.next;
return;
}
while(null != current && data != current.data) {
temp = current;
current = current.next;
}
if(null == current)
return;
temp.next = current.next;
}
public void display(ListNode head) {
ListNode current = head;
while(current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.print("null");
System.out.println();
}
public int length() {
ListNode current = head;
int count = 0;
if(current == null)
return count;
while(current != null) {
count++;
current = current.next;
}
return count;
}
private static class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
this.next = null;
}
}
}
| 20.886555 | 84 | 0.62241 |
bce456860d97da783581c513250f0121e331c16b | 746 | package org.zwobble.mammoth.tests.docx;
import org.zwobble.mammoth.internal.docx.FileReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import static org.zwobble.mammoth.internal.util.Maps.lookup;
public class InMemoryFileReader implements FileReader {
private final Map<String, String> entries;
public InMemoryFileReader(Map<String, String> entries) {
this.entries = entries;
}
@Override
public InputStream getInputStream(String name) throws IOException {
String value = lookup(entries, name).get();
return new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8));
}
}
| 28.692308 | 80 | 0.760054 |
c81a1777d8184a8a92b3422f08067d768f6daf8a | 28,961 | package com.luoshang.zkweb.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.luoshang.zkweb.facade.ZkManager;
import com.luoshang.zkweb.service.ZkManagerImpl.ZkConnectInfo.ZkHostPort;
public class ZkManagerImpl implements Watcher, ZkManager {
private ZooKeeper zk = null;
private ServerStatusByCMD serverStatusByCMD;
private ZkConnectInfo zkConnectInfo = new ZkConnectInfo();
private final String ROOT = "/";
private static final org.slf4j.Logger log = LoggerFactory.getLogger(ZkManagerImpl.class);
// private static final ZkManagerImpl _instance = new ZkManagerImpl();
public ZkManagerImpl() {
new ZkJMXInfo(zkConnectInfo);
serverStatusByCMD = new ServerStatusByCMD(zkConnectInfo);
}
public static ZkManagerImpl createZk() {
return new ZkManagerImpl();
}
public static class ZkConnectInfo {
private String connectStr;
private int timeout;
public static class ZkHostPort {
private String host;
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
public String getConnectStr() {
return connectStr;
}
public void setConnectStr(String connectStr) {
this.connectStr = connectStr;
}
public List<ZkHostPort> getConnectInfo() {
List<ZkHostPort> retList = new ArrayList<>();
for (String hostIp : connectStr.split(",")) {
ZkHostPort zkHostPort = new ZkHostPort();
String[] hostIpArray = hostIp.split(":");
zkHostPort.setHost(hostIpArray[0]);
if (hostIpArray.length == 1) {
zkHostPort.setPort(2181);
} else {
zkHostPort.setPort(Integer.parseInt(hostIpArray[1]));
}
retList.add(zkHostPort);
}
return retList;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
private interface ZkState {
List<PropertyPanel> state() throws IOException, MalformedObjectNameException, InstanceNotFoundException,
IntrospectionException, ReflectionException;
List<PropertyPanel> simpleState() throws IOException, MalformedObjectNameException, InstanceNotFoundException,
IntrospectionException, ReflectionException;
};
public static class ServerStatusByCMD implements ZkState {
private ZkConnectInfo zkConnectInfo;
private static final ImmutableMap<String, ImmutableList<String>> cmdKeys = new ImmutableMap.Builder<String, ImmutableList<String>>()
.put("srvr",
ImmutableList.of("Zookeeper version", "Latency min/avg/max", "Received", "Sent", "Connections",
"Outstanding", "Zxid", "Mode", "Node"))
.put("conf", ImmutableList.of()).put("cons", ImmutableList.of()).put("envi", ImmutableList.of())
.put("ruok", ImmutableList.of()).put("wchs", ImmutableList.of()).put("wchc", ImmutableList.of())
.put("wchp", ImmutableList.of()).put("mntr", ImmutableList.of()).build();
private static final ImmutableMap<String, String> cmdFindStr = new ImmutableMap.Builder<String, String>()
.put("srvr", ": ").put("conf", "=").put("cons", "(").put("envi", "=").put("ruok", "").put("wchs", "")
.put("wchc", "").put("wchp", "").put("mntr", " ").build();
public ServerStatusByCMD(ZkConnectInfo zkConnectInfo) {
this.zkConnectInfo = zkConnectInfo;
}
private List<PropertyPanel> executeOneCmdByWch(Socket sock, String cmd, String group) throws IOException {
BufferedReader reader = null;
List<PropertyPanel> retList = new ArrayList<>();
try {
reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
String lines = "";
PropertyPanel propertyPanel = new PropertyPanel();
while ((line = reader.readLine()) != null) {
List<String> keys = cmdKeys.get(cmd);
if (keys == null) {
continue;
}
lines = lines + line;
}
propertyPanel = new PropertyPanel();
propertyPanel.setInfo(cmd, lines.trim(), group);
retList.add(propertyPanel);
return retList;
} finally {
if (reader != null) {
reader.close();
}
}
}
private List<PropertyPanel> executeOneCmd(Socket sock, String cmd, String group) throws IOException {
BufferedReader reader = null;
List<PropertyPanel> retList = new ArrayList<>();
try {
reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
PropertyPanel propertyPanel = new PropertyPanel();
while ((line = reader.readLine()) != null) {
List<String> keys = cmdKeys.get(cmd);
if (keys == null) {
continue;
}
for (int i = 0; i < keys.size(); i++) {
if (cmd.equals("ruok")) {
propertyPanel = new PropertyPanel();
propertyPanel.setInfo(keys.get(i), line.trim(), group);
retList.add(propertyPanel);
continue;
}
if (cmd.equals("conf") || cmd.equals("cons") || cmd.equals("envi") || cmd.equals("mntr")) {
propertyPanel = new PropertyPanel();
String[] strArray = line.split(cmdFindStr.get(cmd));
if (cmd.equals("cons")) {
String vString = line.replaceFirst(strArray[0] + cmdFindStr.get(cmd), "").trim();
vString = vString.substring(0, vString.length() - 1);
if (vString.isEmpty()) {
continue;
}
propertyPanel.setInfo(strArray[0], vString, group);
} else {
String vString = line.replaceFirst(strArray[0] + cmdFindStr.get(cmd), "").trim();
if (vString.isEmpty()) {
continue;
}
propertyPanel.setInfo(strArray[0], vString, group);
}
retList.add(propertyPanel);
continue;
}
if (line.indexOf(keys.get(i) + cmdFindStr.get(cmd)) != -1) {
propertyPanel = new PropertyPanel();
String vString = line.replaceFirst(keys.get(i) + cmdFindStr.get(cmd), "").trim();
if (vString.isEmpty()) {
continue;
}
propertyPanel.setInfo(keys.get(i), vString, group);
retList.add(propertyPanel);
}
}
}
return retList;
} finally {
if (reader != null) {
reader.close();
}
}
}
private List<PropertyPanel> executeOneCmdSimple(Socket sock, String cmd, String group) throws IOException {
BufferedReader reader = null;
List<PropertyPanel> retList = new ArrayList<>();
try {
reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
PropertyPanel propertyPanel = new PropertyPanel();
while ((line = reader.readLine()) != null) {
List<String> keys = cmdKeys.get(cmd);
if (keys == null) {
continue;
}
for (int i = 0; i < keys.size(); i++) {
if (line.indexOf(keys.get(i) + cmdFindStr.get(cmd)) != -1) {
if (keys.get(i).equals("Mode")) {
propertyPanel = new PropertyPanel();
String vString = line.replaceFirst(keys.get(i) + cmdFindStr.get(cmd), "").trim();
if (vString.isEmpty()) {
continue;
}
propertyPanel.setInfo(keys.get(i), vString, group);
retList.add(propertyPanel);
return retList;
}
}
}
}
return retList;
} finally {
if (reader != null) {
reader.close();
}
}
}
public List<PropertyPanel> state() throws IOException, MalformedObjectNameException, InstanceNotFoundException,
IntrospectionException, ReflectionException {
return innerState(false);
}
public List<PropertyPanel> simpleState() throws MalformedObjectNameException, InstanceNotFoundException,
IntrospectionException, ReflectionException, IOException {
return innerState(true);
}
public List<PropertyPanel> innerState(boolean simpleFlag) throws IOException, MalformedObjectNameException,
InstanceNotFoundException, IntrospectionException, ReflectionException {
String host;
int port;
List<PropertyPanel> retList = new ArrayList<>();
String group;
for (ZkHostPort zkHostPort : zkConnectInfo.getConnectInfo()) {
host = zkHostPort.getHost();
port = zkHostPort.getPort();
Socket sock = null;
// cmd="srvr";
for (String cmd : cmdKeys.keySet()) {
try {
sock = new Socket(host, port);
OutputStream outstream = sock.getOutputStream();
// 通过Zookeeper的四字命令获取服务器的状态
outstream.write(cmd.getBytes());
outstream.flush();
group = host + "." + port + "." + cmd;
log.info("group=" + group);
if (simpleFlag) {
retList.addAll(executeOneCmdSimple(sock, cmd, group));
break;
} else {
if (cmd.equals("wchs") || cmd.equals("wchc") || cmd.equals("wchp")) {
retList.addAll(executeOneCmdByWch(sock, cmd, group));
} else {
retList.addAll(executeOneCmd(sock, cmd, group));
}
}
} catch (Exception e) {
sock = null;
e.printStackTrace();
log.error("zk open error for state(four cmd): echo {} |nc {} {}", cmd, host, port, e);
break;
} finally {
if (sock != null) {
// sock.shutdownOutput();
sock.close();
}
}
}
}
return retList;
}
}
public static class ZkJMXInfo {
private JMXConnector connectorJMX;
public ZkJMXInfo(ZkConnectInfo zkConnectInfo) {
}
/**
* @param args
* @throws IOException
* @throws MalformedObjectNameException
* @throws InstanceNotFoundException
* @throws ReflectionException
* @throws IntrospectionException
*/
public List<Object> state() throws IOException, MalformedObjectNameException, InstanceNotFoundException,
IntrospectionException, ReflectionException {
return innerState(false);
}
public List<Object> simpleState() throws MalformedObjectNameException, InstanceNotFoundException,
IntrospectionException, ReflectionException, IOException {
return innerState(true);
}
public List<Object> innerState(boolean simpleFlag) throws IOException, MalformedObjectNameException,
InstanceNotFoundException, IntrospectionException, ReflectionException {
List<Object> retList = new ArrayList<>();
PropertyPanel propertyPanel = new PropertyPanel();
propertyPanel.setInfo("jmx", "unsupported", "jmx");
retList.add(propertyPanel);
return retList;
/*
* OperatingSystemMXBean osbean = ManagementFactory.getOperatingSystemMXBean();
* ///TODO System.out.println("体系结构:" + osbean.getArch());//操作系统体系结构
* System.out.println("处理器核数:" + osbean.getAvailableProcessors());///核数
* System.out.println("名字:" + osbean.getName());//名字
*
* System.out.println(osbean.getVersion());//操作系统版本 ThreadMXBean
* threadBean=ManagementFactory.getThreadMXBean(); System.out.println("活动线程:" +
* threadBean.getThreadCount());//总线程数
*
* ClassLoadingMXBean classLoadingMXBean =
* ManagementFactory.getClassLoadingMXBean(); CompilationMXBean
* compilationMXBean = ManagementFactory.getCompilationMXBean();
* System.out.println("===========");
*
* // 通过 MBeanServer间接地访问 MXBean 接口 MBeanServerConnection mbsc =
* createMBeanServer("192.168.1.100", "9991", "controlRole", "123456");
*
* // 操作系统 ObjectName os = new ObjectName("java.lang:type=OperatingSystem");
* System.out.println("体系结构:" + getAttribute(mbsc, os, "Arch"));//体系结构
* System.out.println("处理器核数:" + getAttribute(mbsc, os,
* "AvailableProcessors"));//核数 System.out.println("总物理内存:" + getAttribute(mbsc,
* os, "TotalPhysicalMemorySize"));//总物理内存 System.out.println("空闲物理内存:" +
* getAttribute(mbsc, os, "FreePhysicalMemorySize"));//空闲物理内存
* System.out.println("总交换空间:" + getAttribute(mbsc, os,
* "TotalSwapSpaceSize"));//总交换空间 System.out.println("空闲交换空间:" +
* getAttribute(mbsc, os, "FreeSwapSpaceSize"));//空闲交换空间
*
* System.out.println("操作系统:" + getAttribute(mbsc, os, "Name")+
* getAttribute(mbsc, os, "Version"));//操作系统 System.out.println("提交的虚拟内存:" +
* getAttribute(mbsc, os, "CommittedVirtualMemorySize"));//提交的虚拟内存
* System.out.println("系统cpu使用率:" + getAttribute(mbsc, os,
* "SystemCpuLoad"));//系统cpu使用率 System.out.println("进程cpu使用率:" +
* getAttribute(mbsc, os, "ProcessCpuLoad"));//进程cpu使用率
*
* System.out.println("============");// // 线程 ObjectName Threading = new
* ObjectName("java.lang:type=Threading"); System.out.println("活动线程:" +
* getAttribute(mbsc, Threading, "ThreadCount"));// 活动线程
* System.out.println("守护程序线程:" + getAttribute(mbsc, Threading,
* "DaemonThreadCount"));// 守护程序线程 System.out.println("峰值:" + getAttribute(mbsc,
* Threading, "PeakThreadCount"));// 峰值 System.out.println("启动的线程总数:" +
* getAttribute(mbsc, Threading, "TotalStartedThreadCount"));// 启动的线程总数
* ThreadMXBean threadBean2 = ManagementFactory.newPlatformMXBeanProxy (mbsc,
* ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class);
* System.out.println("活动线程:" + threadBean2.getThreadCount());// 活动线程
* ThreadMXBean threadBean3 = ManagementFactory.getThreadMXBean();
* System.out.println("本地活动线程:" + threadBean3.getThreadCount());// 本地活动线程
*
* System.out.println("============");// ObjectName Compilation = new
* ObjectName("java.lang:type=Compilation"); System.out.println("总编译时间 毫秒:" +
* getAttribute(mbsc, Compilation, "TotalCompilationTime"));// 总编译时间 毫秒
*
* System.out.println("============");// ObjectName ClassLoading = new
* ObjectName("java.lang:type=ClassLoading"); System.out.println("已加载类总数:" +
* getAttribute(mbsc, ClassLoading, "TotalLoadedClassCount"));// 已加载类总数
* System.out.println("已加装当前类:" + getAttribute(mbsc, ClassLoading,
* "LoadedClassCount"));// 已加装当前类 System.out.println("已卸载类总数:" +
* getAttribute(mbsc, ClassLoading, "UnloadedClassCount"));// 已卸载类总数
*
*
* System.out.println(
* "==========================================================");// //
* http://zookeeper.apache.org/doc/r3.4.6/zookeeperJMX.html //
* org.apache.ZooKeeperService:name0=ReplicatedServer_id1,name1=replica.1,name2=
* Follower ObjectName replica = new ObjectName(
* "org.apache.ZooKeeperService:name0=ReplicatedServer_id1,name1=replica.1");
* System.out.println("replica.1运行状态:" + getAttribute(mbsc, replica,
* "State"));// 运行状态
*
* mbsc = createMBeanServer("192.168.1.100", "9992", "controlRole", "123456");
* System.out.println("==============节点树对象==========="); ObjectName
* dataTreePattern = new ObjectName(
* "org.apache.ZooKeeperService:name0=ReplicatedServer_id?,name1=replica.?,name2=*,name3=InMemoryDataTree"
* ); Set<ObjectName> dataTreeSets = mbsc.queryNames(dataTreePattern, null);
* Iterator<ObjectName> dataTreeIterator = dataTreeSets.iterator(); // 只有一个
* while (dataTreeIterator.hasNext()) { ObjectName dataTreeObjectName =
* dataTreeIterator.next(); DataTreeMXBean dataTree = JMX.newMBeanProxy(mbsc,
* dataTreeObjectName, DataTreeMXBean.class); System.out.println("节点总数:" +
* dataTree.getNodeCount());// 节点总数 System.out.println("Watch总数:" +
* dataTree.getWatchCount());// Watch总数 System.out.println("临时节点总数:" +
* dataTree.countEphemerals());// Watch总数 System.out.println("节点名及字符总数:" +
* dataTree.approximateDataSize());// 节点全路径和值的总字符数
*
* Map<String, String> dataTreeMap = dataTreeObjectName.getKeyPropertyList();
* String replicaId = dataTreeMap.get("name1").replace("replica.", ""); String
* role = dataTreeMap.get("name2");// Follower,Leader,Observer,Standalone String
* canonicalName = dataTreeObjectName.getCanonicalName(); int roleEndIndex =
* canonicalName.indexOf(",name3");
*
* ObjectName roleObjectName = new ObjectName(canonicalName.substring(0,
* roleEndIndex)); System.out.println("==============zk服务状态===========");
* ZooKeeperServerMXBean ZooKeeperServer = JMX.newMBeanProxy(mbsc,
* roleObjectName, ZooKeeperServerMXBean.class); System.out.println(role +
* " 的IP和端口:" + ZooKeeperServer.getClientPort());// IP和端口
* System.out.println(role + " 活着的连接数:" +
* ZooKeeperServer.getNumAliveConnections());// 连接数 System.out.println(role +
* " 未完成请求数:" + ZooKeeperServer.getOutstandingRequests());// 未完成的请求数
* System.out.println(role + " 接收的包:" + ZooKeeperServer.getPacketsReceived());//
* 收到的包 System.out.println(role + " 发送的包:" +
* ZooKeeperServer.getPacketsSent());// 发送的包 System.out.println(role +
* " 平均延迟(毫秒):" + ZooKeeperServer.getAvgRequestLatency());
* System.out.println(role + " 最大延迟(毫秒):" +
* ZooKeeperServer.getMaxRequestLatency());
*
* System.out.println(role + " 每个客户端IP允许的最大连接数:" +
* ZooKeeperServer.getMaxClientCnxnsPerHost()); System.out.println(role +
* " 最大Session超时(毫秒):" + ZooKeeperServer.getMaxSessionTimeout());
* System.out.println(role + " 心跳时间(毫秒):" + ZooKeeperServer.getTickTime());
* System.out.println(role + " 版本:" + ZooKeeperServer.getVersion());// 版本 //
* 三个重置操作 // ZooKeeperServer.resetLatency(); //重置min/avg/max latency statistics
* // ZooKeeperServer.resetMaxLatency(); //重置最大延迟统计 //
* ZooKeeperServer.resetStatistics(); // 重置包和延迟所有统计
*
*
* System.out.println("==============所有客户端的连接信息==========="); ObjectName
* connectionPattern = new ObjectName(
* "org.apache.ZooKeeperService:name0=ReplicatedServer_id?,name1=replica.?,name2=*,name3=Connections,*"
* ); Set<ObjectName> connectionSets = mbsc.queryNames(connectionPattern, null);
* List<ObjectName> connectionList = new
* ArrayList<ObjectName>(connectionSets.size());
* connectionList.addAll(connectionSets); Collections.sort(connectionList); for
* (ObjectName connectionON : connectionList) {
* System.out.println("========================="); ConnectionMXBean
* connectionBean = JMX.newMBeanProxy(mbsc, connectionON,
* ConnectionMXBean.class); System.out.println(" IP+Port:" +
* connectionBean.getSourceIP());// System.out.println(" SessionId:" +
* connectionBean.getSessionId());// System.out.println(" PacketsReceived:" +
* connectionBean.getPacketsReceived());// 收到的包
* System.out.println(" PacketsSent:" + connectionBean.getPacketsSent());// 发送的包
* System.out.println(" MinLatency:" + connectionBean.getMinLatency());//
* System.out.println(" AvgLatency:" + connectionBean.getAvgLatency());//
* System.out.println(" MaxLatency:" + connectionBean.getMaxLatency());//
* System.out.println(" StartedTime:" + connectionBean.getStartedTime());//
* System.out.println(" EphemeralNodes:" +
* connectionBean.getEphemeralNodes().length);//
* System.out.println(" EphemeralNodes:" +
* Arrays.asList(connectionBean.getEphemeralNodes()));//
* System.out.println(" OutstandingRequests:" +
* connectionBean.getOutstandingRequests());//
*
* //connectionBean.resetCounters(); //connectionBean.terminateConnection();
* //connectionBean.terminateSession(); } } // close connection if (connectorJMX
* != null) { connectorJMX.close(); } return retList;
*/
}
/**
* 建立连接
*
* @param ip
* @param jmxport
* @return
*/
public MBeanServerConnection createMBeanServer(String ip, String jmxport, String userName, String password) {
try {
String jmxURL = "service:jmx:rmi:///jndi/rmi://" + ip + ":" + jmxport + "/jmxrmi";
// jmxurl
JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
Map<String, String[]> map = new HashMap<String, String[]>();
String[] credentials = new String[] { userName, password };
map.put("jmx.remote.credentials", credentials);
connectorJMX = JMXConnectorFactory.connect(serviceURL, map);
MBeanServerConnection mbsc = connectorJMX.getMBeanServerConnection();
return mbsc;
} catch (IOException ioe) {
ioe.printStackTrace();
System.err.println(ip + ":" + jmxport + " 连接建立失败");
}
return null;
}
/**
* 使用MBeanServer获取对象名为[objName]的MBean的[objAttr]属性值
* <p>
* 静态代码: return MBeanServer.getAttribute(ObjectName name, String attribute)
*
* @param mbeanServer
* - MBeanServer实例
* @param objName
* - MBean的对象名
* @param objAttr
* - MBean的某个属性名
* @return 属性值
*/
@SuppressWarnings("unused")
private String getAttribute(MBeanServerConnection mbeanServer, ObjectName objName, String objAttr) {
if (mbeanServer == null || objName == null || objAttr == null)
throw new IllegalArgumentException();
try {
return String.valueOf(mbeanServer.getAttribute(objName, objAttr));
} catch (Exception e) {
return null;
}
}
}
// public boolean connect(Properties p) {
//
// try {
// return this.connect(p.getProperty(P.host.toString()), (Integer
// .valueOf(p.getProperty(P.sessionTimeOut.toString()))));
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// };
//
// private boolean connect(String host, int timeout) {
// try {
// if (null == zk) {
// zk = new ZooKeeper(host, timeout, this);
// }
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// return true;
// }
// public ZkManagerImpl connect() {
//
// try {
// Properties p = ConfigUtil.getP();
// return this.connect(p.getProperty(P.host.toString()), (Integer
// .valueOf(p.getProperty(P.sessionTimeOut.toString()))));
// } catch (Exception e) {
// e.printStackTrace();
// return this;
// }
// };
//
// public ZkManagerImpl connect(Properties p) {
//
// try {
// return this.connect(p.getProperty(P.host.toString()), (Integer
// .valueOf(p.getProperty(P.sessionTimeOut.toString()))));
// } catch (Exception e) {
// e.printStackTrace();
// return this;
// }
// };
@Override
public List<PropertyPanel> getJMXInfo(boolean simpleFlag) {
try {
if (simpleFlag)
return serverStatusByCMD.simpleState();
// return jmxInfo.state();
return serverStatusByCMD.state();
} catch (MalformedObjectNameException | InstanceNotFoundException | IntrospectionException | ReflectionException
| IOException e) {
e.printStackTrace();
}
return Collections.emptyList();
}
public ZkManagerImpl connect(String host, int timeout) {
try {
zkConnectInfo.setConnectStr(host);
zkConnectInfo.setTimeout(timeout);
if (null == zk) {
zk = new ZooKeeper(host, timeout, this);
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public boolean disconnect() {
if (zk != null) {
try {
zk.close();
zk = null;
return true;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
} else {
log.error("zk is not init");
}
return false;
};
public List<String> getChildren(String path) {
try {
return zk.getChildren(path == null ? ROOT : path, false);
} catch (Exception e) {
e.printStackTrace();
reconnect();
}
return new ArrayList<String>();
}
public String getData(String path) {
return getData(path, true);
}
public String getData(String path, boolean isPrintLog) {
try {
Stat s = zk.exists(path, false);
if (s != null) {
byte b[] = zk.getData(path, false, s);
if (null == b) {
return "";
}
String pathContent = new String(zk.getData(path, false, s));
if (isPrintLog)
log.info("data[{}] : {}", path, pathContent);
return pathContent;
}
} catch (Exception e) {
e.printStackTrace();
reconnect();
}
return null;
}
public Map<String, String> getNodeMeta(String nodePath) {
Map<String, String> nodeMeta = new LinkedHashMap<String, String>();
try {
if (nodePath.length() == 0) {
nodePath = ROOT;
}
Stat s = zk.exists(nodePath, false);
if (s != null) {
nodeMeta.put(Meta.aversion.toString(), String.valueOf(s.getAversion()));
nodeMeta.put(Meta.ctime.toString(), String.valueOf(s.getCtime()));
nodeMeta.put(Meta.cversion.toString(), String.valueOf(s.getCversion()));
nodeMeta.put(Meta.czxid.toString(), String.valueOf(s.getCzxid()));
nodeMeta.put(Meta.dataLength.toString(), String.valueOf(s.getDataLength()));
nodeMeta.put(Meta.ephemeralOwner.toString(), String.valueOf(s.getEphemeralOwner()));
nodeMeta.put(Meta.mtime.toString(), String.valueOf(s.getMtime()));
nodeMeta.put(Meta.mzxid.toString(), String.valueOf(s.getMzxid()));
nodeMeta.put(Meta.numChildren.toString(), String.valueOf(s.getNumChildren()));
nodeMeta.put(Meta.pzxid.toString(), String.valueOf(s.getPzxid()));
nodeMeta.put(Meta.version.toString(), String.valueOf(s.getVersion()));
}
} catch (Exception e) {
e.printStackTrace();
log.error("", e);
reconnect();
}
return nodeMeta;
}
public List<Map<String, String>> getACLs(String nodePath) {
List<Map<String, String>> returnACLs = new ArrayList<Map<String, String>>();
try {
if (nodePath.length() == 0) {
nodePath = ROOT;
}
Stat s = zk.exists(nodePath, false);
if (s != null) {
List<ACL> acls = zk.getACL(nodePath, s);
for (ACL acl : acls) {
Map<String, String> aclMap = new LinkedHashMap<String, String>();
aclMap.put(Acl.scheme.toString(), acl.getId().getScheme());
aclMap.put(Acl.id.toString(), acl.getId().getId());
StringBuilder sb = new StringBuilder();
int perms = acl.getPerms();
boolean addedPerm = false;
if ((perms & Perms.READ) == Perms.READ) {
sb.append("Read");
addedPerm = true;
}
if (addedPerm) {
sb.append(", ");
}
if ((perms & Perms.WRITE) == Perms.WRITE) {
sb.append("Write");
addedPerm = true;
}
if (addedPerm) {
sb.append(", ");
}
if ((perms & Perms.CREATE) == Perms.CREATE) {
sb.append("Create");
addedPerm = true;
}
if (addedPerm) {
sb.append(", ");
}
if ((perms & Perms.DELETE) == Perms.DELETE) {
sb.append("Delete");
addedPerm = true;
}
if (addedPerm) {
sb.append(", ");
}
if ((perms & Perms.ADMIN) == Perms.ADMIN) {
sb.append("Admin");
addedPerm = true;
}
aclMap.put(Acl.perms.toString(), sb.toString());
returnACLs.add(aclMap);
}
}
} catch (Exception e) {
e.printStackTrace();
log.error("", e);
reconnect();
}
return returnACLs;
}
public boolean createNode(String path, String nodeName, String data) {
try {
String p;
if (ROOT.equals(path)) {
p = path + nodeName;
} else {
p = path + "/" + nodeName;
}
Stat s = zk.exists(p, false);
if (s == null) {
zk.create(p, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
return true;
} catch (Exception e) {
e.printStackTrace();
log.error("", e);
reconnect();
}
return false;
}
public boolean deleteNode(String nodePath) {
try {
Stat s = zk.exists(nodePath, false);
if (s != null) {
List<String> children = zk.getChildren(nodePath, false);
for (String child : children) {
String node = nodePath + "/" + child;
deleteNode(node);
}
zk.delete(nodePath, -1);
}
return true;
} catch (Exception e) {
e.printStackTrace();
log.error("", e);
reconnect();
}
return false;
}
public boolean setData(String nodePath, String data) {
try {
zk.setData(nodePath, data.getBytes("utf-8"), -1);
return true;
} catch (Exception e) {
e.printStackTrace();
log.error("", e);
reconnect();
}
return false;
}
public void process(WatchedEvent arg0) {
// do nothing
}
public long getNodeId(String nodePath) {
try {
Stat s = zk.exists(nodePath, false);
if (s != null) {
return s.getPzxid();
}
} catch (Exception e) {
e.printStackTrace();
reconnect();
}
return 0l;
}
@Override
public void reconnect() {
if (zk != null) {
try {
zk.close();
} catch (Exception e) {
}
try {
zk = new ZooKeeper(this.zkConnectInfo.getConnectStr(), this.zkConnectInfo.getTimeout(), this);
} catch (Exception e) {
e.printStackTrace();
zk = null;
}
}
}
}
| 33.872515 | 134 | 0.658161 |
354a858920d720608121f92f6fd5c5a7b8650c16 | 1,096 |
package javax.servlet.http;
import java.util.EventListener;
/**
* Causes an object to be notified when it is bound to or unbound from a
* session. The object is notified by an {@link HttpSessionBindingEvent} object.
* This may be as a result of a servlet programmer explicitly unbinding an
* attribute from a session, due to a session being invalidated, or due to a
* session timing out.
*
* @see HttpSession
* @see HttpSessionBindingEvent
*/
public interface HttpSessionBindingListener extends EventListener {
/**
* Notifies the object that it is being bound to a session and identifies
* the session.
*
* @param event
* the event that identifies the session
* @see #valueUnbound
*/
public void valueBound(HttpSessionBindingEvent event);
/**
* Notifies the object that it is being unbound from a session and
* identifies the session.
*
* @param event
* the event that identifies the session
* @see #valueBound
*/
public void valueUnbound(HttpSessionBindingEvent event);
}
| 28.102564 | 80 | 0.686131 |
537ee460d19e25d15def7ea098ba162d7884901a | 3,948 | // Template Source: BaseMethodCollectionRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.KeyLongValuePair;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder;
import com.microsoft.graph.requests.MicrosoftTunnelServerGetHealthMetricsCollectionRequest;
import com.microsoft.graph.requests.MicrosoftTunnelServerGetHealthMetricsCollectionResponse;
import com.microsoft.graph.models.MicrosoftTunnelServerGetHealthMetricsParameterSet;
import com.microsoft.graph.options.FunctionOption;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseActionCollectionRequestBuilder;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Microsoft Tunnel Server Get Health Metrics Collection Request Builder.
*/
public class MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder extends BaseActionCollectionRequestBuilder<KeyLongValuePair, MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder, MicrosoftTunnelServerGetHealthMetricsCollectionResponse, MicrosoftTunnelServerGetHealthMetricsCollectionPage, MicrosoftTunnelServerGetHealthMetricsCollectionRequest> {
/**
* The request builder for this collection of MicrosoftTunnelServer
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder.class, MicrosoftTunnelServerGetHealthMetricsCollectionRequest.class);
}
private MicrosoftTunnelServerGetHealthMetricsParameterSet body;
/**
* The request builder for this collection of MicrosoftTunnelServer
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
* @param parameters the parameters for the service method
*/
public MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final MicrosoftTunnelServerGetHealthMetricsParameterSet parameters) {
super(requestUrl, client, requestOptions, MicrosoftTunnelServerGetHealthMetricsCollectionRequestBuilder.class, MicrosoftTunnelServerGetHealthMetricsCollectionRequest.class);
this.body = parameters;
}
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the MicrosoftTunnelServerGetHealthMetricsCollectionRequest instance
*/
@Override
@Nonnull
public MicrosoftTunnelServerGetHealthMetricsCollectionRequest buildRequest(@Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
final MicrosoftTunnelServerGetHealthMetricsCollectionRequest request = super.buildRequest(requestOptions);
request.body = this.body;
return request;
}
}
| 58.058824 | 366 | 0.77305 |
917aa953d7c4139df08d5692b48b015449b4f867 | 20,842 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dialer.historyitemactions;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract;
import android.support.annotation.IntDef;
import android.text.TextUtils;
import com.android.dialer.blockreportspam.BlockReportSpamDialogInfo;
import com.android.dialer.callintent.CallInitiationType;
import com.android.dialer.callintent.CallIntentBuilder;
import com.android.dialer.clipboard.ClipboardUtils;
import com.android.dialer.common.Assert;
import com.android.dialer.duo.Duo;
import com.android.dialer.duo.DuoComponent;
import com.android.dialer.logging.DialerImpression;
import com.android.dialer.logging.ReportingLocation;
import com.android.dialer.spam.Spam;
import com.android.dialer.util.CallUtil;
import com.android.dialer.util.PermissionsUtil;
import com.android.dialer.util.UriUtils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Builds a list of {@link HistoryItemActionModule HistoryItemActionModules}.
*
* <p>Example usage:
*
* <pre><code>
* // Create a HistoryItemActionModuleInfo proto with the information you have.
* // You can simply skip a field if there is no information for it.
* HistoryItemActionModuleInfo moduleInfo =
* HistoryItemActionModuleInfo.newBuilder()
* .setNormalizedNumber("+16502530000")
* .setCountryIso("US")
* .setName("Google")
* .build();
*
* // Initialize the builder using the module info above.
* // Note that some modules require an activity context to work so it is preferred to pass one
* // instead of an application context to the builder.
* HistoryItemActionModulesBuilder modulesBuilder =
* new HistoryItemActionModulesBuilder(activityContext, moduleInfo);
*
* // Add all modules you want in the order you like.
* // If a module shouldn't be added according to the module info, it won't be.
* // For example, if the module info is not for a video call and doesn't indicate the presence
* // of video calling capabilities, calling addModuleForVideoCall() is a no-op.
* modulesBuilder
* .addModuleForVoiceCall()
* .addModuleForVideoCall()
* .addModuleForSendingTextMessage()
* .addModuleForDivider()
* .addModuleForAddingToContacts()
* .addModuleForBlockedOrSpamNumber()
* .addModuleForCopyingNumber();
*
* List<HistoryItemActionModule> modules = modulesBuilder.build();
* </code></pre>
*/
public final class HistoryItemActionModulesBuilder {
/** Represents events when a module is tapped by the user. */
@Retention(RetentionPolicy.SOURCE)
@IntDef({
Event.ADD_TO_CONTACT,
Event.BLOCK_NUMBER,
Event.BLOCK_NUMBER_AND_REPORT_SPAM,
Event.REPORT_NOT_SPAM,
Event.REQUEST_CARRIER_VIDEO_CALL,
Event.REQUEST_DUO_VIDEO_CALL,
Event.REQUEST_DUO_VIDEO_CALL_FOR_NON_CONTACT,
Event.SEND_TEXT_MESSAGE,
Event.UNBLOCK_NUMBER
})
@interface Event {
int ADD_TO_CONTACT = 1;
int BLOCK_NUMBER = 2;
int BLOCK_NUMBER_AND_REPORT_SPAM = 3;
int REPORT_NOT_SPAM = 4;
int REQUEST_CARRIER_VIDEO_CALL = 5;
int REQUEST_DUO_VIDEO_CALL = 6;
int REQUEST_DUO_VIDEO_CALL_FOR_NON_CONTACT = 7;
int SEND_TEXT_MESSAGE = 8;
int UNBLOCK_NUMBER = 9;
}
/**
* Maps each {@link Event} to a {@link DialerImpression.Type} to be logged when the modules are
* hosted by the call log.
*/
private static final ImmutableMap<Integer, DialerImpression.Type> CALL_LOG_IMPRESSIONS =
new ImmutableMap.Builder<Integer, DialerImpression.Type>()
.put(Event.ADD_TO_CONTACT, DialerImpression.Type.ADD_TO_A_CONTACT_FROM_CALL_LOG)
.put(Event.BLOCK_NUMBER, DialerImpression.Type.CALL_LOG_BLOCK_NUMBER)
.put(Event.BLOCK_NUMBER_AND_REPORT_SPAM, DialerImpression.Type.CALL_LOG_BLOCK_REPORT_SPAM)
.put(Event.REPORT_NOT_SPAM, DialerImpression.Type.CALL_LOG_REPORT_AS_NOT_SPAM)
.put(
Event.REQUEST_CARRIER_VIDEO_CALL,
DialerImpression.Type.IMS_VIDEO_REQUESTED_FROM_CALL_LOG)
.put(
Event.REQUEST_DUO_VIDEO_CALL,
DialerImpression.Type.LIGHTBRINGER_VIDEO_REQUESTED_FROM_CALL_LOG)
.put(
Event.REQUEST_DUO_VIDEO_CALL_FOR_NON_CONTACT,
DialerImpression.Type.LIGHTBRINGER_NON_CONTACT_VIDEO_REQUESTED_FROM_CALL_LOG)
.put(Event.SEND_TEXT_MESSAGE, DialerImpression.Type.CALL_LOG_SEND_MESSAGE)
.put(Event.UNBLOCK_NUMBER, DialerImpression.Type.CALL_LOG_UNBLOCK_NUMBER)
.build();
private final Context context;
private final HistoryItemActionModuleInfo moduleInfo;
private final List<HistoryItemActionModule> modules;
public HistoryItemActionModulesBuilder(Context context, HistoryItemActionModuleInfo moduleInfo) {
Assert.checkArgument(
moduleInfo.getHost() != HistoryItemActionModuleInfo.Host.UNKNOWN,
"A host must be specified.");
this.context = context;
this.moduleInfo = moduleInfo;
this.modules = new ArrayList<>();
}
public List<HistoryItemActionModule> build() {
return new ArrayList<>(modules);
}
/**
* Adds a module for placing a voice call.
*
* <p>The method is a no-op if the number is blocked.
*/
public HistoryItemActionModulesBuilder addModuleForVoiceCall() {
if (moduleInfo.getIsBlocked()) {
return this;
}
// TODO(zachh): Support post-dial digits; consider using DialerPhoneNumber.
// Do not set PhoneAccountHandle so that regular PreCall logic will be used. The account used to
// place or receive the call should be ignored for voice calls.
CallIntentBuilder callIntentBuilder =
new CallIntentBuilder(moduleInfo.getNormalizedNumber(), getCallInitiationType())
.setAllowAssistedDial(moduleInfo.getCanSupportAssistedDialing());
modules.add(IntentModule.newCallModule(context, callIntentBuilder));
return this;
}
/**
* Adds a module for a carrier video call *or* a Duo video call.
*
* <p>This method is a no-op if
*
* <ul>
* <li>the call is one made to/received from an emergency number,
* <li>the call is one made to a voicemail box,
* <li>the call should be shown as spam, or
* <li>the number is blocked.
* </ul>
*
* <p>If the provided module info is for a Duo video call and Duo is available, add a Duo video
* call module.
*
* <p>If the provided module info is for a Duo video call but Duo is unavailable, add a carrier
* video call module.
*
* <p>If the provided module info is for a carrier video call, add a carrier video call module.
*
* <p>If the provided module info is for a voice call and the device has carrier video call
* capability, add a carrier video call module.
*
* <p>If the provided module info is for a voice call, the device doesn't have carrier video call
* capability, and Duo is available, add a Duo video call module.
*/
public HistoryItemActionModulesBuilder addModuleForVideoCall() {
if (moduleInfo.getIsEmergencyNumber()
|| moduleInfo.getIsVoicemailCall()
|| Spam.shouldShowAsSpam(moduleInfo.getIsSpam(), moduleInfo.getCallType())
|| moduleInfo.getIsBlocked()) {
return this;
}
// Do not set PhoneAccountHandle so that regular PreCall logic will be used. The account used to
// place or receive the call should be ignored for carrier video calls.
// TODO(a bug): figure out the correct video call behavior
CallIntentBuilder callIntentBuilder =
new CallIntentBuilder(moduleInfo.getNormalizedNumber(), getCallInitiationType())
.setAllowAssistedDial(moduleInfo.getCanSupportAssistedDialing())
.setIsVideoCall(true);
// If the module info is for a video call, add an appropriate video call module.
if ((moduleInfo.getFeatures() & Calls.FEATURES_VIDEO) == Calls.FEATURES_VIDEO) {
boolean isDuoCall = isDuoCall();
modules.add(
IntentModule.newCallModule(
context,
callIntentBuilder.setIsDuoCall(isDuoCall),
isDuoCall
? getImpressionsForDuoVideoCall()
: getImpressions(Event.REQUEST_CARRIER_VIDEO_CALL)));
return this;
}
// At this point, the module info is for an audio call. We will also add a video call module if
// the video capability is present.
//
// The carrier video call module takes precedence over the Duo module.
if (canPlaceCarrierVideoCall()) {
modules.add(
IntentModule.newCallModule(
context, callIntentBuilder, getImpressions(Event.REQUEST_CARRIER_VIDEO_CALL)));
} else if (canPlaceDuoCall()) {
modules.add(
IntentModule.newCallModule(
context, callIntentBuilder.setIsDuoCall(true), getImpressionsForDuoVideoCall()));
}
return this;
}
/**
* Returns a list of impressions to be logged when the user taps the module that attempts to
* initiate a Duo video call.
*/
private ImmutableList<DialerImpression.Type> getImpressionsForDuoVideoCall() {
return isExistingContact()
? getImpressions(Event.REQUEST_DUO_VIDEO_CALL)
: getImpressions(
Event.REQUEST_DUO_VIDEO_CALL, Event.REQUEST_DUO_VIDEO_CALL_FOR_NON_CONTACT);
}
/**
* Adds a module for sending text messages.
*
* <p>The method is a no-op if
*
* <ul>
* <li>the permission to send SMS is not granted,
* <li>the call is one made to/received from an emergency number,
* <li>the call is one made to a voicemail box,
* <li>the number is blocked, or
* <li>the number is empty.
* </ul>
*/
public HistoryItemActionModulesBuilder addModuleForSendingTextMessage() {
// TODO(zachh): There are other conditions where this module should not be shown
// (e.g., business numbers).
if (!PermissionsUtil.hasSendSmsPermissions(context)
|| moduleInfo.getIsEmergencyNumber()
|| moduleInfo.getIsVoicemailCall()
|| moduleInfo.getIsBlocked()
|| TextUtils.isEmpty(moduleInfo.getNormalizedNumber())) {
return this;
}
modules.add(
IntentModule.newModuleForSendingTextMessage(
context, moduleInfo.getNormalizedNumber(), getImpressions(Event.SEND_TEXT_MESSAGE)));
return this;
}
/**
* Adds a module for a divider.
*
* <p>The method is a no-op if the divider module will be the first module.
*/
public HistoryItemActionModulesBuilder addModuleForDivider() {
if (modules.isEmpty()) {
return this;
}
modules.add(new DividerModule());
return this;
}
/**
* Adds a module for adding a number to Contacts.
*
* <p>The method is a no-op if
*
* <ul>
* <li>the permission to write contacts is not granted,
* <li>the call is one made to/received from an emergency number,
* <li>the call is one made to a voicemail box,
* <li>the call should be shown as spam,
* <li>the number is blocked,
* <li>the number is empty, or
* <li>the number belongs to an existing contact.
* </ul>
*/
public HistoryItemActionModulesBuilder addModuleForAddingToContacts() {
if (!PermissionsUtil.hasContactsWritePermissions(context)
|| moduleInfo.getIsEmergencyNumber()
|| moduleInfo.getIsVoicemailCall()
|| Spam.shouldShowAsSpam(moduleInfo.getIsSpam(), moduleInfo.getCallType())
|| moduleInfo.getIsBlocked()
|| isExistingContact()
|| TextUtils.isEmpty(moduleInfo.getNormalizedNumber())) {
return this;
}
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, moduleInfo.getNormalizedNumber());
if (!TextUtils.isEmpty(moduleInfo.getName())) {
intent.putExtra(ContactsContract.Intents.Insert.NAME, moduleInfo.getName());
}
modules.add(
new IntentModule(
context,
intent,
R.string.add_to_contacts,
R.drawable.quantum_ic_person_add_vd_theme_24,
getImpressions(Event.ADD_TO_CONTACT)));
return this;
}
/**
* Add modules for blocking/unblocking a number and/or marking it as spam/not spam.
*
* <p>The method is a no-op if
*
* <ul>
* <li>the call is one made to/received from an emergency number, or
* <li>the call is one made to a voicemail box.
* </ul>
*
* <p>If the call should be shown as spam, add two modules:
*
* <ul>
* <li>"Not spam" and "Block", or
* <li>"Not spam" and "Unblock".
* </ul>
*
* <p>If the number is blocked but the call should not be shown as spam, add the "Unblock" module.
*
* <p>If the number is not blocked and the call should not be shown as spam, add the "Block/Report
* spam" module.
*/
public HistoryItemActionModulesBuilder addModuleForBlockedOrSpamNumber() {
if (moduleInfo.getIsEmergencyNumber() || moduleInfo.getIsVoicemailCall()) {
return this;
}
BlockReportSpamDialogInfo blockReportSpamDialogInfo =
BlockReportSpamDialogInfo.newBuilder()
.setNormalizedNumber(moduleInfo.getNormalizedNumber())
.setCountryIso(moduleInfo.getCountryIso())
.setCallType(moduleInfo.getCallType())
.setReportingLocation(getReportingLocation())
.setContactSource(moduleInfo.getContactSource())
.build();
// For a call that should be shown as spam, add two modules:
// (1) "Not spam" and "Block", or
// (2) "Not spam" and "Unblock".
if (Spam.shouldShowAsSpam(moduleInfo.getIsSpam(), moduleInfo.getCallType())) {
modules.add(
BlockReportSpamModules.moduleForMarkingNumberAsNotSpam(
context, blockReportSpamDialogInfo, getImpression(Event.REPORT_NOT_SPAM)));
modules.add(
moduleInfo.getIsBlocked()
? BlockReportSpamModules.moduleForUnblockingNumber(
context, blockReportSpamDialogInfo, getImpression(Event.UNBLOCK_NUMBER))
: BlockReportSpamModules.moduleForBlockingNumber(
context, blockReportSpamDialogInfo, getImpression(Event.BLOCK_NUMBER)));
return this;
}
// For a blocked number associated with a call that should not be shown as spam, add the
// "Unblock" module.
if (moduleInfo.getIsBlocked()) {
modules.add(
BlockReportSpamModules.moduleForUnblockingNumber(
context, blockReportSpamDialogInfo, getImpression(Event.UNBLOCK_NUMBER)));
return this;
}
// For a number that is not blocked and is associated with a call that should not be shown as
// spam, add the "Block/Report spam" module.
modules.add(
BlockReportSpamModules.moduleForBlockingNumberAndOptionallyReportingSpam(
context, blockReportSpamDialogInfo, getImpression(Event.BLOCK_NUMBER_AND_REPORT_SPAM)));
return this;
}
/**
* Adds a module for copying a number.
*
* <p>The method is a no-op if the number is empty.
*/
public HistoryItemActionModulesBuilder addModuleForCopyingNumber() {
if (TextUtils.isEmpty(moduleInfo.getNormalizedNumber())) {
return this;
}
modules.add(
new HistoryItemActionModule() {
@Override
public int getStringId() {
return R.string.copy_number;
}
@Override
public int getDrawableId() {
return R.drawable.quantum_ic_content_copy_vd_theme_24;
}
@Override
public boolean onClick() {
ClipboardUtils.copyText(
context,
/* label = */ null,
moduleInfo.getNormalizedNumber(),
/* showToast = */ true);
return false;
}
});
return this;
}
private boolean canPlaceCarrierVideoCall() {
int carrierVideoAvailability = CallUtil.getVideoCallingAvailability(context);
boolean isCarrierVideoCallingEnabled =
((carrierVideoAvailability & CallUtil.VIDEO_CALLING_ENABLED)
== CallUtil.VIDEO_CALLING_ENABLED);
boolean canRelyOnCarrierVideoPresence =
((carrierVideoAvailability & CallUtil.VIDEO_CALLING_PRESENCE)
== CallUtil.VIDEO_CALLING_PRESENCE);
return isCarrierVideoCallingEnabled
&& canRelyOnCarrierVideoPresence
&& moduleInfo.getCanSupportCarrierVideoCall();
}
private boolean isDuoCall() {
return DuoComponent.get(context)
.getDuo()
.isDuoAccount(moduleInfo.getPhoneAccountComponentName());
}
private boolean canPlaceDuoCall() {
Duo duo = DuoComponent.get(context).getDuo();
return duo.isInstalled(context)
&& duo.isEnabled(context)
&& duo.isActivated(context)
&& duo.isReachable(context, moduleInfo.getNormalizedNumber());
}
/**
* Lookup URIs are currently fetched from the cached column of the system call log. This URI
* contains encoded information for non-contacts for the purposes of populating contact cards.
*
* <p>We infer whether a contact is existing or not by checking if the lookup URI is "encoded" or
* not.
*
* <p>TODO(zachh): We should revisit this once the contact URI is no longer being read from the
* cached column in the system database, in case we decide not to overload the column.
*/
private boolean isExistingContact() {
return !TextUtils.isEmpty(moduleInfo.getLookupUri())
&& !UriUtils.isEncodedContactUri(Uri.parse(moduleInfo.getLookupUri()));
}
/**
* Maps the value of {@link HistoryItemActionModuleInfo#getHost()} to {@link
* CallInitiationType.Type}, which is required by {@link CallIntentBuilder} to build a call
* intent.
*/
private CallInitiationType.Type getCallInitiationType() {
switch (moduleInfo.getHost()) {
case CALL_LOG:
return CallInitiationType.Type.CALL_LOG;
case VOICEMAIL:
return CallInitiationType.Type.VOICEMAIL_LOG;
default:
throw Assert.createUnsupportedOperationFailException(
String.format("Unsupported host: %s", moduleInfo.getHost()));
}
}
/**
* Maps the value of {@link HistoryItemActionModuleInfo#getHost()} to {@link
* ReportingLocation.Type}, which is for logging where a spam number is reported.
*/
private ReportingLocation.Type getReportingLocation() {
switch (moduleInfo.getHost()) {
case CALL_LOG:
return ReportingLocation.Type.CALL_LOG_HISTORY;
case VOICEMAIL:
return ReportingLocation.Type.VOICEMAIL_HISTORY;
default:
throw Assert.createUnsupportedOperationFailException(
String.format("Unsupported host: %s", moduleInfo.getHost()));
}
}
/** Returns a list of impressions to be logged for the given {@link Event events}. */
private ImmutableList<DialerImpression.Type> getImpressions(@Event int... events) {
Assert.isNotNull(events);
ImmutableList.Builder<DialerImpression.Type> impressionListBuilder =
new ImmutableList.Builder<>();
for (@Event int event : events) {
getImpression(event).ifPresent(impressionListBuilder::add);
}
return impressionListBuilder.build();
}
/**
* Returns an impression to be logged for the given {@link Event}, or {@link Optional#empty()} if
* no impression is available for the event.
*/
private Optional<DialerImpression.Type> getImpression(@Event int event) {
switch (moduleInfo.getHost()) {
case CALL_LOG:
return Optional.of(CALL_LOG_IMPRESSIONS.get(event));
case VOICEMAIL:
// TODO(a bug): Return proper impressions for voicemail.
return Optional.empty();
default:
throw Assert.createUnsupportedOperationFailException(
String.format("Unsupported host: %s", moduleInfo.getHost()));
}
}
}
| 37.688969 | 100 | 0.691968 |
0ca87a645490454e57bfdfc3ce95a669956d78f8 | 3,904 | // BEGIN LICENSE BLOCK
// Version: CMPL 1.1
//
// The contents of this file are subject to the Cisco-style Mozilla Public
// License Version 1.1 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License
// at www.eclipse-clp.org/license.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is The ECLiPSe Constraint Logic Programming System.
// The Initial Developer of the Original Code is Cisco Systems, Inc.
// Portions created by the Initial Developer are
// Copyright (C) 2006 Cisco Systems, Inc. All Rights Reserved.
//
// Contributor(s):
//
// END LICENSE BLOCK
package com.parctechnologies.eclipse.visualisation.viewers;
import com.parctechnologies.eclipse.*;
import com.parctechnologies.eclipse.visualisation.*;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.*;
import java.awt.Color;
import java.awt.Component;
import java.util.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.*;
import att.grappa.*;
public class CustRenderer extends GrappaShape implements CustomRenderer {
/** Stores copy of element for which this Custom Renderer was
created */
protected Element element;
/**
* This constructor is called by the GrappaNexus updateShape method */
public CustRenderer(Element element,
double x, double y, double w, double h) {
super(CUSTOM_SHAPE, x+(w/2), y+(h/2), w, h,
4,
1,
0.0,
0.0,
0.0,
false,
false,
null);
this.element = element;
}
/**
* Retrieves the viewletData which this renderer must display.
*
* <p> Requires that element.object is a two element array
* containing the ContainerViewer and the element index for this
* viewlet.
**/
public ViewletData getViewletData() {
return (ViewletData)element.object;
}
/**
* The method called when the element needs to be drawn.
* When used with an extention of <i>GrappaShape</i>,
* the default behavior is obtained by:
* <pre>
* public void draw(java.awt.Graphics2D g2d) {
* g2d.draw(this);
* }
* </pre>
*
* @param g2d the Graphics2D context to be used for drawing
*/
public void draw(java.awt.Graphics2D g2d) {
g2d.draw(this);
}
/**
* The method called when the element needs to be filled.
* When used with an extention of <i>GrappaShape</i>,
* the default behavior is obtained by:
* <pre>
* public void fill(java.awt.Graphics2D g2d) {
* g2d.fill(this);
* }
* </pre>
*
* @param g2d the Graphics2D context to be used for drawing
*/
public void fill(java.awt.Graphics2D g2d) {
g2d.fill(this);
}
/**
* The method called when the element needs to draw its background
* image.
* When used with an extention of <i>GrappaShape</i> that provides
* the underlying element as a global variable, the default behavior
* is obtained by:
* <pre>
* public void drawImage(java.awt.Graphics2D g2d) {
* Rectangle sbox = this.getBounds();
* Shape clip = g2d.getClip();
* g2d.clip(this);
* g2d.drawImage(element.getGrappaNexus().getImage(), sbox.x, sbox.y, sbox.width, sbox.height, null);
* g2d.setClip(clip);
* }
* </pre>
*
* @param g2d the Graphics2D context to be used for drawing
*/
public void drawImage(java.awt.Graphics2D g2d) {
Rectangle sbox = this.getBounds();
Shape clip = g2d.getClip();
g2d.clip(this);
g2d.drawImage(element.getGrappaNexus().getImage(),
sbox.x, sbox.y, sbox.width, sbox.height, null);
g2d.setClip(clip);
}
}
| 30.030769 | 105 | 0.663934 |
80d70776de24fa0e8e770dd7a352525ecefc1c4f | 1,765 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.repo.mysql.handler;
import com.alibaba.polardbx.executor.utils.ExecUtils;
import com.alibaba.polardbx.optimizer.config.table.ColumnMeta;
import com.alibaba.polardbx.optimizer.utils.CalciteUtils;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.logical.LogicalValues;
import com.alibaba.polardbx.optimizer.context.ExecutionContext;
import com.alibaba.polardbx.executor.cursor.Cursor;
import com.alibaba.polardbx.executor.cursor.impl.LogicalValueCursor;
import com.alibaba.polardbx.executor.handler.HandlerCommon;
import java.util.List;
/**
* Created by chuanqin on 17/7/13.
*/
public class LogicalValueHandler extends HandlerCommon {
public LogicalValueHandler() {
super(null);
}
@Override
public Cursor handle(RelNode logicalPlan, ExecutionContext executionContext) {
LogicalValues logicalValues = (LogicalValues) logicalPlan;
int count = ExecUtils.getTupleCount(logicalValues, executionContext);
List<ColumnMeta> columns = CalciteUtils.buildColumnMeta(logicalPlan, "Value");
return new LogicalValueCursor(count, columns);
}
}
| 36.020408 | 86 | 0.766572 |
2697e9a5ca6443ad044448a3d9dcbe9ad0b43414 | 111,429 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.inventario.presentation.swing.jinternalframes;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.inventario.presentation.web.jsf.sessionbean.*;//;
import com.bydan.erp.inventario.presentation.swing.jinternalframes.*;
import com.bydan.erp.inventario.presentation.swing.jinternalframes.auxiliar.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
//import com.bydan.erp.inventario.presentation.report.source.*;
import com.bydan.framework.erp.business.entity.Reporte;
import com.bydan.erp.seguridad.business.entity.Modulo;
import com.bydan.erp.seguridad.business.entity.Opcion;
import com.bydan.erp.seguridad.business.entity.Usuario;
import com.bydan.erp.seguridad.business.entity.ResumenUsuario;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario;
import com.bydan.erp.seguridad.util.SistemaParameterReturnGeneral;
import com.bydan.erp.inventario.business.entity.*;
import com.bydan.erp.inventario.util.PresupuestoLineaConstantesFunciones;
import com.bydan.erp.inventario.business.logic.*;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.OrderBy;
import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverter;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate;
import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing;
import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase;
import com.bydan.framework.erp.presentation.desktop.swing.*;
import com.bydan.framework.erp.util.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.TableColumn;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("unused")
public class PresupuestoLineaDetalleFormJInternalFrame extends PresupuestoLineaBeanSwingJInternalFrameAdditional {
private static final long serialVersionUID = 1L;
public JToolBar jTtoolBarDetallePresupuestoLinea;
protected JMenuBar jmenuBarDetallePresupuestoLinea;
protected JMenu jmenuDetallePresupuestoLinea;
protected JMenu jmenuDetalleArchivoPresupuestoLinea;
protected JMenu jmenuDetalleAccionesPresupuestoLinea;
protected JMenu jmenuDetalleDatosPresupuestoLinea;
protected JPanel jContentPane = null;
protected JPanel jContentPaneDetallePresupuestoLinea = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
protected GridBagLayout gridaBagLayoutPresupuestoLinea;
protected GridBagConstraints gridBagConstraintsPresupuestoLinea;
//protected JInternalFrameBase jInternalFrameParent; //ESTA EN BASE
//protected PresupuestoLineaBeanSwingJInternalFrameAdditional jInternalFrameDetallePresupuestoLinea;
//VENTANAS PARA ACTUALIZAR Y BUSCAR FK
protected EmpresaBeanSwingJInternalFrame empresaBeanSwingJInternalFrame;
public String sFinalQueryGeneral_empresa="";
protected LineaBeanSwingJInternalFrame lineaBeanSwingJInternalFrame;
public String sFinalQueryGeneral_linea="";
public PresupuestoLineaSessionBean presupuestolineaSessionBean;
public EmpresaSessionBean empresaSessionBean;
public LineaSessionBean lineaSessionBean;
public PresupuestoLineaLogic presupuestolineaLogic;
public JScrollPane jScrollPanelDatosPresupuestoLinea;
public JScrollPane jScrollPanelDatosEdicionPresupuestoLinea;
public JScrollPane jScrollPanelDatosGeneralPresupuestoLinea;
protected JPanel jPanelCamposPresupuestoLinea;
protected JPanel jPanelCamposOcultosPresupuestoLinea;
protected JPanel jPanelAccionesPresupuestoLinea;
protected JPanel jPanelAccionesFormularioPresupuestoLinea;
protected Integer iXPanelCamposPresupuestoLinea=0;
protected Integer iYPanelCamposPresupuestoLinea=0;
protected Integer iXPanelCamposOcultosPresupuestoLinea=0;
protected Integer iYPanelCamposOcultosPresupuestoLinea=0;
;
;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
public JButton jButtonNuevoPresupuestoLinea;
public JButton jButtonModificarPresupuestoLinea;
public JButton jButtonActualizarPresupuestoLinea;
public JButton jButtonEliminarPresupuestoLinea;
public JButton jButtonCancelarPresupuestoLinea;
public JButton jButtonGuardarCambiosPresupuestoLinea;
public JButton jButtonGuardarCambiosTablaPresupuestoLinea;
protected JButton jButtonCerrarPresupuestoLinea;
protected JButton jButtonProcesarInformacionPresupuestoLinea;
protected JCheckBox jCheckBoxPostAccionNuevoPresupuestoLinea;
protected JCheckBox jCheckBoxPostAccionSinCerrarPresupuestoLinea;
protected JCheckBox jCheckBoxPostAccionSinMensajePresupuestoLinea;
//TOOLBAR
protected JButton jButtonNuevoToolBarPresupuestoLinea;
protected JButton jButtonModificarToolBarPresupuestoLinea;
protected JButton jButtonActualizarToolBarPresupuestoLinea;
protected JButton jButtonEliminarToolBarPresupuestoLinea;
protected JButton jButtonCancelarToolBarPresupuestoLinea;
protected JButton jButtonGuardarCambiosToolBarPresupuestoLinea;
protected JButton jButtonGuardarCambiosTablaToolBarPresupuestoLinea;
protected JButton jButtonMostrarOcultarTablaToolBarPresupuestoLinea;
protected JButton jButtonCerrarToolBarPresupuestoLinea;
protected JButton jButtonProcesarInformacionToolBarPresupuestoLinea;
//TOOLBAR
//MENU
protected JMenuItem jMenuItemNuevoPresupuestoLinea;
protected JMenuItem jMenuItemModificarPresupuestoLinea;
protected JMenuItem jMenuItemActualizarPresupuestoLinea;
protected JMenuItem jMenuItemEliminarPresupuestoLinea;
protected JMenuItem jMenuItemCancelarPresupuestoLinea;
protected JMenuItem jMenuItemGuardarCambiosPresupuestoLinea;
protected JMenuItem jMenuItemGuardarCambiosTablaPresupuestoLinea;
protected JMenuItem jMenuItemCerrarPresupuestoLinea;
protected JMenuItem jMenuItemDetalleCerrarPresupuestoLinea;
protected JMenuItem jMenuItemDetalleMostarOcultarPresupuestoLinea;
protected JMenuItem jMenuItemProcesarInformacionPresupuestoLinea;
protected JMenuItem jMenuItemNuevoGuardarCambiosPresupuestoLinea;
protected JMenuItem jMenuItemMostrarOcultarPresupuestoLinea;
//MENU
protected JLabel jLabelAccionesPresupuestoLinea;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposRelacionesPresupuestoLinea;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposAccionesPresupuestoLinea;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxTiposAccionesFormularioPresupuestoLinea;
protected Boolean conMaximoRelaciones=true;
protected Boolean conFuncionalidadRelaciones=true;
public Boolean conCargarMinimo=false;
public Boolean conMostrarAccionesCampo=false;
public Boolean permiteRecargarForm=false;//PARA NUEVO PREPARAR Y MANEJO DE EVENTOS, EVITAR QUE SE EJECUTE AL CARGAR VENTANA O LOAD
public Boolean conCargarFormDetalle=false;
public JPanel jPanelidPresupuestoLinea;
public JLabel jLabelIdPresupuestoLinea;
public JLabel jLabelidPresupuestoLinea;
public JButton jButtonidPresupuestoLineaBusqueda= new JButtonMe();
public JPanel jPanelmargenPresupuestoLinea;
public JLabel jLabelmargenPresupuestoLinea;
public JTextField jTextFieldmargenPresupuestoLinea;
public JButton jButtonmargenPresupuestoLineaBusqueda= new JButtonMe();
public JPanel jPaneldescuentoPresupuestoLinea;
public JLabel jLabeldescuentoPresupuestoLinea;
public JTextField jTextFielddescuentoPresupuestoLinea;
public JButton jButtondescuentoPresupuestoLineaBusqueda= new JButtonMe();
public JPanel jPaneles_para_presupuestoPresupuestoLinea;
public JLabel jLabeles_para_presupuestoPresupuestoLinea;
public JCheckBox jCheckBoxes_para_presupuestoPresupuestoLinea;
public JButton jButtones_para_presupuestoPresupuestoLineaBusqueda= new JButtonMe();
public JPanel jPanelid_empresaPresupuestoLinea;
public JLabel jLabelid_empresaPresupuestoLinea;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxid_empresaPresupuestoLinea;
public JButton jButtonid_empresaPresupuestoLinea= new JButtonMe();
public JButton jButtonid_empresaPresupuestoLineaUpdate= new JButtonMe();
public JButton jButtonid_empresaPresupuestoLineaBusqueda= new JButtonMe();
public JPanel jPanelid_lineaPresupuestoLinea;
public JLabel jLabelid_lineaPresupuestoLinea;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxid_lineaPresupuestoLinea;
public JButton jButtonid_lineaPresupuestoLinea= new JButtonMe();
public JButton jButtonid_lineaPresupuestoLineaUpdate= new JButtonMe();
public JButton jButtonid_lineaPresupuestoLineaBusqueda= new JButtonMe();
public JButton jButtonid_lineaPresupuestoLineaArbol= new JButtonMe();
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
protected JTabbedPane jTabbedPaneRelacionesPresupuestoLinea;
public static int openFrameCount = 0;
public static final int xOffset = 10, yOffset = 35;
//LOS DATOS DE NUEVO Y EDICION ACTUAL APARECEN EN OTRA VENTANA(true) O NO(false)
public static Boolean CON_DATOS_FRAME=true;
public static Boolean ISBINDING_MANUAL=true;
public static Boolean ISLOAD_FKLOTE=true;
public static Boolean ISBINDING_MANUAL_TABLA=true;
public static Boolean CON_CARGAR_MEMORIA_INICIAL=true;
//Al final no se utilizan, se inicializan desde JInternalFrameBase, desde ParametroGeneralUsuario
public static String STIPO_TAMANIO_GENERAL="NORMAL";
public static String STIPO_TAMANIO_GENERAL_TABLA="NORMAL";
public static Boolean CONTIPO_TAMANIO_MANUAL=false;
public static Boolean CON_LLAMADA_SIMPLE=true;
public static Boolean CON_LLAMADA_SIMPLE_TOTAL=true;
public static Boolean ESTA_CARGADO_PORPARTE=false;
public int iWidthScroll=0;//(screenSize.width-screenSize.width/2)+(250*0);
public int iHeightScroll=0;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
public int iWidthFormulario=515;//(screenSize.width-screenSize.width/2)+(250*0);
public int iHeightFormulario=330;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
public int iHeightFormularioMaximo=0;
public int iWidthFormularioMaximo=0;
public int iWidthTableDefinicion=0;
public double dStart = 0;
public double dEnd = 0;
public double dDif = 0;
public SistemaParameterReturnGeneral sistemaReturnGeneral;
public List<Opcion> opcionsRelacionadas=new ArrayList<Opcion>();
public PresupuestoLineaDetalleFormJInternalFrame(String sTipo) throws Exception {
super(PaginaTipo.FORMULARIO);
try {
if(sTipo.equals("MINIMO")) {
/*
this.jPanelCamposPresupuestoLinea=new JPanel();
this.jPanelAccionesFormularioPresupuestoLinea=new JPanel();
this.jmenuBarDetallePresupuestoLinea=new JMenuBar();
this.jTtoolBarDetallePresupuestoLinea=new JToolBar();
*/
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public PresupuestoLineaDetalleFormJInternalFrame(PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("PresupuestoLinea No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
Boolean cargarRelaciones=false;
this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
//ES AUXILIAR PARA WINDOWS FORMS
public PresupuestoLineaDetalleFormJInternalFrame() throws Exception {
super(PaginaTipo.FORMULARIO);
//super("PresupuestoLinea No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
Boolean cargarRelaciones=false;
this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public PresupuestoLineaDetalleFormJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("PresupuestoLinea No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public PresupuestoLineaDetalleFormJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("PresupuestoLinea No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
this.initialize(null,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public PresupuestoLineaDetalleFormJInternalFrame(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);//,jdesktopPane
this.jDesktopPane=jdesktopPane;
this.dStart=(double)System.currentTimeMillis();
//super("PresupuestoLinea No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
long start_time=0;
long end_time=0;
if(Constantes2.ISDEVELOPING2) {
start_time = System.currentTimeMillis();
}
this.initialize(jdesktopPane,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
if(Constantes2.ISDEVELOPING2) {
end_time = System.currentTimeMillis();
String sTipo="Clase Padre Ventana";
Funciones2.getMensajeTiempoEjecucion(start_time, end_time, sTipo,false);
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public JInternalFrameBase getJInternalFrameParent() {
return jInternalFrameParent;
}
public void setJInternalFrameParent(JInternalFrameBase internalFrameParent) {
jInternalFrameParent = internalFrameParent;
}
public JButton getjButtonActualizarToolBarPresupuestoLinea() {
return this.jButtonActualizarToolBarPresupuestoLinea;
}
public JButton getjButtonEliminarToolBarPresupuestoLinea() {
return this.jButtonEliminarToolBarPresupuestoLinea;
}
public JButton getjButtonCancelarToolBarPresupuestoLinea() {
return this.jButtonCancelarToolBarPresupuestoLinea;
}
public JButton getjButtonProcesarInformacionPresupuestoLinea() {
return this.jButtonProcesarInformacionPresupuestoLinea;
}
public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionPresupuestoLinea) {
this.jButtonProcesarInformacionPresupuestoLinea = jButtonProcesarInformacionPresupuestoLinea;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesPresupuestoLinea() {
return this.jComboBoxTiposAccionesPresupuestoLinea;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposRelacionesPresupuestoLinea(
JComboBox jComboBoxTiposRelacionesPresupuestoLinea) {
this.jComboBoxTiposRelacionesPresupuestoLinea = jComboBoxTiposRelacionesPresupuestoLinea;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesPresupuestoLinea(
JComboBox jComboBoxTiposAccionesPresupuestoLinea) {
this.jComboBoxTiposAccionesPresupuestoLinea = jComboBoxTiposAccionesPresupuestoLinea;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesFormularioPresupuestoLinea() {
return this.jComboBoxTiposAccionesFormularioPresupuestoLinea;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesFormularioPresupuestoLinea(
JComboBox jComboBoxTiposAccionesFormularioPresupuestoLinea) {
this.jComboBoxTiposAccionesFormularioPresupuestoLinea = jComboBoxTiposAccionesFormularioPresupuestoLinea;
}
private void initialize(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
this.presupuestolineaSessionBean=new PresupuestoLineaSessionBean();
this.presupuestolineaSessionBean.setConGuardarRelaciones(conGuardarRelaciones);
this.presupuestolineaSessionBean.setEsGuardarRelacionado(esGuardarRelacionado);
this.conCargarMinimo=this.presupuestolineaSessionBean.getEsGuardarRelacionado();
this.conMostrarAccionesCampo=parametroGeneralUsuario.getcon_mostrar_acciones_campo_general() || opcionActual.getcon_mostrar_acciones_campo();
if(!this.conCargarMinimo) {
}
this.sTipoTamanioGeneral=FuncionesSwing.getTipoTamanioGeneral(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.sTipoTamanioGeneralTabla=FuncionesSwing.getTipoTamanioGeneralTabla(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioManual=FuncionesSwing.getConTipoTamanioManual(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioTodo=FuncionesSwing.getConTipoTamanioTodo(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
PresupuestoLineaJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral;
PresupuestoLineaJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla;
PresupuestoLineaJInternalFrame.CONTIPO_TAMANIO_MANUAL=this.conTipoTamanioManual;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidth=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
int iHeight=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.opcionActual,this.usuarioActual,"Presupuesto Linea MANTENIMIENTO"));
if(iWidth > 650) {
iWidth=650;
}
if(iHeight > 660) {
iHeight=660;
}
this.setSize(iWidth,iHeight);
this.setFrameIcon(new ImageIcon(FuncionesSwing.getImagenBackground(Constantes2.S_ICON_IMAGE)));
this.setContentPane(this.getJContentPane(iWidth,iHeight,jdesktopPane,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo));
if(!this.presupuestolineaSessionBean.getEsGuardarRelacionado()) {
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
this.iconable=true;
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
if(Constantes.CON_VARIAS_VENTANAS) {
openFrameCount++;
if(openFrameCount==Constantes.INUM_MAX_VENTANAS) {
openFrameCount=0;
}
}
}
PresupuestoLineaJInternalFrame.ESTA_CARGADO_PORPARTE=true;
}
public void inicializarToolBar() {
this.jTtoolBarDetallePresupuestoLinea= new JToolBar("MENU DATOS");
//TOOLBAR
//PRINCIPAL
this.jButtonProcesarInformacionToolBarPresupuestoLinea=new JButtonMe();
this.jButtonModificarToolBarPresupuestoLinea=new JButtonMe();
//PRINCIPAL
//DETALLE
this.jButtonActualizarToolBarPresupuestoLinea=FuncionesSwing.getButtonToolBarGeneral(this.jButtonActualizarToolBarPresupuestoLinea,this.jTtoolBarDetallePresupuestoLinea,
"actualizar","actualizar","Actualizar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"),"Actualizar",false);
this.jButtonEliminarToolBarPresupuestoLinea=FuncionesSwing.getButtonToolBarGeneral(this.jButtonEliminarToolBarPresupuestoLinea,this.jTtoolBarDetallePresupuestoLinea,
"eliminar","eliminar","Eliminar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"),"Eliminar",false);
this.jButtonCancelarToolBarPresupuestoLinea=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCancelarToolBarPresupuestoLinea,this.jTtoolBarDetallePresupuestoLinea,
"cancelar","cancelar","Cancelar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"),"Cancelar",false);
this.jButtonGuardarCambiosToolBarPresupuestoLinea=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosToolBarPresupuestoLinea,this.jTtoolBarDetallePresupuestoLinea,
"guardarcambios","guardarcambios","Guardar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false);
FuncionesSwing.setBoldButtonToolBar(this.jButtonActualizarToolBarPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButtonToolBar(this.jButtonEliminarToolBarPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButtonToolBar(this.jButtonCancelarToolBarPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
}
public void cargarMenus() {
this.jmenuBarDetallePresupuestoLinea=new JMenuBarMe();
//DETALLE
this.jmenuDetallePresupuestoLinea=new JMenuMe("Datos Relacionados");
this.jmenuDetalleArchivoPresupuestoLinea=new JMenuMe("Archivo");
this.jmenuDetalleAccionesPresupuestoLinea=new JMenuMe("Acciones");
this.jmenuDetalleDatosPresupuestoLinea=new JMenuMe("Datos");
//DETALLE_FIN
this.jMenuItemNuevoPresupuestoLinea= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jMenuItemNuevoPresupuestoLinea.setActionCommand("Nuevo");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoPresupuestoLinea,"nuevo_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemModificarPresupuestoLinea= new JMenuItem("Editar" + FuncionesSwing.getKeyMensaje("MODIFICAR"));
this.jMenuItemModificarPresupuestoLinea.setActionCommand("Editar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemModificarPresupuestoLinea,"modificar_button","Editar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemModificarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemActualizarPresupuestoLinea= new JMenuItem("Actualizar" + FuncionesSwing.getKeyMensaje("ACTUALIZAR"));
this.jMenuItemActualizarPresupuestoLinea.setActionCommand("Actualizar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemActualizarPresupuestoLinea,"actualizar_button","Actualizar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemActualizarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemEliminarPresupuestoLinea= new JMenuItem("Eliminar" + FuncionesSwing.getKeyMensaje("ELIMINAR"));
this.jMenuItemEliminarPresupuestoLinea.setActionCommand("Eliminar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemEliminarPresupuestoLinea,"eliminar_button","Eliminar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemEliminarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCancelarPresupuestoLinea= new JMenuItem("Cancelar" + FuncionesSwing.getKeyMensaje("CANCELAR"));
this.jMenuItemCancelarPresupuestoLinea.setActionCommand("Cancelar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCancelarPresupuestoLinea,"cancelar_button","Cancelar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCancelarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosPresupuestoLinea= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosPresupuestoLinea.setActionCommand("Guardar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosPresupuestoLinea,"guardarcambios_button","Guardar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCerrarPresupuestoLinea= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemCerrarPresupuestoLinea.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarPresupuestoLinea,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleCerrarPresupuestoLinea= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemDetalleCerrarPresupuestoLinea.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleCerrarPresupuestoLinea,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleCerrarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemMostrarOcultarPresupuestoLinea= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemMostrarOcultarPresupuestoLinea.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarPresupuestoLinea,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleMostarOcultarPresupuestoLinea= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemDetalleMostarOcultarPresupuestoLinea.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarPresupuestoLinea,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
//DETALLE
this.jmenuDetalleArchivoPresupuestoLinea.add(this.jMenuItemDetalleCerrarPresupuestoLinea);
this.jmenuDetalleAccionesPresupuestoLinea.add(this.jMenuItemActualizarPresupuestoLinea);
this.jmenuDetalleAccionesPresupuestoLinea.add(this.jMenuItemEliminarPresupuestoLinea);
this.jmenuDetalleAccionesPresupuestoLinea.add(this.jMenuItemCancelarPresupuestoLinea);
//this.jmenuDetalleDatosPresupuestoLinea.add(this.jMenuItemDetalleAbrirOrderByPresupuestoLinea);
this.jmenuDetalleDatosPresupuestoLinea.add(this.jMenuItemDetalleMostarOcultarPresupuestoLinea);
//this.jmenuDetalleAccionesPresupuestoLinea.add(this.jMenuItemGuardarCambiosPresupuestoLinea);
//DETALLE_FIN
//RELACIONES
//RELACIONES
//DETALLE
FuncionesSwing.setBoldMenu(this.jmenuDetalleArchivoPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDetalleAccionesPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDetalleDatosPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
this.jmenuBarDetallePresupuestoLinea.add(this.jmenuDetalleArchivoPresupuestoLinea);
this.jmenuBarDetallePresupuestoLinea.add(this.jmenuDetalleAccionesPresupuestoLinea);
this.jmenuBarDetallePresupuestoLinea.add(this.jmenuDetalleDatosPresupuestoLinea);
//DETALLE_FIN
//AGREGA MENU DETALLE A PANTALLA
this.setJMenuBar(this.jmenuBarDetallePresupuestoLinea);
}
public void inicializarElementosCamposPresupuestoLinea() {
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
jLabelIdPresupuestoLinea = new JLabelMe();
jLabelIdPresupuestoLinea.setText(""+Constantes2.S_CODIGO_UNICO+"");
jLabelIdPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
jLabelIdPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
jLabelIdPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelIdPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelidPresupuestoLinea = new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelidPresupuestoLinea.setToolTipText(PresupuestoLineaConstantesFunciones.LABEL_ID);
this.gridaBagLayoutPresupuestoLinea= new GridBagLayout();
this.jPanelidPresupuestoLinea.setLayout(this.gridaBagLayoutPresupuestoLinea);
jLabelidPresupuestoLinea = new JLabel();
jLabelidPresupuestoLinea.setText("Id");
jLabelidPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jLabelidPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jLabelidPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelmargenPresupuestoLinea = new JLabelMe();
this.jLabelmargenPresupuestoLinea.setText(""+PresupuestoLineaConstantesFunciones.LABEL_MARGEN+" : *");
this.jLabelmargenPresupuestoLinea.setToolTipText("Margen");
this.jLabelmargenPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelmargenPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelmargenPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelmargenPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelmargenPresupuestoLinea=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelmargenPresupuestoLinea.setToolTipText(PresupuestoLineaConstantesFunciones.LABEL_MARGEN);
this.gridaBagLayoutPresupuestoLinea = new GridBagLayout();
this.jPanelmargenPresupuestoLinea.setLayout(this.gridaBagLayoutPresupuestoLinea);
jTextFieldmargenPresupuestoLinea= new JTextFieldMe();
jTextFieldmargenPresupuestoLinea.setEnabled(false);
jTextFieldmargenPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldmargenPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldmargenPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldTextField(jTextFieldmargenPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
jTextFieldmargenPresupuestoLinea.setText("0.0");
this.jButtonmargenPresupuestoLineaBusqueda= new JButtonMe();
this.jButtonmargenPresupuestoLineaBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonmargenPresupuestoLineaBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonmargenPresupuestoLineaBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonmargenPresupuestoLineaBusqueda.setText("U");
this.jButtonmargenPresupuestoLineaBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonmargenPresupuestoLineaBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonmargenPresupuestoLineaBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFieldmargenPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFieldmargenPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"margenPresupuestoLineaBusqueda"));
if(this.presupuestolineaSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonmargenPresupuestoLineaBusqueda.setVisible(false); }
this.jLabeldescuentoPresupuestoLinea = new JLabelMe();
this.jLabeldescuentoPresupuestoLinea.setText(""+PresupuestoLineaConstantesFunciones.LABEL_DESCUENTO+" : *");
this.jLabeldescuentoPresupuestoLinea.setToolTipText("Descuento");
this.jLabeldescuentoPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabeldescuentoPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabeldescuentoPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabeldescuentoPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPaneldescuentoPresupuestoLinea=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPaneldescuentoPresupuestoLinea.setToolTipText(PresupuestoLineaConstantesFunciones.LABEL_DESCUENTO);
this.gridaBagLayoutPresupuestoLinea = new GridBagLayout();
this.jPaneldescuentoPresupuestoLinea.setLayout(this.gridaBagLayoutPresupuestoLinea);
jTextFielddescuentoPresupuestoLinea= new JTextFieldMe();
jTextFielddescuentoPresupuestoLinea.setEnabled(false);
jTextFielddescuentoPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFielddescuentoPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFielddescuentoPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldTextField(jTextFielddescuentoPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
jTextFielddescuentoPresupuestoLinea.setText("0.0");
this.jButtondescuentoPresupuestoLineaBusqueda= new JButtonMe();
this.jButtondescuentoPresupuestoLineaBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtondescuentoPresupuestoLineaBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtondescuentoPresupuestoLineaBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtondescuentoPresupuestoLineaBusqueda.setText("U");
this.jButtondescuentoPresupuestoLineaBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtondescuentoPresupuestoLineaBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtondescuentoPresupuestoLineaBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFielddescuentoPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFielddescuentoPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"descuentoPresupuestoLineaBusqueda"));
if(this.presupuestolineaSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtondescuentoPresupuestoLineaBusqueda.setVisible(false); }
this.jLabeles_para_presupuestoPresupuestoLinea = new JLabelMe();
this.jLabeles_para_presupuestoPresupuestoLinea.setText(""+PresupuestoLineaConstantesFunciones.LABEL_ESPARAPRESUPUESTO+" : *");
this.jLabeles_para_presupuestoPresupuestoLinea.setToolTipText("Para Presupuesto");
this.jLabeles_para_presupuestoPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
this.jLabeles_para_presupuestoPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
this.jLabeles_para_presupuestoPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
FuncionesSwing.setBoldLabel(jLabeles_para_presupuestoPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPaneles_para_presupuestoPresupuestoLinea=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPaneles_para_presupuestoPresupuestoLinea.setToolTipText(PresupuestoLineaConstantesFunciones.LABEL_ESPARAPRESUPUESTO);
this.gridaBagLayoutPresupuestoLinea = new GridBagLayout();
this.jPaneles_para_presupuestoPresupuestoLinea.setLayout(this.gridaBagLayoutPresupuestoLinea);
jCheckBoxes_para_presupuestoPresupuestoLinea= new JCheckBoxMe();
jCheckBoxes_para_presupuestoPresupuestoLinea.setEnabled(false);
jCheckBoxes_para_presupuestoPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jCheckBoxes_para_presupuestoPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jCheckBoxes_para_presupuestoPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldCheckBox(jCheckBoxes_para_presupuestoPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtones_para_presupuestoPresupuestoLineaBusqueda= new JButtonMe();
this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setText("U");
this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtones_para_presupuestoPresupuestoLineaBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jCheckBoxes_para_presupuestoPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jCheckBoxes_para_presupuestoPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"es_para_presupuestoPresupuestoLineaBusqueda"));
if(this.presupuestolineaSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtones_para_presupuestoPresupuestoLineaBusqueda.setVisible(false); }
}
public void inicializarElementosCamposForeigKeysPresupuestoLinea() {
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jLabelid_empresaPresupuestoLinea = new JLabelMe();
this.jLabelid_empresaPresupuestoLinea.setText(""+PresupuestoLineaConstantesFunciones.LABEL_IDEMPRESA+" : *");
this.jLabelid_empresaPresupuestoLinea.setToolTipText("Empresa");
this.jLabelid_empresaPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_empresaPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_empresaPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelid_empresaPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelid_empresaPresupuestoLinea=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelid_empresaPresupuestoLinea.setToolTipText(PresupuestoLineaConstantesFunciones.LABEL_IDEMPRESA);
this.gridaBagLayoutPresupuestoLinea = new GridBagLayout();
this.jPanelid_empresaPresupuestoLinea.setLayout(this.gridaBagLayoutPresupuestoLinea);
jComboBoxid_empresaPresupuestoLinea= new JComboBoxMe();
jComboBoxid_empresaPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jComboBoxid_empresaPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jComboBoxid_empresaPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldComboBox(jComboBoxid_empresaPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
jComboBoxid_empresaPresupuestoLinea.setEnabled(false);
this.jButtonid_empresaPresupuestoLinea= new JButtonMe();
this.jButtonid_empresaPresupuestoLinea.setMinimumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_empresaPresupuestoLinea.setMaximumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_empresaPresupuestoLinea.setPreferredSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_empresaPresupuestoLinea.setText("Buscar");
this.jButtonid_empresaPresupuestoLinea.setToolTipText("Buscar ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA")+")");
this.jButtonid_empresaPresupuestoLinea.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaPresupuestoLinea,"buscar_form","Buscar");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSQUEDA");
jComboBoxid_empresaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_empresaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaPresupuestoLinea"));
this.jButtonid_empresaPresupuestoLineaBusqueda= new JButtonMe();
this.jButtonid_empresaPresupuestoLineaBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaPresupuestoLineaBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaPresupuestoLineaBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_empresaPresupuestoLineaBusqueda.setText("U");
this.jButtonid_empresaPresupuestoLineaBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonid_empresaPresupuestoLineaBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaPresupuestoLineaBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jComboBoxid_empresaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_empresaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaPresupuestoLineaBusqueda"));
if(this.presupuestolineaSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonid_empresaPresupuestoLineaBusqueda.setVisible(false); }
this.jButtonid_empresaPresupuestoLineaUpdate= new JButtonMe();
this.jButtonid_empresaPresupuestoLineaUpdate.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaPresupuestoLineaUpdate.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaPresupuestoLineaUpdate.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_empresaPresupuestoLineaUpdate.setText("U");
this.jButtonid_empresaPresupuestoLineaUpdate.setToolTipText("ACTUALIZAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR")+")");
this.jButtonid_empresaPresupuestoLineaUpdate.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaPresupuestoLineaUpdate,"actualizardatos","ACTUALIZAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_ACTUALIZAR");
jComboBoxid_empresaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_empresaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaPresupuestoLineaUpdate"));
this.jLabelid_lineaPresupuestoLinea = new JLabelMe();
this.jLabelid_lineaPresupuestoLinea.setText(""+PresupuestoLineaConstantesFunciones.LABEL_IDLINEA+" : *");
this.jLabelid_lineaPresupuestoLinea.setToolTipText("Linea");
this.jLabelid_lineaPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_lineaPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_lineaPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-22),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelid_lineaPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelid_lineaPresupuestoLinea=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelid_lineaPresupuestoLinea.setToolTipText(PresupuestoLineaConstantesFunciones.LABEL_IDLINEA);
this.gridaBagLayoutPresupuestoLinea = new GridBagLayout();
this.jPanelid_lineaPresupuestoLinea.setLayout(this.gridaBagLayoutPresupuestoLinea);
jComboBoxid_lineaPresupuestoLinea= new JComboBoxMe();
jComboBoxid_lineaPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jComboBoxid_lineaPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jComboBoxid_lineaPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldComboBox(jComboBoxid_lineaPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonid_lineaPresupuestoLinea= new JButtonMe();
this.jButtonid_lineaPresupuestoLinea.setMinimumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_lineaPresupuestoLinea.setMaximumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_lineaPresupuestoLinea.setPreferredSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_lineaPresupuestoLinea.setText("Buscar");
this.jButtonid_lineaPresupuestoLinea.setToolTipText("Buscar ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA")+")");
this.jButtonid_lineaPresupuestoLinea.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_lineaPresupuestoLinea,"buscar_form","Buscar");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSQUEDA");
jComboBoxid_lineaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_lineaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_lineaPresupuestoLinea"));
this.jButtonid_lineaPresupuestoLineaBusqueda= new JButtonMe();
this.jButtonid_lineaPresupuestoLineaBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_lineaPresupuestoLineaBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_lineaPresupuestoLineaBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_lineaPresupuestoLineaBusqueda.setText("U");
this.jButtonid_lineaPresupuestoLineaBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonid_lineaPresupuestoLineaBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_lineaPresupuestoLineaBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jComboBoxid_lineaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_lineaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_lineaPresupuestoLineaBusqueda"));
if(this.presupuestolineaSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonid_lineaPresupuestoLineaBusqueda.setVisible(false); }
this.jButtonid_lineaPresupuestoLineaUpdate= new JButtonMe();
this.jButtonid_lineaPresupuestoLineaUpdate.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_lineaPresupuestoLineaUpdate.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_lineaPresupuestoLineaUpdate.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_lineaPresupuestoLineaUpdate.setText("U");
this.jButtonid_lineaPresupuestoLineaUpdate.setToolTipText("ACTUALIZAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR")+")");
this.jButtonid_lineaPresupuestoLineaUpdate.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_lineaPresupuestoLineaUpdate,"actualizardatos","ACTUALIZAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_ACTUALIZAR");
jComboBoxid_lineaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_lineaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_lineaPresupuestoLineaUpdate"));
jButtonid_lineaPresupuestoLineaArbol= new JButtonMe();
jButtonid_lineaPresupuestoLineaArbol.setMinimumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
jButtonid_lineaPresupuestoLineaArbol.setMaximumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
jButtonid_lineaPresupuestoLineaArbol.setPreferredSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
jButtonid_lineaPresupuestoLineaArbol.setText("Arbol");
jButtonid_lineaPresupuestoLineaArbol.setToolTipText("Buscar Por Arbol ("+FuncionesSwing.getKeyNameControl("CONTROL_ARBOL")+")");
jButtonid_lineaPresupuestoLineaArbol.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_lineaPresupuestoLineaArbol,"arbol","Buscar Por Arbol");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_ARBOL");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl("CONTROL_ARBOL");
jComboBoxid_lineaPresupuestoLinea.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_lineaPresupuestoLinea.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_lineaPresupuestoLineaArbol"));
}
public void jButtonActionPerformedTecladoGeneral(String sTipo,ActionEvent evt) {
//System.out.println("TRANSFIERE EL MANEJO AL PADRE O FORM PRINCIPAL");
jInternalFrameParent.jButtonActionPerformedTecladoGeneral(sTipo,evt);
}
//JPanel
//@SuppressWarnings({"unchecked" })//"rawtypes"
public JScrollPane getJContentPane(int iWidth,int iHeight,JDesktopPane jDesktopPane,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
//PARA TABLA PARAMETROS
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jContentPane = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.usuarioActual=usuarioActual;
this.resumenUsuarioActual=resumenUsuarioActual;
this.opcionActual=opcionActual;
this.moduloActual=moduloActual;
this.parametroGeneralSg=parametroGeneralSg;
this.parametroGeneralUsuario=parametroGeneralUsuario;
this.jDesktopPane=jDesktopPane;
this.conFuncionalidadRelaciones=parametroGeneralUsuario.getcon_guardar_relaciones();
int iGridyPrincipal=0;
this.inicializarToolBar();
//CARGAR MENUS
//this.jInternalFrameDetallePresupuestoLinea = new PresupuestoLineaBeanSwingJInternalFrameAdditional(paginaTipo);//JInternalFrameBase("Presupuesto Linea DATOS");
this.cargarMenus();
this.gridaBagLayoutPresupuestoLinea= new GridBagLayout();
String sToolTipPresupuestoLinea="";
sToolTipPresupuestoLinea=PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO;
if(Constantes.ISDEVELOPING) {
sToolTipPresupuestoLinea+="(Inventario.PresupuestoLinea)";
}
if(!this.presupuestolineaSessionBean.getEsGuardarRelacionado()) {
sToolTipPresupuestoLinea+="_"+this.opcionActual.getId();
}
this.jButtonNuevoPresupuestoLinea = new JButtonMe();
this.jButtonModificarPresupuestoLinea = new JButtonMe();
this.jButtonActualizarPresupuestoLinea = new JButtonMe();
this.jButtonEliminarPresupuestoLinea = new JButtonMe();
this.jButtonCancelarPresupuestoLinea = new JButtonMe();
this.jButtonGuardarCambiosPresupuestoLinea = new JButtonMe();
this.jButtonGuardarCambiosTablaPresupuestoLinea = new JButtonMe();
this.jButtonCerrarPresupuestoLinea = new JButtonMe();
this.jScrollPanelDatosPresupuestoLinea = new JScrollPane();
this.jScrollPanelDatosEdicionPresupuestoLinea = new JScrollPane();
this.jScrollPanelDatosGeneralPresupuestoLinea = new JScrollPane();
this.jPanelCamposPresupuestoLinea = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelCamposOcultosPresupuestoLinea = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelAccionesPresupuestoLinea = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelAccionesFormularioPresupuestoLinea = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
//if(!this.conCargarMinimo) {
;
;
//}
this.sPath=" <---> Acceso: Presupuesto Linea";
if(!this.presupuestolineaSessionBean.getEsGuardarRelacionado()) {
this.jScrollPanelDatosPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Presupuesto Lineaes" + this.sPath));
} else {
this.jScrollPanelDatosPresupuestoLinea.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
this.jScrollPanelDatosEdicionPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jScrollPanelDatosGeneralPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jPanelCamposPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelCamposPresupuestoLinea.setName("jPanelCamposPresupuestoLinea");
this.jPanelCamposOcultosPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos Ocultos"));
this.jPanelCamposOcultosPresupuestoLinea.setName("jPanelCamposOcultosPresupuestoLinea");
this.jPanelAccionesPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
this.jPanelAccionesPresupuestoLinea.setToolTipText("Acciones");
this.jPanelAccionesPresupuestoLinea.setName("Acciones");
this.jPanelAccionesFormularioPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones Extra/Post"));
this.jPanelAccionesFormularioPresupuestoLinea.setToolTipText("Acciones");
this.jPanelAccionesFormularioPresupuestoLinea.setName("Acciones");
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosEdicionPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelCamposPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelCamposOcultosPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelAccionesFormularioPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
//if(!this.conCargarMinimo) {
;
;
//}
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
this.jButtonNuevoPresupuestoLinea.setText("Nuevo");
this.jButtonModificarPresupuestoLinea.setText("Editar");
this.jButtonActualizarPresupuestoLinea.setText("Actualizar");
this.jButtonEliminarPresupuestoLinea.setText("Eliminar");
this.jButtonCancelarPresupuestoLinea.setText("Cancelar");
this.jButtonGuardarCambiosPresupuestoLinea.setText("Guardar");
this.jButtonGuardarCambiosTablaPresupuestoLinea.setText("Guardar");
this.jButtonCerrarPresupuestoLinea.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoPresupuestoLinea,"nuevo_button","Nuevo",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonModificarPresupuestoLinea,"modificar_button","Editar",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonActualizarPresupuestoLinea,"actualizar_button","Actualizar",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonEliminarPresupuestoLinea,"eliminar_button","Eliminar",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCancelarPresupuestoLinea,"cancelar_button","Cancelar",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosPresupuestoLinea,"guardarcambios_button","Guardar",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaPresupuestoLinea,"guardarcambiostabla_button","Guardar",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarPresupuestoLinea,"cerrar_button","Salir",this.presupuestolineaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonModificarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCerrarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonActualizarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButton(this.jButtonEliminarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButton(this.jButtonCancelarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonNuevoPresupuestoLinea.setToolTipText("Nuevo"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jButtonModificarPresupuestoLinea.setToolTipText("Editar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO+"");// + FuncionesSwing.getKeyMensaje("MODIFICAR"))
this.jButtonActualizarPresupuestoLinea.setToolTipText("Actualizar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"));
this.jButtonEliminarPresupuestoLinea.setToolTipText("Eliminar)"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"));
this.jButtonCancelarPresupuestoLinea.setToolTipText("Cancelar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"));
this.jButtonGuardarCambiosPresupuestoLinea.setToolTipText("Guardar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonGuardarCambiosTablaPresupuestoLinea.setToolTipText("Guardar"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonCerrarPresupuestoLinea.setToolTipText("Salir"+" "+PresupuestoLineaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"));
//HOT KEYS
/*
N->Nuevo
N->Alt + Nuevo Relaciones (ANTES R)
A->Actualizar
E->Eliminar
S->Cerrar
C->->Mayus + Cancelar (ANTES Q->Quit)
G->Guardar Cambios
D->Duplicar
C->Alt + Cop?ar
O->Orden
N->Nuevo Tabla
R->Recargar Informacion Inicial (ANTES I)
Alt + Pag.Down->Siguientes
Alt + Pag.Up->Anteriores
NO UTILIZADOS
M->Modificar
*/
String sMapKey = "";
InputMap inputMap =null;
//NUEVO
sMapKey = "NuevoPresupuestoLinea";
inputMap = this.jButtonNuevoPresupuestoLinea.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey);
this.jButtonNuevoPresupuestoLinea.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoPresupuestoLinea"));
//ACTUALIZAR
sMapKey = "ActualizarPresupuestoLinea";
inputMap = this.jButtonActualizarPresupuestoLinea.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ACTUALIZAR") , FuncionesSwing.getMaskKey("ACTUALIZAR")), sMapKey);
this.jButtonActualizarPresupuestoLinea.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ActualizarPresupuestoLinea"));
//ELIMINAR
sMapKey = "EliminarPresupuestoLinea";
inputMap = this.jButtonEliminarPresupuestoLinea.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ELIMINAR") , FuncionesSwing.getMaskKey("ELIMINAR")), sMapKey);
this.jButtonEliminarPresupuestoLinea.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"EliminarPresupuestoLinea"));
//CANCELAR
sMapKey = "CancelarPresupuestoLinea";
inputMap = this.jButtonCancelarPresupuestoLinea.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CANCELAR") , FuncionesSwing.getMaskKey("CANCELAR")), sMapKey);
this.jButtonCancelarPresupuestoLinea.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CancelarPresupuestoLinea"));
//CERRAR
sMapKey = "CerrarPresupuestoLinea";
inputMap = this.jButtonCerrarPresupuestoLinea.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey);
this.jButtonCerrarPresupuestoLinea.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarPresupuestoLinea"));
//GUARDAR CAMBIOS
sMapKey = "GuardarCambiosTablaPresupuestoLinea";
inputMap = this.jButtonGuardarCambiosTablaPresupuestoLinea.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey);
this.jButtonGuardarCambiosTablaPresupuestoLinea.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaPresupuestoLinea"));
//HOT KEYS
this.jCheckBoxPostAccionNuevoPresupuestoLinea = new JCheckBoxMe();
this.jCheckBoxPostAccionNuevoPresupuestoLinea.setText("Nuevo");
this.jCheckBoxPostAccionNuevoPresupuestoLinea.setToolTipText("Nuevo PresupuestoLinea");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionNuevoPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
this.jCheckBoxPostAccionSinCerrarPresupuestoLinea = new JCheckBoxMe();
this.jCheckBoxPostAccionSinCerrarPresupuestoLinea.setText("Sin Cerrar");
this.jCheckBoxPostAccionSinCerrarPresupuestoLinea.setToolTipText("Sin Cerrar Ventana PresupuestoLinea");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinCerrarPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
this.jCheckBoxPostAccionSinMensajePresupuestoLinea = new JCheckBoxMe();
this.jCheckBoxPostAccionSinMensajePresupuestoLinea.setText("Sin Mensaje");
this.jCheckBoxPostAccionSinMensajePresupuestoLinea.setToolTipText("Sin Mensaje Confirmacion");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinMensajePresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
this.jComboBoxTiposAccionesPresupuestoLinea = new JComboBoxMe();
//this.jComboBoxTiposAccionesPresupuestoLinea.setText("Accion");
this.jComboBoxTiposAccionesPresupuestoLinea.setToolTipText("Tipos de Acciones");
this.jComboBoxTiposAccionesFormularioPresupuestoLinea = new JComboBoxMe();
//this.jComboBoxTiposAccionesFormularioPresupuestoLinea.setText("Accion");
this.jComboBoxTiposAccionesFormularioPresupuestoLinea.setToolTipText("Tipos de Acciones");
this.jLabelAccionesPresupuestoLinea = new JLabelMe();
this.jLabelAccionesPresupuestoLinea.setText("Acciones");
this.jLabelAccionesPresupuestoLinea.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesPresupuestoLinea.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesPresupuestoLinea.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
//HOT KEYS2
/*
T->Nuevo Tabla
*/
//NUEVO GUARDAR CAMBIOS O NUEVO TABLA
//HOT KEYS2
//ELEMENTOS
this.inicializarElementosCamposPresupuestoLinea();
//ELEMENTOS FK
this.inicializarElementosCamposForeigKeysPresupuestoLinea();
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
//ELEMENTOS TABLAS PARAMETOS_FIN
this.jTabbedPaneRelacionesPresupuestoLinea=new JTabbedPane();
this.jTabbedPaneRelacionesPresupuestoLinea.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Relacionados"));
//ESTA EN BEAN
FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneRelacionesPresupuestoLinea,STIPO_TAMANIO_GENERAL,false,false,this);
int iPosXAccionPaginacion=0;
this.jComboBoxTiposAccionesPresupuestoLinea.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesPresupuestoLinea.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesPresupuestoLinea.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposAccionesFormularioPresupuestoLinea.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFormularioPresupuestoLinea.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFormularioPresupuestoLinea.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesFormularioPresupuestoLinea, STIPO_TAMANIO_GENERAL,false,false,this);
GridBagLayout gridaBagLayoutCamposPresupuestoLinea = new GridBagLayout();
GridBagLayout gridaBagLayoutCamposOcultosPresupuestoLinea = new GridBagLayout();
this.jPanelCamposPresupuestoLinea.setLayout(gridaBagLayoutCamposPresupuestoLinea);
this.jPanelCamposOcultosPresupuestoLinea.setLayout(gridaBagLayoutCamposOcultosPresupuestoLinea);
;
;
//SUBPANELES SIMPLES
//SUBPANELES POR CAMPO
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelidPresupuestoLinea.add(jLabelIdPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 1;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelidPresupuestoLinea.add(jLabelidPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_empresaPresupuestoLinea.add(jLabelid_empresaPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 2;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPanelid_empresaPresupuestoLinea.add(jButtonid_empresaPresupuestoLineaBusqueda, this.gridBagConstraintsPresupuestoLinea);
}
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 3;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPanelid_empresaPresupuestoLinea.add(jButtonid_empresaPresupuestoLineaUpdate, this.gridBagConstraintsPresupuestoLinea);
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 1;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_empresaPresupuestoLinea.add(jComboBoxid_empresaPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_lineaPresupuestoLinea.add(jLabelid_lineaPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 2;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPanelid_lineaPresupuestoLinea.add(jButtonid_lineaPresupuestoLineaBusqueda, this.gridBagConstraintsPresupuestoLinea);
}
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 3;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPanelid_lineaPresupuestoLinea.add(jButtonid_lineaPresupuestoLineaUpdate, this.gridBagConstraintsPresupuestoLinea);
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 1;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_lineaPresupuestoLinea.add(jComboBoxid_lineaPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelmargenPresupuestoLinea.add(jLabelmargenPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 2;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPanelmargenPresupuestoLinea.add(jButtonmargenPresupuestoLineaBusqueda, this.gridBagConstraintsPresupuestoLinea);
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 1;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelmargenPresupuestoLinea.add(jTextFieldmargenPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPaneldescuentoPresupuestoLinea.add(jLabeldescuentoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 2;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPaneldescuentoPresupuestoLinea.add(jButtondescuentoPresupuestoLineaBusqueda, this.gridBagConstraintsPresupuestoLinea);
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 1;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPaneldescuentoPresupuestoLinea.add(jTextFielddescuentoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPaneles_para_presupuestoPresupuestoLinea.add(jLabeles_para_presupuestoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
//this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 2;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(0, 0, 0, 0);
this.jPaneles_para_presupuestoPresupuestoLinea.add(jButtones_para_presupuestoPresupuestoLineaBusqueda, this.gridBagConstraintsPresupuestoLinea);
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = 1;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPaneles_para_presupuestoPresupuestoLinea.add(jCheckBoxes_para_presupuestoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
//SUBPANELES SIMPLES
//SUBPANELES EN PANEL
//SUBPANELES EN PANEL CAMPOS NORMAL
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iYPanelCamposPresupuestoLinea;
this.gridBagConstraintsPresupuestoLinea.gridx = iXPanelCamposPresupuestoLinea++;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposPresupuestoLinea.add(this.jPanelidPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(iXPanelCamposPresupuestoLinea % 1==0) {
iXPanelCamposPresupuestoLinea=0;
iYPanelCamposPresupuestoLinea++;
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iYPanelCamposPresupuestoLinea;
this.gridBagConstraintsPresupuestoLinea.gridx = iXPanelCamposPresupuestoLinea++;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposPresupuestoLinea.add(this.jPanelid_lineaPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(iXPanelCamposPresupuestoLinea % 1==0) {
iXPanelCamposPresupuestoLinea=0;
iYPanelCamposPresupuestoLinea++;
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iYPanelCamposPresupuestoLinea;
this.gridBagConstraintsPresupuestoLinea.gridx = iXPanelCamposPresupuestoLinea++;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposPresupuestoLinea.add(this.jPanelmargenPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(iXPanelCamposPresupuestoLinea % 1==0) {
iXPanelCamposPresupuestoLinea=0;
iYPanelCamposPresupuestoLinea++;
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iYPanelCamposPresupuestoLinea;
this.gridBagConstraintsPresupuestoLinea.gridx = iXPanelCamposPresupuestoLinea++;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposPresupuestoLinea.add(this.jPaneldescuentoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(iXPanelCamposPresupuestoLinea % 1==0) {
iXPanelCamposPresupuestoLinea=0;
iYPanelCamposPresupuestoLinea++;
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iYPanelCamposPresupuestoLinea;
this.gridBagConstraintsPresupuestoLinea.gridx = iXPanelCamposPresupuestoLinea++;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposPresupuestoLinea.add(this.jPaneles_para_presupuestoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(iXPanelCamposPresupuestoLinea % 1==0) {
iXPanelCamposPresupuestoLinea=0;
iYPanelCamposPresupuestoLinea++;
}
//SUBPANELES EN PANEL CAMPOS OCULTOS
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iYPanelCamposOcultosPresupuestoLinea;
this.gridBagConstraintsPresupuestoLinea.gridx = iXPanelCamposOcultosPresupuestoLinea++;
this.gridBagConstraintsPresupuestoLinea.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsPresupuestoLinea.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposOcultosPresupuestoLinea.add(this.jPanelid_empresaPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
if(iXPanelCamposOcultosPresupuestoLinea % 1==0) {
iXPanelCamposOcultosPresupuestoLinea=0;
iYPanelCamposOcultosPresupuestoLinea++;
}
//SUBPANELES EN PANEL CAMPOS INICIO
//SUBPANELES EN PANEL CAMPOS FIN
//SUBPANELES EN PANEL
//ELEMENTOS TABLAS PARAMETOS
//SUBPANELES POR CAMPO
if(!this.conCargarMinimo) {
//SUBPANELES EN PANEL CAMPOS
}
//ELEMENTOS TABLAS PARAMETOS_FIN
Integer iGridXParametrosAccionesFormulario=0;
Integer iGridYParametrosAccionesFormulario=0;
GridBagLayout gridaBagLayoutAccionesPresupuestoLinea= new GridBagLayout();
this.jPanelAccionesPresupuestoLinea.setLayout(gridaBagLayoutAccionesPresupuestoLinea);
GridBagLayout gridaBagLayoutAccionesFormularioPresupuestoLinea= new GridBagLayout();
this.jPanelAccionesFormularioPresupuestoLinea.setLayout(gridaBagLayoutAccionesFormularioPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsPresupuestoLinea.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioPresupuestoLinea.add(this.jComboBoxTiposAccionesFormularioPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsPresupuestoLinea.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioPresupuestoLinea.add(this.jCheckBoxPostAccionNuevoPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
//DEBE CERRARSE Y ACTUALIZARSE TODO NUEVAMENTE, SI ES RELACIONADO PUEDE FUNCIONAR
//if(!this.presupuestolineaSessionBean.getEstaModoGuardarRelaciones()) {
//SE ARRIESGA
//if(!this.conFuncionalidadRelaciones) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsPresupuestoLinea.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioPresupuestoLinea.add(this.jCheckBoxPostAccionSinCerrarPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
//}
//NO TIENE MENSAJE POR DEFINICION, O ES MUY COMPLEJO LA PANTALLA PARA HACERLO MAS COMPLICADO
if(!this.presupuestolineaSessionBean.getEsGuardarRelacionado()
){
//&& !this.presupuestolineaSessionBean.getEstaModoGuardarRelaciones()) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsPresupuestoLinea.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioPresupuestoLinea.add(this.jCheckBoxPostAccionSinMensajePresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
}
int iPosXAccion=0;
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = iPosXAccion++;
this.jPanelAccionesPresupuestoLinea.add(this.jButtonModificarPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx =iPosXAccion++;
this.jPanelAccionesPresupuestoLinea.add(this.jButtonEliminarPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = iPosXAccion++;
this.jPanelAccionesPresupuestoLinea.add(this.jButtonActualizarPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx = iPosXAccion++;
this.jPanelAccionesPresupuestoLinea.add(this.jButtonGuardarCambiosPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = 0;
this.gridBagConstraintsPresupuestoLinea.gridx =iPosXAccion++;
this.jPanelAccionesPresupuestoLinea.add(this.jButtonCancelarPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
//this.setJProgressBarToJPanel();
GridBagLayout gridaBagLayoutPresupuestoLinea = new GridBagLayout();
this.jContentPane.setLayout(gridaBagLayoutPresupuestoLinea);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.presupuestolineaSessionBean.getEsGuardarRelacionado()) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
//this.gridBagConstraintsPresupuestoLinea.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH
this.gridBagConstraintsPresupuestoLinea.ipadx = 100;
}
//PROCESANDO EN OTRA PANTALLA
int iGridxBusquedasParametros=0;
//PARAMETROS TABLAS PARAMETROS
if(!this.conCargarMinimo) {
//NO BUSQUEDA
}
//PARAMETROS TABLAS PARAMETROS_FIN
//PARAMETROS REPORTES
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy =iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx =0;
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsPresupuestoLinea.ipady =150;
this.jContentPane.add(this.jScrollPanelDatosPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
iWidthScroll=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO_RELSCROLL)+(250*0);
iHeightScroll=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO_RELSCROLL);
//if(PresupuestoLineaJInternalFrame.CON_DATOS_FRAME) {
//this.jInternalFrameDetallePresupuestoLinea = new PresupuestoLineaBeanSwingJInternalFrameAdditional();//JInternalFrameBase("Presupuesto Linea DATOS");
this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
//this.setjInternalFrameParent(this);
iHeightFormularioMaximo=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
if(iHeightFormulario>iHeightFormularioMaximo) {
iHeightFormulario=iHeightFormularioMaximo;
}
iWidthFormularioMaximo=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
if(iWidthFormulario>iWidthFormularioMaximo) {
iWidthFormulario=iWidthFormularioMaximo;
}
//this.setTitle("[FOR] - Presupuesto Linea DATOS");
this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.usuarioActual,"Presupuesto Linea Formulario",PaginaTipo.FORMULARIO,paginaTipo));
this.setSize(iWidthFormulario,iHeightFormulario);
this.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
PresupuestoLineaModel presupuestolineaModel=new PresupuestoLineaModel(this);
//SI USARA CLASE INTERNA
//PresupuestoLineaModel.PresupuestoLineaFocusTraversalPolicy presupuestolineaFocusTraversalPolicy = presupuestolineaModel.new PresupuestoLineaFocusTraversalPolicy(this);
//presupuestolineaFocusTraversalPolicy.setpresupuestolineaJInternalFrame(this);
this.setFocusTraversalPolicy(presupuestolineaModel);
this.jContentPaneDetallePresupuestoLinea = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
int iGridyRelaciones=0;
GridBagLayout gridaBagLayoutDetallePresupuestoLinea = new GridBagLayout();
this.jContentPaneDetallePresupuestoLinea.setLayout(gridaBagLayoutDetallePresupuestoLinea);
GridBagLayout gridaBagLayoutBusquedasParametrosPresupuestoLinea = new GridBagLayout();
if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) {
//AGREGA TOOLBAR DETALLE A PANTALLA
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyRelaciones++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPaneDetallePresupuestoLinea.add(jTtoolBarDetallePresupuestoLinea, gridBagConstraintsPresupuestoLinea);
}
this.jScrollPanelDatosEdicionPresupuestoLinea= new JScrollPane(jContentPaneDetallePresupuestoLinea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosEdicionPresupuestoLinea.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionPresupuestoLinea.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionPresupuestoLinea.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralPresupuestoLinea= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosGeneralPresupuestoLinea.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralPresupuestoLinea.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralPresupuestoLinea.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyRelaciones++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPaneDetallePresupuestoLinea.add(jPanelCamposPresupuestoLinea, gridBagConstraintsPresupuestoLinea);
//if(!this.conCargarMinimo) {
;
//}
this.conMaximoRelaciones=true;
if(this.parametroGeneralUsuario.getcon_cargar_por_parte()) {
}
//CARGA O NO CARGA RELACIONADOS(MAESTRO DETALLE)
// ABAJO VIENE DE PARAMETRO GENERAL USUARIO
if(conMaximoRelaciones) { // && this.conFuncionalidadRelaciones) {
if(!this.conCargarMinimo) {
if(cargarRelaciones
&& presupuestolineaSessionBean.getConGuardarRelaciones()
) {
//paraCargarPorParte es false por defecto(y ejecuta funcion normal cargando detalle en tab panel), si se utiliza funcionalidad es true y carga tab panel auxiliar temporal
if(this.presupuestolineaSessionBean.getConGuardarRelaciones()) {
this.gridBagConstraintsPresupuestoLinea= new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyRelaciones++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPaneDetallePresupuestoLinea.add(this.jTabbedPaneRelacionesPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
}
//RELACIONES OTROS AGRUPADOS
;
} else {
//this.jButtonNuevoRelacionesPresupuestoLinea.setVisible(false);
}
}
}
Boolean tieneColumnasOcultas=false;
tieneColumnasOcultas=true;
if(!Constantes.ISDEVELOPING) {
this.jPanelCamposOcultosPresupuestoLinea.setVisible(false);
} else {
if(tieneColumnasOcultas) {
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.fill=GridBagConstraints.NONE;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyRelaciones++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPaneDetallePresupuestoLinea.add(jPanelCamposOcultosPresupuestoLinea, gridBagConstraintsPresupuestoLinea);
this.jPanelCamposOcultosPresupuestoLinea.setVisible(true);
}
}
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyRelaciones++;//1;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.CENTER;//WEST;
this.jContentPaneDetallePresupuestoLinea.add(this.jPanelAccionesFormularioPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyRelaciones;//1;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPaneDetallePresupuestoLinea.add(this.jPanelAccionesPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
//this.setContentPane(jScrollPanelDatosEdicionPresupuestoLinea);
//} else {
//DISENO_DETALLE COMENTAR Y
//DISENO_DETALLE(Solo Descomentar Seccion Inferior)
//NOTA-DISENO_DETALLE(Si cambia lo de abajo, cambiar lo comentado, Al final no es lo mismo)
/*
this.jScrollPanelDatosEdicionPresupuestoLinea= new JScrollPane(this.jPanelCamposPresupuestoLinea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosEdicionPresupuestoLinea.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionPresupuestoLinea.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionPresupuestoLinea.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.gridBagConstraintsPresupuestoLinea.fill = GridBagConstraints.BOTH;
this.gridBagConstraintsPresupuestoLinea.ipady = this.getSize().height-yOffset*3;
this.gridBagConstraintsPresupuestoLinea.anchor = GridBagConstraints.WEST;
this.jContentPane.add(this.jScrollPanelDatosEdicionPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
//ACCIONES FORMULARIO
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy =iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPane.add(this.jPanelAccionesFormularioPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy =iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPane.add(this.jPanelAccionesPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
*/
//}
//DISENO_DETALLE-(Descomentar)
/*
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPane.add(this.jPanelCamposPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy = iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx = 0;
this.jContentPane.add(this.jPanelCamposOcultosPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
this.gridBagConstraintsPresupuestoLinea = new GridBagConstraints();
this.gridBagConstraintsPresupuestoLinea.gridy =iGridyPrincipal++;
this.gridBagConstraintsPresupuestoLinea.gridx =0;
this.jContentPane.add(this.jPanelAccionesPresupuestoLinea, this.gridBagConstraintsPresupuestoLinea);
*/
//pack();
//return this.jScrollPanelDatosGeneralPresupuestoLinea;//jContentPane;
return jScrollPanelDatosEdicionPresupuestoLinea;
}
/*
case "CONTROL_BUSQUEDA":
sKeyName="F3";
case "CONTROL_BUSCAR":
sKeyName="F4";
case "CONTROL_ARBOL":
sKeyName="F5";
case "CONTROL_ACTUALIZAR":
sKeyName="F6";
sKeyName="N";
*/
}
| 52.710028 | 385 | 0.820128 |
18ba18f3d090896ba33f10e6672c00886cf73aee | 34,512 | /*
* Copyright © 2018-2019 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.servicetalk.http.netty;
import io.servicetalk.buffer.api.Buffer;
import io.servicetalk.http.api.EmptyHttpHeaders;
import io.servicetalk.http.api.HttpHeaders;
import io.servicetalk.http.api.HttpHeadersFactory;
import io.servicetalk.http.api.HttpMetaData;
import io.servicetalk.http.api.HttpProtocolVersion;
import io.servicetalk.http.api.HttpRequestMetaData;
import io.servicetalk.http.api.HttpResponseMetaData;
import io.servicetalk.transport.netty.internal.ByteToMessageDecoder;
import io.servicetalk.transport.netty.internal.CloseHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.PrematureChannelClosureException;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.HttpExpectationFailedEvent;
import io.netty.util.AsciiString;
import io.netty.util.ByteProcessor;
import javax.annotation.Nullable;
import static io.netty.handler.codec.http.HttpConstants.CR;
import static io.netty.util.ByteProcessor.FIND_LF;
import static io.netty.util.ByteProcessor.FIND_LINEAR_WHITESPACE;
import static io.netty.util.ByteProcessor.FIND_NON_LINEAR_WHITESPACE;
import static io.servicetalk.buffer.netty.BufferUtils.newBufferFrom;
import static io.servicetalk.http.api.CharSequences.emptyAsciiString;
import static io.servicetalk.http.api.CharSequences.newAsciiString;
import static io.servicetalk.http.api.HeaderUtils.isTransferEncodingChunked;
import static io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH;
import static io.servicetalk.http.api.HttpHeaderNames.SEC_WEBSOCKET_KEY1;
import static io.servicetalk.http.api.HttpHeaderNames.SEC_WEBSOCKET_KEY2;
import static io.servicetalk.http.api.HttpHeaderNames.SEC_WEBSOCKET_LOCATION;
import static io.servicetalk.http.api.HttpHeaderNames.SEC_WEBSOCKET_ORIGIN;
import static io.servicetalk.http.api.HttpHeaderNames.UPGRADE;
import static io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_0;
import static io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1;
import static io.servicetalk.http.api.HttpRequestMethod.GET;
import static io.servicetalk.http.api.HttpResponseStatus.SWITCHING_PROTOCOLS;
import static io.servicetalk.http.netty.HeaderUtils.removeTransferEncodingChunked;
import static io.servicetalk.http.netty.HttpKeepAlive.shouldClose;
import static java.lang.Character.isISOControl;
import static java.lang.Character.isWhitespace;
import static java.lang.Math.min;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.util.Objects.requireNonNull;
abstract class HttpObjectDecoder<T extends HttpMetaData> extends ByteToMessageDecoder {
private static final byte COLON_BYTE = (byte) ':';
private static final byte SPACE_BYTE = (byte) ' ';
private static final byte HTAB_BYTE = (byte) '\t';
private static final ByteProcessor FIND_COLON_OR_WHITE_SPACE =
value -> value != COLON_BYTE && value != SPACE_BYTE && value != HTAB_BYTE;
private static final ByteProcessor FIND_COLON =
value -> value != COLON_BYTE;
private static final ByteProcessor SKIP_CONTROL_CHARS_PROCESSOR = value ->
value == SPACE_BYTE || value == HTAB_BYTE || isISOControl((char) (value & 0xff));
private static final int MAX_HEX_CHARS_FOR_LONG = 16; // 0x7FFFFFFFFFFFFFFF == Long.MAX_INT
private static final int CHUNK_DELIMETER_SIZE = 2; // CRLF
private final int maxStartLineLength;
private final int maxHeaderFieldLength;
private final HttpHeadersFactory headersFactory;
private final CloseHandler closeHandler;
@Nullable
private T message;
@Nullable
private HttpHeaders trailer;
private long chunkSize;
private int cumulationIndex = -1;
private long contentLength = Long.MIN_VALUE;
/**
* The internal state of {@link HttpObjectDecoder}.
*/
private enum State {
SKIP_CONTROL_CHARS,
READ_INITIAL,
READ_HEADER,
READ_VARIABLE_LENGTH_CONTENT,
READ_FIXED_LENGTH_CONTENT,
READ_CHUNK_SIZE,
READ_CHUNKED_CONTENT,
READ_CHUNK_DELIMITER,
READ_CHUNK_FOOTER,
UPGRADED
}
private State currentState = State.SKIP_CONTROL_CHARS;
/**
* Creates a new instance with the specified parameters.
*/
protected HttpObjectDecoder(HttpHeadersFactory headersFactory, int maxStartLineLength, int maxHeaderFieldLength,
final CloseHandler closeHandler) {
this.closeHandler = closeHandler;
if (maxStartLineLength <= 0) {
throw new IllegalArgumentException("maxStartLineLength: " + maxStartLineLength + " (expected >0)");
}
if (maxHeaderFieldLength <= 0) {
throw new IllegalArgumentException("maxHeaderFieldLength: " + maxHeaderFieldLength + " (expected >0)");
}
this.headersFactory = requireNonNull(headersFactory);
this.maxStartLineLength = maxStartLineLength;
this.maxHeaderFieldLength = maxHeaderFieldLength;
}
final HttpHeadersFactory headersFactory() {
return headersFactory;
}
/**
* Determine if this {@link HttpObjectDecoder} is responsible for decoding requests or not. Behavior may differ
* if a request/response is being parsed around request/response termination. See
* <a href="https://tools.ietf.org/html/rfc7230.html#section-3.3.3">RFC 7230, section 3.3.3</a> for more details.
* @return {@code true} if requests are being decoded.
*/
protected abstract boolean isDecodingRequest();
/**
* When the initial line is expected, and a buffer is received which does not contain a CRLF that terminates the
* initial line.
* @param ctx the {@link ChannelHandlerContext}.
* @param buffer the {@link Buffer} received.
*/
protected abstract void handlePartialInitialLine(ChannelHandlerContext ctx, ByteBuf buffer);
/**
* Create a new {@link HttpMetaData} because a new request/response
* <a href="https://tools.ietf.org/html/rfc7230.html#section-3.1">start line</a> has been parsed.
*
* @param buffer The {@link ByteBuf} which contains a start line
* @param firstStart Start index of the first item in the start line
* @param firstLength Length of the first item in the start line
* @param secondStart Start index of the second item in the start line
* @param secondLength Length of the second item in the start line
* @param thirdStart Start index of the third item in the start line
* @param thirdLength Length of the third item in the start line, a negative value indicates the absence of the
* third component
* @return a new {@link HttpMetaData} that represents the parsed start line
*/
protected abstract T createMessage(ByteBuf buffer, int firstStart, int firstLength,
int secondStart, int secondLength,
int thirdStart, int thirdLength);
@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf buffer) {
switch (currentState) {
case SKIP_CONTROL_CHARS: {
if (!skipControlCharacters(buffer)) {
return;
}
currentState = State.READ_INITIAL;
}
case READ_INITIAL: {
final int lfIndex = findCRLF(buffer, maxStartLineLength);
if (lfIndex < 0) {
handlePartialInitialLine(ctx, buffer);
return;
}
// Parse the initial line:
// https://tools.ietf.org/html/rfc7230#section-3.1.1
// request-line = method SP request-target SP HTTP-version CRLF
// https://tools.ietf.org/html/rfc7230#section-3.1.2
// status-line = HTTP-version SP status-code SP reason-phrase CRLF
final int nonControlIndex = lfIndex - 2;
int aStart = buffer.forEachByte(FIND_NON_LINEAR_WHITESPACE);
if (aStart < 0) {
splitInitialLineError();
}
int aEnd = buffer.forEachByte(aStart + 1, nonControlIndex - aStart, FIND_LINEAR_WHITESPACE);
if (aEnd < 0) {
splitInitialLineError();
}
int bStart = buffer.forEachByte(aEnd + 1, nonControlIndex - aEnd, FIND_NON_LINEAR_WHITESPACE);
if (bStart < 0) {
splitInitialLineError();
}
int bEnd = buffer.forEachByte(bStart + 1, nonControlIndex - bStart, FIND_LINEAR_WHITESPACE);
if (bEnd < 0) {
splitInitialLineError();
}
int cStart = buffer.forEachByte(bEnd + 1, nonControlIndex - bEnd, FIND_NON_LINEAR_WHITESPACE);
int cEnd = -1;
if (cStart >= 0) {
// Find End Of String
cEnd = buffer.forEachByteDesc(cStart, lfIndex - cStart, FIND_NON_LINEAR_WHITESPACE);
if (cEnd < 0) {
splitInitialLineError();
}
}
// Consume the initial line bytes from the buffer.
consumeCRLF(buffer, lfIndex);
message = createMessage(buffer, aStart, aEnd - aStart, bStart, bEnd - bStart, cStart,
cEnd < 0 ? -1 : cEnd - cStart);
currentState = State.READ_HEADER;
closeHandler.protocolPayloadBeginInbound(ctx);
// fall-through
}
case READ_HEADER: {
State nextState = readHeaders(buffer);
if (nextState == null) {
return;
}
assert message != null;
if (shouldClose(message)) {
closeHandler.protocolClosingInbound(ctx);
}
currentState = nextState;
switch (nextState) {
case SKIP_CONTROL_CHARS:
// fast-path
// No content is expected.
ctx.fireChannelRead(message);
ctx.fireChannelRead(EmptyHttpHeaders.INSTANCE);
closeHandler.protocolPayloadEndInbound(ctx);
resetNow();
return;
case READ_CHUNK_SIZE:
// Chunked encoding - generate HttpMessage first. HttpChunks will follow.
ctx.fireChannelRead(message);
return;
default:
// <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230, 3.3.3</a> states that
// if a request does not have either a transfer-encoding or a content-length header then the
// message body length is 0. However for a response the body length is the number of octets
// received prior to the server closing the connection. So we treat this as variable length
// chunked encoding.
long contentLength = contentLength();
if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) {
ctx.fireChannelRead(message);
ctx.fireChannelRead(EmptyHttpHeaders.INSTANCE);
closeHandler.protocolPayloadEndInbound(ctx);
resetNow();
return;
}
assert nextState == State.READ_FIXED_LENGTH_CONTENT ||
nextState == State.READ_VARIABLE_LENGTH_CONTENT;
ctx.fireChannelRead(message);
if (nextState == State.READ_FIXED_LENGTH_CONTENT) {
// chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT state reads data chunk by
// chunk.
chunkSize = contentLength;
}
// We return here, this forces decode to be called again where we will decode the content
return;
}
// fall-through
}
case READ_VARIABLE_LENGTH_CONTENT: {
// Keep reading data as a chunk until the end of connection is reached.
int toRead = buffer.readableBytes();
if (toRead > 0) {
ByteBuf content = buffer.readRetainedSlice(toRead);
cumulationIndex = buffer.readerIndex();
ctx.fireChannelRead(newBufferFrom(content));
}
return;
}
case READ_FIXED_LENGTH_CONTENT: {
int toRead = buffer.readableBytes();
// Check if the buffer is readable first as we use the readable byte count
// to create the HttpChunk. This is needed as otherwise we may end up with
// create a HttpChunk instance that contains an empty buffer and so is
// handled like it is the last HttpChunk.
//
// See https://github.com/netty/netty/issues/433
if (toRead == 0) {
return;
}
if (toRead > chunkSize) {
toRead = (int) chunkSize;
}
ByteBuf content = buffer.readRetainedSlice(toRead);
chunkSize -= toRead;
cumulationIndex = buffer.readerIndex();
if (chunkSize == 0) {
// Read all content.
// https://tools.ietf.org/html/rfc7230.html#section-4.1
// This is not chunked encoding so there will not be any trailers.
ctx.fireChannelRead(newBufferFrom(content));
ctx.fireChannelRead(EmptyHttpHeaders.INSTANCE);
closeHandler.protocolPayloadEndInbound(ctx);
resetNow();
} else {
ctx.fireChannelRead(newBufferFrom(content));
}
return;
}
// everything else after this point takes care of reading chunked content. basically, read chunk size,
// read chunk, read and ignore the CRLF and repeat until 0
case READ_CHUNK_SIZE: {
int lfIndex = findCRLF(buffer, MAX_HEX_CHARS_FOR_LONG);
if (lfIndex < 0) {
return;
}
long chunkSize = getChunkSize(buffer, lfIndex);
consumeCRLF(buffer, lfIndex);
this.chunkSize = chunkSize;
if (chunkSize == 0) {
currentState = State.READ_CHUNK_FOOTER;
return;
}
currentState = State.READ_CHUNKED_CONTENT;
// fall-through
}
case READ_CHUNKED_CONTENT: {
assert chunkSize <= Integer.MAX_VALUE;
final int toRead = min((int) chunkSize, buffer.readableBytes());
if (toRead == 0) {
return;
}
Buffer chunk = newBufferFrom(buffer.readRetainedSlice(toRead));
chunkSize -= toRead;
cumulationIndex = buffer.readerIndex();
ctx.fireChannelRead(chunk);
if (chunkSize != 0) {
return;
}
currentState = State.READ_CHUNK_DELIMITER;
// fall-through
}
case READ_CHUNK_DELIMITER: {
// Read the chunk delimiter
int lfIndex = findCRLF(buffer, CHUNK_DELIMETER_SIZE);
if (lfIndex < 0) {
return;
}
consumeCRLF(buffer, lfIndex);
currentState = State.READ_CHUNK_SIZE;
break;
}
case READ_CHUNK_FOOTER: {
HttpHeaders trailer = readTrailingHeaders(buffer);
if (trailer == null) {
return;
}
ctx.fireChannelRead(trailer);
closeHandler.protocolPayloadEndInbound(ctx);
resetNow();
return;
}
case UPGRADED: {
int readableBytes = buffer.readableBytes();
if (readableBytes > 0) {
// Keep on consuming as otherwise we may trigger an DecoderException,
// other handler will replace this codec with the upgraded protocol codec to
// take the traffic over at some point then.
// See https://github.com/netty/netty/issues/2173
ByteBuf opaquePayload = buffer.readBytes(readableBytes);
cumulationIndex = buffer.readerIndex();
// TODO(scott): revisit how upgrades are going to be done. Do we use Netty buffers or not?
ctx.fireChannelRead(opaquePayload);
}
break;
}
default:
throw new Error();
}
}
@Override
protected final ByteBuf swapCumulation(ByteBuf cumulation, ByteBufAllocator allocator) {
final int readerIndex = cumulation.readerIndex();
ByteBuf newCumulation = super.swapCumulation(cumulation, allocator);
cumulationIndex -= readerIndex - newCumulation.readerIndex();
return newCumulation;
}
@Override
protected final void cumulationReset() {
cumulationIndex = -1;
}
@Override
protected final void decodeLast(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
super.decodeLast(ctx, in);
// Handle the last unfinished message.
if (message != null) {
boolean chunked = isTransferEncodingChunked(message.headers());
if (currentState == State.READ_VARIABLE_LENGTH_CONTENT && !in.isReadable() && !chunked) {
// End of connection.
ctx.fireChannelRead(EmptyHttpHeaders.INSTANCE);
closeHandler.protocolPayloadEndInbound(ctx);
resetNow();
return;
}
if (currentState == State.READ_HEADER) {
// If we are still in the state of reading headers we need to create a new invalid message that
// signals that the connection was closed before we received the headers.
ctx.fireExceptionCaught(
new PrematureChannelClosureException("Connection closed before received headers"));
resetNow();
return;
}
// Check if the closure of the connection signifies the end of the content.
boolean prematureClosure;
if (isDecodingRequest() || chunked) {
// The last request did not wait for a response.
prematureClosure = true;
} else {
// Compare the length of the received content and the 'Content-Length' header.
// If the 'Content-Length' header is absent, the length of the content is determined by the end of the
// connection, so it is perfectly fine.
prematureClosure = contentLength() > 0;
}
if (!prematureClosure) {
ctx.fireChannelRead(EmptyHttpHeaders.INSTANCE);
closeHandler.protocolPayloadEndInbound(ctx);
}
resetNow();
}
}
@Override
public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof HttpExpectationFailedEvent) {
switch (currentState) {
case READ_FIXED_LENGTH_CONTENT:
case READ_VARIABLE_LENGTH_CONTENT:
case READ_CHUNK_SIZE:
// TODO(scott): this was previously reset, which delayed resetting state ... is that necessary?
resetNow();
break;
default:
break;
}
}
super.userEventTriggered(ctx, evt);
}
protected abstract boolean isContentAlwaysEmpty(T msg);
/**
* Returns true if the server switched to a different protocol than HTTP/1.0 or HTTP/1.1, e.g. HTTP/2 or Websocket.
* Returns false if the upgrade happened in a different layer, e.g. upgrade from HTTP/1.1 to HTTP/1.1 over TLS.
*/
private static boolean isSwitchingToNonHttp1Protocol(HttpResponseMetaData msg) {
if (msg.status().code() != SWITCHING_PROTOCOLS.code()) {
return false;
}
CharSequence newProtocol = msg.headers().get(UPGRADE);
return newProtocol == null ||
!AsciiString.contains(newProtocol, HTTP_1_0.toString()) &&
!AsciiString.contains(newProtocol, HTTP_1_1.toString());
}
private void resetNow() {
T message = this.message;
this.message = null;
this.trailer = null;
contentLength = Long.MIN_VALUE;
cumulationIndex = -1;
if (!isDecodingRequest()) {
HttpResponseMetaData res = (HttpResponseMetaData) message;
if (res != null && isSwitchingToNonHttp1Protocol(res)) {
currentState = State.UPGRADED;
return;
}
}
currentState = State.SKIP_CONTROL_CHARS;
}
private boolean skipControlCharacters(ByteBuf buffer) {
if (cumulationIndex < 0) {
cumulationIndex = buffer.readerIndex();
}
int i = buffer.forEachByte(cumulationIndex, buffer.writerIndex() - cumulationIndex,
SKIP_CONTROL_CHARS_PROCESSOR);
if (i < 0) {
cumulationIndex = buffer.writerIndex();
return false;
} else {
cumulationIndex = i;
buffer.readerIndex(i);
return true;
}
}
private void parseHeaderLine(HttpHeaders headers, ByteBuf buffer, final int lfIndex) {
// https://tools.ietf.org/html/rfc7230#section-3.2
// header-field = field-name ":" OWS field-value OWS
//
// field-name = token
// field-value = *( field-content / obs-fold )
// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
// field-vchar = VCHAR / obs-text
//
// obs-fold = CRLF 1*( SP / HTAB )
// ; obsolete line folding
// ; see Section 3.2.4
final int nonControlIndex = lfIndex - 2;
int headerStart = buffer.forEachByte(buffer.readerIndex(), nonControlIndex - buffer.readerIndex(),
FIND_NON_LINEAR_WHITESPACE);
if (headerStart < 0) {
throw new IllegalArgumentException("unable to find start of header name");
}
int headerEnd = buffer.forEachByte(headerStart + 1, nonControlIndex - headerStart,
FIND_COLON_OR_WHITE_SPACE);
if (headerEnd < 0) {
throw new IllegalArgumentException("unable to find end of header name");
}
int valueStart = headerEnd + 1;
// We assume the allocator will not leak memory, and so we retain + slice to avoid copying data.
CharSequence name = newAsciiString(newBufferFrom(buffer.retainedSlice(headerStart, headerEnd - headerStart)));
if (buffer.getByte(headerEnd) != COLON_BYTE) {
valueStart = buffer.forEachByte(headerEnd + 1, nonControlIndex - headerEnd, FIND_COLON) + 1;
if (valueStart < 0) {
throw new IllegalArgumentException("unable to find colon");
}
}
if (nonControlIndex < valueStart) {
headers.add(name, emptyAsciiString());
} else {
valueStart = buffer.forEachByte(valueStart, nonControlIndex - valueStart + 1, FIND_NON_LINEAR_WHITESPACE);
// Find End Of String
int valueEnd;
if (valueStart < 0 || (valueEnd = buffer.forEachByteDesc(valueStart, lfIndex - valueStart - 1,
FIND_NON_LINEAR_WHITESPACE)) < 0) {
headers.add(name, emptyAsciiString());
} else {
// We assume the allocator will not leak memory, and so we retain + slice to avoid copying data.
headers.add(name, newAsciiString(newBufferFrom(
buffer.retainedSlice(valueStart, valueEnd - valueStart + 1))));
}
}
// Consume the header line bytes from the buffer.
consumeCRLF(buffer, lfIndex);
}
@Nullable
private State readHeaders(ByteBuf buffer) {
int lfIndex = findCRLF(buffer, maxHeaderFieldLength);
if (lfIndex < 0) {
return null;
}
final T message = this.message;
assert message != null;
if (!parseAllHeaders(buffer, message.headers(), lfIndex, maxHeaderFieldLength)) {
return null;
}
if (isContentAlwaysEmpty(message)) {
removeTransferEncodingChunked(message.headers());
return State.SKIP_CONTROL_CHARS;
} else if (isTransferEncodingChunked(message.headers())) {
return State.READ_CHUNK_SIZE;
} else if (contentLength() >= 0) {
return State.READ_FIXED_LENGTH_CONTENT;
} else {
return State.READ_VARIABLE_LENGTH_CONTENT;
}
}
private long contentLength() {
if (contentLength == Long.MIN_VALUE) {
assert message != null;
contentLength = getContentLength(message);
}
return contentLength;
}
@Nullable
private HttpHeaders readTrailingHeaders(ByteBuf buffer) {
final int lfIndex = findCRLF(buffer, maxHeaderFieldLength);
if (lfIndex < 0) {
return null;
}
if (lfIndex - 2 > buffer.readerIndex()) {
HttpHeaders trailer = this.trailer;
if (trailer == null) {
trailer = this.trailer = headersFactory.newTrailers();
}
return parseAllHeaders(buffer, trailer, lfIndex, maxHeaderFieldLength) ? trailer : null;
}
consumeCRLF(buffer, lfIndex);
// The RFC says the trailers are optional [1] so use an empty trailers instance from the headers factory.
// [1] https://tools.ietf.org/html/rfc7230.html#section-4.1
return trailer != null ? trailer : headersFactory.newEmptyTrailers();
}
private boolean parseAllHeaders(ByteBuf buffer, HttpHeaders headers, int lfIndex, int maxHeaderFieldLength) {
for (;;) {
if (lfIndex - 1 == buffer.readerIndex()) {
consumeCRLF(buffer, lfIndex);
return true;
}
final int nextLFIndex = findCRLF(buffer, lfIndex + 1, maxHeaderFieldLength);
parseHeaderLine(headers, buffer, lfIndex);
if (nextLFIndex < 0) {
return false;
} else if (nextLFIndex - 2 == lfIndex) {
consumeCRLF(buffer, nextLFIndex);
return true;
}
lfIndex = nextLFIndex;
}
}
private static long getChunkSize(ByteBuf buffer, int lfIndex) {
if (lfIndex - 2 < buffer.readerIndex()) {
throw new DecoderException("chunked encoding specified but chunk-size not found");
}
return getChunkSize(buffer.toString(buffer.readerIndex(),
lfIndex - 1 - buffer.readerIndex(), US_ASCII));
}
private static long getChunkSize(String hex) {
hex = hex.trim();
for (int i = 0; i < hex.length(); ++i) {
char c = hex.charAt(i);
if (c == ';' || isWhitespace(c) || isISOControl(c)) {
hex = hex.substring(0, i);
break;
}
}
return Long.parseLong(hex, 16);
}
private void consumeCRLF(ByteBuf buffer, int lfIndex) {
// Consume the initial line bytes from the buffer.
if (buffer.writerIndex() - 1 >= lfIndex) {
buffer.readerIndex(lfIndex + 1);
cumulationIndex = lfIndex + 1;
} else {
buffer.readerIndex(lfIndex);
cumulationIndex = lfIndex;
}
}
private int findCRLF(ByteBuf buffer, int maxLineSize) {
if (cumulationIndex < 0) {
cumulationIndex = buffer.readerIndex();
}
int lfIndex = findCRLF(buffer, cumulationIndex, maxLineSize);
cumulationIndex = lfIndex < 0 ? min(buffer.writerIndex(), cumulationIndex + maxLineSize) : lfIndex;
return lfIndex;
}
private static int findCRLF(ByteBuf buffer, int startIndex, final int maxLineSize) {
final int maxToIndex = startIndex + maxLineSize;
for (;;) {
final int toIndex = min(buffer.writerIndex(), maxToIndex);
final int lfIndex = findLF(buffer, startIndex, toIndex);
if (lfIndex == -1) {
if (toIndex - startIndex == maxLineSize) {
throw new IllegalStateException("Could not find CRLF within " + maxLineSize + " bytes.");
}
return -2;
} else if (lfIndex == buffer.readerIndex()) {
buffer.skipBytes(1);
++startIndex;
} else if (buffer.getByte(lfIndex - 1) == CR) {
return lfIndex;
} else if (lfIndex != maxToIndex) {
// Found LF but no CR before
if (lfIndex == buffer.writerIndex()) {
return -2;
}
startIndex = lfIndex + 1;
} else {
throw new TooLongFrameException("An HTTP line is larger than " + maxLineSize + " bytes.");
}
}
}
private static int findLF(final ByteBuf buffer, final int fromIndex, final int toIndex) {
if (fromIndex >= toIndex) {
return -1;
}
return buffer.forEachByte(fromIndex, toIndex - fromIndex, FIND_LF);
}
static void splitInitialLineError() {
throw new IllegalArgumentException("invalid initial line");
}
private static int getWebSocketContentLength(HttpMetaData message) {
// WebSocket messages have constant content-lengths.
HttpHeaders h = message.headers();
if (message instanceof HttpRequestMetaData) {
HttpRequestMetaData req = (HttpRequestMetaData) message;
// Note that we are using ServiceTalk constants for HttpRequestMethod here, and assume the decoders will
// also use ServiceTalk constants which allows us to use reference check here:
if (req.method() == GET &&
h.contains(SEC_WEBSOCKET_KEY1) &&
h.contains(SEC_WEBSOCKET_KEY2)) {
return 8;
}
} else if (message instanceof HttpResponseMetaData) {
HttpResponseMetaData res = (HttpResponseMetaData) message;
if (res.status().code() == SWITCHING_PROTOCOLS.code() &&
h.contains(SEC_WEBSOCKET_ORIGIN) &&
h.contains(SEC_WEBSOCKET_LOCATION)) {
return 16;
}
}
// Not a web socket message
return -1;
}
private static long getContentLength(HttpMetaData message) {
CharSequence value = message.headers().get(CONTENT_LENGTH);
if (value != null) {
return Long.parseLong(value.toString());
}
// We know the content length if it's a Web Socket message even if
// Content-Length header is missing.
long webSocketContentLength = getWebSocketContentLength(message);
if (webSocketContentLength >= 0) {
return webSocketContentLength;
}
// Otherwise we don't.
return -1;
}
static HttpProtocolVersion nettyBufferToHttpVersion(ByteBuf buffer, int start, int length) {
if (length < 8) {
httpVersionError(buffer, start, length);
}
if (buffer.getByte(start + 6) != (byte) '.') {
httpVersionError(buffer, start, length);
}
final int major = buffer.getByte(start + 5) - '0';
if (major < 0 || major > 9) {
httpVersionError(buffer, start, length);
}
final int minor = buffer.getByte(start + 7) - '0';
if (minor < 0 || minor > 9) {
httpVersionError(buffer, start, length);
}
return HttpProtocolVersion.of(major, minor);
}
private static void httpVersionError(ByteBuf buffer, int start, int length) {
throw new IllegalArgumentException("Incorrect http version: " + buffer.toString(start, length, US_ASCII));
}
}
| 42.87205 | 119 | 0.591678 |
69de20a39e00328d5ca4acfa0a0495b19a0639b3 | 3,491 | /*
* Copyright 2015-2019 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* 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.n52.shetland.w3c.soap;
import java.util.List;
import org.n52.shetland.ogc.ows.exception.OwsExceptionReport;
import org.n52.shetland.ogc.ows.service.OwsServiceResponse;
/**
* Representation of a SOAP response
*
* @since 1.0.0
*
*/
public class SoapResponse {
private String soapNamespace;
private String soapVersion;
private String soapAction;
private SoapFault soapFault;
private OwsServiceResponse bodyContent;
private List<SoapHeader> header;
private OwsExceptionReport exception;
public SoapResponse() {
}
/**
* @return the soapNamespace
*/
public String getSoapNamespace() {
return soapNamespace;
}
/**
* @param soapNamespace
* the soapNamespace to set
*/
public void setSoapNamespace(String soapNamespace) {
this.soapNamespace = soapNamespace;
}
public boolean hasSoapNamespace() {
return getSoapNamespace() != null && !getSoapNamespace().isEmpty();
}
/**
* @return the soapVersion
*/
public String getSoapVersion() {
return soapVersion;
}
/**
* @param soapVersion
* the soapVersion to set
*/
public void setSoapVersion(String soapVersion) {
this.soapVersion = soapVersion;
}
public boolean hasSoapVersion() {
return getSoapVersion() != null && !getSoapVersion().isEmpty();
}
public void setSoapFault(SoapFault soapFault) {
this.soapFault = soapFault;
}
public SoapFault getSoapFault() {
return soapFault;
}
public OwsServiceResponse getSoapBodyContent() {
return bodyContent;
}
public void setSoapAction(String soapAction) {
this.soapAction = soapAction;
}
public String getSoapAction() {
return soapAction;
}
public void setSoapBodyContent(OwsServiceResponse bodyContent) {
this.bodyContent = bodyContent;
}
public void setBodyContent(OwsServiceResponse response) {
this.bodyContent = response;
}
public OwsServiceResponse getBodyContent() {
return bodyContent;
}
public void setHeader(List<SoapHeader> list) {
this.header = list;
}
public List<SoapHeader> getHeader() {
return header;
}
public void setException(OwsExceptionReport owse) {
this.exception = owse;
}
public OwsExceptionReport getException() {
return exception;
}
public boolean hasException() {
return exception != null;
}
public boolean isSetXmlBodyContent() {
return getSoapBodyContent() != null;
}
public boolean isSetBodyContent() {
return getBodyContent() != null;
}
public boolean isSetSoapFault() {
return getSoapFault() != null;
}
}
| 22.967105 | 75 | 0.657118 |
1a8d366d73b6f2443fdbd11d4b099a2f341b1ae0 | 159 | package com.projectlounge.json;
import lombok.Data;
/**
* Created by main on 24.08.17.
*/
@Data
public class RawIndices {
private Integer[] indices;
}
| 13.25 | 31 | 0.691824 |
829216dd9228f66599d12013226a4c84c133a057 | 2,584 | package com.listenergao.customview.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import com.listenergao.customview.R;
import com.listenergao.customview.utils.ResourceUtil;
import androidx.core.app.ActivityCompat;
/**
* 自定义简单的SportsView
* 练习ObjectAnimator动画使用
* <p>
* 使用方式:
* 1.如果是自定义控件, 需要添加 setter / getter 方法
* 2.用ObjectAnimator.ofXXX()创建ObjectAnimator对象(XXX和属性声明的类型有关, 如本例中 progress 为 int类型, 使用时就是ObjectAnimator.ofInt())
* 3.使用start方法执行动画
*
* @author ListenerGao
* @date 2019-04-17 15:24
*/
public class SportsWithAnimatorView extends View {
private static final int RADIUS = ResourceUtil.dp2px(130);
private Paint paint;
private RectF bounds;
private Rect textBounds = new Rect();
private int progress = 0;
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
invalidate();
}
public SportsWithAnimatorView(Context context) {
super(context);
}
public SportsWithAnimatorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SportsWithAnimatorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(ResourceUtil.dp2px(20));
bounds = new RectF();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float centerX = getWidth() / 2;
float centerY = getHeight() / 2;
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(ResourceUtil.dp2px(20));
paint.setColor(ActivityCompat.getColor(getContext(), R.color.colorAccent));
paint.setStrokeCap(Paint.Cap.ROUND);
bounds.set(centerX - RADIUS, centerY - RADIUS, centerX + RADIUS, centerY + RADIUS);
canvas.drawArc(bounds, 90, progress * 3.6f, false, paint);
paint.setStrokeCap(Paint.Cap.BUTT);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
String text = progress + "%";
paint.getTextBounds(text, 0, text.length(), textBounds);
float yOffset = (textBounds.top + textBounds.bottom) / 2;
canvas.drawText(text, centerX, centerY - yOffset, paint);
}
}
| 27.489362 | 113 | 0.684211 |
a5388e419ff69b0d871168a4105ee36af6effdb7 | 4,502 | package com.example.singhnicershop;
import android.content.Context;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.singhnicershop.model.ShoppingItems;
import java.util.LinkedList;
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder>{
@NonNull
private LayoutInflater mInflater;
private final LinkedList<ShoppingItems> mdata;
private static final String TAG = "com.example.android.singhnicershop";
public ProductAdapter(Context context, LinkedList<ShoppingItems> list) {
mInflater = LayoutInflater.from(context);
this.mdata = list;
}
//inflate the item layout and return a ViewHolder object
public ProductAdapter.ProductViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View mItemView = mInflater.inflate(R.layout.card1_content,viewGroup,false);
return new ProductViewHolder(mItemView, this);
}
// set the ViewHolder attributes based on the position of the item
@Override
public void onBindViewHolder(@NonNull ProductAdapter.ProductViewHolder holder, int position) {
ShoppingItems mCurrent = mdata.get(position);
holder.image.setImageResource(mCurrent.getImage());
holder.title_textView.setText(mCurrent.getTitle());
holder.description_textView.setText(mCurrent.getDescription());
holder.price_textView.setText(mCurrent.getPrice());
holder.quantity_textView.setText(mCurrent.getQuantity());
holder.subtotal_textView.setText(mCurrent.getSubtotal());
}
//return the size of the data
@Override
public int getItemCount() {
return mdata.size();
}
//registers the clicks
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final ProductAdapter mAdapter;
TextView title_textView;
TextView price_textView;
TextView description_textView;
TextView quantity_textView;
ImageView image;
TextView subtotal_textView;
Button increase;
Button decrease;
CardView cardView;
//int mPosition = getLayoutPosition();
int mPosition;
public ProductViewHolder(@NonNull View itemView, ProductAdapter adapter) {
super(itemView);
this.mAdapter = adapter;
cardView = itemView.findViewById(R.id.cardView);
title_textView = itemView.findViewById(R.id.title_textview);
price_textView = itemView.findViewById(R.id.price_textview);
description_textView = itemView.findViewById(R.id.description);
quantity_textView = itemView.findViewById(R.id.amount);
image = itemView.findViewById(R.id.pictureView);
subtotal_textView = itemView.findViewById(R.id.subtotal);
increase = itemView.findViewById(R.id.increaseButton);
decrease = itemView.findViewById(R.id.decreaseButton);
int mPosition = getLayoutPosition();
increase.setOnClickListener(this);
decrease.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//registere what button is clicked
int position = getLayoutPosition();
ShoppingItems sample = mdata.get(position);
int quantity = Integer.parseInt(sample.getQuantity());
double price = Double.parseDouble(sample.getPrice().substring(1));
switch (v.getId()){
case R.id.increaseButton:
quantity++;
Log.d(TAG,"Increase pressed, "+sample.getTitle() +", "+ sample.getPrice());
break;
case R.id.decreaseButton:
if(quantity > 0)
quantity--;
Log.d(TAG,"Decrease pressed, "+sample.getTitle() +", "+ sample.getPrice());
break;
}
double subtotal = quantity*price;
sample.setQuantity(""+quantity);
sample.setSubtotal(""+subtotal);
mAdapter.notifyDataSetChanged();
}
}
}
| 37.206612 | 101 | 0.664149 |
c1f6bd41d43ecefb6521b7aeef7f6ed42d36d1da | 1,072 | package ru.javawebinar.basejava;
public class MainConcurrency {
Object lock1 = new Object();
Object lock2 = new Object();
public static void main(String[] args) {
MainConcurrency deadlock = new MainConcurrency();
for (int i = 0; i < 2; i++) {
new Thread(deadlock::method1).start();
new Thread(deadlock::method2).start();
}
}
public void method1() {
synchronized (lock1) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + " executing method1");
}
}
}
public void method2() {
synchronized (lock2) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + " executing method2");
}
}
}
}
| 26.8 | 92 | 0.514925 |
6e298469457b86ec67d0d799136a683f165c4e2c | 1,613 | package com.young.share.adapter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.ActionBar;
import android.view.View;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.young.share.R;
import com.young.share.adapter.baseAdapter.BasePagerAdapter;
import com.young.share.model.PictureInfo;
import com.young.share.views.photoview.PhotoView;
import java.util.List;
public class ImageEditorPagerAdapter extends BasePagerAdapter<PictureInfo> {
private ActionBar mActionBar;
public ImageEditorPagerAdapter(Context context, List<PictureInfo> dataList, ActionBar mActionBar) {
super(context);
this.dataList = dataList;
this.mActionBar = mActionBar;
}
@Override
protected int getLayout() {
return R.layout.item_photoview;
}
@Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
@Override
protected void instanceItem(View v, PictureInfo pictureInfo, int position) {
PhotoView photo = (PhotoView) v.findViewById(R.id.pv_item_photoview);
// photo.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
// @Override
// public void onPhotoTap(View view, float x, float y) {
// if (mActionBar.isShowing()) {
// mActionBar.hide();
// } else {
// mActionBar.show();
// }
// }
// });
ImageLoader.getInstance().displayImage(pictureInfo.imageUrl, photo);
}
}
| 27.810345 | 103 | 0.67142 |
e770ca687dcaedc698186903e6e4f563a9c91a7f | 210 | package examples.classdesign.superclassmismatch.interfaces;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
public interface Multiple extends Iterator, Function, List {}
| 26.25 | 61 | 0.828571 |
836f25010870b4b1ab38ac36a0b9da246569252f | 6,396 | package com.github.kmizu.parser_hands_on_kansai.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JSONNode {
public static class Pair<A, B> {
public final A _1;
public final B _2;
public Pair(A _1, B _2) {
this._1 = _1;
this._2 = _2;
}
@Override
public int hashCode() {
return _1.hashCode() + _2.hashCode();
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Pair<?, ?>)) {
return false;
} else {
Pair<A, B> that = (Pair<A, B>)obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
@Override
public String toString() {
return "(" + _1 + ", " + _2 + ")";
}
}
public static class JSONString extends JSONNode {
public final String value;
public JSONString(String value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof JSONString)) {
return false;
} else {
JSONString that = (JSONString)obj;
return value.equals(that.value);
}
}
@Override
public String toString() {
return "\"" + value.toString() + "\"";
}
}
public static class JSONBoolean extends JSONNode {
public final boolean value;
public JSONBoolean(boolean value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof JSONBoolean)) {
return false;
} else {
JSONBoolean that = (JSONBoolean)obj;
return value == that.value;
}
}
@Override
public String toString() {
return "" + value;
}
}
public static class JSONNumber extends JSONNode {
public final double value;
public JSONNumber(double value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof JSONNumber)) {
return false;
} else {
JSONNumber that = (JSONNumber)obj;
return value == that.value;
}
}
@Override
public String toString() {
return "" + value;
}
}
public static class JSONNull extends JSONNode {
/**
* nullの構文木のインスタンスは一つだけでいい(位置情報を持ちたい場合は別)
*/
private static final JSONNull instance = new JSONNull();
private JSONNull() {}
public static JSONNull getInstance() {
return instance;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public String toString() {
return "null";
}
}
public static class JSONObject extends JSONNode {
public final Map<String, JSONNode> properties;
public JSONObject(Map<String, JSONNode> properties) {
this.properties = properties;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof JSONObject)) {
return false;
} else {
JSONObject that = (JSONObject)obj;
return properties.equals(that.properties);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{\n");
if(properties.size() != 0) {
for(Map.Entry<String, JSONNode> p : properties.entrySet()) {
builder.append(p.getKey());
builder.append(" : ");
builder.append(p.getValue());
}
}
builder.append("}\n");
return new String(builder);
}
}
public static class JSONArray extends JSONNode {
public final List<? extends JSONNode> elements;
public JSONArray(List<JSONNode> elements) {
this.elements = elements;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof JSONArray)) {
return false;
} else {
JSONArray that = (JSONArray) obj;
return elements.equals(that.elements);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
if(elements.size() != 0) {
builder.append(elements.get(0).toString());
for(JSONNode e : elements.subList(1, elements.size())) {
builder.append(", ");
builder.append(e.toString());
}
}
builder.append("]");
return new String(builder);
}
}
public static JSONObject jobject(Pair<String, JSONNode>... pairs) {
Map<String, JSONNode> properties = new HashMap<>();
for(Pair<String, JSONNode> p:pairs) {
properties.put(p._1, p._2);
}
return new JSONObject(properties);
}
public static JSONArray jarray(JSONNode... elements) {
List<JSONNode> es = new ArrayList<>();
for(JSONNode e:elements) {
es.add(e);
}
return new JSONArray(es);
}
public static JSONNull jnull() {
return JSONNull.getInstance();
}
public static JSONNumber jnumber(double value) {
return new JSONNumber(value);
}
public static JSONBoolean jboolean(boolean value) {
return new JSONBoolean(value);
}
public static JSONString jstring(String value) {
return new JSONString(value);
}
public static Pair<String, JSONNode> property(String key, JSONNode value) {
return new Pair<>(key ,value);
}
public static Pair<String, JSONNode> p(String key, JSONNode value) {
return property(key, value);
}
}
| 27.808696 | 79 | 0.512664 |
a291bd7219ecb51095d3a4e6cdfbf78760b620e2 | 116 | package edu.fiuba.algo3.modelo.excepciones;
public class LaTarjetaYaEstaDesactivadaException extends Exception {
}
| 23.2 | 68 | 0.853448 |
ce64ae9b1f57eba0ee3c0d14830265bf46c76360 | 716 | package org.ovirt.engine.core.common.config;
import java.io.File;
public class ConfigUtil {
/**
* Given a relative path, this method will resolve the path relative to the supplied directory. If supplied an
* absolute path, it will be returned unmodified.
*
* @param baseDirectory
* the base directory for relative paths
* @param path
* the path to be resolved if it is relative
* @return an absolute path
*/
public static String resolvePath(String baseDirectory, String path) {
if (new File(path).isAbsolute()) {
return path;
} else {
return baseDirectory + File.separator + path;
}
}
}
| 29.833333 | 114 | 0.618715 |
f7d6e458a899ff4ca5fd72f82f2403991bb4565f | 4,868 | /**
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.bsoncodec.test;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.assertj.core.data.MapEntry;
import org.bson.Document;
import org.bson.codecs.ObjectIdGenerator;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.junit.Test;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import ch.rasc.bsoncodec.test.pojo.StringPojo;
import ch.rasc.bsoncodec.test.pojo.StringPojoCodec;
public class StringPojoTest extends AbstractMongoDBTest {
private final static String COLL_NAME = "strings";
private MongoDatabase connect() {
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(new StringPojoCodec(new ObjectIdGenerator())));
MongoDatabase db = getMongoClient().getDatabase("pojo")
.withCodecRegistry(codecRegistry);
return db;
}
private static StringPojo insert(MongoDatabase db) {
MongoCollection<StringPojo> coll = db.getCollection(COLL_NAME, StringPojo.class);
StringPojo pojo = new StringPojo();
pojo.setScalar("a");
pojo.setArray(new String[] { "b", "cc", "ddd" });
pojo.setArray2(new String[][] { { "111", "112" }, { "221", "222" } });
pojo.setList(Arrays.asList("zxy", "yxz"));
Set<String> set = new HashSet<>();
set.add("eee");
set.add("fff");
pojo.setSet(set);
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, null);
pojo.setMap(map);
coll.insertOne(pojo);
return pojo;
}
private static StringPojo insertEmpty(MongoDatabase db) {
MongoCollection<StringPojo> coll = db.getCollection(COLL_NAME, StringPojo.class);
StringPojo pojo = new StringPojo();
coll.insertOne(pojo);
return pojo;
}
@Test
public void testInsertAndFind() {
MongoDatabase db = connect();
StringPojo pojo = insert(db);
MongoCollection<StringPojo> coll = db.getCollection(COLL_NAME, StringPojo.class);
StringPojo read = coll.find().first();
assertThat(read).usingRecursiveComparison().isEqualTo(pojo);
StringPojo empty = coll.find().projection(Projections.include("id")).first();
assertThat(empty.getScalar()).isNull();
assertThat(empty.getArray()).isNull();
assertThat(empty.getArray2()).isNull();
assertThat(empty.getList()).isNull();
assertThat(empty.getSet()).isNull();
assertThat(empty.getMap()).isNull();
}
@Test
public void testInsertAndFindEmpty() {
MongoDatabase db = connect();
StringPojo pojo = insertEmpty(db);
MongoCollection<StringPojo> coll = db.getCollection(COLL_NAME, StringPojo.class);
StringPojo read = coll.find().first();
assertThat(read).usingRecursiveComparison().isEqualTo(pojo);
}
@SuppressWarnings("unchecked")
@Test
public void testWithDocument() {
MongoDatabase db = connect();
StringPojo pojo = insert(db);
MongoCollection<Document> coll = db.getCollection(COLL_NAME);
Document doc = coll.find().first();
assertThat(doc).hasSize(7);
assertThat(doc.get("_id")).isEqualTo(pojo.getId());
assertThat(doc.get("scalar")).isEqualTo("a");
assertThat((List<String>) doc.get("array")).containsExactly("b", "cc", "ddd");
assertThat((List<List<String>>) doc.get("array2")).containsExactly(
Arrays.asList("111", "112"), Arrays.asList("221", "222"));
assertThat((List<String>) doc.get("list")).containsExactly("zxy", "yxz");
assertThat((List<String>) doc.get("set")).containsOnly("eee", "fff");
assertThat((Map<String, String>) doc.get("map")).containsOnly(
MapEntry.entry("1", "one"), MapEntry.entry("2", "two"),
MapEntry.entry("3", "three"), MapEntry.entry("4", null));
}
@Test
public void testEmptyWithDocument() {
MongoDatabase db = connect();
StringPojo pojo = insertEmpty(db);
MongoCollection<Document> coll = db.getCollection(COLL_NAME);
Document doc = coll.find().first();
assertThat(doc).hasSize(1);
assertThat(doc.get("_id")).isEqualTo(pojo.getId());
}
}
| 32.671141 | 83 | 0.725144 |
c5761a644f929d87ecfd436f5527a32dcc0150da | 1,511 | /*
* Copyright 2015 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.tableeditor.settings.handler;
import java.util.List;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.robotframework.ide.eclipse.main.plugin.model.RobotSetting;
import org.robotframework.ide.eclipse.main.plugin.model.cmd.settings.DeleteSettingCommand;
import org.robotframework.ide.eclipse.main.plugin.tableeditor.RobotEditorCommandsStack;
import org.robotframework.ide.eclipse.main.plugin.tableeditor.settings.handler.DeleteSettingsHandler.E4DeleteSettingsHandler;
import org.robotframework.red.commands.DIParameterizedHandler;
import org.robotframework.red.viewers.Selections;
public class DeleteSettingsHandler extends DIParameterizedHandler<E4DeleteSettingsHandler> {
public DeleteSettingsHandler() {
super(E4DeleteSettingsHandler.class);
}
public static class E4DeleteSettingsHandler {
@Execute
public void deleteSettings(final RobotEditorCommandsStack commandsStack,
@Named(Selections.SELECTION) final IStructuredSelection selection) {
final List<RobotSetting> settings = Selections.getElements(selection, RobotSetting.class);
commandsStack.execute(new DeleteSettingCommand(settings));
}
}
}
| 39.763158 | 125 | 0.776969 |
7c0cbffd8e2095958b05bb0bc219a9b54f5a16ae | 404 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edacc.manageDB;
/**
*
* @author rretz
*/
public class NoInstancesToSaveException extends Exception{
public NoInstancesToSaveException() {
this("There is no instance to save in the table.");
}
public NoInstancesToSaveException(String msg) {
super(msg);
}
}
| 19.238095 | 59 | 0.670792 |
73584b74f06909173b8e8adaf4472d6448d847b6 | 9,491 | package de.kodestruktor.grief.taglib.property;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import de.kodestruktor.grief.taglib.tag.Favicon;
import de.kodestruktor.grief.taglib.tag.Image;
import de.kodestruktor.grief.taglib.tag.Pagination;
import de.kodestruktor.grief.taglib.tag.Script;
import de.kodestruktor.grief.taglib.tag.Style;
import de.kodestruktor.grief.taglib.tag.Version;
/**
* Constants used in grief internally.
*
* @author Christoph Wende
*/
public final class GriefTaglibProperty {
/**
* Empty private constructor to avoid instantiation.
*/
private GriefTaglibProperty() {
// Here be dragons...
}
static {
final Map<Pattern, String> map = new HashMap<>(2);
map.put(Pattern.compile(".+\\.ico$"), "image/x-icon");
map.put(Pattern.compile(".+\\.gif$"), "image/gif");
map.put(Pattern.compile(".+\\.png$"), "image/png");
map.put(Pattern.compile(".+\\.jp[eg]{1,2}$"), "image/jpeg");
FAVICON_MIME_TYPES = Collections.unmodifiableMap(map);
}
/**
* Property containing possible mime types for simple mapping against a file extension.
*
* @see Favicon
*/
public static final Map<Pattern, String> FAVICON_MIME_TYPES;
/**
* Property containing the default mime type, in case the correct mime type cannot be determined.
*
* @see Favicon
*/
public static final String FAVICON_DEFAULT_MIME_TYPE = "application/octet-stream";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Used to globally enable or disable the version tag, e.g.:<br>
* <br>
* <code>grief.version.enabled=true</code>
*
* @see Version
*/
public static final String VERSION_PROP_ENABLED = "grief.version.enabled";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Used to globally enable or disable the version tags outpus in comment style, e.g.:<br>
* <br>
* <code>grief.version.comment.enabled=true</code>
*
* @see Version
*/
public static final String VERSION_PROP_COMMENT_ENABLED = "grief.version.comment.enabled";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Used to globally enable or disable the version tags outpus in content style, e.g.:<br>
* <br>
* <code>grief.version.content.enabled=true</code>
*
* @see Version
*/
public static final String VERSION_PROP_CONTENT_ENABLED = "grief.version.content.enabled";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Used to globally enable or disable the version tags outpus in meta style, e.g.:<br>
* <br>
* <code>grief.version.meta.enabled=true</code>
*
* @see Version
*/
public static final String VERSION_PROP_META_ENABLED = "grief.version.meta.enabled";
/**
* Output format of the version tag, when rendered in meta style.
*
* @see Version
*/
public static final String VERSION_TAG_META_SIMPLE = "<meta name=\"%s\" content=\"%s\" />";
/**
* Output format of the version tag, when rendered in meta style.
*
* @see Version
*/
public static final String VERSION_TAG_META_COMBINED = "<meta name=\"%s\" content=\"%sr%s\" />";
/**
* Output format of the version tag, when rendered in content style.
*
* @see Version
*/
public static final String VERSION_TAG_CONTENT_SIMPLE = "<span id=\"%s\">%s: %s</span>";
/**
* Output format of the version tag, when rendered in content style.
*
* @see Version
*/
public static final String VERSION_TAG_CONTENT_COMBINED = "<span id=\"%s\">%s: %sr%s</span>";
/**
* Output format of the version tag, when rendered in comment style.
*
* @see Version
*/
public static final String VERSION_TAG_COMMENT_SIMPLE = "<!-- %s: %s -->";
/**
* Output format of the version tag, when rendered in comment style.
*
* @see Version
*/
public static final String VERSION_TAG_COMMENT_COMBINED = "<!-- %s: %sr%s -->";
/**
* Default URL parameter name for defining the page size in generated links of the page numbers.
*
* @see Pagination
*/
public static final String PAGINATION_PAGE_SIZE_PARAMETER = "size";
/**
* Default URL parameter name for defining the page number in generated links of the page numbers.
*
* @see Pagination
*/
public static final String PAGINATION_PAGE_NUMBER_PARAMETER = "page";
/**
* Message code that may be set in the resource bundle of the application using grief. <br>
* Lables the paginations 'next' button.
*
* @see Pagination
*/
public static final String PAGINATION_PROP_NEXT = "grief.pagiantion.next";
/**
* Message code that may be set in the resource bundle of the application using grief. <br>
* Lables the paginations 'prev' button.
*
* @see Pagination
*/
public static final String PAGINATION_PROP_PREV = "grief.pagiantion.prev";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Configures the base directory for all web resources such as js, css or images; e.g.:<br>
* <br>
* <code>grief.resource.dir.base.resource=/resources</code>
*
* @see Image
* @see Script
* @see Style
*/
public static final String RESOURCE_PROP_BASEDIR_RESOURCES = "grief.resource.dir.base.resource";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Configures the base directory for <b>static</b> web resources, relative to the resources basedir configured in
* {@link GriefTaglibProperty#RESOURCE_PROP_BASEDIR_RESOURCES}. <br>
* <br>
* Example: <br>
* <code>grief.resource.dir.base.static=/static</code>
*
* @see Image
* @see Script
* @see Style
*/
public static final String RESOURCE_PROP_BASEDIR_STATIC = "grief.resource.dir.base.static";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Configures the prefix for the <b>versioned</b> web resources base directory, relative to the resources basedir configured in
* {@link GriefTaglibProperty#RESOURCE_PROP_BASEDIR_RESOURCES}. <br>
* <br>
* Example: <br>
* <code>grief.resource.dir.version.prefix=/r</code>
*
* @see Image
* @see Script
* @see Style
*/
public static final String RESOURCE_PROP_VERSIONDIR_PREFIX = "grief.resource.dir.version.prefix";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Configures the directory for image resources, relative to the static and/or versioned directories. <br>
* <br>
* Example: <br>
* <code>grief.resource.dir.image=/images</code>
*
* @see GriefTaglibProperty#RESOURCE_PROP_BASEDIR_RESOURCES
* @see GriefTaglibProperty#RESOURCE_PROP_VERSIONDIR_PREFIX
* @see Image
* @see Script
* @see Style
*/
public static final String RESOURCE_PROP_IMAGEDIR = "grief.resource.dir.image";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Configures the directory for script resources, relative to the static and/or versioned directories. <br>
* <br>
* Example: <br>
* <code>grief.resource.dir.image=/images</code>
*
* @see GriefTaglibProperty#RESOURCE_PROP_BASEDIR_RESOURCES
* @see GriefTaglibProperty#RESOURCE_PROP_VERSIONDIR_PREFIX
* @see Image
* @see Script
* @see Style
*/
public static final String RESOURCE_PROP_SCRIPTDIR = "grief.resource.dir.script";
/**
* Property that may be set in the configuration of the application using grief. <br>
* Configures the directory for stylesheet resources, relative to the static and/or versioned directories. <br>
* <br>
* Example: <br>
* <code>grief.resource.dir.image=/images</code>
*
* @see GriefTaglibProperty#RESOURCE_PROP_BASEDIR_RESOURCES
* @see GriefTaglibProperty#RESOURCE_PROP_VERSIONDIR_PREFIX
* @see Image
* @see Script
* @see Style
*/
public static final String RESOURCE_PROP_STYLEDIR = "grief.resource.dir.style";
/**
* Output format of the static/versioned favicon/link tag.
*
* @see Image
*/
public static final String RESOURCE_TAG_FAVICON = "<link href=\"%s\" rel=\"icon\" type=\"%s\" />";
/**
* Output format of the static/versioned image tag.
*
* @see Image
*/
public static final String RESOURCE_TAG_IMAGE = "<img src=\"%s\" alt=\"%s\" title=\"%s\" class=\"%s\" id=\"%s\" />";
/**
* Output format of the static/versioned script tag.
*
* @see Script
*/
public static final String RESOURCE_TAG_SCRIPT = "<script type=\"text/javascript\" src=\"%s\" id=\"%s\"></script>";
/**
* Output format of the static/versioned asynchronous script tag.
*
* @see Script
*/
public static final String RESOURCE_TAG_SCRIPT_ASYNC = "<script type=\"text/javascript\" src=\"%s\" id=\"%s\" async></script>";
/**
* Output format of the static/versioned style/link tag.
*
* @see Style
*/
public static final String RESOURCE_TAG_STYLE = "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\" id=\"%s\" />";
}
| 33.301754 | 130 | 0.662101 |
a05b3ea8ff6aefcc79c18c844ade0f011c6bd6ed | 7,460 | /*
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* Copyright (c) 2019, Jordan Atwood <[email protected]>
* Copyright (c) 2019, Jajack
* Copyright (c) 2019, Siraz <https://github.com/Sirazzz>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 net.sanlite.client.plugins.playerindicatorsextended;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.FriendsChatRank;
import net.runelite.api.Player;
import net.runelite.api.Point;
import net.runelite.client.game.ChatIconManager;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.util.Text;
import net.sanlite.client.config.PlayerNameLocation;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.awt.*;
import java.awt.image.BufferedImage;
@Slf4j
@Singleton
public class PlayerIndicatorsExtendedOverlay extends Overlay
{
private static final int ACTOR_OVERHEAD_TEXT_MARGIN = 40;
private static final int ACTOR_HORIZONTAL_TEXT_MARGIN = 10;
private final PlayerIndicatorsExtendedService playerIndicatorsService;
private final PlayerIndicatorsExtendedConfig config;
private final ChatIconManager chatIconManager;
@Inject
private PlayerIndicatorsExtendedOverlay(PlayerIndicatorsExtendedConfig config, PlayerIndicatorsExtendedService playerIndicatorsService,
ChatIconManager chatIconManager)
{
this.config = config;
this.playerIndicatorsService = playerIndicatorsService;
this.chatIconManager = chatIconManager;
setPosition(OverlayPosition.DYNAMIC);
setPriority(OverlayPriority.MED);
}
@Override
public Dimension render(Graphics2D graphics)
{
playerIndicatorsService.forEachPlayer((player, type) -> checkPlayerTypes(graphics, player, type));
return null;
}
private void checkPlayerTypes(Graphics2D graphics, Player player, PlayerIndicatorType type)
{
switch (type)
{
case LOCAL:
renderPlayerName(graphics, player, type, config.getOwnPlayerNamePosition(), config.getOwnPlayerColor());
break;
case FRIEND:
renderPlayerName(graphics, player, type, config.getFriendPlayerNamePosition(), config.getFriendColor());
break;
case CUSTOM_LIST_1:
renderPlayerName(graphics, player, type, config.getListOneNamePosition(), config.getListOneColor());
break;
case CUSTOM_LIST_2:
renderPlayerName(graphics, player, type, config.getListTwoNamePosition(), config.getListTwoColor());
break;
case CUSTOM_LIST_3:
renderPlayerName(graphics, player, type, config.getListThreeNamePosition(), config.getListThreeColor());
break;
case CUSTOM_LIST_4:
renderPlayerName(graphics, player, type, config.getListFourNamePosition(), config.getListFourColor());
break;
case CUSTOM_LIST_5:
renderPlayerName(graphics, player, type, config.getListFiveNamePosition(), config.getListFiveColor());
break;
case FRIENDS_CHAT:
renderPlayerName(graphics, player, type, config.getFriendsChatMemberPlayerNamePosition(), config.getFriendsChatMemberColor());
break;
case TEAM_CAPE:
renderPlayerName(graphics, player, type, config.getTeamPlayerNamePosition(), config.getTeamMemberColor());
break;
case OTHER:
renderPlayerName(graphics, player, type, config.getOthersPlayerNamePosition(), config.getOthersColor());
break;
default:
log.warn("Tried rendering name for player: {} with unknown PlayerIndicatorType: {}", player.getName(), type);
}
}
private void renderPlayerName(Graphics2D graphics, Player player, PlayerIndicatorType type, PlayerNameLocation nameLocation, Color color)
{
if (nameLocation == PlayerNameLocation.DISABLED)
{
return;
}
final int zOffset;
switch (nameLocation)
{
case MODEL_CENTER:
case MODEL_RIGHT:
zOffset = player.getLogicalHeight() / 2;
break;
default:
zOffset = player.getLogicalHeight() + ACTOR_OVERHEAD_TEXT_MARGIN;
}
final String playerName = player.getName();
if (playerName == null)
{
return;
}
final String name = Text.sanitize(playerName);
Point textLocation = player.getCanvasTextLocation(graphics, name, zOffset);
if (nameLocation == PlayerNameLocation.MODEL_RIGHT)
{
textLocation = player.getCanvasTextLocation(graphics, "", zOffset);
if (textLocation == null)
{
return;
}
textLocation = new Point(textLocation.getX() + ACTOR_HORIZONTAL_TEXT_MARGIN, textLocation.getY());
}
if (textLocation == null)
{
return;
}
if (config.showFriendsChatRanks() && type == PlayerIndicatorType.FRIENDS_CHAT)
{
final FriendsChatRank rank = playerIndicatorsService.getFriendsChatRank(player);
Point clanRankTextLocation = getNameTextLocationWithClanRank(graphics, rank, textLocation, nameLocation);
if (clanRankTextLocation != null)
{
textLocation = clanRankTextLocation;
}
}
OverlayUtil.renderTextLocation(graphics, textLocation, name, color);
}
private Point getNameTextLocationWithClanRank(Graphics2D graphics, FriendsChatRank rank, Point textLocation, PlayerNameLocation nameLocation)
{
if (rank != FriendsChatRank.UNRANKED)
{
final BufferedImage clanChatImage = chatIconManager.getRankImage(rank);
if (clanChatImage != null)
{
final int clanImageWidth = clanChatImage.getWidth();
final int clanImageTextMargin;
final int clanImageNegativeMargin;
if (nameLocation == PlayerNameLocation.MODEL_RIGHT)
{
clanImageTextMargin = clanImageWidth;
clanImageNegativeMargin = 0;
}
else
{
clanImageTextMargin = clanImageWidth / 2;
clanImageNegativeMargin = clanImageWidth / 2;
}
final int textHeight = graphics.getFontMetrics().getHeight() - graphics.getFontMetrics().getMaxDescent();
final Point imageLocation = new Point(textLocation.getX() - clanImageNegativeMargin - 1, textLocation.getY() - textHeight / 2 - clanChatImage.getHeight() / 2);
OverlayUtil.renderImageLocation(graphics, imageLocation, clanChatImage);
// move text
return new Point(textLocation.getX() + clanImageTextMargin, textLocation.getY());
}
}
return null;
}
} | 36.390244 | 163 | 0.763271 |
433dfb3b304d497fdb7413235f76641bb0a6cd01 | 906 | package main;
/**
* @author Tony Liang
*
*/
public class DaysInAYear
{
public static void main(String[] args)
{
final int STARTING_YEAR = 2000;
final int ENDING_YEAR = 2010;
System.out.println("Year\tDays");
for (int year = STARTING_YEAR; year <= ENDING_YEAR; year++)
{
System.out.printf("%-4d\t%-3d\n", year, numberOfDaysInAYear(year));
}
System.out.println();
}
/**
* Returns the number of days in the specified year.
* <ul>
* <li>
* If the integer argument is less than 1, the number of days will default to 365.
* </li>
* </ul>
*
* @param year year
* @return number of days
*/
public static int numberOfDaysInAYear(int year)
{
boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
if (year < 1)
{
isLeapYear = false;
}
if (isLeapYear)
{
return 366;
}
else
{
return 365;
}
}
} | 17.09434 | 85 | 0.589404 |
69be93e3c454753e230ae6d2ce9955c9080a8ea9 | 114 | package com.autowired;
import org.springframework.stereotype.Component;
@Component
public class TestService {
}
| 14.25 | 48 | 0.815789 |
b740ce081dcc585621c2fb4e9e2f31bca987b206 | 1,334 | package org.infernus.idea.checkstyle.service;
import com.intellij.openapi.project.Project;
import org.infernus.idea.checkstyle.model.ConfigurationLocation;
import org.infernus.idea.checkstyle.model.ConfigurationType;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class StringConfigurationLocation
extends ConfigurationLocation {
private final String configurationXml;
public StringConfigurationLocation(@NotNull final String configurationXml,
@NotNull final Project project) {
super(ConfigurationType.LOCAL_FILE, project);
setDescription("In-memory String-based configuration: " + //
configurationXml.substring(0, Math.min(100, configurationXml.length())) + " ...");
this.configurationXml = configurationXml;
}
@NotNull
@Override
protected InputStream resolveFile(@NotNull ClassLoader checkstyleClassLoader) throws IOException {
return new ByteArrayInputStream(configurationXml.getBytes(StandardCharsets.UTF_8));
}
@Override
public StringConfigurationLocation clone() {
return new StringConfigurationLocation(configurationXml, getProject());
}
}
| 36.054054 | 102 | 0.744378 |
987b9d052fe745f41cb365f4ea63c372c732268d | 3,625 | package org.reggy93.ccrsa.service.impl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.reggy93.ccrsa.service.dao.CountryRepository;
import org.reggy93.ccrsa.service.entity.car.Country;
import org.reggy93.ccrsa.service.exception.ServiceOperationException;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
/**
* Unit test for {@link CountryServiceImpl}.
*
* @author Reggy93 <[email protected]>
* created on 01 Sep 2020
*/
@ExtendWith(MockitoExtension.class)
class CountryServiceImplUnitTest {
private static final Long COUNTRY_POLAND_ID = 1L;
private static final String SERVICE_OPERATION_EXCEPTION_SHOULD_BE_THROWN = "ServiceOperationException should be " +
"thrown as RuntimeException is thrown by countryRepository";
@InjectMocks
private CountryServiceImpl testedService;
@Mock
private CountryRepository countryRepository;
@Mock
private Country country1;
@Mock
private Country country2;
@BeforeEach
void setUp() {
testedService = new CountryServiceImpl(countryRepository);
}
@Test
void retrieveAllCountriesTest() throws ServiceOperationException {
when(countryRepository.findAll()).thenReturn(List.of(country1, country2));
final List<Country> resultList = testedService.retrieveAllCountries();
assertFalse(CollectionUtils.isEmpty(resultList), () -> "Should retrieve 2 countries");
assertThat(resultList, hasSize(2));
assertThat(resultList, hasItems(country1, country2));
}
@Test
void retrieveAllCountriesWhenNoCountryReturnedTest() throws ServiceOperationException {
assertTrue(CollectionUtils.isEmpty(testedService.retrieveAllCountries()));
}
@Test
void retrieveAllCountriesWhenRuntimeExceptionIsThrownTest() {
when(countryRepository.findAll()).thenThrow(new RuntimeException());
assertThrows(ServiceOperationException.class, () -> testedService.retrieveAllCountries(), () ->
SERVICE_OPERATION_EXCEPTION_SHOULD_BE_THROWN);
}
@Test
void retrieveCountryByIdTest() throws ServiceOperationException {
when(countryRepository.findById(COUNTRY_POLAND_ID)).thenReturn(Optional.of(country1));
final Optional<Country> result = testedService.retrieveCountryById(COUNTRY_POLAND_ID);
assertTrue(result.isPresent());
assertThat(result.get(), is(country1));
}
@Test
void retrieveCountryByIdWhenNoCountryReturnedTest() throws ServiceOperationException {
assertTrue(testedService.retrieveCountryById(COUNTRY_POLAND_ID).isEmpty());
}
@Test
void retrieveCountryByIdWhenRuntimeExceptionIsThrownTest() {
when(countryRepository.findById(COUNTRY_POLAND_ID)).thenThrow(new RuntimeException());
assertThrows(ServiceOperationException.class, () -> testedService.retrieveCountryById(COUNTRY_POLAND_ID), () ->
SERVICE_OPERATION_EXCEPTION_SHOULD_BE_THROWN);
}
} | 33.256881 | 119 | 0.758897 |
b95778be6be2df31df14d828d5d7b11c089c9f53 | 746 | package com.sun.raceDetection.moel;
public class FuncPairs {
public String sharedVariable = null;
public String methodOne = null;
public String methodTwo = null;
public int sign = -1;
public FuncPairs(String sharedVariable, String methodOne,
String methodTwo, int sINGLE_ASYNC) {
super();
this.sharedVariable = sharedVariable;
this.methodOne = methodOne;
this.methodTwo = methodTwo;
this.sign = sINGLE_ASYNC;
}
public String toFileName(){
return sharedVariable+"_"+methodOne+"_"+methodTwo+"_"+String.valueOf(sign);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "[Var: ]"+sharedVariable+"\n"
+"[M1: ]"+methodOne+"\n"
+"[M2: ]"+methodTwo+"\n"
+"[sign: ]"+sign;
}
}
| 24.064516 | 77 | 0.691689 |
4f0ffb2692760ef10c5b1b3173edc0b2440f7402 | 2,111 | /*
* Copyright 2018 VetsEZ Inc, Sagebits LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sagebits.tmp.isaac.rest.api1.data.classifier;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import net.sagebits.tmp.isaac.rest.api1.data.concept.RestConceptChronology;
import sh.isaac.api.Get;
/**
* {@link RestClassifierCycle}
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
@XmlRootElement
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
public class RestClassifierCycle
{
/**
* A concept that has a cycle in the taxonomy
*/
@XmlElement
private RestConceptChronology conceptWithCycle;
/**
* The isA path(s) of concepts that forms the cycle(s) from the conceptWithCycle back to itself
*/
@XmlElement
private RestClassifierCyclePath[] cyclePaths;
protected RestClassifierCycle()
{
//For jaxb
}
/**
* @param cc
*/
public RestClassifierCycle(ClassifierCycle cc)
{
conceptWithCycle = new RestConceptChronology(Get.concept(cc.conceptWithCycle), false, false, false);
cyclePaths = new RestClassifierCyclePath[cc.cyclePaths.size()];
for (int i = 0; i < cc.cyclePaths.size(); i++)
{
cyclePaths[i] = new RestClassifierCyclePath(cc.cyclePaths.get(i));
}
}
}
| 31.044118 | 166 | 0.75604 |
20c810da71c53632631f6662a885bdc05904886f | 1,744 | package com.journal.nn.school123.rest.info.subject;
import androidx.annotation.NonNull;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.journal.nn.school123.rest.AbstractGetRequest;
import com.journal.nn.school123.rest.RequestParameters;
import java.util.HashMap;
import java.util.Map;
import static com.journal.nn.school123.util.VersionUtil.getJsonSize;
public class SubjectNames extends AbstractGetRequest {
public SubjectNames(@NonNull RequestParameters requestParameters) {
super("/act/GET_SBJ_NAMES_STORE_DATA?_dc=" + System.currentTimeMillis(),
requestParameters,
response -> {
JsonArray jsonArray = requestParameters.getGson().fromJson(response, JsonArray.class);
Map<Integer, String> subjects = new HashMap<>();
for (JsonElement jsonElement : jsonArray) {
JsonArray subject = jsonElement.getAsJsonArray();
if (subject.size() == getJsonSize(requestParameters, SubjectNames.class)) {
int subjectId = subject.get(0).getAsInt();
String subjectName = subject.get(1).getAsString();
subjects.put(subjectId, subjectName);
} else {
System.out.println("Too many data in subject=" + subject);
}
}
requestParameters.getData().setSubjects(subjects);
StudentSubjects studentSubjects = new StudentSubjects(requestParameters);
requestParameters.getRequestQueue().add(studentSubjects);
}
);
}
}
| 44.717949 | 106 | 0.608372 |
e7721eda6b5bd8325d5f1296709a6fb57279da92 | 5,124 | package org.programmingbasics.plom.core.view;
import org.junit.Assert;
import org.junit.Test;
import org.programmingbasics.plom.core.ast.StatementContainer;
import org.programmingbasics.plom.core.ast.Token;
import org.programmingbasics.plom.core.ast.TokenContainer;
import org.programmingbasics.plom.core.ast.gen.Symbol;
import junit.framework.TestCase;
public class CodeNestingCounterTest extends TestCase
{
private Token getToken(StatementContainer code, int...pos)
{
return GetToken.inStatements(code, CodePosition.fromOffsets(pos), 0);
}
private int getNesting(CodeNestingCounter nestingCounter, StatementContainer code, int ...pos)
{
return nestingCounter.tokenNesting.get(getToken(code, pos)).intValue();
}
@Test
public void testStatements()
{
StatementContainer code = new StatementContainer(
new TokenContainer(
new Token.SimpleToken("var", Symbol.Var),
Token.ParameterToken.fromContents(".a", Symbol.DotVariable),
// new Token.SimpleToken(":", Symbol.Colon),
Token.ParameterToken.fromContents(".number", Symbol.DotVariable)
),
new TokenContainer(
new Token.SimpleToken("var", Symbol.Var),
Token.ParameterToken.fromContents(".b", Symbol.DotVariable),
// new Token.SimpleToken(":", Symbol.Colon),
Token.ParameterToken.fromContents(".boolean", Symbol.DotVariable)
),
new TokenContainer(
new Token.OneExpressionOneBlockToken("if", Symbol.COMPOUND_IF,
new TokenContainer(
Token.ParameterToken.fromContents(".b", Symbol.DotVariable),
new Token.SimpleToken("and", Symbol.And),
Token.ParameterToken.fromContents(".a", Symbol.DotVariable),
new Token.SimpleToken("=", Symbol.Gt),
new Token.SimpleToken("5", Symbol.Number)
),
new StatementContainer())
)
);
CodeNestingCounter nestingCounter = new CodeNestingCounter();
nestingCounter.calculateNestingForStatements(code);
Assert.assertEquals(1, getNesting(nestingCounter, code, 0, 0));
Assert.assertEquals(1, getNesting(nestingCounter, code, 1, 1));
Assert.assertEquals(1, getNesting(nestingCounter, code, 1, 2));
Assert.assertEquals(1, getNesting(nestingCounter, code, 2, 0, CodeRenderer.EXPRBLOCK_POS_EXPR, 0));
Assert.assertEquals(1, getNesting(nestingCounter, code, 2, 0, CodeRenderer.EXPRBLOCK_POS_EXPR, 1));
}
@Test
public void testParameterToken()
{
StatementContainer code = new StatementContainer(
new TokenContainer(
new Token.SimpleToken("\"hello\"", Symbol.String),
Token.ParameterToken.fromContents(".substring from:to:", Symbol.DotVariable,
new TokenContainer(
new Token.SimpleToken("2", Symbol.Number)),
new TokenContainer(
new Token.SimpleToken("3", Symbol.Number)))),
new TokenContainer(
new Token.SimpleToken("var", Symbol.Var),
Token.ParameterToken.fromContents(".a", Symbol.DotVariable),
// new Token.SimpleToken(":", Symbol.Colon),
Token.ParameterToken.fromContents(".number", Symbol.DotVariable)
),
new TokenContainer(
Token.ParameterToken.fromContents(".a", Symbol.DotVariable),
Token.ParameterToken.fromContents(".abs", Symbol.DotVariable),
Token.ParameterToken.fromContents(".to string", Symbol.DotVariable)
),
new TokenContainer(
new Token.SimpleToken("1", Symbol.Number),
Token.ParameterToken.fromContents(".+:", Symbol.DotVariable,
new TokenContainer(
new Token.SimpleToken("2", Symbol.Number),
Token.ParameterToken.fromContents(".+:", Symbol.DotVariable,
new TokenContainer(
new Token.SimpleToken("3", Symbol.Number)
)
)
)
)
));
CodeNestingCounter nestingCounter = new CodeNestingCounter();
nestingCounter.calculateNestingForStatements(code);
Assert.assertEquals(1, getNesting(nestingCounter, code, 2, 0));
Assert.assertEquals(1, getNesting(nestingCounter, code, 2, 1));
Assert.assertEquals(1, getNesting(nestingCounter, code, 2, 2));
Assert.assertEquals(2, getNesting(nestingCounter, code, 0, 1));
Assert.assertEquals(1, getNesting(nestingCounter, code, 0, 1, CodeRenderer.PARAMTOK_POS_EXPRS, 0, 0));
Assert.assertEquals(1, getNesting(nestingCounter, code, 3, 1, CodeRenderer.PARAMTOK_POS_EXPRS, 0, 1, CodeRenderer.PARAMTOK_POS_EXPRS, 0, 0));
Assert.assertEquals(2, getNesting(nestingCounter, code, 3, 1, CodeRenderer.PARAMTOK_POS_EXPRS, 0, 1));
Assert.assertEquals(3, getNesting(nestingCounter, code, 3, 1));
}
}
| 45.75 | 146 | 0.630952 |
1a84640ae8dd7946273734a0ec9ac65182cf0b46 | 406 | package cn.bugstack.springframework.beans.factory;
/**
* Interface to be implemented by beans that want to release resources
* on destruction. A BeanFactory is supposed to invoke the destroy
* method if it disposes a cached singleton. An application context
* is supposed to dispose all of its singletons on close.
*
*
*/
public interface DisposableBean {
void destroy() throws Exception;
}
| 23.882353 | 70 | 0.756158 |
3a2b2429f706a13babc12c958c334174223e7582 | 401 | package com.bookstore.entity;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name = "author")
public class AuthorDeep extends BaseAuthor {
@Lob
private byte[] avatar;
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
}
| 18.227273 | 44 | 0.648379 |
20f9b7a1275a075f1d2f29d596aa85105e7da7cd | 10,148 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.design.transformation;
import android.content.Context;
import android.support.design.animation.MotionSpec;
import android.support.design.animation.Positioning;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import java.util.HashMap;
import java.util.Map;
// Referenced classes of package android.support.design.transformation:
// FabTransformationBehavior, FabTransformationScrimBehavior
public class FabTransformationSheetBehavior extends FabTransformationBehavior
{
public FabTransformationSheetBehavior()
{
// 0 0:aload_0
// 1 1:invokespecial #11 <Method void FabTransformationBehavior()>
// 2 4:return
}
public FabTransformationSheetBehavior(Context context, AttributeSet attributeset)
{
super(context, attributeset);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:invokespecial #15 <Method void FabTransformationBehavior(Context, AttributeSet)>
// 4 6:return
}
private void updateImportantForAccessibility(View view, boolean flag)
{
Object obj = ((Object) (view.getParent()));
// 0 0:aload_1
// 1 1:invokevirtual #23 <Method android.view.ViewParent View.getParent()>
// 2 4:astore 6
if(!(obj instanceof CoordinatorLayout))
//* 3 6:aload 6
//* 4 8:instanceof #25 <Class CoordinatorLayout>
//* 5 11:ifne 15
return;
// 6 14:return
obj = ((Object) ((CoordinatorLayout)obj));
// 7 15:aload 6
// 8 17:checkcast #25 <Class CoordinatorLayout>
// 9 20:astore 6
int j = ((CoordinatorLayout) (obj)).getChildCount();
// 10 22:aload 6
// 11 24:invokevirtual #29 <Method int CoordinatorLayout.getChildCount()>
// 12 27:istore 5
if(android.os.Build.VERSION.SDK_INT >= 16 && flag)
//* 13 29:getstatic #35 <Field int android.os.Build$VERSION.SDK_INT>
//* 14 32:bipush 16
//* 15 34:icmplt 54
//* 16 37:iload_2
//* 17 38:ifeq 54
importantForAccessibilityMap = ((Map) (new HashMap(j)));
// 18 41:aload_0
// 19 42:new #37 <Class HashMap>
// 20 45:dup
// 21 46:iload 5
// 22 48:invokespecial #40 <Method void HashMap(int)>
// 23 51:putfield #42 <Field Map importantForAccessibilityMap>
for(int i = 0; i < j; i++)
//* 24 54:iconst_0
//* 25 55:istore_3
//* 26 56:iload_3
//* 27 57:iload 5
//* 28 59:icmpge 214
{
View view1 = ((CoordinatorLayout) (obj)).getChildAt(i);
// 29 62:aload 6
// 30 64:iload_3
// 31 65:invokevirtual #46 <Method View CoordinatorLayout.getChildAt(int)>
// 32 68:astore 7
boolean flag1;
if((view1.getLayoutParams() instanceof android.support.design.widget.CoordinatorLayout.LayoutParams) && (((android.support.design.widget.CoordinatorLayout.LayoutParams)view1.getLayoutParams()).getBehavior() instanceof FabTransformationScrimBehavior))
//* 33 70:aload 7
//* 34 72:invokevirtual #50 <Method android.view.ViewGroup$LayoutParams View.getLayoutParams()>
//* 35 75:instanceof #52 <Class android.support.design.widget.CoordinatorLayout$LayoutParams>
//* 36 78:ifeq 104
//* 37 81:aload 7
//* 38 83:invokevirtual #50 <Method android.view.ViewGroup$LayoutParams View.getLayoutParams()>
//* 39 86:checkcast #52 <Class android.support.design.widget.CoordinatorLayout$LayoutParams>
//* 40 89:invokevirtual #56 <Method android.support.design.widget.CoordinatorLayout$Behavior android.support.design.widget.CoordinatorLayout$LayoutParams.getBehavior()>
//* 41 92:instanceof #58 <Class FabTransformationScrimBehavior>
//* 42 95:ifeq 104
flag1 = true;
// 43 98:iconst_1
// 44 99:istore 4
else
//* 45 101:goto 107
flag1 = false;
// 46 104:iconst_0
// 47 105:istore 4
if(view1 == view || flag1)
//* 48 107:aload 7
//* 49 109:aload_1
//* 50 110:if_acmpeq 207
//* 51 113:iload 4
//* 52 115:ifeq 121
continue;
// 53 118:goto 207
if(!flag)
//* 54 121:iload_2
//* 55 122:ifne 173
{
Map map = importantForAccessibilityMap;
// 56 125:aload_0
// 57 126:getfield #42 <Field Map importantForAccessibilityMap>
// 58 129:astore 8
if(map != null && map.containsKey(((Object) (view1))))
//* 59 131:aload 8
//* 60 133:ifnull 207
//* 61 136:aload 8
//* 62 138:aload 7
//* 63 140:invokeinterface #64 <Method boolean Map.containsKey(Object)>
//* 64 145:ifeq 207
ViewCompat.setImportantForAccessibility(view1, ((Integer)importantForAccessibilityMap.get(((Object) (view1)))).intValue());
// 65 148:aload 7
// 66 150:aload_0
// 67 151:getfield #42 <Field Map importantForAccessibilityMap>
// 68 154:aload 7
// 69 156:invokeinterface #68 <Method Object Map.get(Object)>
// 70 161:checkcast #70 <Class Integer>
// 71 164:invokevirtual #73 <Method int Integer.intValue()>
// 72 167:invokestatic #79 <Method void ViewCompat.setImportantForAccessibility(View, int)>
continue;
// 73 170:goto 207
}
if(android.os.Build.VERSION.SDK_INT >= 16)
//* 74 173:getstatic #35 <Field int android.os.Build$VERSION.SDK_INT>
//* 75 176:bipush 16
//* 76 178:icmplt 201
importantForAccessibilityMap.put(((Object) (view1)), ((Object) (Integer.valueOf(view1.getImportantForAccessibility()))));
// 77 181:aload_0
// 78 182:getfield #42 <Field Map importantForAccessibilityMap>
// 79 185:aload 7
// 80 187:aload 7
// 81 189:invokevirtual #82 <Method int View.getImportantForAccessibility()>
// 82 192:invokestatic #86 <Method Integer Integer.valueOf(int)>
// 83 195:invokeinterface #90 <Method Object Map.put(Object, Object)>
// 84 200:pop
ViewCompat.setImportantForAccessibility(view1, 4);
// 85 201:aload 7
// 86 203:iconst_4
// 87 204:invokestatic #79 <Method void ViewCompat.setImportantForAccessibility(View, int)>
}
// 88 207:iload_3
// 89 208:iconst_1
// 90 209:iadd
// 91 210:istore_3
//* 92 211:goto 56
if(!flag)
//* 93 214:iload_2
//* 94 215:ifne 223
importantForAccessibilityMap = null;
// 95 218:aload_0
// 96 219:aconst_null
// 97 220:putfield #42 <Field Map importantForAccessibilityMap>
// 98 223:return
}
protected FabTransformationBehavior.FabTransformationSpec onCreateMotionSpec(Context context, boolean flag)
{
int i;
if(flag)
//* 0 0:iload_2
//* 1 1:ifeq 11
i = android.support.design.R.animator.mtrl_fab_transformation_sheet_expand_spec;
// 2 4:getstatic #97 <Field int android.support.design.R$animator.mtrl_fab_transformation_sheet_expand_spec>
// 3 7:istore_3
else
//* 4 8:goto 15
i = android.support.design.R.animator.mtrl_fab_transformation_sheet_collapse_spec;
// 5 11:getstatic #100 <Field int android.support.design.R$animator.mtrl_fab_transformation_sheet_collapse_spec>
// 6 14:istore_3
FabTransformationBehavior.FabTransformationSpec fabtransformationspec = new FabTransformationBehavior.FabTransformationSpec();
// 7 15:new #102 <Class FabTransformationBehavior$FabTransformationSpec>
// 8 18:dup
// 9 19:invokespecial #103 <Method void FabTransformationBehavior$FabTransformationSpec()>
// 10 22:astore 4
fabtransformationspec.timings = MotionSpec.createFromResource(context, i);
// 11 24:aload 4
// 12 26:aload_1
// 13 27:iload_3
// 14 28:invokestatic #109 <Method MotionSpec MotionSpec.createFromResource(Context, int)>
// 15 31:putfield #113 <Field MotionSpec FabTransformationBehavior$FabTransformationSpec.timings>
fabtransformationspec.positioning = new Positioning(17, 0.0F, 0.0F);
// 16 34:aload 4
// 17 36:new #115 <Class Positioning>
// 18 39:dup
// 19 40:bipush 17
// 20 42:fconst_0
// 21 43:fconst_0
// 22 44:invokespecial #118 <Method void Positioning(int, float, float)>
// 23 47:putfield #122 <Field Positioning FabTransformationBehavior$FabTransformationSpec.positioning>
return fabtransformationspec;
// 24 50:aload 4
// 25 52:areturn
}
protected boolean onExpandedStateChange(View view, View view1, boolean flag, boolean flag1)
{
updateImportantForAccessibility(view1, flag);
// 0 0:aload_0
// 1 1:aload_2
// 2 2:iload_3
// 3 3:invokespecial #127 <Method void updateImportantForAccessibility(View, boolean)>
return super.onExpandedStateChange(view, view1, flag, flag1);
// 4 6:aload_0
// 5 7:aload_1
// 6 8:aload_2
// 7 9:iload_3
// 8 10:iload 4
// 9 12:invokespecial #129 <Method boolean FabTransformationBehavior.onExpandedStateChange(View, View, boolean, boolean)>
// 10 15:ireturn
}
private Map importantForAccessibilityMap;
}
| 43.741379 | 253 | 0.606819 |
8725c4e1b87bcf2c14e8e246b6df116152750838 | 10,020 | package com.axxessio.oauth2.server.facade;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.axxessio.oauth2.server.cipher.AsymetricCipher;
import com.axxessio.oauth2.server.common.ApplicationException;
import com.axxessio.oauth2.server.common.Enums;
import com.axxessio.oauth2.server.controller.to.AccessTokenTO;
import com.axxessio.oauth2.server.controller.to.ErrorMessageTO;
import com.axxessio.oauth2.server.controller.to.PublicKeyTO;
import com.axxessio.oauth2.server.service.TokenService;
import com.axxessio.oauth2.server.service.UserService;
import com.axxessio.oauth2.server.service.pdo.AccessToken;
import com.axxessio.oauth2.server.service.pdo.SessionScope;
import com.fasterxml.jackson.core.JsonProcessingException;
@RestController
@RequestMapping("/services/oauth2")
public class WebClientFacade {
@Autowired
TokenService ts;
@Autowired
UserService us;
private static final Logger logger = Logger.getLogger(TokenService.class);
/**
* This method accepts POST requests to generate new or update existing access token.
*
* For a new token with scope for customer and order please send the following request
* <pre>
* POST http://{server}:{port}/services/oauth2/token
*
* == Header ==
* Accept: application/json
* Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
* Content-Type: application/x-www-form-urlencoded
*
* == Body ==
* grant_type=password&username=admin&password=d033e22ae348aeb5660fc2140aec35850c4da997&scope=~customer~order
* </pre>
*
* To refresh a token please send the following request
* <pre>
* POST http://{server}:{port}/services/oauth2/token
*
* == Header ==
* Accept: application/json
* Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
* Content-Type: application/x-www-form-urlencoded
*
* == Body ==
* grant_type=refresh_token&refresh_token=############################
* </pre>
* @param accept
* @param authorization
* @param contentType
* @param host
* @param grantType
* @param password
* @param refreshToken
* @param username
* @param request
* @return JSON object with access and refresh token, timestamp, scope and associated rights
*/
@RequestMapping(value="/token", method=RequestMethod.POST)
public ResponseEntity<?> createToken(@RequestHeader(value="Accept") String accept,
@RequestHeader(value="Authorization") String authorization,
@RequestHeader(value="Content-Type") String contentType,
@RequestHeader(value="Host") String host,
@RequestBody MultiValueMap<String, String> body,
HttpServletRequest request) {
String grantType = body.getFirst("grant_type");
String password = body.getFirst("password");
String refreshToken = body.getFirst("refresh_token");
String scope = body.getFirst("scope");
String username = body.getFirst("username");
try {
// validate request
AccessToken at;
AccessTokenTO ato;
Request r = new Request(accept, authorization, contentType, grantType, password, refreshToken, scope, username);
SessionScope<String, String> sessionScope;
String sessionId;
logger.info("=================== Header =================");
logger.info("Accept: " + accept + " - Authorization: " + authorization + " - Content-Type: " + contentType + " - Host: " + host);
logger.info("=================== Form =================");
logger.info("grant_type [" + grantType + "] - username [" + username + "] - password [" + password + "] - refresh_token [" + refreshToken + "]");
sessionScope = us.getSessionScope(username, r.getScopes());
if (grantType.equals("password")) {
sessionId = request.getSession(true).getId();
at = ts.createToken(us.getUser(username), sessionId, username, password, grantType, scope, sessionScope);
} else {
// only token refresh, therefore only new access token is generated, refresh_token remains the same
sessionId = request.getSession().getId();
at = ts.refreshToken(sessionId, refreshToken);
}
ato = new AccessTokenTO (at);
HttpHeaders rh = new HttpHeaders();
rh.set("Cache-Control", "no-store");
rh.set("Pragman", "no-cache");
rh.set("Signature-Algorithm", "DSASHA1");
rh.set("Signature-Encoding", "base64");
rh.set("Signature-Value", Base64.encodeBase64String(ts.getTokenSign(at)));
rh.set("Token-Encoding", "base64");
rh.set("Token-Value", Base64.encodeBase64String(ato.toJSON().getBytes()));
return new ResponseEntity<AccessTokenTO>(ato, rh, HttpStatus.OK);
} catch (ApplicationException axcptn) {
return buildStatusResponse(getResponseStatus(axcptn), axcptn.getErrorCode(), axcptn.getErrorDescription());
} catch (JsonProcessingException jpxcptn) {
return buildStatusResponse(HttpStatus.INTERNAL_SERVER_ERROR, 0x0001, "Error in processoing JSON mapping");
}
}
/**
* This method is not part of OAuth2 specification. The intention is to delete a given token.
* This is usually be done by client.
* <pre>
* DELETE http://{server}:{port}/services/oauth2/token?refresh_token=############################
*
* == Header ==
* Host: oauth2server.axxessio.com
* Accept: application/json
* Authorization: Basic c3lzdGVtOnN5c3RlbQ== (system:system)
*
* @param accept
* @param authorization
* @param refreshToken
* @param request
* @return
*/
@RequestMapping(value="/token", method=RequestMethod.DELETE)
public ResponseEntity<?> deleteToken(@RequestHeader(value="Accept") String accept,
@RequestHeader(value="Authorization") String authorization,
@RequestParam(value="refresh_token") String refreshToken,
HttpServletRequest request) {
logger.info("DELETE /token - refresh_token: " + refreshToken);
// Do some validation regarding parameters
try {
new Request(accept, authorization);
} catch (ApplicationException axcptn) {
return buildStatusResponse(getResponseStatus(axcptn), axcptn.getErrorCode(), axcptn.getErrorDescription());
}
ts.deleteAccessToken(request.getSession().getId(), refreshToken);
return new ResponseEntity<String> ("token delted", HttpStatus.OK);
}
/**
* This method is not part of OAuth2 specification. The intention is to validate whether a given token is still valid or not.
* This is usually be done be a resource server, not by a client.
* <pre>
* GET http://{server}:{port}/services/oauth2/pubkey
*
* == Header ==
* Accept: application/json
* Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
*
* @return public key for DSA algorithm in base64 encoded format.
*/
@RequestMapping(value="/pubkey", method=RequestMethod.GET)
public ResponseEntity<?> getPublicKey(@RequestHeader(value="Accept") String accept,
@RequestHeader(value="Authorization") String authorization) {
logger.info("GET /pubkey");
// Do some validation regarding parameters
try {
new Request(accept, authorization);
} catch (ApplicationException axcptn) {
return buildStatusResponse(getResponseStatus(axcptn), axcptn.getErrorCode(), axcptn.getErrorDescription());
}
// return new ResponseEntity<PublicKeyTO> (new PublicKeyTO(AsymetricCipher.getPublicKey()), HttpStatus.OK);
PublicKeyTO pkto = new PublicKeyTO(AsymetricCipher.getPublicKey());
return new ResponseEntity<PublicKeyTO>(pkto, HttpStatus.OK);
}
/**
* This method is not part of OAuth2 specification. The intention is to validate whether a given token is still valid or not.
* This is usually be done be a resource server, not by a client.
* <pre>
* GET http://{server}:{port}/services/oauth2/token?access_token=############################
*
* == Header ==
* Host: oauth2server.axxessio.com
* Accept: application/json
* Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
*
* @param accept
* @param authorization
* @param accessToken
* @param request
* @return
*/
@RequestMapping(value="/token", method=RequestMethod.GET)
public ResponseEntity<?> getToken(@RequestHeader(value="Accept") String accept,
@RequestHeader(value="Authorization") String authorization,
@RequestParam(value="access_token") String accessToken) {
logger.info("GET /token - access_token: " + accessToken);
// Do some validation regarding parameters
try {
new Request(accept, authorization);
} catch (ApplicationException axcptn) {
return buildStatusResponse(getResponseStatus(axcptn), axcptn.getErrorCode(), axcptn.getErrorDescription());
}
if (ts.getAccessToken(accessToken, Enums.TOKEN_TYPE.ACCESS) == null)
return buildStatusResponse(HttpStatus.NOT_FOUND, 0x0004, "access_token not valid!");
else
return new ResponseEntity<String> ("token is valid", HttpStatus.OK);
}
private HttpStatus getResponseStatus (ApplicationException axcptn) {
return axcptn.getErrorStatus() == Request.BAD_REQUEST ? HttpStatus.BAD_REQUEST : HttpStatus.NOT_FOUND;
}
private ResponseEntity<ErrorMessageTO> buildStatusResponse (HttpStatus hs, int errorCode, String errorDescription) {
ErrorMessageTO emto = new ErrorMessageTO("invalid_request", errorCode, errorDescription);
return new ResponseEntity<ErrorMessageTO>(emto, hs);
}
} | 38.837209 | 149 | 0.714271 |
59be90b6ff75cbecca331c942bab657f1b03b707 | 1,076 | package dqm.jku.dqmeerkat.dsd.elements;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class AggregationAssociation extends Association {
private static final long serialVersionUID = 1L;
private ForeignKey aggregate;
public AggregationAssociation(String label, Datasource datasource) {
super(label, datasource);
}
public Concept getAggregate() {
return aggregate.getReferencedConcept();
}
public void setAggregate(ForeignKey aggregate) {
this.aggregate = aggregate;
}
public void setAggregate(Concept aggregate) {
List<ForeignKey> fkList = this.foreignKeys.stream().filter(x -> x.getReferencedConcept() == aggregate).collect(Collectors.toList());
if (fkList.size() != 1) {
throw new IllegalArgumentException("Can not infer aggregate direction from Concept. Please add ForeignKey directly.");
}
this.aggregate = fkList.get(0);
}
public Set<Concept> getParts() {
return foreignKeys.stream().map(x -> x.getReferencedConcept()).filter(x -> x.equals(getAggregate())).collect(Collectors.toSet());
}
}
| 29.081081 | 134 | 0.753717 |
d648cdf483370a0af09cb6437cc84c543b716dc7 | 1,127 | package classes;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
public class JPanelArredondado extends JPanel{
private Color backgroundColor;
private int cornerRadius;
public JPanelArredondado(int radius, Color bgColor) {
super();
cornerRadius = radius;
backgroundColor = bgColor;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension dims = new Dimension(cornerRadius, cornerRadius);
int width = getWidth(), height = getHeight();
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (backgroundColor != null) {
graphics.setColor(backgroundColor);
} else {
graphics.setColor(getBackground());
}
graphics.fillRoundRect(0, 0, width-1, height-1, dims.width, dims.height);
graphics.setColor(getForeground());
}
} | 29.657895 | 102 | 0.669033 |
42887eb0f16d13c7f7aa217fe9d4d64813304789 | 447 | package uk.gov.dvsa.motr.config;
/**
* Config based on Environment Variables
*/
public class EnvironmentVariableConfig implements Config {
@Override
public String getValue(ConfigKey key) {
String value = System.getenv(key.getName());
if (value == null) {
throw new RuntimeException(
String.format("Config key: %s not specified!", key.getName()));
}
return value;
}
}
| 24.833333 | 83 | 0.612975 |
17b75dc76d6afada1b5aff831c43f308c72c00b0 | 1,017 | package co.imdo.perfect.callback;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
@Slf4j
public class MyMqConfirmCallback implements RabbitTemplate.ConfirmCallback {
/**
* Confirmation callback.
*
* @param correlationData - correlation data for the callback.
* @param ack – true for ack, false for nack
* @param cause – An optional cause, for nack, when available, otherwise null.
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
log.info("========这里接收消息确认信息==========");
log.info(JSON.toJSONString(correlationData));
log.info(JSON.toJSONString(ack));
log.info(JSON.toJSONString(cause));
log.info(new String(correlationData.getReturnedMessage().getBody()));
log.info("========这里接收消息确认信息==========");
}
}
| 35.068966 | 92 | 0.672566 |
698da14979601e596cac88f052e40f4ded71665a | 4,293 | package com.smalljnes.mappers;
import com.smalljnes.Cpu;
import com.smalljnes.Mirroring;
/**
* @author sad
*/
public class Mapper4 extends AbstractMapper {
byte reg8000;
byte[] regs = new byte[8];
boolean horizontalMirroring;
byte irqPeriod;
byte irqCounter;
boolean irqEnabled;
public Mapper4(byte[] rom) {
super(rom);
}
@Override
public void cartridgeInserted(Cpu cpu) {
super.cartridgeInserted(cpu);
horizontalMirroring = true;
irqEnabled = false;
irqPeriod = irqCounter = 0;
mapPrg(8, 3, -1);
apply();
}
void apply() {
cpu.printStatus("MP:apply. regs[7]=" + (regs[7] & 0xFF) + " reg8000=" + (reg8000 & 0xFF));
mapPrg(8, 1, regs[7] & 0xFF);
if ((((reg8000 & 0xFF) & (1 << 6))) == 0) {
cpu.printStatus("MP:apply. PRG Mode 0 regs[6]=" + (regs[6] & 0xFF));
mapPrg(8, 0, regs[6] & 0xFF);
mapPrg(8, 2, -2);
} else {
cpu.printStatus("MP:apply. PRG Mode 1 regs[6]=" + (regs[6] & 0xFF));
mapPrg(8, 0, -2);
mapPrg(8, 2, regs[6] & 0xFF);
}
// CHR Mode 0:
if ((reg8000 & (1 << 7)) == 0) {
cpu.printStatus("MP:apply. CHR Mode 0 regs[0]=" + (regs[0] & 0xFF));
cpu.printStatus("MP:apply. CHR Mode 0 regs[1]=" + (regs[1] & 0xFF));
mapChr(2, 0, (regs[0] & 0xFF) >> 1);
mapChr(2, 1, (regs[1] & 0xFF) >> 1);
for (int i = 0; i < 4; i++) {
mapChr(1, 4 + i, (regs[2 + i] & 0xFF));
}
} else {
cpu.printStatus("MP:apply. CHR Mode 1 regs[0]=" + (regs[0] & 0xFF));
cpu.printStatus("MP:apply. CHR Mode 1 regs[1]=" + (regs[1] & 0xFF));
for (int i = 0; i < 4; i++) {
mapChr(1, i, (regs[2 + i] & 0xFF));
}
mapChr(2, 2, (regs[0] & 0xFF) >> 1);
mapChr(2, 3, (regs[1] & 0xFF) >> 1);
}
cpu.printStatus("MP:apply.Mirror=" + (horizontalMirroring?1:0));
cpu.getPpu().setMirrorMode(horizontalMirroring ? Mirroring.HORIZONTAL : Mirroring.VERTICAL);
}
@Override
public void chrWrite(int address, byte value) {
chr[address] = value;
}
@Override
public void write(int addr, byte v) {
if (addr < 0x8000) {
cpu.printStatus("MP:writeRam:addr=" + (addr) + " v=" + (v & 0xFF));
prgRam[addr - 0x6000] = v;
} else if ((addr & 0x8000) > 0) {
switch (addr & 0xE001) {
case 0x8000:
reg8000 = v;
cpu.printStatus("MP:setreg1:r8000=" + (reg8000 & 0xFF) + " v=" + (v & 0xFF));
break;
case 0x8001:
regs[reg8000 & 0b111] = v;
cpu.printStatus("MP:setreg2:r8000=" + (reg8000 & 0xFF) + " v=" + (v & 0xFF));
break;
case 0xA000:
cpu.printStatus("MP:mirror=" + (v & 0xFF));
horizontalMirroring = ((v & 0xFF) & 0x1) > 0;
break;
case 0xC000:
irqPeriod = v;
cpu.printStatus("MP:irqPeriod=" + (v & 0xFF));
break;
case 0xC001:
cpu.printStatus("MP:C001");
irqCounter = 0;
break;
case 0xE000:
cpu.setIrq(irqEnabled = false);
cpu.printStatus("MP:E000");
break;
case 0xE001:
irqEnabled = true;
cpu.printStatus("MP:E000");
break;
}
apply();
}
//return v;
}
@Override
public void signalScanline() {
cpu.printStatus("MP:scanline irqCounter=" + (irqCounter & 0xFF));
if (irqCounter == 0) {
irqCounter = irqPeriod;
} else {
irqCounter = (byte) ((irqCounter & 0xFF) - 1);
}
if (irqEnabled && irqCounter == 0) {
cpu.printStatus("MP:scanline irq");
cpu.setIrq(true);
}
}
@Override
public String toString() {
return "MMC3";
}
}
| 32.037313 | 100 | 0.454461 |
9dc02dc3f1ca58d09b00b873ce7ead87961549ec | 15,229 | package mchorse.blockbuster_pack.morphs;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.structure.PacketStructure;
import mchorse.blockbuster.network.common.structure.PacketStructureRequest;
import mchorse.blockbuster.network.server.ServerHandlerStructureRequest;
import mchorse.blockbuster_pack.morphs.structure.StructureAnimation;
import mchorse.blockbuster_pack.morphs.structure.StructureRenderer;
import mchorse.blockbuster_pack.morphs.structure.StructureStatus;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.utils.Interpolations;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.api.morphs.utils.Animation;
import mchorse.metamorph.api.morphs.utils.IAnimationProvider;
import mchorse.metamorph.api.morphs.utils.ISyncableMorph;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Biomes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.management.PlayerList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class StructureMorph extends AbstractMorph implements IAnimationProvider, ISyncableMorph
{
private static final ResourceLocation DEFAULT_BIOME = new ResourceLocation("ocean");
/**
* Map of baked structures
*/
@SideOnly(Side.CLIENT)
public static Map<String, StructureRenderer> STRUCTURES;
/**
* Cache of structures
*/
public static final Map<String, Long> STRUCTURE_CACHE = new HashMap<String, Long>();
/**
* The name of the structure which should be rendered
*/
public String structure = "";
/**
* The biome used for render
*/
public ResourceLocation biome = DEFAULT_BIOME;
/**
* Whether this structure use world lighting.
*/
public boolean lighting = true;
/**
* TSR for structure morph
*/
public ModelTransform pose = new ModelTransform();
public StructureAnimation animation = new StructureAnimation();
/* Rotation point */
public float anchorX;
public float anchorY;
public float anchorZ;
@SideOnly(Side.CLIENT)
public static void request()
{
if (STRUCTURES.isEmpty())
{
Dispatcher.sendToServer(new PacketStructureRequest());
}
}
@SideOnly(Side.CLIENT)
public static void reloadStructures()
{
cleanUp();
request();
}
/**
* Update structures
*/
public static void checkStructures()
{
for (String name : ServerHandlerStructureRequest.getAllStructures())
{
File file = ServerHandlerStructureRequest.getStructureFolder(name);
Long modified = STRUCTURE_CACHE.get(name);
if (modified == null)
{
modified = file.lastModified();
STRUCTURE_CACHE.put(name, modified);
}
if (modified < file.lastModified())
{
STRUCTURE_CACHE.put(name, file.lastModified());
IMessage packet = new PacketStructure(name, null);
PlayerList players = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList();
for (String username : players.getOnlinePlayerNames())
{
EntityPlayerMP player = players.getPlayerByUsername(username);
if (player != null)
{
Dispatcher.sendTo(packet, player);
}
}
}
}
}
@SideOnly(Side.CLIENT)
public static void cleanUp()
{
for (StructureRenderer renderer : STRUCTURES.values())
{
renderer.delete();
}
STRUCTURES.clear();
}
public StructureMorph()
{
super();
this.name = "structure";
}
@Override
public Animation getAnimation()
{
return this.animation;
}
public Biome getBiome()
{
Biome biome = Biome.REGISTRY.getObject(this.biome);
return biome == null ? Biomes.DEFAULT : biome;
}
@Override
public void pause(AbstractMorph previous, int offset)
{
this.animation.pause(offset);
if (previous instanceof StructureMorph)
{
StructureMorph structure = (StructureMorph) previous;
this.animation.last = new ModelTransform();
this.animation.last.copy(structure.pose);
}
}
@Override
public boolean isPaused()
{
return this.animation.paused;
}
@Override
@SideOnly(Side.CLIENT)
protected String getSubclassDisplayName()
{
String suffix = this.structure != null && !this.structure.isEmpty() ? " (" + this.structure + "-" + this.biome.getResourcePath() + ")" : "";
return I18n.format("blockbuster.morph.structure") + suffix;
}
@Override
@SideOnly(Side.CLIENT)
public void renderOnScreen(EntityPlayer player, int x, int y, float scale, float alpha)
{
StructureRenderer renderer = STRUCTURES.get(this.structure);
if (renderer != null)
{
if (renderer.status != StructureStatus.LOADED)
{
if (renderer.status == StructureStatus.UNLOADED)
{
renderer.status = StructureStatus.LOADING;
Dispatcher.sendToServer(new PacketStructureRequest(this.structure));
}
return;
}
int max = Math.max(renderer.size.getX(), Math.max(renderer.size.getY(), renderer.size.getZ()));
scale /= 0.65F * max;
Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
float lastX = OpenGlHelper.lastBrightnessX;
float lastY = OpenGlHelper.lastBrightnessY;
GlStateManager.enableDepth();
GlStateManager.enableAlpha();
GlStateManager.disableCull();
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, 0);
GlStateManager.scale(scale, scale, scale);
GlStateManager.rotate(45.0F, -1.0F, 0.0F, 0.0F);
GlStateManager.rotate(45.0F, 0.0F, -1.0F, 0.0F);
GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F);
renderer.render(this);
renderer.renderTEs(this);
GlStateManager.disableLighting();
GlStateManager.popMatrix();
GlStateManager.enableCull();
GlStateManager.disableAlpha();
GlStateManager.disableDepth();
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, lastX, lastY);
}
}
@Override
@SideOnly(Side.CLIENT)
public void render(EntityLivingBase entity, double x, double y, double z, float entityYaw, float partialTicks)
{
StructureRenderer renderer = STRUCTURES.get(this.structure);
if (renderer != null)
{
if (renderer.status != StructureStatus.LOADED)
{
if (renderer.status == StructureStatus.UNLOADED)
{
renderer.status = StructureStatus.LOADING;
Dispatcher.sendToServer(new PacketStructureRequest(this.structure));
}
return;
}
float lastX = OpenGlHelper.lastBrightnessX;
float lastY = OpenGlHelper.lastBrightnessY;
if (GuiModelRenderer.isRendering() && !this.lighting)
{
Minecraft.getMinecraft().entityRenderer.enableLightmap();
}
Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
/* These states are important to enable */
GlStateManager.pushMatrix();
GlStateManager.enableRescaleNormal();
GlStateManager.translate(x, y, z);
ModelTransform transform = this.pose;
float anchorX = this.anchorX;
float anchorY = this.anchorY;
float anchorZ = this.anchorZ;
if (this.animation.isInProgress())
{
transform = new ModelTransform();
transform.copy(this.pose);
this.animation.apply(transform, partialTicks);
if (this.animation.lastAnchorX != null)
{
float factor = this.animation.getFactor(partialTicks);
anchorX = this.animation.interp.interpolate(this.animation.lastAnchorX, anchorX, factor);
anchorY = this.animation.interp.interpolate(this.animation.lastAnchorY, anchorY, factor);
anchorZ = this.animation.interp.interpolate(this.animation.lastAnchorZ, anchorZ, factor);
}
}
transform.transform();
GlStateManager.translate(anchorX, anchorY, anchorZ);
RenderHelper.disableStandardItemLighting();
GlStateManager.shadeModel(GL11.GL_SMOOTH);
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
renderer.render(this);
GlStateManager.disableBlend();
GlStateManager.disableAlpha();
GlStateManager.shadeModel(GL11.GL_FLAT);
GlStateManager.enableLighting();
GlStateManager.enableLight(0);
GlStateManager.enableLight(1);
GlStateManager.enableColorMaterial();
GL11.glColor4f(1, 1, 1, 1);
renderer.renderTEs(this);
GlStateManager.popMatrix();
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, lastX, lastY);
if (GuiModelRenderer.isRendering() && !this.lighting)
{
Minecraft.getMinecraft().entityRenderer.disableLightmap();
}
}
}
@Override
public void update(EntityLivingBase target)
{
super.update(target);
this.animation.update();
}
@Override
public AbstractMorph create()
{
return new StructureMorph();
}
@Override
public void copy(AbstractMorph from)
{
super.copy(from);
if (from instanceof StructureMorph)
{
StructureMorph morph = (StructureMorph) from;
this.structure = morph.structure;
this.pose.copy(morph.pose);
this.animation.copy(morph.animation);
this.biome = morph.biome;
this.lighting = morph.lighting;
this.anchorX = morph.anchorX;
this.anchorY = morph.anchorY;
this.anchorZ = morph.anchorZ;
}
}
@Override
public float getWidth(EntityLivingBase target)
{
return 0.6F;
}
@Override
public float getHeight(EntityLivingBase target)
{
return 1.8F;
}
@Override
public boolean equals(Object obj)
{
boolean result = super.equals(obj);
if (obj instanceof StructureMorph)
{
StructureMorph morph = (StructureMorph) obj;
result = result && Objects.equals(this.structure, morph.structure);
result = result && Objects.equals(this.pose, morph.pose);
result = result && Objects.equals(this.animation, morph.animation);
result = result && Objects.equals(this.biome, morph.biome);
result = result && this.lighting == morph.lighting;
result = result && this.anchorX == morph.anchorX;
result = result && this.anchorY == morph.anchorY;
result = result && this.anchorZ == morph.anchorZ;
}
return result;
}
@Override
public boolean canMerge(AbstractMorph morph)
{
if (morph instanceof StructureMorph)
{
StructureMorph structure = (StructureMorph) morph;
this.mergeBasic(morph);
if (!structure.animation.ignored)
{
this.animation.merge(this, structure);
this.copy(structure);
this.animation.progress = 0;
}
return true;
}
return super.canMerge(morph);
}
@Override
public void fromNBT(NBTTagCompound tag)
{
super.fromNBT(tag);
if (tag.hasKey("Structure")) this.structure = tag.getString("Structure");
if (tag.hasKey("Pose")) this.pose.fromNBT(tag.getCompoundTag("Pose"));
if (tag.hasKey("Animation")) this.animation.fromNBT(tag.getCompoundTag("Animation"));
if (tag.hasKey("Biome")) this.biome = new ResourceLocation(tag.getString("Biome"));
if (tag.hasKey("Lighting")) this.lighting = tag.getBoolean("Lighting");
if (tag.hasKey("AnchorX")) this.anchorX = tag.getFloat("AnchorX");
if (tag.hasKey("AnchorY")) this.anchorY = tag.getFloat("AnchorY");
if (tag.hasKey("AnchorZ")) this.anchorZ = tag.getFloat("AnchorZ");
}
@Override
public void toNBT(NBTTagCompound tag)
{
super.toNBT(tag);
if (!this.structure.isEmpty())
{
tag.setString("Structure", this.structure);
}
if (!this.pose.isDefault())
{
tag.setTag("Pose", this.pose.toNBT());
}
NBTTagCompound animation = this.animation.toNBT();
if (!animation.hasNoTags())
{
tag.setTag("Animation", animation);
}
if (!this.biome.equals(DEFAULT_BIOME))
{
ResourceLocation biome = this.biome == null ? DEFAULT_BIOME : this.biome;
tag.setString("Biome", biome.toString());
}
if (!this.lighting)
{
tag.setBoolean("Lighting", this.lighting);
}
if (this.anchorX != 0)
{
tag.setFloat("AnchorX", this.anchorX);
}
if (this.anchorY != 0)
{
tag.setFloat("AnchorY", this.anchorY);
}
if (this.anchorZ != 0)
{
tag.setFloat("AnchorZ", this.anchorZ);
}
}
} | 30.953252 | 148 | 0.606868 |
36c511101e1a583a73f665c1ae0ec93a711bd996 | 2,615 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under The MIT License (Massachusetts Institute of Technology License)
*
* See http://opensource.org/licenses/MIT
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.code;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import net.sourceforge.plantuml.FileUtils;
import net.sourceforge.plantuml.brotli.BrotliInputStream;
public class CompressionBrotli implements Compression {
public byte[] compress(byte[] in) {
throw new UnsupportedOperationException();
}
public ByteArray decompress(byte[] in) throws NoPlantumlCompressionException {
try {
final BrotliInputStream brotli = new BrotliInputStream(new ByteArrayInputStream(in));
final ByteArrayOutputStream result = new ByteArrayOutputStream();
FileUtils.copyToStream(brotli, result);
brotli.close();
result.close();
return ByteArray.from(result.toByteArray());
} catch (IOException e) {
e.printStackTrace();
throw new NoPlantumlCompressionException(e);
}
}
}
| 37.357143 | 88 | 0.710516 |
5bbbed618231f07e51a74755d66843b06cbda130 | 2,993 | package ru.ok.technopolis.firedemoapp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import java.util.Locale;
public class FpsIndicatorView extends View implements Handler.Callback {
private static final int MSG_NEXT_FRAME = 1;
private int frameCount;
private long startTs;
String fpsText;
int fpsDigits;
final Paint bgPaint = new Paint();
final TextPaint textPaint = new TextPaint();
final Rect textBounds = new Rect();
final Handler handler = new Handler(this);
public FpsIndicatorView(Context context) {
this(context, null);
}
public FpsIndicatorView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
bgPaint.setColor(Color.BLACK);
textPaint.setTextSize(20 * context.getResources().getDisplayMetrics().density);
textPaint.setColor(Color.YELLOW);
textPaint.getTextBounds("WWWW", 0, 3, textBounds);
startTs = SystemClock.uptimeMillis();
handler.sendMessage(Message.obtain(handler, MSG_NEXT_FRAME));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int width = getWidth();
final int height = getHeight();
final int textLeft = fpsDigits >= 4 ? 0
: fpsDigits == 3 ? width / 4
: fpsDigits == 2 ? width / 2
: width * 3 / 4;
canvas.drawRect(0, 0, width, height, bgPaint);
if (fpsText != null) {
canvas.drawText(fpsText, textLeft, height, textPaint);
}
frameCount++;
invalidate();
}
@Override
public boolean handleMessage(Message msg) {
if (msg.what == MSG_NEXT_FRAME) {
final long ts = SystemClock.uptimeMillis();
if (ts - startTs > 1000) {
if (frameCount > 10) {
fpsText = Integer.toString(1000 * frameCount / (int) (ts - startTs));
} else {
double fps = 1000.0 * frameCount / (ts - startTs);
fpsText = String.format(Locale.FRENCH, "%.2f", fps);
}
fpsDigits = fpsText.length();
startTs = ts;
frameCount = 0;
invalidate();
}
handler.sendMessageDelayed(Message.obtain(handler, MSG_NEXT_FRAME), 100);
}
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(resolveSize(textBounds.width(), widthMeasureSpec),
resolveSize(textBounds.height(), heightMeasureSpec));
}
}
| 32.89011 | 89 | 0.61577 |
705a3095d41ea330075e5b6d17a34696cfefbefb | 2,612 | package org.folio.marccat.resources;
import org.folio.marccat.config.log.Log;
import org.folio.marccat.config.log.MessageCatalog;
import org.folio.marccat.exception.DataAccessException;
import org.folio.marccat.exception.SubsystemCommunicationException;
import org.folio.marccat.exception.SystemInternalFailureException;
import org.folio.marccat.exception.UnableToCreateOrUpdateEntityException;
import org.folio.marccat.integration.Configuration;
import org.folio.marccat.resources.domain.ErrorCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.RestTemplate;
@CrossOrigin(origins = {
"http://folio.atcult.it:3000",
"http://folio.atcult.it",
"http://localhost:3000",
"http://localhost:8080",
"*"
})
public abstract class BaseResource {
protected Log logger = new Log(getClass());
@Autowired
protected Configuration configurator;
@Autowired
protected RestTemplate CLIENT;
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Communication failure with one or more internal subsystems")
@ExceptionHandler(SubsystemCommunicationException.class)
public void ioFailure(final Exception exception) {
logger.error(MessageCatalog._00013_IO_FAILURE, exception);
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "System internal failure has occurred.")
@ExceptionHandler(DataAccessException.class)
public void dataAccessFailure(final DataAccessException exception) {
logger.error(MessageCatalog._00011_NWS_FAILURE, exception);
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "System internal failure has occurred.")
@ExceptionHandler(SystemInternalFailureException.class)
public ResponseEntity<Object> systemInternalFailure(final Exception exception, final ErrorCollection errors) {
logger.error(MessageCatalog._00011_NWS_FAILURE, exception);
return new ResponseEntity<Object>(errors, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY, reason = "Cannot create the requested entity.")
@ExceptionHandler(UnableToCreateOrUpdateEntityException.class)
public void unableToUpsertEntity(final UnableToCreateOrUpdateEntityException exception) {
logger.error(MessageCatalog._00018_CANNOT_CREATE, exception);
}
}
| 43.533333 | 130 | 0.819296 |
dc96783b36e9c6b9e9470dff03aed7fc9389bced | 1,981 | package com.skytala.eCommerce.domain.login.relations.x509IssuerProvision.model;
import java.util.Map;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Map;
import java.io.Serializable;
import com.skytala.eCommerce.domain.login.relations.x509IssuerProvision.mapper.X509IssuerProvisionMapper;
public class X509IssuerProvision implements Serializable{
private static final long serialVersionUID = 1L;
private String certProvisionId;
private String commonName;
private String organizationalUnit;
private String organizationName;
private String cityLocality;
private String stateProvince;
private String country;
private String serialNumber;
public String getCertProvisionId() {
return certProvisionId;
}
public void setCertProvisionId(String certProvisionId) {
this.certProvisionId = certProvisionId;
}
public String getCommonName() {
return commonName;
}
public void setCommonName(String commonName) {
this.commonName = commonName;
}
public String getOrganizationalUnit() {
return organizationalUnit;
}
public void setOrganizationalUnit(String organizationalUnit) {
this.organizationalUnit = organizationalUnit;
}
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
public String getCityLocality() {
return cityLocality;
}
public void setCityLocality(String cityLocality) {
this.cityLocality = cityLocality;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public Map<String, Object> mapAttributeField() {
return X509IssuerProvisionMapper.map(this);
}
}
| 21.769231 | 105 | 0.81474 |
a709de38d8c6862be7006f09e052adc55f6599c3 | 545 | package com.rsg.rsgportal;
/**
* Created by adamsingle on 16/02/2016.
*/
public interface GenericProgressFeedbackCallback<T> {
// Call this when the operation has completed successfully
//
void success(T data);
//
// Call this if the operation fails to complete
//
void fail(Exception ex);
//
// Call this with the progress of the operation. Value is expected to be
// between 0 and 1
//
void progress(float progress);
}
| 23.695652 | 81 | 0.570642 |
f1d9c2ec1ea9f108f04d48c8946cbc48c75bc145 | 2,401 | /*******************************************************************************
* Copyright © 2019 by California Community Colleges Chancellor's Office
*
* 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.cccnext.tesuto.placement.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.io.Serializable;
import java.util.Calendar;
import org.hibernate.envers.AuditTable;
import org.hibernate.envers.Audited;
@Entity
@Audited
@AuditTable(schema="public",value = "history_cb21")
@Table(schema="public",name = "cb21")
public class CB21 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="cb21_code")
private char cb21Code;
@Column(name="levels_below_transfer")
private int levelsBelowTransfer;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_on")
private Calendar createdOn;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="updated_on")
private Calendar updatedOn;
public char getCb21Code() {
return cb21Code;
}
public void setCb21Code(char cb21Code) {
this.cb21Code = cb21Code;
}
public int getLevelsBelowTransfer() {
return levelsBelowTransfer;
}
public void setLevelsBelowTransfer(int level) {
this.levelsBelowTransfer = level;
}
public Calendar getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Calendar createdOn) {
this.createdOn = createdOn;
}
public Calendar getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Calendar updatedOn) {
this.updatedOn = updatedOn;
}
}
| 27.284091 | 80 | 0.670554 |
d539c016a3de8a6ccc53a3e3b53efe300649cd47 | 25,338 | package jmutops;
import java.util.ArrayList;
import java.util.List;
import mutationoperators.MutationOperator;
import mutationoperators.MutationOperatorProperty;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.WhileStatement;
import results.JMutOpsEventListenerMulticaster;
import utils.Preperator;
import ch.uzh.ifi.seal.changedistiller.model.entities.Delete;
import ch.uzh.ifi.seal.changedistiller.model.entities.Insert;
import ch.uzh.ifi.seal.changedistiller.model.entities.Move;
import ch.uzh.ifi.seal.changedistiller.model.entities.SourceCodeChange;
import ch.uzh.ifi.seal.changedistiller.model.entities.Update;
/**
* Class that stores and maintains the implemented MutationOperators.
* <p>
* It handles the requests to check for matching mutation operators and performs
* some preparing steps.
*
* @author Lukas Subel
*
*/
public class MutationOperatorTester {
//////////////////////////////////////////////////////
/// Fields
//////////////////////////////////////////////////////
/**
* Array containing all method level related mutation operators.
*/
private ArrayList<MutationOperator> methodlevel_list;
/**
* Array containing all class level related mutation operators.
*/
private ArrayList<MutationOperator> classlevel_list;
/**
* Array containing all class and method level related mutation operators.
*/
private ArrayList<MutationOperator> bothlevel_list;
/**
* Multicaster which will talk to all ResultListeners which were added
*/
private JMutOpsEventListenerMulticaster listener = new JMutOpsEventListenerMulticaster();
// ////////////////////////////////////////////////////
// / Methods
// ////////////////////////////////////////////////////
/**
* Default constructor.
*
* @param listener Reference to the event multi caster so it can fire events.
*/
public MutationOperatorTester(JMutOpsEventListenerMulticaster listener) {
this.methodlevel_list = new ArrayList<MutationOperator>();
this.classlevel_list = new ArrayList<MutationOperator>();
this.bothlevel_list = new ArrayList<MutationOperator>();
this.listener = listener;
}
/**
* Add another {@link MutationOperator} to be included in testings.
* <p>
* @param mutop
* MutationOperator which should be used on checked ASTs.
* @return True if the MutationOperator was added, otherwise false.
*/
public boolean addMutationOperator(MutationOperator mutop) {
switch (mutop.getCategory()) {
case CLASS_LEVEL:
this.listener.OnMutationOperatorInit(mutop);
// check if this operator was added before
if (!this.classlevel_list.contains(mutop)) {
// if not, add it
this.classlevel_list.add(mutop);
return true;
} else {
return false;
}
case METHOD_LEVEL:
this.listener.OnMutationOperatorInit(mutop);
// check if this operator was added before
if (!this.methodlevel_list.contains(mutop)) {
// if not, add it
this.methodlevel_list.add(mutop);
return true;
} else {
return false;
}
case BOTH_LEVELS:
this.listener.OnMutationOperatorInit(mutop);
// check if this operator was added before
if (!this.bothlevel_list.contains(mutop)) {
// if not, add it
this.bothlevel_list.add(mutop);
return true;
} else {
return false;
}
default:
// default case means some error
String error_message = "Unexpected MutationOperatorCategory in input MutationOperator: " + mutop.getCategory().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - addMutationOperator(MutationOperator)" , error_message);
throw new IllegalArgumentException(error_message);
}
}
/**
* Check for any applied {@link MutationOperator} which occurred in the {@link ASTNode} {@code node}
* related to the {@link SourceCodeChange} {@code change}.
* @param node The {@link ASTNode} related to the {@code change}.
* @param change The {@link SourceCodeChange} retrieved from ChangeDistiller.
*/
public void checkForMutationOperators(ASTNode node, SourceCodeChange change) {
if (change instanceof Insert) {
this.check(node, (Insert) change);
} else if (change instanceof Delete) {
this.check(node, (Delete) change);
} else {
// default case means some error
String error_message = "Unexpected subclass for change on one version.: " + change.getClass().getSimpleName();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - checkForMutationOperators(ASTNode, SourceCodeChange)" , error_message);
throw new IllegalArgumentException(error_message);
}
}
/**
* This method runs the following steps:
* <ul>
* <li>It selects a subset of all registered {@link MutationOperator} which
* could occur in this {@link SourceCodeChange},</li>
* <li>It tries to select a subAST depending on the the
* {@link SourceCodeChange},</li>
* <li>It calls the {@link MutationOperator} to check for a match.</li>
* </ul>
*
* @param leftNode
* {@link ASTNode} with the prefix version.
* @param rightNode
* {@link ASTNode} with the postfix version.
* @param change
* ChangeDistiller object describing the change related betweeen
* both {@link ASTNode} versions.
*/
public void checkForMutationOperators(ASTNode leftNode, ASTNode rightNode,
SourceCodeChange change) {
if (change instanceof Update) {
this.check(leftNode, rightNode, (Update) change);
} else if (change instanceof Move) {
this.check(leftNode, rightNode, (Move) change);
} else {
// default case means some error
String error_message = "Unexpected subclass for change on two versions.: " + change.getClass().getSimpleName();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - checkForMutationOperators(ASTNode, ASTNode, SourceCodeChange)" , error_message);
throw new IllegalArgumentException(error_message);
}
}
/**
* Check for {@link MutationOperator} which implement the method
* {@link MutationOperator#check(List, Preperator, Preperator)}.
* @param changes All detected {@link SourceCodeChange} found in the file under test.
* @param prefixed_preperator The {@link Preperator} related to the prefix file.
* @param postfixed_preperator The {@link Preperator} related to the postfix file.
*/
public void checkForMutationOperators(List<SourceCodeChange> changes,
Preperator prefixed_preperator, Preperator postfixed_preperator) {
// get the correct list of MutationOperator's to check
ArrayList<MutationOperator> mutationOperatorList = getInitialMutationOperators(changes);
// filter out all mutation operator which do not implement it
filterPreCheck(mutationOperatorList, true);
// perform the pre check on all remaining mutation operators
preRunMutationOperators(mutationOperatorList, changes, prefixed_preperator, postfixed_preperator);
}
private void check(ASTNode node, Insert change) {
// get the correct list of MutationOperator's to check
ArrayList<MutationOperator> mutationOperatorList = getInitialMutationOperators(change);
// filter the list of mutationOperators
filterOneAST(mutationOperatorList, true);
filterInsert(mutationOperatorList, true);
// check the location of update
if (change.getChangeType().isBodyChange()) {
// in case of a body change
switch (change.getChangeType()) {
case COMMENT_INSERT:
// since comment updates do not fix bugs,
// we cannot find possible matches to this case
// and therefore return a "no matching found"
this.listener.OnNoMatchingFound(mutationOperatorList);
break;
case ADDITIONAL_CLASS:
case ADDITIONAL_FUNCTIONALITY:
case ADDITIONAL_OBJECT_STATE:
case ALTERNATIVE_PART_INSERT:
case STATEMENT_INSERT:
case UNCLASSIFIED_CHANGE:
runMutationOperators(mutationOperatorList, node);
break;
default:
// default case means some error
String error_message = "Expected body insert, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, Insert)" , error_message);
throw new IllegalStateException(error_message);
}
} else {
// in case of a class change
switch (change.getChangeType()) {
case DOC_INSERT:
// since comment updates do not fix bugs, we ignore this case
// break;
case ADDING_CLASS_DERIVABILITY:
case ADDING_METHOD_OVERRIDABILITY:
case PARAMETER_INSERT:
case PARENT_CLASS_INSERT:
case PARENT_INTERFACE_INSERT:
case REMOVING_ATTRIBUTE_MODIFIABILITY:
case RETURN_TYPE_INSERT:
runMutationOperators(mutationOperatorList, node);
break;
default:
String error_message = "Expected class insert, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, Insert)" , error_message);
throw new IllegalStateException(error_message);
}
}
}
private void check(ASTNode node, Delete change) {
// get the correct list of MutationOperator's to check
ArrayList<MutationOperator> mutationOperatorList = getInitialMutationOperators(change);
// filter the list of mutationOperators
filterOneAST(mutationOperatorList, true);
filterDelete(mutationOperatorList, true);
// check the location of update
if (change.getChangeType().isBodyChange()) {
// in case of a body change
switch (change.getChangeType()) {
case COMMENT_DELETE:
// since comment updates do not fix bugs,
// we cannot find possible matches to this case
// and therefore return a "no matching found"
this.listener.OnNoMatchingFound(mutationOperatorList);
break;
case ALTERNATIVE_PART_DELETE:
case REMOVED_CLASS:
case REMOVED_FUNCTIONALITY:
case REMOVED_OBJECT_STATE:
case STATEMENT_DELETE:
case UNCLASSIFIED_CHANGE:
runMutationOperators(mutationOperatorList, node);
break;
default:
// default case means some error
String error_message = "Expected body delete, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, Delete)" , error_message);
throw new IllegalStateException(error_message);
}
} else {
// in case of a class change
switch (change.getChangeType()) {
case ADDING_ATTRIBUTE_MODIFIABILITY:
case DOC_DELETE:
case PARAMETER_DELETE:
case PARENT_CLASS_DELETE:
case PARENT_INTERFACE_DELETE:
case RETURN_TYPE_DELETE:
runMutationOperators(mutationOperatorList, node);
break;
default:
String error_message = "Expected class delete, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, Delete)" , error_message);
throw new IllegalStateException(error_message);
}
}
}
private void check(ASTNode leftNode, ASTNode rightNode, Move change) {
// get the correct list of MutationOperator's to check
ArrayList<MutationOperator> mutationOperatorList = getInitialMutationOperators(change);
// filter the list of mutationOperators
filterTwoAST(mutationOperatorList, true);
filterMove(mutationOperatorList, true);
// check the location of update
if (change.getChangeType().isBodyChange()) {
// in case of a body change
switch (change.getChangeType()) {
case COMMENT_MOVE:
// since comment updates do not fix bugs,
// we cannot find possible matches to this case
// and therefore return a "no matching found"
this.listener.OnNoMatchingFound(mutationOperatorList);
break;
case STATEMENT_ORDERING_CHANGE:
case STATEMENT_PARENT_CHANGE:
case UNCLASSIFIED_CHANGE:
runMutationOperators(mutationOperatorList, leftNode, rightNode);
break;
default:
String error_message = "Expected body move, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, ASTNode, Move)" , error_message);
throw new IllegalStateException(error_message);
}
} else {
// in case of a class change
switch (change.getChangeType()) {
case PARAMETER_ORDERING_CHANGE:
runMutationOperators(mutationOperatorList, leftNode, rightNode);
break;
default:
String error_message = "Expected class move, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, ASTNode, Move)" , error_message);
throw new IllegalStateException(error_message);
}
}
}
private void check(ASTNode leftNode, ASTNode rightNode, Update change) {
// get the correct list of MutationOperator's to check
ArrayList<MutationOperator> mutationOperatorList = getInitialMutationOperators(change);
// filter the list of mutationOperators
filterTwoAST(mutationOperatorList, true);
filterUpdate(mutationOperatorList, true);
// check the location of update
if (change.getChangeType().isBodyChange()) {
// in case of a body change
switch (change.getChangeType()) {
case COMMENT_UPDATE:
// since comment updates do not fix bugs,
// we cannot find possible matches to this case
// and therefore return a "no matching found"
this.listener.OnNoMatchingFound(mutationOperatorList);
break;
case CONDITION_EXPRESSION_CHANGE:
// check only the condition of the node
// TODO check why arg.equals("-d") ~> arg.equals("-encoding") does not match ACO
if ((leftNode instanceof IfStatement)
&& (rightNode instanceof IfStatement)) {
runMutationOperators(mutationOperatorList,
((IfStatement) leftNode).getExpression(),
((IfStatement) rightNode).getExpression());
} else if ((leftNode instanceof WhileStatement)
&& (rightNode instanceof WhileStatement)) {
runMutationOperators(mutationOperatorList,
((WhileStatement) leftNode).getExpression(),
((WhileStatement) rightNode).getExpression());
} else if ((leftNode instanceof DoStatement)
&& (rightNode instanceof DoStatement)) {
runMutationOperators(mutationOperatorList,
((DoStatement) leftNode).getExpression(),
((DoStatement) rightNode).getExpression());
// TODO check why j.hasNext() ~> it.hasNext() does not match VRO
} else if ((leftNode instanceof ForStatement)
&& (rightNode instanceof ForStatement)) {
runMutationOperators(mutationOperatorList,
((ForStatement) leftNode).getExpression(),
((ForStatement) rightNode).getExpression());
} else {
String error_message = "Could not find ASTNode with same nodetype on changetype CONDITION_EXPRESSION_CHANGE: " + leftNode.getClass().getName() + " & " + rightNode.getClass().getName();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, ASTNode, Update)" , error_message);
throw new IllegalStateException(error_message);
}
break;
case STATEMENT_UPDATE:
case UNCLASSIFIED_CHANGE:
// in this case, we cannot specify the area to search
runMutationOperators(mutationOperatorList, leftNode, rightNode);
break;
default:
String error_message = "Expected body update, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, ASTNode, Update)" , error_message);
throw new IllegalStateException(error_message);
}
} else {
// in case of a class change
switch (change.getChangeType()) {
case DOC_UPDATE:
// since comment updates do not fix bugs, we ignore this case
// break;
case ATTRIBUTE_RENAMING:
case ATTRIBUTE_TYPE_CHANGE:
case CLASS_RENAMING:
case DECREASING_ACCESSIBILITY_CHANGE:
case INCREASING_ACCESSIBILITY_CHANGE:
case METHOD_RENAMING:
case PARAMETER_RENAMING:
case PARAMETER_TYPE_CHANGE:
case PARENT_CLASS_CHANGE:
case PARENT_INTERFACE_CHANGE:
case REMOVING_CLASS_DERIVABILITY:
case REMOVING_METHOD_OVERRIDABILITY:
case RETURN_TYPE_CHANGE:
case UNCLASSIFIED_CHANGE:
runMutationOperators(mutationOperatorList, leftNode, rightNode);
break;
default:
String error_message = "Expected class update, but found " + change.getChangeType().toString();
this.listener.OnErrorDetected(this.getClass().getSimpleName() + " - check(ASTNode, Update)" , error_message);
throw new IllegalStateException(error_message);
}
}
}
/**
* Helper method. Check for each MutationOperator in operatorlist, if
* leftNode to rightNode applied the corresponding operator.
*
* @param operatorlist
* A {@link List} of {@link MutationOperator} containing all
* MutationOperators to check in this case.
* @param prefix
* The prefixed version.
* @param postfix
* The postfixed version.
*/
private void runMutationOperators(List<MutationOperator> operatorlist, ASTNode prefix, ASTNode postfix) {
// initialize a variable which counts the number of detected
// applications
int detected_applications = 0;
// check all mutation operators
for (MutationOperator operator : operatorlist) {
try {
detected_applications += operator.check(prefix, postfix);
} catch (Exception e) {
String errorMessage =
"Exception thrown while checking mutation operator " + operator.getShortname() + ": "
+ e.toString();
this.listener.OnErrorDetected("MutationOperatorTester - runMutationOperators(List<MutationOperator>, ASTNode, ASTNode)", errorMessage);
continue;
}
}
// fire event when there was no matching detected
if (detected_applications == 0) {
this.listener.OnNoMatchingFound(operatorlist);
}
}
/**
* Helper method. Check for each MutationOperator in {@code operatorlist},
* if one of the {@ink MutationOperator} in {@code operatorlist} could be applied to {@code node}.
* @param operatorlist
* A {@link List} of {@link MutationOperator} containing all
* MutationOperators to check in this case.
* @param node
* The version to check
*/
private void runMutationOperators(List<MutationOperator> operatorlist, ASTNode node) {
// initialize a variable which counts the number of detected
// applications
int detected_applications = 0;
// check all mutation operators
for (MutationOperator operator : operatorlist) {
try {
detected_applications += operator.check(node);
} catch (Exception e) {
String errorMessage =
"Exception thrown while checking mutation operator " + operator.getShortname() + ": "
+ e.toString();
this.listener.OnErrorDetected("MutationOperatorTester - runMutationOperators(List<MutationOperator>, ASTNode)", errorMessage);
continue;
}
}
// fire event when there was no matching detected
if (detected_applications == 0) {
this.listener.OnNoMatchingFound(operatorlist);
}
}
private void preRunMutationOperators(
ArrayList<MutationOperator> operatorlist,
List<SourceCodeChange> changes, Preperator prefixed_preperator,
Preperator postfixed_preperator) {
// initialize a variable which counts the number of detected
// applications
int detected_applications = 0;
// check all mutation operators
for (MutationOperator operator : operatorlist) {
try {
operator.check(changes, prefixed_preperator, postfixed_preperator);
} catch (Exception e) {
String errorMessage =
"Exception thrown while checking mutation operator " + operator.getShortname() + ": " + "\n"
+ e.toString();
this.listener.OnErrorDetected("MutationOperatorTester - preRunMutationOperators(ArrayList<MutationOperator>, List<SourceCodeChange>, Preperator, Preperator)", errorMessage);
continue;
}
}
// fire event when there was no matching detected
if (detected_applications == 0) {
this.listener.OnNoMatchingFound(operatorlist);
}
}
private ArrayList<MutationOperator> getInitialMutationOperators(SourceCodeChange change) {
ArrayList<MutationOperator> mutationOperatorList;
// get level based operators
if (change.getChangeType().isBodyChange()) {
mutationOperatorList = getCopyOfList(methodlevel_list);
} else {
mutationOperatorList = getCopyOfList(classlevel_list);
}
// at both leveled operators to it
mutationOperatorList.addAll(bothlevel_list);
return mutationOperatorList;
}
private ArrayList<MutationOperator> getInitialMutationOperators(List<SourceCodeChange> changes) {
ArrayList<MutationOperator> mutationOperatorList = new ArrayList<MutationOperator>();
boolean isMethod = false;
boolean isClass = false;
for(SourceCodeChange change: changes) {
if(change.getChangeType().isBodyChange() && (!isMethod)){
isMethod = true;
mutationOperatorList.addAll(getCopyOfList(methodlevel_list));
}
else if(!change.getChangeType().isBodyChange() && (!isClass)){
isClass = true;
mutationOperatorList.addAll(getCopyOfList(classlevel_list));
}
if(isMethod && isClass) {
break;
}
}
// at both leveled operators to it
mutationOperatorList.addAll(bothlevel_list);
return mutationOperatorList;
}
private ArrayList<MutationOperator> getCopyOfList(
ArrayList<MutationOperator> list) {
return (ArrayList<MutationOperator>) list.clone();
}
/**
* Removes all {@link MutationOperator} from {@code list} where the move property is equal to {@code moveValue}.
* @param list The list of {@link MutationOperator} to filter.
* @param moveValue The expected value of {@link MutationOperatorProperty} related to the move field.
*/
private void filterMove(ArrayList<MutationOperator> list, boolean moveValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canMove() != moveValue){
list.remove(mutop);
}
}
}
private void filterInsert(ArrayList<MutationOperator> list, boolean insertValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canInsert() != insertValue){
list.remove(mutop);
}
}
}
private void filterDelete(ArrayList<MutationOperator> list, boolean deleteValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canDelete() != deleteValue){
list.remove(mutop);
}
}
}
private void filterUpdate(ArrayList<MutationOperator> list, boolean updateValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canUpdate() != updateValue){
list.remove(mutop);
}
}
}
/**
* Removes all {@link MutationOperator} from {@code list} where the canOneAST property is not equal to {@code oneASTValue}.
* @param list The list of {@link MutationOperator} to filter.
* @param moveValue The expected value of {@link MutationOperatorProperty} related to the canOneAST field.
*/
private void filterOneAST(ArrayList<MutationOperator> list, boolean oneASTValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canHandleOneAST() != oneASTValue){
list.remove(mutop);
}
}
}
/**
* Removes all {@link MutationOperator} from {@code list} where the canTwoAST property is not equal to {@code oneTwoValue}.
* @param list The list of {@link MutationOperator} to filter.
* @param moveValue The expected value of {@link MutationOperatorProperty} related to the oneTwoValue field.
*/
private void filterTwoAST(ArrayList<MutationOperator> list, boolean oneTwoValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canHandleTwoASTs() != oneTwoValue){
list.remove(mutop);
}
}
}
/**
* Removes all {@link MutationOperator} from {@code list} where the preCheck property is not equal to {@code precheckValue}.
* @param list The list of {@link MutationOperator} to filter.
* @param moveValue The expected value of {@link MutationOperatorProperty} related to the precheckValue field.
*/
private void filterPreCheck(ArrayList<MutationOperator> list, boolean precheckValue){
ArrayList<MutationOperator> copy = (ArrayList<MutationOperator>) list.clone();
for(MutationOperator mutop: copy){
if(mutop.getProperty().canHandleMultipleChanges() != precheckValue){
list.remove(mutop);
}
}
}
}
| 38.390909 | 190 | 0.706765 |
87ae0149b77459fb0b997bf9ce0f53927aae10aa | 20,698 | /*
* Copyright (c) 2020 Dennis Lang (LanDen Labs) [email protected]
* 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.
*
* @author Dennis Lang
* @see http://LanDenLabs.com/
*/
package com.landenlabs.all_devtool;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.icu.text.TimeZoneNames;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import com.landenlabs.all_devtool.receivers.AlarmReceiver;
import com.landenlabs.all_devtool.util.ALogNotification;
import com.landenlabs.all_devtool.util.LLog;
import com.landenlabs.all_devtool.util.Ui;
import com.landenlabs.all_devtool.util.Utils;
import org.joda.time.DateTimeZone;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Display "Clock" information.
*
* @author Dennis Lang
*
*/
public class ClockFragment extends DevFragment implements View.OnClickListener {
private final LLog m_log = LLog.DBG;
public static String s_name = "Clock";
SubMenu m_menu;
Date m_date = new Date();
TimeZone m_timeZone = TimeZone.getDefault();
// ---- Alaram ----
AlarmManager m_alarmManager;
private PendingIntent m_pendingIntent;
private TimePicker m_alarmTimePicker;
private TextView m_alarmTextView;
private ToggleButton alarmToggle;
private ImageView alarmExpander;
// ---- Clock / Times ----
private TextView m_clockLocalTv;
private TextView m_clockGmtTv;
private TextView m_timePartsTv;
private TextView m_dayLight;
private TextView m_localeTv;
// Timezone Daylight savings
enum DaylightFilter { NoDS, HasDS, InDS}
DaylightFilter m_daylightFilter = DaylightFilter.HasDS;
// Additional times
private TextView m_clockSysClkUpTm;
private TextView m_clockSysClkReal;
private static SimpleDateFormat s_time12Format = new SimpleDateFormat("MMM-dd hh:mm a");
private static SimpleDateFormat s_time12ZoneFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zzz");
private static SimpleDateFormat s_time12GmtFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a 'GMT'");
private static SimpleDateFormat s_time24Format = new SimpleDateFormat("MMM-dd HH:mm");
private static SimpleDateFormat s_time24ZoneFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss zzz");
private static SimpleDateFormat s_time24GmtFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss 'GMT'");
private static SimpleDateFormat s_timeFormat = s_time12Format;
private static SimpleDateFormat s_timeZoneFormat = s_time12ZoneFormat;
private static SimpleDateFormat s_timeGmtFormat = s_time12GmtFormat;
static {
s_timeGmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
// ---- Timer ----
private static final int REFRESH_MSEC = 1000;
private Handler m_handler = new Handler();
private Runnable m_updateElapsedTimeTask = new Runnable() {
public void run() {
updateClock();
m_handler.postDelayed(this, REFRESH_MSEC); // Re-execute after xxx ms.
}
};
public static DevFragment create() {
return new ClockFragment();
}
AlarmManager getAlarmMgr() {
return (AlarmManager)getActivitySafe().getSystemService(Context.ALARM_SERVICE);
}
// ============================================================================================
// DevFragment methods
@Override
public String getName() {
return s_name;
}
@Override
public List<Bitmap> getBitmaps(int maxHeight) {
List<Bitmap> bitmapList = new ArrayList<>();
bitmapList.add(Utils.grabScreen(getActivitySafe()));
return bitmapList;
}
@Override
public List<String> getListAsCsv() {
return null;
}
@Override
public void onSelected() {
GlobalInfo.s_globalInfo.mainFragActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
GlobalInfo.s_globalInfo.mainFragActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
// ============================================================================================
// Fragment methods
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
m_log.e("onViewCreated savedInstanceState");
setHasOptionsMenu(true);
View m_rootView = inflater.inflate(R.layout.clock_tab, container, false);
m_alarmTimePicker = Ui.viewById(m_rootView, R.id.alarmTimePicker);
m_alarmTextView = Ui.viewById(m_rootView, R.id.alarmText);
m_clockLocalTv = Ui.viewById(m_rootView, R.id.clockLocal);
m_clockGmtTv = Ui.viewById(m_rootView, R.id.clockGmt);
m_timePartsTv = Ui.viewById(m_rootView, R.id.timeParts);
LinearLayout m_timeTopList = Ui.viewById(m_rootView, R.id.timeTopList);
Ui.viewById(m_rootView, R.id.timezone_hasds).setOnClickListener(this);
Ui.viewById(m_rootView, R.id.timezone_inds).setOnClickListener(this);
Ui.viewById(m_rootView, R.id.timezone_nods).setOnClickListener(this);
Ui.viewById(m_rootView, R.id.showTzMapBtn).setOnClickListener(this);
// ---- Additional times ----
m_clockSysClkUpTm = new TextView(m_timeTopList.getContext());
m_timeTopList.addView(m_clockSysClkUpTm);
m_clockSysClkReal = new TextView(m_timeTopList.getContext());
m_timeTopList.addView(m_clockSysClkReal);
m_localeTv = new TextView(m_timeTopList.getContext());
m_timeTopList.addView(m_localeTv);
LinearLayout m_timeBotList = Ui.viewById(m_rootView, R.id.timeBotList);
m_dayLight = new TextView(m_timeBotList.getContext());
m_timeBotList.addView(m_dayLight);
// ---- Alaram ----
alarmToggle = Ui.viewById(m_rootView, R.id.alarmToggle);
alarmToggle.setOnClickListener(this);
alarmExpander = Ui.viewById(m_rootView, R.id.alarmExpand);
alarmExpander.setOnClickListener(this);
m_alarmTimePicker.setVisibility(alarmExpander.getTag() != null ? View.VISIBLE : View.GONE);
m_alarmManager = getAlarmMgr();
return m_rootView;
}
@Override
public void onResume() {
super.onResume();
m_handler.removeCallbacks(m_updateElapsedTimeTask);
m_handler.postDelayed(m_updateElapsedTimeTask, 0);
updateAlarm();
}
@Override
public void onPause() {
super.onPause();
m_handler.removeCallbacks(m_updateElapsedTimeTask);
}
@Override
public void onStart(){
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.clock_12:
s_timeFormat = s_time12Format;
s_timeZoneFormat = s_time12ZoneFormat;
s_timeGmtFormat = s_time12GmtFormat;
break;
case R.id.clock_24:
s_timeFormat = s_time24Format;
s_timeZoneFormat = s_time24ZoneFormat;
s_timeGmtFormat = s_time24GmtFormat;
break;
default:
break;
}
item.setChecked(true);
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
m_menu = menu.addSubMenu("Clock Format");
inflater.inflate(R.menu.clock_menu, m_menu);
m_menu.findItem(R.id.clock_12).setChecked(true);
}
// ============================================================================================
// OnClick
@Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.showTzMapBtn:
showTimezoneMap();
break;
case R.id.timezone_hasds:
m_daylightFilter = DaylightFilter.HasDS;
updateClock();
break;
case R.id.timezone_inds:
m_daylightFilter = DaylightFilter.InDS;
updateClock();
break;
case R.id.timezone_nods:
m_daylightFilter = DaylightFilter.NoDS;
updateClock();
break;
case R.id.alarmToggle:
if (alarmToggle.isChecked() && alarmToggle.getTag() == null) {
toggleAlaramExpand();
}
updateAlarm();
break;
case R.id.alarmExpand:
toggleAlaramExpand();
updateAlarm();
break;
}
}
// ============================================================================================
// Clock methods
private static final long MIN_MILLI = 60 * 1000;
private static final long HOUR_MILLI = MIN_MILLI * 60;
private String getTzOffsetStr(TimeZone tz) {
long tzOffMilli = tz.getRawOffset();
long hours = tzOffMilli / HOUR_MILLI;
long mins = Math.abs(tzOffMilli % HOUR_MILLI) / MIN_MILLI;
return String.format(" GMT%+2d:%02d",
hours, mins);
}
private String getTzDetailStr(TimeZone tz) {
return String.format("%13s %s %s %s\n",
getTzOffsetStr(tz),
tz.getID(),
tz.useDaylightTime() ? "HasDS" : "",
tz.inDaylightTime(m_date) ? "InDs" : "");
}
private String getTzOffsetStr(TimeZone tz, SimpleDateFormat dateFormat) {
dateFormat.setTimeZone(tz);
return String.format("%13s %s %s\n",
getTzOffsetStr(tz),
dateFormat.format(m_date),
tz.getID());
}
/**
* Update clock on screen
*/
private void updateClock() {
m_date.setTime(System.currentTimeMillis());
// m_timeZone = TimeZone.getDefault();
m_timeZone = Calendar.getInstance().getTimeZone();
s_timeZoneFormat.setTimeZone(m_timeZone);
String localTmStr = s_timeZoneFormat.format(m_date);
// localTmStr += "\n zzz=" + new SimpleDateFormat("zzz", Locale.getDefault()).format(m_date);
localTmStr += "\n " + new SimpleDateFormat("zzzz", Locale.getDefault()).format(m_date);
// localTmStr += "\n ZZZ=" + new SimpleDateFormat("ZZZ").format(m_date);
localTmStr += "\n " + new SimpleDateFormat("ZZZZ", Locale.getDefault()).format(m_date);
// localTmStr += "\n Build Ver=" + Build.VERSION.SDK_INT;
if (Build.VERSION.SDK_INT >= 24) {
String tzId = m_timeZone.getID();
Locale us = Locale.US;
TimeZoneNames tzNames = TimeZoneNames.getInstance(us);
String tzName = tzNames.getDisplayName(tzId, TimeZoneNames.NameType.SHORT_STANDARD, m_date.getTime());
Log.d("ZZ_", "tzName=" + tzName);
}
m_clockLocalTv.setText(localTmStr);
String gmtTmStr = s_timeGmtFormat.format(m_date);
m_clockGmtTv.setText(gmtTmStr);
long currDay = TimeUnit.DAYS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
m_timePartsTv.setText(String.format("Days since Jan 1 1970: %d", currDay));
Locale ourLocale = Locale.getDefault();
StringBuilder tzStr1 = new StringBuilder();
StringBuilder tzStr2 = new StringBuilder();
tzStr1.append(String.format("Locale %s\n", ourLocale.getDisplayName()));
tzStr1.append(getTzDetailStr(m_timeZone));
tzStr1.append("Daylight Savings:\n");
// tzStr.append((m_timeZone.useDaylightTime() ? "Has" : "No") + " daylight savings\n");
String ds_short = m_timeZone.getDisplayName(false, TimeZone.SHORT, ourLocale);
tzStr1.append(String.format(" %s=%s\n", ds_short,m_timeZone.getDisplayName(false, TimeZone.LONG, ourLocale)));
if (m_timeZone.useDaylightTime()) {
String std_short = m_timeZone.getDisplayName(true, TimeZone.SHORT, ourLocale);
tzStr1.append(String.format(" %s=%s\n", std_short, m_timeZone.getDisplayName(true, TimeZone.LONG, ourLocale)));
// ----
// DateTimeZone zone1 = DateTimeZone.forID("Europe/London");
// DateTimeZone zone2 = DateTimeZone.forID("America/New_York");
DateTimeZone zone = DateTimeZone.forTimeZone(m_timeZone);
org.joda.time.format.DateTimeFormatter format = org.joda.time.format.DateTimeFormat.mediumDateTime();
long current = System.currentTimeMillis();
for (int i=0; i < 4; i++)
{
long next = zone.nextTransition(current);
if (current == next)
{
break;
}
tzStr1.append(String.format(" %s %s\n", zone.isStandardOffset(next-3600000) ? std_short : ds_short,
format.print(next)));
current = next;
}
// m_localeTv.setText(tzStr1.toString());
String[] ids = TimeZone.getAvailableIDs();
if (ids != null && ids.length > 0) {
switch (m_daylightFilter) {
case NoDS:
tzStr2.append("TimeZones (no Daylight savings):\n");
break;
case HasDS:
tzStr2.append("TimeZone (Has Daylight savings):\n");
break;
case InDS:
tzStr2.append("TimeZone (In Daylight savings):\n");
break;
}
SparseIntArray zones = new SparseIntArray();
for (int tzIdx = 0; tzIdx < ids.length; tzIdx++) {
TimeZone tz = TimeZone.getTimeZone(ids[tzIdx]);
boolean addTz = false;
switch (m_daylightFilter) {
case NoDS:
addTz = !tz.useDaylightTime();
break;
case HasDS:
addTz = tz.useDaylightTime() && !tz.inDaylightTime(m_date);
break;
case InDS:
addTz = tz.inDaylightTime(m_date);
break;
}
if (addTz) {
zones.put(tz.getRawOffset(), tzIdx);
}
}
for (int idx = 0; idx != zones.size(); idx++) {
TimeZone tz = TimeZone.getTimeZone(ids[zones.valueAt(idx)]);
tzStr2.append(getTzOffsetStr(tz, s_timeFormat));
}
}
}
m_localeTv.setText(tzStr1.toString());
m_dayLight.setText(tzStr2.toString());
m_clockSysClkUpTm.setText("uptimeMillis:"+ formatInterval(SystemClock.uptimeMillis()));
m_clockSysClkReal.setText("elapsedRealtime:" + formatInterval(SystemClock.elapsedRealtime()));
}
/**
* Format time interval
*/
private static String formatInterval(final long elapsedMillis)
{
final long day = TimeUnit.MICROSECONDS.toHours(elapsedMillis) / 24;
final long hr = TimeUnit.MILLISECONDS.toHours(elapsedMillis) % 24;
final long min = TimeUnit.MILLISECONDS.toMinutes(elapsedMillis) % 60;
final long sec = TimeUnit.MILLISECONDS.toSeconds(elapsedMillis) % 60;
final long ms = TimeUnit.MILLISECONDS.toMillis(elapsedMillis) % 1000;
return String.format("%s %02d:%02d:%02d.%03d", (day == 0 ? "" : String.valueOf(day)), hr, min, sec, ms);
}
private void showTimezoneMap() {
String htmlStr = Utils.LoadData(getContextSafe(), "timezone.html");
Ui.showWebMessage(getContext(), Ui.HTML_CENTER_BOX, htmlStr);
// Ui.showWebImage(getContext(), "file:///android_asset/world_timezone_map.png");
}
// ============================================================================================
// Alarm methods
private void toggleAlaramExpand() {
alarmExpander.animate().rotationBy(180).setDuration(1000).start();
alarmExpander.setTag(alarmExpander.getTag() == null ? 1 : null);
}
/**
* Toogle alarm setting UI on/off and start/stop pending intent.
*/
private void updateAlarm() {
boolean isOn = alarmToggle.isChecked();
m_alarmTimePicker.setVisibility(alarmExpander.getTag() != null ? View.VISIBLE : View.GONE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, m_alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, m_alarmTimePicker.getCurrentMinute());
if (isOn && calendar.getTimeInMillis() - System.currentTimeMillis() < TimeUnit.SECONDS.toMillis(60)) {
calendar.add(Calendar.SECOND, 60);
m_alarmTimePicker.setCurrentHour(calendar.get(Calendar.HOUR));
m_alarmTimePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
}
if (isOn) {
if (m_pendingIntent == null) {
Intent myIntent = new Intent(GlobalInfo.s_globalInfo.mainFragActivity, AlarmReceiver.class);
m_pendingIntent = PendingIntent.getBroadcast(
GlobalInfo.s_globalInfo.mainFragActivity, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
m_alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), m_pendingIntent);
}
s_timeFormat.setTimeZone(m_timeZone);
String alarmStr = s_timeFormat.format(calendar.getTime());
// Utils.showAlarmNotification(this.getActivity(), Utils.CLOCK_NOTIFICATION_ID, "Alarm " + alarmStr);
ALogNotification.updateNotification(this.getActivity(), "Alarm " + alarmStr);
m_alarmTextView.setText(alarmStr);
m_log.i("Alarm On " + alarmStr);
} else {
if (m_pendingIntent != null) {
m_alarmManager.cancel(m_pendingIntent);
Utils.cancelNotification(this.getActivity(), Utils.CLOCK_NOTIFICATION_ID);
m_pendingIntent = null;
RingtoneManager ringMan = new RingtoneManager(getActivity());
ringMan.stopPreviousRingtone();
}
m_alarmTextView.setText("");
m_log.i("Alarm Off");
}
}
} | 38.25878 | 126 | 0.620301 |
6e8d648cb63db7d38eee3cd74b3a2c039541007c | 1,033 | /*
* @(#)StyleConverterAdapter.java
* Copyright © 2021 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.text;
import javafx.css.ParsedValue;
import javafx.css.StyleConverter;
import javafx.scene.text.Font;
import org.jhotdraw8.annotation.NonNull;
import org.jhotdraw8.annotation.Nullable;
import java.io.IOException;
import java.text.ParseException;
/**
* Allows to use a {@code Converter} with the {@code javafx.css.StyleConverter}
* API.
*
* @author Werner Randelshofer
* rawcoder $
*/
public class StyleConverterAdapter<T> extends StyleConverter<String, T> {
private Converter<T> converter;
public StyleConverterAdapter(Converter<T> converter) {
this.converter = converter;
}
@Override
public @Nullable T convert(@NonNull ParsedValue<String, T> value, Font font) {
try {
return converter.fromString(value.getValue());
} catch (ParseException | IOException ex) {
return converter.getDefaultValue();
}
}
}
| 25.825 | 82 | 0.704743 |
8978956dc2444ad46b8b94c8e0a7d7435ab4cb79 | 933 | package com.solr.clientwrapper.usecase.solr.schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.solr.clientwrapper.domain.dto.solr.SolrFieldDTO;
import com.solr.clientwrapper.domain.dto.solr.SolrSchemaDTO;
import com.solr.clientwrapper.domain.port.api.SolrSchemaServicePort;
@Service
@Transactional
public class CreateSolrSchema {
private final Logger log = LoggerFactory.getLogger(CreateSolrSchema.class);
private final SolrSchemaServicePort solrSchemaServicePort;
public CreateSolrSchema(SolrSchemaServicePort solrSchemaServicePort) {
this.solrSchemaServicePort = solrSchemaServicePort;
}
public SolrSchemaDTO create(String tableName,String name,SolrFieldDTO [] attributes ) {
log.debug("create Schema");
return solrSchemaServicePort.create(tableName, name, attributes);
}
}
| 32.172414 | 88 | 0.831726 |
8e6fbbbe20fbb335372cd5177b30686103e4c6fb | 358 | package org.gollum.bank.domain.account;
import org.gollum.core.eventing.DomainEvent;
/**
* @author wurenhai
* @date 2018/1/4
*/
public class BankAccountCreated extends DomainEvent {
private String owner;
public BankAccountCreated(String owner) {
this.owner = owner;
}
public String getOwner() {
return owner;
}
}
| 16.272727 | 53 | 0.670391 |
6d6514a079988877dbd444fda586c84f8a8e2369 | 12,455 | /*
* Copyright (c) 2010-2021 Haifeng Li. All rights reserved.
*
* Smile 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.
*
* Smile 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 Smile. If not, see <https://www.gnu.org/licenses/>.
*/
package smile.clustering;
import java.util.Arrays;
import smile.math.MathEx;
/**
* Balanced Box-Decomposition Tree. BBD tree is a specialized k-d tree that
* vastly speeds up an iteration of k-means. This is used internally by KMeans
* and batch SOM., and will most likely not need to be used directly.
* <p>
* The structure works as follows:
* <ul>
* <li> All data are placed into a tree where we choose child nodes by
* partitioning all data data along a plane parallel to the axis.
* <li> We maintain for each node, the bounding box of all data data stored
* at that node.
* <li> To do a k-means iteration, we need to assign data to clusters and
* calculate the sum and the number of data assigned to each cluster.
* For each node in the tree, we can rule out some cluster centroids as
* being too far away from every single point in that bounding box.
* Once only one cluster is left, all data in the node can be assigned
* to that cluster in batch.
* </ul>
*
* <h2>References</h2>
* <ol>
* <li>Tapas Kanungo, David M. Mount, Nathan S. Netanyahu, Christine D. Piatko, Ruth Silverman, and Angela Y. Wu. An Efficient k-Means Clustering Algorithm: Analysis and Implementation. IEEE TRANS. PAMI, 2002.</li>
* </ol>
*
* @see KMeans
* @see smile.vq.SOM
*
* @author Haifeng Li
*/
public class BBDTree {
static class Node {
/**
* The number of data stored in this node.
*/
int size;
/**
* The smallest point index stored in this node.
*/
int index;
/**
* The center/mean of bounding box.
*/
double[] center;
/**
* The half side-lengths of bounding box.
*/
double[] radius;
/**
* The sum of the data stored in this node.
*/
double[] sum;
/**
* The min cost for putting all data in this node in 1 cluster
*/
double cost;
/**
* The child node of lower half box.
*/
Node lower;
/**
* The child node of upper half box.
*/
Node upper;
/**
* Constructor.
* @param d the dimension of vector space.
*/
Node(int d) {
center = new double[d];
radius = new double[d];
sum = new double[d];
}
}
/**
* Root node.
*/
private final Node root;
/**
* The index of data objects.
*/
private final int[] index;
/**
* Constructs a tree out of the given n data points living in R^d.
* @param data the data points.
*/
public BBDTree(double[][] data) {
int n = data.length;
index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
// Build the tree
root = buildNode(data, 0, n);
}
/**
* Build a k-d tree from the given set of data.
*/
private Node buildNode(double[][] data, int begin, int end) {
int d = data[0].length;
// Allocate the node
Node node = new Node(d);
// Fill in basic info
node.size = end - begin;
node.index = begin;
// Calculate the bounding box
double[] lowerBound = new double[d];
double[] upperBound = new double[d];
for (int i = 0; i < d; i++) {
lowerBound[i] = data[index[begin]][i];
upperBound[i] = data[index[begin]][i];
}
for (int i = begin + 1; i < end; i++) {
for (int j = 0; j < d; j++) {
double c = data[index[i]][j];
if (lowerBound[j] > c) {
lowerBound[j] = c;
}
if (upperBound[j] < c) {
upperBound[j] = c;
}
}
}
// Calculate bounding box stats
double maxRadius = -1;
int splitIndex = -1;
for (int i = 0; i < d; i++) {
node.center[i] = (lowerBound[i] + upperBound[i]) / 2;
node.radius[i] = (upperBound[i] - lowerBound[i]) / 2;
if (node.radius[i] > maxRadius) {
maxRadius = node.radius[i];
splitIndex = i;
}
}
// If the max spread is 0, make this a leaf node
if (maxRadius < 1E-10) {
node.lower = node.upper = null;
System.arraycopy(data[index[begin]], 0, node.sum, 0, d);
if (end > begin + 1) {
int len = end - begin;
for (int i = 0; i < d; i++) {
node.sum[i] *= len;
}
}
node.cost = 0;
return node;
}
// Partition the data around the midpoint in this dimension. The
// partitioning is done in-place by iterating from left-to-right and
// right-to-left in the same way that partitioning is done in quicksort.
double splitCutoff = node.center[splitIndex];
int i1 = begin, i2 = end - 1, size = 0;
while (i1 <= i2) {
boolean i1Good = (data[index[i1]][splitIndex] < splitCutoff);
boolean i2Good = (data[index[i2]][splitIndex] >= splitCutoff);
if (!i1Good && !i2Good) {
int temp = index[i1];
index[i1] = index[i2];
index[i2] = temp;
i1Good = i2Good = true;
}
if (i1Good) {
i1++;
size++;
}
if (i2Good) {
i2--;
}
}
// Create the child nodes
node.lower = buildNode(data, begin, begin + size);
node.upper = buildNode(data, begin + size, end);
// Calculate the new sum and opt cost
for (int i = 0; i < d; i++) {
node.sum[i] = node.lower.sum[i] + node.upper.sum[i];
}
double[] mean = new double[d];
for (int i = 0; i < d; i++) {
mean[i] = node.sum[i] / node.size;
}
node.cost = getNodeCost(node.lower, mean) + getNodeCost(node.upper, mean);
return node;
}
/**
* Returns the total contribution of all data in the given kd-tree node,
* assuming they are all assigned to a mean at the given location.
* <p>
* sum_{x \in node} ||x - mean||<sup>2</sup>
* <p>
* If c denotes the mean of mass of the data in this node and n denotes
* the number of data in it, then this quantity is given by
* <p>
* n * ||c - mean||<sup>2</sup> + sum_{x \in node} ||x - c||<sup>2</sup>
* <p>
* The sum is precomputed for each node as cost. This formula follows
* from expanding both sides as dot products.
*/
private double getNodeCost(Node node, double[] center) {
int d = center.length;
double scatter = 0.0;
for (int i = 0; i < d; i++) {
double x = (node.sum[i] / node.size) - center[i];
scatter += x * x;
}
return node.cost + node.size * scatter;
}
/**
* Given k cluster centroids, this method assigns data to nearest centroids.
* The return value is the distortion to the centroids. The parameter sums
* will hold the sum of data for each cluster. The parameter counts hold
* the number of data of each cluster. If membership is
* not null, it should be an array of size n that will be filled with the
* index of the cluster [0, k) that each data point is assigned to.
*
* @param centroids the current centroids of clusters.
* @param sum the workspace storing the sum of data in each cluster.
* @param size the number of samples in each cluster.
* @param y the class labels.
* @return the within cluster sum of the squared distance.
*/
public double clustering(double[][] centroids, double[][] sum, int[] size, int[] y) {
int k = centroids.length;
Arrays.fill(size, 0);
int[] candidates = new int[k];
for (int i = 0; i < k; i++) {
candidates[i] = i;
Arrays.fill(sum[i], 0.0);
}
double wcss = filter(root, centroids, candidates, k, sum, size, y);
int d = centroids[0].length;
for (int i = 0; i < k; i++) {
if (size[i] > 0) {
for (int j = 0; j < d; j++) {
centroids[i][j] = sum[i][j] / size[i];
}
}
}
return wcss;
}
/**
* This determines which clusters all data that are rooted node will be
* assigned to, and updates sums, counts and membership (if not null)
* accordingly. Candidates maintains the set of cluster indices which
* could possibly be the closest clusters for data in this subtree.
*/
private double filter(Node node, double[][] centroids, int[] candidates, int k, double[][] sum, int[] size, int[] y) {
int d = centroids[0].length;
// Determine which mean the node mean is closest to
double minDist = MathEx.squaredDistance(node.center, centroids[candidates[0]]);
int closest = candidates[0];
for (int i = 1; i < k; i++) {
double dist = MathEx.squaredDistance(node.center, centroids[candidates[i]]);
if (dist < minDist) {
minDist = dist;
closest = candidates[i];
}
}
// If this is a non-leaf node, recurse if necessary
if (node.lower != null) {
// Build the new list of candidates
int[] newCandidates = new int[k];
int k2 = 0;
for (int i = 0; i < k; i++) {
if (!prune(node.center, node.radius, centroids, closest, candidates[i])) {
newCandidates[k2++] = candidates[i];
}
}
// Recurse if there's at least two
if (k2 > 1) {
return filter(node.lower, centroids, newCandidates, k2, sum, size, y) + filter(node.upper, centroids, newCandidates, k2, sum, size, y);
}
}
// Assigns all data within this node to a single mean
for (int i = 0; i < d; i++) {
sum[closest][i] += node.sum[i];
}
size[closest] += node.size;
int last = node.index + node.size;
for (int i = node.index; i < last; i++) {
y[index[i]] = closest;
}
return getNodeCost(node, centroids[closest]);
}
/**
* Determines whether every point in the box is closer to centroids[bestIndex] than to
* centroids[testIndex].
*
* If x is a point, c_0 = centroids[bestIndex], c = centroids[testIndex], then:
* (x-c).(x-c) < (x-c_0).(x-c_0)
* <=> (c-c_0).(c-c_0) < 2(x-c_0).(c-c_0)
*
* The right-hand side is maximized for a vertex of the box where for each
* dimension, we choose the low or high value based on the sign of x-c_0 in
* that dimension.
*/
private boolean prune(double[] center, double[] radius, double[][] centroids, int bestIndex, int testIndex) {
if (bestIndex == testIndex) {
return false;
}
int d = centroids[0].length;
double[] best = centroids[bestIndex];
double[] test = centroids[testIndex];
double lhs = 0.0, rhs = 0.0;
for (int i = 0; i < d; i++) {
double diff = test[i] - best[i];
lhs += diff * diff;
if (diff > 0) {
rhs += (center[i] + radius[i] - best[i]) * diff;
} else {
rhs += (center[i] - radius[i] - best[i]) * diff;
}
}
return (lhs >= 2 * rhs);
}
} | 32.862797 | 214 | 0.530389 |
4355bdec4c4a708940b506fff02c60666fc4246a | 19,794 | package net.congueror.cgalaxy.gui.galaxy_map;
import net.minecraft.ChatFormatting;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level;
import java.util.*;
import java.util.stream.Collectors;
public abstract class GalacticObjectBuilder<T extends GalacticObjectBuilder<T>> {
public final ResourceLocation id;
private String diameter;
private double age;
private ResourceLocation texture;
public final Map<String, String> locale = new HashMap<>();
//sub, super
public static final Map<GalacticObject<?>, GalacticObject<?>> OBJECTS = new HashMap<>();
public GalacticObjectBuilder(ResourceLocation id) {
this.id = id;
}//TODO: Translation key generation.
public static GalacticObject<?> getObjectFromId(ResourceLocation name) {
return OBJECTS.keySet().stream().filter(galacticObject -> galacticObject.getId().equals(name)).findAny().orElse(null);
}
@SuppressWarnings("unchecked")
public static List<GalacticObject<Galaxy>> galaxies() {
return OBJECTS.keySet().stream().filter(object -> object.getType() instanceof Galaxy).map(object -> (GalacticObject<Galaxy>) object).collect(Collectors.toList());
}
public static List<Map.Entry<GalacticObject<SolarSystem>, GalacticObject<Galaxy>>> solarSystems() {
List<Map.Entry<GalacticObject<SolarSystem>, GalacticObject<Galaxy>>> list = new ArrayList<>();
List<GalacticObject<SolarSystem>> a = OBJECTS.keySet().stream()
.filter(object -> object != null && object.getType() instanceof SolarSystem).map(object -> (GalacticObject<SolarSystem>) object).collect(Collectors.toList());
List<GalacticObject<Galaxy>> b = OBJECTS.values().stream()
.filter(object -> object != null && object.getType() instanceof Galaxy).map(object -> (GalacticObject<Galaxy>) object).collect(Collectors.toList());
for (int i = 0; i < a.size(); i++) {
list.add(new AbstractMap.SimpleEntry<>(a.get(i), b.get(i)));
}
return list;
}
public static List<Map.Entry<GalacticObject<Planet>, GalacticObject<SolarSystem>>> planets() {
List<Map.Entry<GalacticObject<Planet>, GalacticObject<SolarSystem>>> list = new ArrayList<>();
List<GalacticObject<Planet>> a = OBJECTS.keySet().stream()
.filter(object -> object != null && object.getType() instanceof Planet).map(object -> (GalacticObject<Planet>) object).collect(Collectors.toList());
List<GalacticObject<SolarSystem>> b = OBJECTS.values().stream()
.filter(object -> object != null && object.getType() instanceof SolarSystem).map(object -> (GalacticObject<SolarSystem>) object).collect(Collectors.toList());
for (int i = 0; i < a.size(); i++) {
list.add(new AbstractMap.SimpleEntry<>(a.get(i), b.get(i)));
}
return list;
}
public static List<Map.Entry<GalacticObject<Moon>, GalacticObject<Planet>>> moons() {
List<Map.Entry<GalacticObject<Moon>, GalacticObject<Planet>>> list = new ArrayList<>();
List<GalacticObject<Moon>> a = OBJECTS.keySet().stream()
.filter(object -> object != null && object.getType() instanceof Moon).map(object -> (GalacticObject<Moon>) object).collect(Collectors.toList());
List<GalacticObject<Planet>> b = OBJECTS.values().stream()
.filter(object -> object != null && object.getType() instanceof Planet).map(object -> (GalacticObject<Planet>) object).collect(Collectors.toList());
for (int i = 0; i < a.size(); i++) {
list.add(new AbstractMap.SimpleEntry<>(a.get(i), b.get(i)));
}
return list;
}
public static List<Map.Entry<GalacticObject<MoonMoon>, GalacticObject<Moon>>> moonMoons() {
List<Map.Entry<GalacticObject<MoonMoon>, GalacticObject<Moon>>> list = new ArrayList<>();
List<GalacticObject<MoonMoon>> a = OBJECTS.keySet().stream()
.filter(object -> object != null && object.getType() instanceof MoonMoon).map(object -> (GalacticObject<MoonMoon>) object).collect(Collectors.toList());
List<GalacticObject<Moon>> b = OBJECTS.values().stream()
.filter(object -> object != null && object.getType() instanceof Moon).map(object -> (GalacticObject<Moon>) object).collect(Collectors.toList());
for (int i = 0; i < a.size(); i++) {
list.add(new AbstractMap.SimpleEntry<>(a.get(i), b.get(i)));
}
return list;
}
public GalacticObject<T> build() {
GalacticObject<T> obj = new GalacticObject<>(self());
if (OBJECTS.keySet().stream().map(GalacticObject::getId).anyMatch(s -> s.equals(obj.getId()))) {
throw new IllegalStateException("Duplicate galactic objects found!");
}
if (self() instanceof Galaxy) {
OBJECTS.put(obj, null);
} else if (self() instanceof SolarSystem system) {
OBJECTS.put(obj, system.galaxy);
} else if (self() instanceof Planet planet) {
OBJECTS.put(obj, planet.solarSystem);
} else if (self() instanceof Moon moon) {
OBJECTS.put(obj, moon.planet);
} else if (self() instanceof MoonMoon moonMoon) {
OBJECTS.put(obj, moonMoon.moon);
}
return obj;
}
public ResourceLocation getId() {
return id;
}
public String getDiameter() {
return diameter;
}
public double getAge() {
return age;
}
public ResourceLocation getTexture() {
return texture;
}
protected abstract String getType();
public String getTranslationKey() {
return getType() + "." + getId().getNamespace() + "." + getId().getPath();
}
public T withDiameter(double diameter, String unit) {
this.diameter = diameter + unit;
return self();
}
public T withAge(double age) {
this.age = age;
return self();
}
public T withTexture(ResourceLocation location) {
this.texture = location;
return self();
}
/**
* Adds a translation to this object in the en_us locale. If you wish to change locale use {@link #withTranslation(String, String)}
*
* @param translation The name of the translated object, e.g. "My Ore"
*/
public T withTranslation(String translation) {
this.locale.put("en_us", translation);
return self();
}
/**
* Adds a translation to this block in the given locale.
*
* @param translation The name of the translated block, e.g. "My Ore"
* @param locale The localization this translation will be added to, e.g. "en_us"
*/
public T withTranslation(String translation, String locale) {
this.locale.put(locale, translation);
return self();
}
@SuppressWarnings("unchecked")
final T self() {
return (T) this;
}
public static class Galaxy extends GalacticObjectBuilder<Galaxy> {
private double stars;
public Galaxy(ResourceLocation name) {
super(name);
}
@Override
protected String getType() {
return "galaxy";
}
public double getStars() {
return stars;
}
public Galaxy withStars(double stars) {
this.stars = stars;
return this;
}
}
public static class SolarSystem extends GalacticObjectBuilder<SolarSystem> {
private final GalacticObject<Galaxy> galaxy;
private int celestialObjects;
private X x;
private Y y;
public SolarSystem(ResourceLocation name, GalacticObject<Galaxy> galaxy) {
super(name);
this.galaxy = galaxy;
}
public GalacticObject<Galaxy> getGalaxy() {
return galaxy;
}
public int getCelestialObjects() {
return celestialObjects;
}
public X getX() {
return x;
}
public Y getY() {
return y;
}
public SolarSystem withCelestialObjects(int celestialObjects) {
this.celestialObjects = celestialObjects;
return this;
}
public SolarSystem withX(X x) {
this.x = x;
return this;
}
public SolarSystem withY(Y y) {
this.y = y;
return this;
}
@Override
protected String getType() {
return "solar_system";
}
}
public static class Planet extends GalacticObjectBuilder<Planet> {
private final GalacticObject<SolarSystem> solarSystem;
private int ringIndex;
private float angle;
private String atmosphere;
private int moons;
private double gravity;
private int tier;
private ResourceKey<Level> dim;
public Planet(ResourceLocation name, GalacticObject<SolarSystem> solarSystem) {
super(name);
this.solarSystem = solarSystem;
}
public GalacticObject<SolarSystem> getSolarSystem() {
return solarSystem;
}
public int getRingIndex() {
return ringIndex;
}
public float getAngle() {
return angle;
}
public String getAtmosphere() {
return atmosphere;
}
public int getMoons() {
return moons;
}
public double getGravity() {
return gravity;
}
public int getTier() {
return tier;
}
public ResourceKey<Level> getDim() {
return dim;
}
@Override
public double getAge() {
return solarSystem.getAge();
}
@Override
protected String getType() {
return "planet";
}
public Planet withAtmosphere(String atmosphere) {
this.atmosphere = atmosphere;
return this;
}
public Planet withMoons(int moons) {
this.moons = moons;
return this;
}
public Planet withGravity(double gravity) {
this.gravity = gravity;
return this;
}
public Planet withTier(int tier) {
this.tier = tier;
return this;
}
public Planet withRingIndex(int ringIndex) {
this.ringIndex = ringIndex;
return this;
}
public Planet withAngle(float angle) {
this.angle = angle;
return this;
}
public Planet withDim(ResourceKey<Level> dim) {
this.dim = dim;
return this;
}
}
public static class Moon extends GalacticObjectBuilder<Moon> {
private final GalacticObject<Planet> planet;
private int ringIndex;
private float angle;
private String atmosphere;
private int moons;
private double gravity;
private int tier;
private ResourceKey<Level> dim;
public Moon(ResourceLocation name, GalacticObject<Planet> planet) {
super(name);
this.planet = planet;
}
public GalacticObject<Planet> getPlanet() {
return planet;
}
public int getRingIndex() {
return ringIndex;
}
public float getAngle() {
return angle;
}
public String getAtmosphere() {
return atmosphere;
}
public int getMoons() {
return moons;
}
public double getGravity() {
return gravity;
}
public int getTier() {
return tier;
}
public ResourceKey<Level> getDim() {
return dim;
}
@Override
public double getAge() {
return planet.getAge();
}
@Override
protected String getType() {
return "moon";
}
public Moon withAtmosphere(String atmosphere) {
this.atmosphere = atmosphere;
return this;
}
public Moon withMoons(int moons) {
this.moons = moons;
return this;
}
public Moon withGravity(double gravity) {
this.gravity = gravity;
return this;
}
public Moon withTier(int tier) {
this.tier = tier;
return this;
}
public Moon withRingIndex(int ringIndex) {
this.ringIndex = ringIndex;
return this;
}
public Moon withAngle(float angle) {
this.angle = angle;
return this;
}
public Moon withDim(ResourceKey<Level> dim) {
this.dim = dim;
return this;
}
}
public static class MoonMoon extends GalacticObjectBuilder<MoonMoon> {
private final GalacticObject<Moon> moon;
private int ringIndex;
private float angle;
private String atmosphere;
private int moons;
private double gravity;
private int tier;
public MoonMoon(ResourceLocation name, GalacticObject<Moon> moon) {
super(name);
this.moon = moon;
}
public GalacticObject<Moon> getMoon() {
return moon;
}
public int getRingIndex() {
return ringIndex;
}
public float getAngle() {
return angle;
}
public String getAtmosphere() {
return atmosphere;
}
public int getMoons() {
return moons;
}
public double getGravity() {
return gravity;
}
public int getTier() {
return tier;
}
@Override
public double getAge() {
return moon.getAge();
}
@Override
protected String getType() {
return "moonmoon";
}
public MoonMoon withRingIndex(int ringIndex) {
this.ringIndex = ringIndex;
return this;
}
public MoonMoon withAngle(float angle) {
this.angle = angle;
return this;
}
public MoonMoon withAtmosphere(String atmosphere) {
this.atmosphere = atmosphere;
return this;
}
public MoonMoon withMoons(int moons) {
this.moons = moons;
return this;
}
public MoonMoon withGravity(double gravity) {
this.gravity = gravity;
return this;
}
public MoonMoon withTier(int tier) {
this.tier = tier;
return this;
}
}
public static class GalacticObject<G extends GalacticObjectBuilder<G>> {
private final G builder;
public GalacticObject(G builder) {
this.builder = builder;
}
public ResourceLocation getId() {
return builder.getId();
}
public G getType() {
return this.builder;
}
public String getDiameter() {
return builder.getDiameter();
}
public double getAge() {
return builder.getAge();
}
public ResourceLocation getTexture() {
return builder.getTexture();
}
public String getTranslationKey() {
return builder.getTranslationKey();
}
public String getAtmosphere() {
if (builder instanceof Planet) {
return ((Planet) builder).getAtmosphere();
} else if (builder instanceof Moon) {
return ((Moon) builder).getAtmosphere();
} else if (builder instanceof MoonMoon) {
return ((MoonMoon) builder).getAtmosphere();
}
return "null";
}
public int getMoons() {
if (builder instanceof Planet) {
return ((Planet) builder).getMoons();
} else if (builder instanceof Moon) {
return ((Moon) builder).getMoons();
} else if (builder instanceof MoonMoon) {
return ((MoonMoon) builder).getMoons();
}
return -1;
}
public double getGravity() {
if (builder instanceof Planet) {
return ((Planet) builder).getGravity();
} else if (builder instanceof Moon) {
return ((Moon) builder).getGravity();
} else if (builder instanceof MoonMoon) {
return ((MoonMoon) builder).getGravity();
}
return -1;
}
public int getTier() {
if (builder instanceof Planet) {
return ((Planet) builder).getTier();
} else if (builder instanceof Moon) {
return ((Moon) builder).getTier();
} else if (builder instanceof MoonMoon) {
return ((MoonMoon) builder).getTier();
}
return -1;
}
public double getStars() {
if (builder instanceof Galaxy) {
return ((Galaxy) builder).getStars();
}
return -1;
}
public int getTerrestrialObjects() {
if (builder instanceof SolarSystem) {
return ((SolarSystem) builder).getCelestialObjects();
}
return -1;
}
public int getSolarSystemX(int width, int leftPos) {
if (builder instanceof SolarSystem) {
return ((SolarSystem) builder).getX().applyX(width, leftPos);
}
return -1;
}
public int getSolarSystemY(int height, int topPos) {
if (builder instanceof SolarSystem) {
return ((SolarSystem) builder).getY().applyY(height, topPos);
}
return -1;
}
public int getRingIndex() {
if (builder instanceof Planet) {
return ((Planet) builder).getRingIndex();
} else if (builder instanceof Moon) {
return ((Moon) builder).getRingIndex();
} else if (builder instanceof MoonMoon) {
return ((MoonMoon) builder).getRingIndex();
}
return -1;
}
public float getAngle() {
if (builder instanceof Planet) {
return ((Planet) builder).getAngle();
} else if (builder instanceof Moon) {
return ((Moon) builder).getAngle();
} else if (builder instanceof MoonMoon) {
return ((MoonMoon) builder).getAngle();
}
return -1;
}
public ResourceKey<Level> getDimension() {
if (builder instanceof Planet) {
return ((Planet) builder).getDim();
} else if (builder instanceof Moon) {
return ((Moon) builder).getDim();
}
return null;
}
public ChatFormatting getColor() {
if (builder instanceof Galaxy) {
return ChatFormatting.DARK_PURPLE;
} else if (builder instanceof SolarSystem) {
return ChatFormatting.GOLD;
} else if (builder instanceof Planet) {
return ChatFormatting.GREEN;
} else if (builder instanceof Moon) {
return ChatFormatting.GRAY;
}
return ChatFormatting.WHITE;
}
}
public interface X {
int applyX(int width, int leftPos);
}
public interface Y {
int applyY(int height, int topPos);
}
}
| 29.720721 | 174 | 0.557694 |
321fe63148d545a023fce420efe351c07df9aa80 | 2,993 | /*******************************************************************************
* Copyright 2013 Sprachliche Informationsverarbeitung, University of Cologne
*
* 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 de.uni_koeln.spinfo.maalr.webapp.ui.user.client;
import java.util.List;
import com.github.gwtbootstrap.client.ui.Heading;
import com.github.gwtbootstrap.client.ui.Modal;
import com.github.gwtbootstrap.client.ui.base.ListItem;
import com.github.gwtbootstrap.client.ui.base.UnorderedList;
import com.github.gwtbootstrap.client.ui.constants.BackdropType;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Widget;
/**
* A Modal/PopupDialog containing several external links.
*
* @author Mihail Atanassov <[email protected]>
*
*/
public class ExternalLinkDialog extends Widget {
private Modal modal;
private Dictionary linksDictionary;
private Dictionary localeDictionary;
private List<String> links;
public ExternalLinkDialog(List<String> links, Dictionary linksDictionary) {
this.linksDictionary = linksDictionary;
this.localeDictionary = DictionaryConstants.getLocaleDictionary();
this.links = links;
init();
}
private void init() {
createModalWithLinks();
modal.show();
}
private void createModalWithLinks() {
modal = new Modal(true);
modal.setBackdrop(BackdropType.NORMAL);
modal.add(new Heading(3, localeDictionary.get(links.get(0))));
UnorderedList list = new UnorderedList();
String ulClassName = list.getElement().getClassName();
list.getElement().setClassName(ulClassName + " ext_links_dicts");
for (int i = 1; i < links.size(); i++) {
list.add(new ListItem(createLink(localeDictionary.get(links.get(i)),
linksDictionary.get(links.get(i)))));
}
modal.add(list);
String modalClassName = modal.getElement().getClassName();
modal.getElement().setClassName(modalClassName + " vertical-center");
}
private Anchor createLink(final String txt, final String url) {
Anchor anchor = new Anchor(txt, url);
anchor.setTarget("_blank");
anchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
modal.hide();
modal.removeFromParent();
}
});
return anchor;
}
}
| 31.505263 | 80 | 0.710324 |
f26d6f059241eccca5ea30e873bce560a01865d9 | 453 | package com.mit.community.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
//设备信息
public class UserInfo {
private String id; // 设备id
private String serialNumber; //设备编号
private String nickName; //设备名称
private String portrait; //角色
private String departmentId; //部门ID
private String terminalType; //int 终端类型:1 一期 2 二期 5 三期
}
| 21.571429 | 61 | 0.730684 |
e93824c4bb57204c60da72a39a449308c8599e97 | 8,466 | package joken.ac.jp.survey2016;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import joken.ac.jp.survey2016.QuestionFragment.OnListFragmentInteractionListener;
import joken.ac.jp.survey2016.QuestionContent.QuestionItem;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;
/**
* {@link RecyclerView.Adapter} that can display a {@link QuestionItem} and makes a call to the
* specified {@link OnListFragmentInteractionListener}.
*/
public class QuestionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<QuestionItem> mValues;
private final OnListFragmentInteractionListener mListener;
private RecyclerView mRecyclerView;
/** View生成時にどのLayoutを使うか特定する一意な識別子 */
private static final int VIEW_HEADER = 4545;
private static final int VIEW_FOOTER = 1919;
public QuestionRecyclerViewAdapter(List<QuestionItem> items, OnListFragmentInteractionListener listener, RecyclerView recyclerView) {
mValues = items;
mListener = listener;
mRecyclerView = recyclerView;
}
/** ViewHolder作成(LayoutをInflateする) */
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
switch (viewType){
case VIEW_HEADER:
view = inflater.inflate(R.layout.fragment_header, parent, false);
return new HeaderViewHolder(view);
case VIEW_FOOTER:
view = inflater.inflate(R.layout.fragment_footer, parent, false);
return new FooterViewHolder(view);
default://通常セル
view = inflater.inflate(R.layout.fragment_question, parent, false);
return new QuestionViewHolder(view);
}
}
/** ViewHolderとViewのBind(ここでViewをつくる) */
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if(holder instanceof HeaderViewHolder){
((HeaderViewHolder)holder).onBindViewHolder();
}
if(holder instanceof FooterViewHolder){
((FooterViewHolder)holder).onBindViewHolder();
}
if(holder instanceof QuestionViewHolder){
((QuestionViewHolder)holder).onBindViewHolder(mValues.get(position), position);
}
}
/** ViewHolderのTypeを決定する */
@Override
public int getItemViewType(int position) {
if(QuestionContent.ITEMS.get(position).toString().equals("Dummy:Header")){//ヘッダ
return VIEW_HEADER;
}else if(QuestionContent.ITEMS.get(position).toString().equals("Dummy:Footer")){//フッタ
return VIEW_FOOTER;
}else{//問題
return 0;
}
}
@Override
public int getItemCount() {
return mValues.size();
}
/** 問題のViewHolder */
class QuestionViewHolder extends RecyclerView.ViewHolder {
public final View mView;
@BindView(R.id.question_id) TextView mIdView;
@BindView(R.id.content) TextView mContentView;
@BindView(R.id.answer_group) RadioGroup mAnswerGroup;
@BindView(R.id.answer_button) BootstrapButton answerButton;
public QuestionItem mItem;
public QuestionViewHolder(View view) {
super(view);
mView = view;
ButterKnife.bind(this, mView);
}
public void onBindViewHolder(QuestionItem item, final int position){
this.mIdView.setText(item.id);
this.mContentView.setText(item.content);
this.mAnswerGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int answerId;
switch (checkedId){
case R.id.positive_max_button:
answerId = 0;
break;
case R.id.positive_button:
answerId = 1;
break;
case R.id.natural_button:
answerId = 2;
break;
case R.id.negative_button:
answerId = 3;
break;
case R.id.negative_max_button:
answerId = 4;
break;
default:
return;
}
if(UserAnswer.THIS.getAnswers().size() <= position){
UserAnswer.THIS.addAnswer(answerId);
}else{
UserAnswer.THIS.setAnswer(position, answerId);
}
}
});
this.answerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int answerId;
switch (mAnswerGroup.getCheckedRadioButtonId()){
case R.id.positive_max_button:
answerId = 0;
break;
case R.id.positive_button:
answerId = 1;
break;
case R.id.natural_button:
answerId = 2;
break;
case R.id.negative_button:
answerId = 3;
break;
case R.id.negative_max_button:
answerId = 4;
break;
default:
return;
}
if(UserAnswer.THIS.getAnswers().size() <= position){
UserAnswer.THIS.addAnswer(answerId);
}else{
UserAnswer.THIS.setAnswer(position, answerId);
}
if(position != QuestionContent.ITEMS.size() - 1){
mRecyclerView.smoothScrollToPosition(position+1);
}
}
});
this.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(mItem);
}
}
});
}
@Override
public String toString() {
return super.toString() + "@" + mIdView.getText();
}
}
/** ヘッダのViewHolder */
class HeaderViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.startButton) BootstrapButton startButton;
@BindView(R.id.userNameText) BootstrapEditText userNameText;
@BindView(R.id.maleButton) BootstrapButton maleButton;
@BindView(R.id.femaleButton) BootstrapButton femaleButton;
public HeaderViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void onBindViewHolder(){
userNameText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length() != 0 && (maleButton.isSelected() || femaleButton.isSelected())){
startButton.setEnabled(true);
}else{
startButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
BootstrapButton.OnCheckedChangedListener buttonlistener = new BootstrapButton.OnCheckedChangedListener() {
@Override
public void OnCheckedChanged(BootstrapButton bootstrapButton, boolean isChecked) {
if((maleButton.isSelected() || femaleButton.isSelected()) && userNameText.getText().length() != 0){
startButton.setEnabled(true);
}else{
startButton.setEnabled(false);
}
}
};
maleButton.setOnCheckedChangedListener(buttonlistener);
femaleButton.setOnCheckedChangedListener(buttonlistener);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
short userSex = UserAnswer.MALE;
if(maleButton.isSelected())userSex = UserAnswer.MALE;
if(femaleButton.isSelected())userSex = UserAnswer.FEMALE;
UserAnswer.THIS.setUserName(userNameText.getText().toString());
UserAnswer.THIS.setUserSex(userSex);
userNameText.getText().clear();
mRecyclerView.smoothScrollToPosition(1);
}
});
}
}
/** フッタのViewHolder */
class FooterViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.UserID_View) TextView userIdView;
@BindView(R.id.endButton) BootstrapButton endButton;
public FooterViewHolder(View itemView){
super(itemView);
ButterKnife.bind(this, itemView);
}
public void onBindViewHolder(){
userIdView.setText(String.valueOf(UserAnswer.THIS.getUserId()));
endButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UserAnswer.THIS.exportUser();
UserAnswer.THIS.clearAnswer();
mRecyclerView.scrollToPosition(0);
}
});
}
}
}
| 29.601399 | 134 | 0.718876 |
d6fcc48892f4a026469585b13ef3fe7ee69ce777 | 6,867 | /*
* Copyright (c) 2019, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License,
* Version 2.0 (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.okta.oidc.clients.sessions;
import android.net.Uri;
import android.os.Process;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.okta.oidc.RequestCallback;
import com.okta.oidc.RequestDispatcher;
import com.okta.oidc.Tokens;
import com.okta.oidc.net.ConnectionParameters;
import com.okta.oidc.net.response.IntrospectInfo;
import com.okta.oidc.net.response.UserInfo;
import com.okta.oidc.storage.security.EncryptionManager;
import com.okta.oidc.util.AuthorizationException;
import org.json.JSONObject;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
class SessionClientImpl implements SessionClient {
private SyncSessionClient mSyncSessionClient;
private RequestDispatcher mDispatcher;
private volatile Future<?> mFutureTask;
SessionClientImpl(Executor callbackExecutor, SyncSessionClient syncSessionClient) {
mSyncSessionClient = syncSessionClient;
mDispatcher = new RequestDispatcher(callbackExecutor);
}
public void getUserProfile(final RequestCallback<UserInfo, AuthorizationException> cb) {
cancelFuture();
mFutureTask = mDispatcher.submit(() -> {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
UserInfo userInfo = mSyncSessionClient.getUserProfile();
mDispatcher.submitResults(() -> cb.onSuccess(userInfo));
} catch (AuthorizationException ae) {
mDispatcher.submitResults(() -> cb.onError(ae.error, ae));
} catch (Exception ex) {
mDispatcher.submitResults(() -> cb.onError(ex.getMessage(),
new AuthorizationException(ex.getMessage(), ex)));
}
});
}
public void introspectToken(String token, String tokenType,
final RequestCallback<IntrospectInfo, AuthorizationException> cb) {
cancelFuture();
mFutureTask = mDispatcher.submit(() -> {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
IntrospectInfo introspectInfo = mSyncSessionClient
.introspectToken(token, tokenType);
mDispatcher.submitResults(() -> cb.onSuccess(introspectInfo));
} catch (AuthorizationException ae) {
mDispatcher.submitResults(() -> cb.onError(ae.error, ae));
} catch (Exception ex) {
mDispatcher.submitResults(() -> cb.onError(ex.getMessage(),
new AuthorizationException(ex.getMessage(), ex)));
}
});
}
public void revokeToken(String token,
final RequestCallback<Boolean, AuthorizationException> cb) {
cancelFuture();
mFutureTask = mDispatcher.submit(() -> {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
Boolean isRevoke = mSyncSessionClient.revokeToken(token);
mDispatcher.submitResults(() -> cb.onSuccess(isRevoke));
} catch (AuthorizationException ae) {
mDispatcher.submitResults(() -> cb.onError(ae.error, ae));
} catch (Exception ex) {
mDispatcher.submitResults(() -> cb.onError(ex.getMessage(),
new AuthorizationException(ex.getMessage(), ex)));
}
});
}
public void refreshToken(final RequestCallback<Tokens, AuthorizationException> cb) {
//Wrap the callback from the app because we want to be consistent in
//returning a Tokens object instead of a TokenResponse.
cancelFuture();
mFutureTask = mDispatcher.submit(() -> {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
Tokens result = mSyncSessionClient.refreshToken();
mDispatcher.submitResults(() -> cb.onSuccess(result));
} catch (AuthorizationException ae) {
mDispatcher.submitResults(() -> cb.onError(ae.error, ae));
} catch (Exception ex) {
mDispatcher.submitResults(() -> cb.onError(ex.getMessage(),
new AuthorizationException(ex.getMessage(), ex)));
}
});
}
@Override
public Tokens getTokens() throws AuthorizationException {
return mSyncSessionClient.getTokens();
}
@Override
public void authorizedRequest(@NonNull Uri uri, @Nullable Map<String, String> properties,
@Nullable Map<String, String> postParameters,
@NonNull ConnectionParameters.RequestMethod method,
final RequestCallback<JSONObject, AuthorizationException> cb) {
cancelFuture();
mFutureTask = mDispatcher.submit(() -> {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
JSONObject result = mSyncSessionClient
.authorizedRequest(uri, properties, postParameters, method);
mDispatcher.submitResults(() -> cb.onSuccess(result));
} catch (AuthorizationException ae) {
mDispatcher.submitResults(() -> cb.onError(ae.error, ae));
} catch (Exception ex) {
mDispatcher.submitResults(() -> cb.onError(ex.getMessage(),
new AuthorizationException(ex.getMessage(), ex)));
}
});
}
public boolean isAuthenticated() {
return mSyncSessionClient.isAuthenticated();
}
public void clear() {
mSyncSessionClient.clear();
}
@Override
public void cancel() {
mDispatcher.runTask(() -> {
mSyncSessionClient.cancel();
cancelFuture();
});
}
@Override
public void migrateTo(EncryptionManager manager) throws AuthorizationException {
mSyncSessionClient.migrateTo(manager);
}
private void cancelFuture() {
if (mFutureTask != null && (!mFutureTask.isDone() || !mFutureTask.isCancelled())) {
mFutureTask.cancel(true);
}
}
}
| 40.157895 | 99 | 0.630115 |
b6362cf41cce72dacd6525eb4a50d5135c1511f5 | 2,404 | package com.alipay.android.a.a.a;
import android.os.Looper;
import com.alipay.android.a.a.a.a.c;
import com.alipay.android.a.a.a.a.d;
import com.alipay.android.a.a.a.a.f;
import com.alipay.d.a.a.a.a;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public final class g
{
private static final ThreadLocal<Object> a = new ThreadLocal();
private static final ThreadLocal<Map<String, Object>> b = new ThreadLocal();
private byte c = 0;
private AtomicInteger d;
private e e;
public g(e parame)
{
this.e = parame;
this.d = new AtomicInteger();
}
public final Object a(Method paramMethod, Object[] paramArrayOfObject)
{
boolean bool = true;
if ((Looper.myLooper() != null) && (Looper.myLooper() == Looper.getMainLooper())) {}
for (int i = 1; i != 0; i = 0) {
throw new IllegalThreadStateException("can't in main thread call rpc .");
}
Object localObject = (a)paramMethod.getAnnotation(a.class);
if (paramMethod.getAnnotation(com.alipay.d.a.a.a.b.class) != null) {}
Type localType;
for (;;)
{
localType = paramMethod.getGenericReturnType();
paramMethod.getAnnotations();
a.set(null);
b.set(null);
if (localObject != null) {
break;
}
throw new IllegalStateException("OperationType must be set.");
bool = false;
}
localObject = ((a)localObject).a();
i = this.d.incrementAndGet();
try
{
if (this.c == 0)
{
paramArrayOfObject = new com.alipay.android.a.a.a.a.e(i, (String)localObject, paramArrayOfObject);
if (b.get() != null) {
paramArrayOfObject.a(b.get());
}
paramArrayOfObject = paramArrayOfObject.a();
paramMethod = (byte[])new t(this.e.a, paramMethod, i, (String)localObject, paramArrayOfObject, bool).a();
b.set(null);
paramMethod = new d(localType, paramMethod).a();
if (localType != Void.TYPE) {
a.set(paramMethod);
}
}
return a.get();
}
catch (b paramMethod)
{
paramMethod.setOperationType((String)localObject);
throw paramMethod;
}
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/alipay/android/a/a/a/g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 29.679012 | 113 | 0.626872 |
2cce4969c14957c692917690493e1fdc2d5979a4 | 522 | package com.matthewoneill.manualscrobbler;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//noinspection deprecation
addPreferencesFromResource(R.xml.preference);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
}
| 22.695652 | 60 | 0.749042 |
416632df3b44ebee2070cfbfdbab64f093dffaae | 6,777 | /*
* Copyright 2002-2015 SCOOP Software GmbH
*
* 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.copperengine.core.common;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.copperengine.core.Workflow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of the {@link TicketPoolManager} interface, using a java maps.
* This implementation is thread safe.
*
* @author austermann
*/
public class DefaultTicketPoolManager implements TicketPoolManager {
private static final Logger logger = LoggerFactory.getLogger(DefaultTicketPoolManager.class);
public static final String DEFAULT_POOL_ID = "DEFAULT";
private volatile Map<String, TicketPool> map = new HashMap<String, TicketPool>();
private final Object mutex = new Object();
private final Map<String, String> mappingDesc = new HashMap<String, String>();
private volatile Map<String, TicketPool> concreteMapping = Collections.emptyMap();
public DefaultTicketPoolManager() {
map.put(DEFAULT_POOL_ID, new TicketPool(DefaultTicketPoolManager.DEFAULT_POOL_ID, 2000));
}
@Override
public boolean exists(String id) {
return map.containsKey(id);
}
@Override
public TicketPool getTicketPool(String id) {
if (id == null)
throw new NullPointerException();
if (id.length() == 0)
throw new IllegalArgumentException();
final Map<String, TicketPool> map = this.map;
TicketPool tp = map.get(id);
if (tp == null) {
logger.error("Ticket pool '" + id + "' does not exist - returning default pool");
tp = map.get(DEFAULT_POOL_ID);
}
assert tp != null;
return tp;
}
@Override
public synchronized void add(TicketPool tp) {
HashMap<String, TicketPool> newMap = new HashMap<String, TicketPool>(map);
newMap.put(tp.getId(), tp);
map = newMap;
}
@Override
public synchronized void remove(TicketPool tp) {
HashMap<String, TicketPool> newMap = new HashMap<String, TicketPool>(map);
newMap.remove(tp.getId());
map = newMap;
}
@Override
public void shutdown() {
// empty
}
@Override
public void startup() {
// empty
}
@Override
public synchronized void setTicketPools(List<TicketPool> ticketPools) {
HashMap<String, TicketPool> newMap = new HashMap<String, TicketPool>(map);
for (TicketPool tp : ticketPools) {
newMap.put(tp.getId(), tp);
}
map = newMap;
}
@Override
public void obtain(Workflow<?> wf) {
findPool(wf.getClass().getName()).obtain();
}
/**
* For testing..
*
* @param wf
* For this workflow, the corresponding ticketPool is searched and then a ticket is obtained from this pool.
* @return
* id of the ticket pool.
*/
public String obtainAndReturnTicketPoolId(Workflow<?> wf) {
TicketPool tp = findPool(wf.getClass().getName());
tp.obtain();
return tp.getId();
}
@Override
public void release(Workflow<?> wf) {
findPool(wf.getClass().getName()).release();
}
@Override
public void addMapping(String workflowClass, String ticketPoolId) {
if (workflowClass == null)
throw new NullPointerException();
if (ticketPoolId == null)
throw new NullPointerException();
if (!map.containsKey(ticketPoolId)) {
throw new IllegalArgumentException("TicketPool '" + ticketPoolId + "' does not exist");
}
synchronized (mutex) {
mappingDesc.put(workflowClass, ticketPoolId);
concreteMapping = Collections.emptyMap();
}
}
@Override
public void removeMapping(String workflowClass) {
if (workflowClass == null)
throw new NullPointerException();
synchronized (mutex) {
mappingDesc.remove(workflowClass);
concreteMapping = Collections.emptyMap();
}
}
@Override
public void setMapping(Map<String, String> mapping) {
if (mapping == null)
throw new NullPointerException();
synchronized (mutex) {
for (Map.Entry<String, String> entry : mapping.entrySet()) {
if (entry.getKey() == null)
throw new NullPointerException();
if (entry.getValue() == null)
throw new NullPointerException();
if (!map.containsKey(entry.getValue())) {
throw new IllegalArgumentException("TicketPool '" + entry.getValue() + "' does not exist");
}
mappingDesc.put(entry.getKey(), entry.getValue());
}
concreteMapping = Collections.emptyMap();
}
}
private TicketPool findPool(String wfClass) {
TicketPool tp = concreteMapping.get(wfClass);
if (tp == null) {
synchronized (mutex) {
tp = concreteMapping.get(wfClass);
if (tp == null) {
HashMap<String, TicketPool> newConcreteMapping = new HashMap<String, TicketPool>(concreteMapping);
for (Map.Entry<String, String> entry : mappingDesc.entrySet()) {
String c = entry.getKey();
if (wfClass.equals(c)) {
tp = map.get(entry.getValue());
}
}
if (tp == null) {
tp = map.get(DEFAULT_POOL_ID);
}
logger.info("Mapping workflow class '" + wfClass + "' to ticket pool " + tp.getId());
newConcreteMapping.put(wfClass, tp);
concreteMapping = newConcreteMapping;
}
}
}
assert tp != null;
return tp;
}
@Override
public void obtain(String workflowClass) {
findPool(workflowClass).obtain();
}
@Override
public void release(String workflowClass) {
findPool(workflowClass).release();
}
}
| 32.581731 | 119 | 0.597757 |
aa2f11e85ca53daa3a77ceba19c004c0dc2d54ad | 180 | package com.github.cschen1205.tensorflow.classifiers.images.models;
import java.io.IOException;
public interface TrainedModelLoader {
void load_model() throws IOException;
}
| 22.5 | 67 | 0.811111 |
1f4ee016ac645074ce200dd79d4822596bc00a78 | 4,437 | package timeflow.app.ui;
import javax.swing.*;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
// custom JTabbedPane-like thing.
public class LinkTabPane extends JPanel {
ArrayList<String> tabNames=new ArrayList<String>();
HashMap<String, JComponent> tabMap=new HashMap<String, JComponent>();
String currentName;
CardLayout cards=new CardLayout();
JPanel center=new JPanel();
LinkTop top=new LinkTop();
public LinkTabPane()
{
setBackground(Color.white);
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(center, BorderLayout.CENTER);
center.setLayout(cards);
top.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
String s=top.getName(e.getX());
if (s!=null)
{
String old=currentName;
setCurrentName(s);
firePropertyChange("tab", old, s);
}
}});
}
public String getTitleAt(int i)
{
return tabNames.get(i);
}
public void setSelectedIndex(int i)
{
setCurrentName(getTitleAt(i));
}
public void addTab(JComponent component, String name, boolean left)
{
tabNames.add(name);
tabMap.put(name, component);
center.add(component, name);
top.addName(name, left);
repaint();
if (currentName==null)
currentName=name;
}
public String getCurrentName()
{
return currentName;
}
public void setCurrentName(final String currentName)
{
this.currentName=currentName;
top.repaint();
SwingUtilities.invokeLater(new Runnable() {public void run() {cards.show(center, currentName);}});
}
class LinkTop extends JPanel
{
int left, right;
ArrayList<HotLink> leftHots=new ArrayList<HotLink>();
ArrayList<HotLink> rightHots=new ArrayList<HotLink>();
Font font=new Font("Verdana", Font.PLAIN, 14);
FontMetrics fm=getFontMetrics(font);
LinkTop()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setBackground(new Color(220,220,220));
}
public void paintComponent(Graphics g1)
{
int w=getSize().width, h=getSize().height;
Graphics2D g=(Graphics2D)g1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getBackground());
g.fillRect(0,0,w,h);
g.setColor(Color.gray);
for (int i=0; i<2; i++)
{
g.drawLine(0,i,w,i);
g.drawLine(0,h-1-i,w,h-1-i);
}
for (HotLink hot: leftHots)
{
draw(g, hot, h, 0);
}
for (HotLink hot: rightHots)
{
draw(g, hot, h, w);
}
for (int i=0; i<leftHots.size(); i++)
{
if (i<leftHots.size()-1)
{
HotLink hot=leftHots.get(i);
for (int j=0; j<1; j++)
g.drawLine(hot.x+hot.width-1-j, 7, hot.x+hot.width-1-j, h-7);
}
}
for (int i=0; i<rightHots.size(); i++)
{
if (i<rightHots.size()-1)
{
HotLink hot=rightHots.get(i);
for (int j=0; j<1; j++)
g.drawLine(hot.x+w-1-j, 7, hot.x+w-1-j, h-7);
}
}
}
void draw(Graphics g, HotLink hot, int h, int dx)
{
int x=hot.x+dx;
if (hot.s.equals(currentName))
{
g.setColor(Color.lightGray);
g.fillRect(x,2,hot.width,h-4);
g.setColor(Color.gray);
g.drawLine(x-1, 0, x-1, h);
g.drawLine(x+hot.width-1, 0, x+hot.width-1, h);
}
g.setColor(Color.darkGray);
g.setFont(font);
int sw=fm.stringWidth(hot.s);
g.drawString(hot.s, x+(hot.width-sw)/2, h-10);
}
String getName(int x)
{
for (HotLink h: leftHots)
{
if (h.x<=x && h.x+h.width>x)
return h.s;
}
for (HotLink h: rightHots)
{
int w=getSize().width;
if (h.x+w<=x && h.x+h.width+w>x)
return h.s;
}
if (leftHots.size()>0)
return leftHots.get(leftHots.size()-1).s;
if (rightHots.size()>0)
return rightHots.get(0).s;
return null;
}
void addName(String name, boolean leftward)
{
if (leftward)
{
int x=right;
int w=fm.stringWidth(name)+24;
leftHots.add(new HotLink(name, x, 0, w, 30));
right+=w;
}
else
{
int x=left;
int w=fm.stringWidth(name)+24;
rightHots.add(new HotLink(name, x-w, 0, w, 30));
left-=w;
}
}
class HotLink extends Rectangle
{
String s;
HotLink(String s, int x, int y, int w, int h)
{
super(x,y,w,h);
this.s=s;
}
}
public Dimension getPreferredSize()
{
return new Dimension(30,30);
}
}
}
| 21.229665 | 100 | 0.6119 |
d8ea6835405436093ee77e6a2fefed0d34f83a32 | 199 | package io.odpf.dagger.core.exception;
public class InvalidDaggerSourceException extends RuntimeException {
public InvalidDaggerSourceException(String message) {
super(message);
}
}
| 24.875 | 68 | 0.768844 |
a4ca05724edde50bdb02423044519ecdedced35e | 23,765 | /*
* Copyright (C) 2015-2017 Lukoh Nam, goForer
*
* 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.goforer.base.presentation.view.fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.goforer.base.presentation.view.adatper.BaseListAdapter;
import com.goforer.base.presentation.view.decoration.DividerItemDecoration;
import com.goforer.goforerarchblueprint.R;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public abstract class RecyclerFragment<T> extends BaseFragment {
private static final String TAG = "RecyclerFragment";
private static final int FIRST_PAGE = 1;
protected static final long STOP_LOADING_TIME0UT = 600;
protected static final long STOP_REFRESHING_TIMEOUT = 500;
private BaseListAdapter mBaseArrayAdapter;
private OnProcessListener mListener;
private ItemTouchHelper mItemTouchHelper;
private boolean mItemTouchHelperEnabled = false;
private boolean mIsLoading = false;
@SuppressWarnings("unused")
private boolean mIsUpdated = false;
private int mTotalPage = 0;
private int mCurrentPage = 0;
private List<T> mItems = new ArrayList<>();
protected RecyclerView.OnScrollListener mOnScrollListener;
@BindView(R.id.swipe_layout)
protected SwipyRefreshLayout mSwipeLayout;
@BindView(R.id.recycler_view)
protected RecyclerView mRecyclerView;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_default_recycler, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setViews();
}
@Override
public void onResume() {
super.onResume();
setScrollListener();
}
@Override
public void onPause() {
super.onPause();
removeScrollListener();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
private void setViews() {
setupSwipeLayout();
mRecyclerView.setLayoutManager(createLayoutManager());
if (isItemDecorationVisible()) {
addItemDecorations();
}
addItemTouchListener();
mRecyclerView.setItemAnimator(createItemAnimator());
Adapter adapter = createAdapter();
ItemTouchHelper.Callback callback = createItemTouchHelper();
if (callback != null) {
setItemTouchHelper(callback);
}
setScrollListener();
if (adapter instanceof BaseListAdapter) {
mBaseArrayAdapter = (BaseListAdapter)adapter;
}
Log.i(TAG, "Initialize views");
}
private void request(boolean isRefreshed) {
if (isLastPage(mCurrentPage)) {
stopRefreshing();
if (mBaseArrayAdapter != null) {
mBaseArrayAdapter.setReachedToLastPage(true);
}
}
if (!mIsLoading) {
mIsLoading = true;
if (mBaseArrayAdapter != null) {
mBaseArrayAdapter.setLoadingItems(true);
}
mCurrentPage = FIRST_PAGE;
setTotalPage(FIRST_PAGE);
if (isRefreshed) {
requestData(false);
} else {
requestData(true);
}
}
}
private void requestUpdate() {
if (!mIsLoading) {
mIsLoading = true;
if (mBaseArrayAdapter != null) {
mBaseArrayAdapter.setLoadingItems(true);
}
mIsUpdated = true;
updateData();
}
}
/**
* An OnScrollListener can be set on a RecyclerView to receive messages
* when a scrolling event has occurred on that RecyclerView.
*
* If you are planning to have several listeners at the same time, use
* RecyclerView#addOnScrollListener. If there will be only one listener at the time and you
* want your components to be able to easily replace the listener use
* RecyclerView#setOnScrollListener.
*/
private void setScrollListener() {
removeScrollListener();
mOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (!mIsLoading && !mBaseArrayAdapter.isReachedToLastPage() && dy >= 0) {
int lastVisibleItemPosition = getLastVisibleItem();
int totalItemCount = recyclerView.getLayoutManager().getItemCount();
if (lastVisibleItemPosition >= totalItemCount - 1) {
mBaseArrayAdapter.setReachedToLastItem(true);
if (isLastPage(mCurrentPage)) {
reachToLastPage();
stopRefreshing();
mBaseArrayAdapter.setReachedToLastPage(true);
return;
}
scrollToEndPage();
reachToEndPage(mCurrentPage);
mListener.onScrolledToLast(recyclerView, dx, dy);
} else {
mBaseArrayAdapter.setReachedToLastItem(false);
}
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
mListener.onScrolling();
// To Do::Implement playing the video file with position in case of video item
onFirstVisibleItem(getFirstCompletelyVisibleItem());
onLastVisibleItem(getLastCompletelyVisibleItem());
} else {
onScrolled(recyclerView, recyclerView.getScrollX(), recyclerView.getScrollY());
mListener.onScrolled(recyclerView, recyclerView.getScrollX(), recyclerView.getScrollY());
}
}
};
mRecyclerView.addOnScrollListener(mOnScrollListener);
}
/**
* Remove a listener that was notified of any changes in scroll state or position.
*/
private void removeScrollListener() {
if (mOnScrollListener != null) {
mRecyclerView.removeOnScrollListener(mOnScrollListener);
}
}
/**
* Set an ItemTouchHelper that will work with the given Callback
*
* @param callback This is the contract between ItemTouchHelper and your application.
* It lets you control which touch behaviors are enabled per each ViewHolder
* and also receive callbacks when user performs these actions.
*
* @see ItemTouchHelper.Callback
*/
private void setItemTouchHelper(ItemTouchHelper.Callback callback) {
mItemTouchHelperEnabled = true;
attachItemTouchHelperToRecyclerView(callback);
}
/**
* Attaches the ItemTouchHelper to the provided RecyclerView. If TouchHelper is already
* attached to a RecyclerView, it will first detach from the previous one. You can call this
* method with {@code null} to detach it from the current RecyclerView.
*
* @param callback This is the contract between ItemTouchHelper and your application.
* It lets you control which touch behaviors are enabled per each ViewHolder
* and also receive callbacks when user performs these actions.
*
* @return the ItemTouchHelper for attaching to the provided RecyclerView
*
* @see ItemTouchHelper
*
*/
private ItemTouchHelper attachItemTouchHelperToRecyclerView(ItemTouchHelper.Callback callback) {
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(getRecyclerView());
return mItemTouchHelper;
}
/**
* Check if the given page is the last page.
* Return true if the given page is the last page
* <p>
* To check if the given page is the last page, you must override
* This method is called whenever the swipe gesture triggers a refresh.
* </p>
*
* @param pageNum the current page number to check if given page is the last page
*
*/
protected boolean isLastPage(int pageNum) {
return (getTotalPage() == pageNum) && (getTotalPage() >= 1);
}
/**
* Set the total page count
*
* @param totalPage The total page count
*
*/
protected void setTotalPage(int totalPage) {
mTotalPage = totalPage;
}
/**
* Get the total page count
*
* @return The total page count
*/
protected int getTotalPage() {
return mTotalPage;
}
/**
* RecyclerView can perform several optimizations if it can know in advance that changes in
* adapter content cannot change the size of the RecyclerView itself.
* If your use of RecyclerView falls into this category, set this to true.
*
* @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.
* setItemHasFixedSize(true) means the RecyclerView has children (items)
* that has fixed width and
*/
protected void setItemHasFixedSize(boolean hasFixedSize) {
mRecyclerView.setHasFixedSize(hasFixedSize);
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
*/
protected void addItemDecorations() {
mRecyclerView.addItemDecoration(createItemDecoration());
}
/**
* Add the touch listener on RecyclerView
*/
protected void addItemTouchListener(){
}
/**
* Sets the {@link SwipyRefreshLayout}'s setting that this RecyclerFragment will use.
*
* <p>
* To set the {@link SwipyRefreshLayout}'s more setting, you must override
* </p>
*
*/
protected void setupSwipeLayout() {
mSwipeLayout.setColorSchemeResources(R.color.redLight);
mSwipeLayout.setOnRefreshListener(direction -> requestUpdate());
}
/**
* Create the {@link LayoutManager} that this RecyclerFragment will use.
*
* <p>
* To set the {@link LayoutManager} to provide RecyclerFragment, you must override
* </p>
*
* <p>In contrast to other adapter-backed views such as {@link android.widget.ListView}
* or {@link android.widget.GridView}, RecyclerFragment allows client code to provide custom
* layout arrangements for child views. These arrangements are controlled by the
* {@link LayoutManager}. A LayoutManager must be provided for RecyclerFragment to function.</p>
*
* <p>Several default strategies are provided for common uses such as lists and grids.</p>
*
* @return LayoutManager to use
*
* If you'd like to use GridLayout, you have to override this setLayoutManager method
* in your fragment as below example:
*
* Example
* @@Override
* protected RecyclerView.LayoutManager setLayoutManager() {
* return new GridLayoutManager(activity, 1);
* }
* or to use LinearLayout, you have to override this setLayoutManager method
* in your fragment as below:
*
* @@Override
* protected RecyclerView.LayoutManager setLayoutManager() {
* return new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
* }
*
*/
protected abstract LayoutManager createLayoutManager();
/**
* Get the last visible item index
*
* @return the last visible item index
*/
protected int getLastVisibleItem() {
LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
return ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
}
return 0;
}
/**
* Get the first completely visible item index
*
* @return the last visible item index
*/
protected int getFirstCompletelyVisibleItem() {
LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
return ((LinearLayoutManager) layoutManager).findFirstCompletelyVisibleItemPosition();
}
return 0;
}
protected int getLastCompletelyVisibleItem() {
LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
return ((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
}
return 0;
}
/**
* Create the ItemDecoration.
*
* An ItemDecoration allows the application to add a special drawing and layout offset
* to specific item views from the adapter's data set. This can be useful for drawing dividers
* between items, highlights, visual grouping boundaries and more.
*
* <p>All ItemDecorations are drawn in the order item were added. </p>
*
*/
protected ItemDecoration createItemDecoration() {
return new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL_LIST);
}
/**
* Starts dragging the provided ViewHolder.
*
* @param viewHolder The ViewHolder to start dragging. It must be a direct child of
* RecyclerView.
*/
@Deprecated
@SuppressWarnings("unused")
protected void startDrag(RecyclerView.ViewHolder viewHolder) {
if (mItemTouchHelper != null && mItemTouchHelperEnabled) {
mSwipeLayout.setRefreshing(false);
mItemTouchHelper.startDrag(viewHolder);
}
}
/**
* This implementation of {@link RecyclerView.ItemAnimator} provides basic
* animations on remove, add, and move events that happen to the items in
* a RecyclerView. RecyclerView uses a DefaultItemAnimator by default.
*
* @return The ItemAnimator for the animations that take place on items as changes are made
* to the adapter.
*
* @see RecyclerView#setItemAnimator(RecyclerView.ItemAnimator)
*/
protected RecyclerView.ItemAnimator createItemAnimator() {
return new DefaultItemAnimator();
}
/**
* Create a new adapter to provide child views on demand.
* <p>
* To set a new adapter to provide child views on demand, you must override
* </p>
* <p>
* When adapter is changed, all existing views are recycled back to the pool. If the pool has
* only one adapter, it will be cleared.
*
* @return The new adapter to set, or null to set no adapter.
*/
protected abstract Adapter createAdapter();
/**
* Attach an ItemTouchHelper to the provided RecyclerView.
* <p>
* To attach an ItemTouchHelper to the provided RecyclerView, you must override.
* </p>
*
* @return The callback which is the contract between ItemTouchHelper and your application.
* It lets you control which touch behaviors are enabled per each ViewHolder
* and also receive callbacks when user performs these actions.
*
* return null if you don't want to attach an ItemTouchHelper to provided RecyclerView.
*/
protected abstract ItemTouchHelper.Callback createItemTouchHelper();
/**
* RequestClient to get the information or images from server.
* <p>
* To request information or data to Web server, you must override
* This method is called whenever the adapter position of the last visible view is to last item on the list.
* </p>
*
* Don't implement any code in this overridden method if you don't like to request any information
* or data to Web server.
*
* @param isNew set to true to request new information or images, or false
*
*/
protected abstract void requestData(boolean isNew);
/**
* Notify when the page reach to the end of tha page
*
* @param page ther current page
*/
protected abstract void reachToEndPage(int page);
/**
* RequestClient to get the updated information or images from server.
* <p>
* To request information or data to Web server, you must override
* This method is called whenever the swipe gesture triggers a refresh.
* </p>
*
*/
protected abstract void updateData();
/**
* Check if the DividerItemDecoration is visible.
*
* <p>
* To check if the given page is the last page, you must override
* This method is called in {@link #onViewCreated}.
* </p>
*
* @return true if the ItemDecoration in {@link RecyclerView} must be visible
*/
protected abstract boolean isItemDecorationVisible();
/**
* Notify when the end of the page is reached
*/
protected abstract void reachToLastPage();
/**
* Notify when the current items are sorted
*
* @param items the sorted items
*/
public abstract void onSorted(List<T> items);
/**
* Notify when the input keyword is searched
*
* @param items the sorted items
*/
@SuppressWarnings("unused")
public abstract void onSearched(List<T> items);
/**
* Callback method to be invoked to notify the first visible position when RecyclerView's scroll
* state is idle.
*
* @param position the adapter position of the first fully visible item on RecyclerView
*/
public abstract void onFirstVisibleItem(int position);
/**
* Callback method to be invoked to notify the last visible position when RecyclerView's scroll
* state is idle.
*
* @param position the adapter position of the last fully visible item on RecyclerView
*/
public abstract void onLastVisibleItem(int position);
/**
* The information should be refreshed whenever the RecyclerFragment is created or
* the user refresh the contents of a view via a vertical swipe gesture.
*
* <P> Must.
* This method have to be called in override onViewCreated{@link #onViewCreated} method
* to get the information from server.
* </P>
*
* <p>
* Be refreshed as a result of the gesture in case a vertical swipe gesture.
* The information must be provided to allow refresh of the content wherever this gesture
* is used in case of a vertical swipe gesture.
* </p>
*
*/
protected void refresh(boolean refreshed) {
Log.i(TAG, "refresh");
if (refreshed) {
mSwipeLayout.post(() -> {
mSwipeLayout.setRefreshing(true);
request(true);
});
}
}
/**
* Set the scrolling is reached to last
*/
protected void scrollToEndPage() {
Log.i(TAG, "scrolledReachToLast");
if (!mIsLoading) {
mIsLoading = true;
if (mBaseArrayAdapter != null) {
mBaseArrayAdapter.setLoadingItems(true);
}
mCurrentPage++;
}
}
@SuppressWarnings("unused")
protected void clear() {
mCurrentPage = FIRST_PAGE;
if (mItems != null && mItems.size() > 0) {
mItems.clear();
}
}
/**
* Stop the data-parsing processing.
*/
public void stopRefreshing() {
mSwipeLayout.setRefreshing(false);
mIsLoading = false;
mIsUpdated = false;
if (mBaseArrayAdapter != null) {
mBaseArrayAdapter.setLoadingItems(false);
}
}
@MainThread
public void stopLoading(final long delayMillis) {
new Handler(Looper.getMainLooper()).postDelayed(this::stopRefreshing, delayMillis);
}
/**
* Sets the listener to be notified when a process is completed
*/
public void setOnProcessListener(OnProcessListener listener) {
mListener = listener;
}
public RecyclerView getRecyclerView() {
return mRecyclerView;
}
public SwipyRefreshLayout getRefreshLayout() {
return mSwipeLayout;
}
/**
* Gets current page
*
* @return current page
*/
@SuppressWarnings("unused")
public int getCurrentPage() {
return mCurrentPage;
}
/**
* Classes that wish to be notified when a process is completed should implement this interfaces.
* An OnProcessListener allows the application to intercept the process events.
*
* <p>This can be useful for applications that wish to implement some module
* after the process is done.
* /p>
*/
public interface OnProcessListener {
/**
* This listener method to be invoked when the RecyclerView has been scrolled to the last.
* This will be called after the scroll has completed.
* <p>
* This listener method will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
*
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
*/
void onScrolledToLast(RecyclerView recyclerView, int dx, int dy);
/**
* This listener method to be invoked on scrolling.
*/
void onScrolling();
/**
* This listener method to be invoked when scrolling is done.
*/
void onScrolled(RecyclerView recyclerView, int dx, int dy);
@SuppressWarnings("unused")
void onError(String message);
}
}
| 33.284314 | 112 | 0.643299 |
424a5f23a4aa08631948d6f9e779d5beeb5c9a05 | 1,430 | /*
* EVE Swagger Interface
* An OpenAPI for EVE Online
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package net.troja.eve.esi.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for CharacterAssetsLocationsPosition
*/
public class CharacterAssetsLocationsPositionTest {
private final CharacterAssetsLocationsPosition model = new CharacterAssetsLocationsPosition();
/**
* Model tests for CharacterAssetsLocationsPosition
*/
@Test
public void testCharacterAssetsLocationsPosition() {
// TODO: test CharacterAssetsLocationsPosition
}
/**
* Test the property 'x'
*/
@Test
public void xTest() {
// TODO: test x
}
/**
* Test the property 'y'
*/
@Test
public void yTest() {
// TODO: test y
}
/**
* Test the property 'z'
*/
@Test
public void zTest() {
// TODO: test z
}
}
| 21.343284 | 98 | 0.67972 |
5c4e6e4e45904abd769340f567c3b744d01a3857 | 968 | package io.quarkus.opentelemetry.restclient.deployment;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
public class OpenTelemeteryRestClientProcessor {
private static final String QUARKUS_REST_CLIENT_LISTENER = "io.quarkus.opentelemetry.restclient.QuarkusRestClientListener";
@BuildStep
void registerRestClientListener(BuildProducer<NativeImageResourceBuildItem> resource,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
resource.produce(new NativeImageResourceBuildItem(
"META-INF/services/org.eclipse.microprofile.rest.client.spi.RestClientListener"));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true, QUARKUS_REST_CLIENT_LISTENER));
}
}
| 44 | 127 | 0.802686 |
b8d1282d9b54c72bf977eb7c0ba7d74a1c618beb | 702 | import java.util.ArrayList;
public class Column {
private final String name;
private final ArrayList<String> rows;
public Column(String name) {
this.name = name;
this.rows = new ArrayList<>();
}
public String getName() {
return this.name;
}
public ArrayList<String> getRows() {
return this.rows;
}
public int getSize() {
return this.rows.size();
}
public String getRowValue(int index) {
return this.rows.get(index);
}
public void setRowValue(int index, String value) {
this.rows.set(index, value);
}
public void addRowValue(String value) {
this.rows.add(value);
}
}
| 19.5 | 54 | 0.595442 |
e578c871f2da324d06b23330acb043853a5a37c8 | 260 | package chp02;
import java.util.Random;
public class LuckyNo {
public static void main(String[] args) {
Random rand = new Random();
int lucky = rand.nextInt(10); //0-9的随机数
System.out.println("今天的幸运数是" + lucky + "。");
}
}
| 17.333333 | 52 | 0.592308 |
db7ae9a5fe43011fa6b9b83279e3943f792e7f49 | 3,988 | package krpc.rpc.dynamicroute;
import krpc.common.Json;
import krpc.common.Plugin;
import krpc.httpclient.HttpClientReq;
import krpc.httpclient.HttpClientRes;
import krpc.rpc.core.DynamicRouteConfig;
import krpc.rpc.core.DynamicRoutePlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class EtcdDynamicRoutePlugin extends AbstractHttpDynamicRoutePlugin implements DynamicRoutePlugin {
static Logger log = LoggerFactory.getLogger(EtcdDynamicRoutePlugin.class);
String routesPathTemplate;
int interval = 15;
// curl -X PUT "http://192.168.31.144:2379/v2/keys/dynamicroutes/default/100/routes.json.version" -d value=1
// curl -X PUT "http://192.168.31.144:2379/v2/keys/dynamicroutes/default/100/routes.json" -d value=%7B%22serviceId%22%3A100%2C%22disabled%22%3Afalse%2C%22weights%22%3A%5B%7B%22addr%22%3A%22192.168.31.27%22%2C%22weight%22%3A50%7D%2C%7B%22addr%22%3A%22192.168.31.28%22%2C%22weight%22%3A50%7D%5D%2C%22rules%22%3A%5B%7B%22from%22%3A%22host%20%3D%20192.168.31.27%22%2C%22to%22%3A%22host%20%3D%20192.168.31.27%22%2C%22priority%22%3A2%7D%2C%7B%22from%22%3A%22host%20%3D%20192.168.31.28%22%2C%22to%22%3A%22host%20%3D%20%24host%22%2C%22priority%22%3A1%7D%5D%7D
ConcurrentHashMap<String, String> versionCache = new ConcurrentHashMap<>();
public void init() {
routesPathTemplate = "http://%s/v2/keys/dynamicroutes";
super.init();
}
public void config(String paramsStr) {
Map<String, String> params = Plugin.defaultSplitParams(paramsStr);
String s = params.get("intervalSeconds");
if (!isEmpty(s)) interval = Integer.parseInt(s);
super.config(params);
}
public int getRefreshIntervalSeconds() {
return interval;
}
public DynamicRouteConfig getConfig(int serviceId, String serviceName, String group) {
String path = routesPathTemplate + "/" + group + "/" + serviceId + "/routes.json";
String versionPath = path + ".version";
String key = serviceId + "." + group;
String oldVersion = versionCache.get(key);
String newVersion = getData(versionPath);
if (newVersion == null || newVersion.isEmpty()) {
log.error("cannot get routes json version for service " + serviceName);
return null;
}
if (oldVersion != null && newVersion != null && oldVersion.equals(newVersion)) {
return null; // no change
}
String json = getData(path);
if (json == null || json.isEmpty()) {
log.error("cannot get routes json for service " + serviceName);
return null;
}
DynamicRouteConfig config = Json.toObject(json, DynamicRouteConfig.class);
if (config == null) return null;
versionCache.put(key, newVersion);
return config;
}
public String getData(String path) {
if (hc == null) return null;
String getPath = String.format(path, addr());
HttpClientReq req = new HttpClientReq("GET", getPath);
HttpClientRes res = hc.call(req);
if (res.getRetCode() != 0 || res.getHttpCode() != 200) {
log.error("cannot get data " + getPath + ", content=" + res.getContent());
if (res.getHttpCode() != 404) nextAddr();
return null;
}
String json = res.getContent();
Map<String, Object> m = Json.toMap(json);
if (m == null) {
nextAddr();
return null;
}
if (m.containsKey("errorCode") || !"get".equals(m.get("action"))) {
log.error("cannot get data " + getPath + ", content=" + res.getContent());
return null;
}
Map node = (Map) m.get("node");
if (node == null || node.size() == 0) return "";
String value = (String) node.get("value");
if (value == null) value = "";
return value;
}
}
| 35.927928 | 555 | 0.633902 |
fe48c32a8d3787b62736e918a2a89da73c130cdd | 13,717 | /**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - [email protected]
*
*/
package org.hoteia.qalingo.web.mvc.controller.paymentgateway;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.hoteia.qalingo.core.Constants;
import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.RequestConstants;
import org.hoteia.qalingo.core.domain.AbstractPaymentGateway;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.domain.enumtype.BoUrls;
import org.hoteia.qalingo.core.fetchplan.common.FetchPlanGraphCommon;
import org.hoteia.qalingo.core.fetchplan.market.FetchPlanGraphMarket;
import org.hoteia.qalingo.core.i18n.enumtype.ScopeWebMessage;
import org.hoteia.qalingo.core.service.MarketService;
import org.hoteia.qalingo.core.service.PaymentGatewayService;
import org.hoteia.qalingo.core.web.mvc.form.PaymentGatewayForm;
import org.hoteia.qalingo.core.web.mvc.viewbean.PaymentGatewayViewBean;
import org.hoteia.qalingo.core.web.resolver.RequestData;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.hoteia.qalingo.core.web.servlet.view.RedirectView;
import org.hoteia.qalingo.web.mvc.controller.AbstractTechnicalBackofficeController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
*
*/
@Controller("paymentGatewayController")
public class PaymentGatewayController extends AbstractTechnicalBackofficeController {
@Autowired
protected PaymentGatewayService paymentGatewayService;
@RequestMapping(value = BoUrls.PAYMENT_GATEWAY_LIST_URL, method = RequestMethod.GET)
public ModelAndView paymentGatewayList(final HttpServletRequest request, final Model model) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.PAYMENT_GATEWAY_LIST.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final MarketArea marketArea = requestData.getMarketArea();
displayList(request, model, requestData);
Object[] params = {marketArea.getName() + " (" + marketArea.getCode() + ")"};
overrideDefaultMainContentTitle(request, modelAndView, BoUrls.PAYMENT_GATEWAY_LIST.getKey(), params);
return modelAndView;
}
@RequestMapping(value = BoUrls.PAYMENT_GATEWAY_DETAILS_URL, method = RequestMethod.GET)
public ModelAndView paymentGatewayDetails(final HttpServletRequest request, final Model model) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.PAYMENT_GATEWAY_DETAILS.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final String currentPaymentGatewayCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_PAYMENT_GATEWAY_CODE);
// SANITY CHECK
if(StringUtils.isEmpty(currentPaymentGatewayCode)){
final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.PAYMENT_GATEWAY_LIST, requestData);
return new ModelAndView(new RedirectView(urlRedirect));
}
final AbstractPaymentGateway paymentGateway = paymentGatewayService.getPaymentGatewayByCode(currentPaymentGatewayCode, FetchPlanGraphCommon.fullPaymentGatewayFetchPlan());
// SANITY CHECK
if(paymentGateway != null){
modelAndView.addObject(ModelConstants.PAYMENT_GATEWAY_VIEW_BEAN, backofficeViewBeanFactory.buildViewBeanPaymentGateway(requestData, paymentGateway));
} else {
final String url = requestUtil.getLastRequestUrl(request);
return new ModelAndView(new RedirectView(url));
}
modelAndView.addObject("availablePaymentGatewayOptions", paymentGatewayService.findPaymentGatewayOptions());
model.addAttribute(ModelConstants.URL_BACK, backofficeUrlService.generateUrl(BoUrls.PAYMENT_GATEWAY_LIST, requestData));
Object[] params = {paymentGateway.getName() + " (" + paymentGateway.getCode() + ")"};
overrideDefaultMainContentTitle(request, modelAndView, BoUrls.PAYMENT_GATEWAY_DETAILS.getKey(), params);
return modelAndView;
}
@RequestMapping(value = BoUrls.PAYMENT_GATEWAY_EDIT_URL, method = RequestMethod.GET)
public ModelAndView paymentGatewayEdit(final HttpServletRequest request, final Model model, @ModelAttribute(ModelConstants.PAYMENT_GATEWAY_FORM) PaymentGatewayForm paymentGatewayForm) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.PAYMENT_GATEWAY_EDIT.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final String paymentGatewayCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_PAYMENT_GATEWAY_CODE);
if(StringUtils.isNotEmpty(paymentGatewayCode)){
// EDIT MODE
final AbstractPaymentGateway paymentGateway = paymentGatewayService.getPaymentGatewayByCode(paymentGatewayCode, FetchPlanGraphCommon.defaultPaymentGatewayFetchPlan());
PaymentGatewayViewBean paymentGatewayViewBean = backofficeViewBeanFactory.buildViewBeanPaymentGateway(requestData, paymentGateway);
request.setAttribute(ModelConstants.PAYMENT_GATEWAY_VIEW_BEAN, paymentGatewayViewBean);
modelAndView.addObject("availableGlobaleAttributeDefinitions", attributeService.findPaymentGatewayGlobalAttributeDefinitions());
modelAndView.addObject("availableMarketAreaAttributeDefinitions", attributeService.findPaymentGatewayMarketAreaAttributeDefinitions());
modelAndView.addObject("availableOptions", paymentGatewayService.findPaymentGatewayOptions());
Object[] params = {paymentGateway.getName() + " (" + paymentGateway.getCode() + ")"};
overrideDefaultMainContentTitle(request, modelAndView, BoUrls.PAYMENT_GATEWAY_EDIT.getKey(), params);
model.addAttribute(ModelConstants.URL_BACK, backofficeUrlService.generateUrl(BoUrls.PAYMENT_GATEWAY_DETAILS, requestData, paymentGateway));
} else {
final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.PAYMENT_GATEWAY_LIST, requestUtil.getRequestData(request));
return new ModelAndView(new RedirectView(urlRedirect));
}
return modelAndView;
}
@RequestMapping(value = BoUrls.PAYMENT_GATEWAY_EDIT_URL, method = RequestMethod.POST)
public ModelAndView submitAbstractPaymentGatewayEdit(final HttpServletRequest request, final Model model, @Valid @ModelAttribute(ModelConstants.PAYMENT_GATEWAY_FORM) PaymentGatewayForm paymentGatewayForm,
BindingResult result) throws Exception {
final RequestData requestData = requestUtil.getRequestData(request);
final Locale locale = requestData.getLocale();
if (result.hasErrors()) {
return paymentGatewayEdit(request, model, paymentGatewayForm);
}
AbstractPaymentGateway paymentGateway = null;
if(StringUtils.isNotEmpty(paymentGatewayForm.getId())){
paymentGateway = paymentGatewayService.getPaymentGatewayById(paymentGatewayForm.getId(), FetchPlanGraphCommon.fullPaymentGatewayFetchPlan());
}
try {
// CREATE OR UPDATE PAYMENT GATEWAY
webBackofficeService.createOrUpdatePaymentGateway(requestData.getMarketArea(), paymentGateway, paymentGatewayForm);
if (paymentGateway == null) {
addSessionSuccessMessage(request, getSpecificMessage(ScopeWebMessage.PAYMENT_GATEWAY, "create_success_message", locale));
final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.PAYMENT_GATEWAY_LIST, requestUtil.getRequestData(request));
return new ModelAndView(new RedirectView(urlRedirect));
} else {
addSessionSuccessMessage(request, getSpecificMessage(ScopeWebMessage.PAYMENT_GATEWAY, "update_success_message", locale));
final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.PAYMENT_GATEWAY_DETAILS, requestUtil.getRequestData(request), paymentGateway);
return new ModelAndView(new RedirectView(urlRedirect));
}
} catch (Exception e) {
addMessageError(result, null, "code", "code", getSpecificMessage(ScopeWebMessage.PAYMENT_GATEWAY, "create_or_update_message", locale));
logger.error("Can't save or update Payment Gateway:" + paymentGatewayForm.getId() + "/" + paymentGatewayForm.getCode(), e);
return paymentGatewayEdit(request, model, paymentGatewayForm);
}
}
/**
*
*/
@ModelAttribute(ModelConstants.PAYMENT_GATEWAY_FORM)
protected PaymentGatewayForm initPaymentGatewayForm(final HttpServletRequest request, final Model model) throws Exception {
final RequestData requestData = requestUtil.getRequestData(request);
final MarketArea marketArea = marketService.getMarketAreaByCode(requestData.getMarketArea().getCode(), FetchPlanGraphMarket.fullMarketAreaFetchPlan());
final String paymentGatewayCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_PAYMENT_GATEWAY_CODE);
if(StringUtils.isNotEmpty(paymentGatewayCode)){
final AbstractPaymentGateway paymentGateway = paymentGatewayService.getPaymentGatewayByCode(paymentGatewayCode, FetchPlanGraphCommon.fullPaymentGatewayFetchPlan());
return backofficeFormFactory.buildPaymentGatewayForm(marketArea, paymentGateway);
}
return backofficeFormFactory.buildPaymentGatewayForm(marketArea, null);
}
protected void displayList(final HttpServletRequest request, final Model model, final RequestData requestData) throws Exception {
String url = request.getRequestURI();
String page = request.getParameter(Constants.PAGINATION_PAGE_PARAMETER);
String sessionKey = "PagedListHolder_PaymentGateways";
PagedListHolder<PaymentGatewayViewBean> paymentGatewayViewBeanPagedListHolder = new PagedListHolder<PaymentGatewayViewBean>();
if(StringUtils.isEmpty(page)){
paymentGatewayViewBeanPagedListHolder = initList(request, sessionKey, requestData);
} else {
paymentGatewayViewBeanPagedListHolder = (PagedListHolder) request.getSession().getAttribute(sessionKey);
if (paymentGatewayViewBeanPagedListHolder == null) {
paymentGatewayViewBeanPagedListHolder = initList(request, sessionKey, requestData);
}
int pageTarget = new Integer(page).intValue() - 1;
int pageCurrent = paymentGatewayViewBeanPagedListHolder.getPage();
if (pageCurrent < pageTarget) {
for (int i = pageCurrent; i < pageTarget; i++) {
paymentGatewayViewBeanPagedListHolder.nextPage();
}
} else if (pageCurrent > pageTarget) {
for (int i = pageTarget; i < pageCurrent; i++) {
paymentGatewayViewBeanPagedListHolder.previousPage();
}
}
}
model.addAttribute(Constants.PAGINATION_PAGE_URL, url);
model.addAttribute(Constants.PAGINATION_PAGE_PAGED_LIST_HOLDER, paymentGatewayViewBeanPagedListHolder);
}
protected PagedListHolder<PaymentGatewayViewBean> initList(final HttpServletRequest request, String sessionKey, final RequestData requestData) throws Exception {
PagedListHolder<PaymentGatewayViewBean> paymentGatewayViewBeanPagedListHolder = new PagedListHolder<PaymentGatewayViewBean>();
final List<PaymentGatewayViewBean> paymentGatewayViewBeans = new ArrayList<PaymentGatewayViewBean>();
final List<AbstractPaymentGateway> paymentGateways = paymentGatewayService.findPaymentGateways(FetchPlanGraphCommon.fullPaymentGatewayFetchPlan());
for (Iterator<AbstractPaymentGateway> iterator = paymentGateways.iterator(); iterator.hasNext();) {
AbstractPaymentGateway paymentGateway = (AbstractPaymentGateway) iterator.next();
paymentGatewayViewBeans.add(backofficeViewBeanFactory.buildViewBeanPaymentGateway(requestUtil.getRequestData(request), paymentGateway));
}
paymentGatewayViewBeanPagedListHolder = new PagedListHolder<PaymentGatewayViewBean>(paymentGatewayViewBeans);
paymentGatewayViewBeanPagedListHolder.setPageSize(Constants.PAGE_SIZE);
request.getSession().setAttribute(sessionKey, paymentGatewayViewBeanPagedListHolder);
return paymentGatewayViewBeanPagedListHolder;
}
} | 58.619658 | 208 | 0.749727 |
99b1db0a9c17907aeb31479e78375da6de90ca78 | 1,032 | package org.doremus.isnimatcher;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "source")
@XmlAccessorType(XmlAccessType.FIELD)
public class Source {
private static final String MUSICBRAINZ_BASE = "https://musicbrainz.org/artist/";
private static final String BNF_BASE = "http://catalogue.bnf.fr/ark:/12148/cb";
private static final String VIAF_BASE = "https://viaf.org/viaf/";
@XmlElement(name = "codeOfSource")
public String codeOfSource;
@XmlElement(name = "sourceIdentifier")
public String sourceIdentifier;
public String asMusicBrainzURI() {
return MUSICBRAINZ_BASE + sourceIdentifier;
}
public String asBNFUri() {
return BNF_BASE + sourceIdentifier + "b";
}
public String asViafURI() {
return makeViafUri(sourceIdentifier);
}
public static String makeViafUri(String viaf) {
return VIAF_BASE + viaf;
}
}
| 27.157895 | 83 | 0.752907 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.